[Tutor] Passing arguments to & running a python script on a remote machine from a python script on local machine .

eryksun eryksun at gmail.com
Thu Sep 20 12:25:07 CEST 2012

On Wed, Sep 19, 2012 at 6:13 PM, eryksun <eryksun at gmail.com> wrote:
>     cmd = 'python remote.py "%s" "%s" "%s"' % (arg1, arg2, arg3)
>     try:
>         out = subprocess.check_output(['ssh', '%s@%s' % (user, hostname), cmd])

I forgot you need to escape special characters in the arguments. You
can add quoting and escape special characters at the same time with
the undocumented function pipes.quote:

    import pipes

    args = tuple(pipes.quote(arg) for arg in (arg1, arg2, arg3))
    cmd = 'python test.py %s %s %s' % args

Notice there are no longer quotes around each %s in cmd. Python 3.3
will have shlex.quote:


Also, if you don't care about the output, use subprocess.check_call()
instead. However, the connection still waits for the remote shell's
stdout to close. If remote.py is long-running, redirect its stdout to
a log file or /dev/null and start the process in the background (&).
For example:

    cmd = 'python remote.py %s %s %s >/dev/null &' % args

With this command remote.py is put in the background, stdout closes,
the forked sshd daemon on the server exits, and ssh on the client
immediately returns.

More information about the Tutor mailing list