# Tag Archives: python

computing

## Python script to upload to a specified directory

Whenever I need to solve a practical computing problem that requires writing a script, tracking down the right tool for the job is often the trickiest part. Especially when I am learning a new language, it is easy to fall down the rabbit hole of documentation and extra libraries (not to mention threads on discussion forums).

Today, I wanted to write a script that would automatically upload a particular file on my local machine to my server that hosts my website. Basically, I got tired of constantly having to remember and type out the (long) destination path for every file I wanted to upload. Since I am learning Python, I thought I would figure out how to solve the problem in Python.

After doing some research, I found the Plumbum library offers exactly the tools I needed to get the job done. Since I didn’t have Plumbum installed on my machine, I installed it using pip.


pip install git+git://github.com/tomerfiliba/plumbum.git


Now with Plumbum installed, I was able to put together this code which does exactly what I want so far:


#!/usr/bin/env python

import plumbum
import sys

host = "willrosenbaum.com"
key = "/path/to/my/public/key"

filename = sys.argv[1]

r = plumbum.machines.SshMachine(host, user = username, keyfile = key)

fro = plumbum.local.path(filename)
remote_path = str(fro).replace(local_prefix, remote_prefix)
to = r.path(remote_path)

plumbum.path.utils.copy(fro, to)


Now whenever I want to copy a file from my local machine to its corresponding directory on my server, all I have to do is run


noga-sync filename