Why doesn't this subprocess.check_call() work?

2019-07-04 08:08发布

问题:

I'm running these snippets with Python 2.7 on Ubuntu 12.

import subprocess
args = ['rsync', '--rsh="ssh"', '/tmp/a/', '127.0.0.1:/tmp/b/']
subprocess.check_call(args)

Fails

import subprocess
args = ['rsync', '--rsh="ssh"', '/tmp/a/', '127.0.0.1:/tmp/b/']
call_string = ' '.join(args)
subprocess.check_call(call_string)

Works

The first code snippet results in rsync getting an invalid command line. Using the short version of this option (-e) doesn't make any difference. If I remove the --rsh part it works fine.

Using shell=True doesn't make any difference. Eliminating the quotes from "ssh" doesn't make any difference and I'd like to keep the quotes so I can pass arguments to ssh.

What's the problem?

回答1:

Remove the quotes around ssh; the shell would normally have parsed those and passed on the argument without the quoting:

import subprocess
args = ['rsync', '--rsh=ssh', '/tmp/a/', '127.0.0.1:/tmp/b/']
subprocess.check_call(args)