I have a tool which returns me some info about the machine I am running on.On the normal command line it would be something like -
sudo /path-to-tool-directory/tool arg
and this works fine .Now when I break this up and include this in my python script as
result = subprocess.call (["sudo /path-to-tool-directory/tool","arg"])
it throws me an error
subprocess.py in line XYZ ,
in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
any clue what might be going wrong here?
2 Answers 2
When using the subprocess module you need to provide the call() function with a list of command line arguments. Taking your example above:
result = subprocess.call (["sudo /path-to-tool-directory/tool","arg"])
This won't work because "sudo /path-to-tool-directory/tool" is a single list item. What you need is all items to be individual list items:
result = subprocess.call (["sudo", "/path-to-tool-directory/tool", "arg"])
This should successfully run and terminate leaving the return code from sudo in result.
1 Comment
Split off the call to sudo (for all the reasons that @zzzrik elaborates on above):
>>> result = subprocess.call (["sudo /usr/bin/python","/home/hughdbrown/Dropbox/src/longwords.py"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
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 1249, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
>>> result = subprocess.call (["sudo", "/usr/bin/python","/home/hughdbrown/Dropbox/src/longwords.py"])
[sudo] password for hughdbrown:
See? The second one is working because I get prompted for a password.
3 Comments
which vim (or whatever you want to test) and then putting that exact path as the first argument to subprocess.call. That way, you know that you will not get "no such file or directory".