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
1 Answer 1
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)
answered Mar 23, 2014 at 11:31
bereal
34.7k8 gold badges65 silver badges111 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
jfs
the first argument may be a string but it is interpreted differently from a list. OPs issue is that
Popen interprets a single item list argument as the path to the program therefore passing the whole command line leads to No such file or directory error (there is no program named like program arg1 arg2 etc)bereal
@J.F.Sebastian thanks, I definitely was not clear enough. Hope, now it's better.
jfs
not quite. A string argument where the value is the whole command line may succeed on Windows but a list argument with a single item (as in OPs case) where the value is the whole command line will fail everywhere.
bereal
@J.F.Sebastian didn't know about Windows. Thanks, fixed.
default
subprocess.call()is looking for a file named "./dropbox_uploader.sh -s download /test/pictures pictures/". Which obviously doesn't exist. See bereal's on how to call it properly.