Reputation: 45
I am trying to redirect the output of a subprocess call to a file
def get_arch():
global ip_vm
in_cmd = "uname -p"
with open('/home/thejdeep/arch_list',"w") as outfile:
print outfile
subprocess.call(in_cmd,stdout=outfile)
print "Hello"
for i in ip_vm:
cmd = "ssh thejdeep@"+i+" 'uname -p'"
with open('/home/thejdeep/arch_list',"a") as outpfile:
subprocess.call(cmd,stdout=outpfile)
The file gets created. This I get to know by printing outfile. However, the subprocess call returns a Errno[2] no such file or directory
Upvotes: 1
Views: 5008
Reputation: 311703
Your first parameter to subprocess.call
is incorrect. It should be a list, not a string. Compare:
>>> subprocess.call('echo hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib64/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib64/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
With:
>>> subprocess.call(['echo', 'hello'])
hello
0
If you really want to pass a shell command to subprocess.call
, you need to set shell=True
:
>>> subprocess.call('echo hello', shell=True)
hello
0
You are in general better off using the list version, because this way you don't need to worry about unexpected effects from shell metacharacters in your command strings.
Upvotes: 2