简体   繁体   中英

Call shell script from python

Attempting to call a shell script with options from a python script. The line ./dropbox_uploader.sh -s download /test/pictures pictures/ runs fine via SSH but errors when called from a python script:

import subprocess
subprocess.call(['./dropbox_uploader.sh -s download /test/pictures pictures/'])

Here is the error message:

Traceback (most recent call last):
  File "sync.py", line 2, in <module>
    subprocess.call(['./dropbox_uploader.sh -s download /test/pictures pictures/'])
  File "/usr/lib/python2.7/subprocess.py", line 493, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

In case if the first argument of subprocess.call is a list, it must contain the executable and arguments as separate items:

subprocess.call(['./dropbox_uploader.sh', '-s', 
                 'download', '/test/pictures', 'pictures/'])

or, maybe, more convenient:

import shlex
cmd = './dropbox_uploader.sh -s download /test/pictures pictures/'
subprocess.call(shlex.split(cmd))

There is also an option to delegate parsing and execution to the shell:

cmd = './dropbox_uploader.sh -s download /test/pictures pictures/'
subprocess.call(cmd, shell=True)

(But please note the security warning )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM