文件被创建,但子进程调用没有这样的文件或目录

时间:2015-06-05 03:23:23

标签: python subprocess

我正在尝试将子进程调用的输出重定向到文件

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)

创建文件。这是我通过打印outfile来了解的。但是,子进程调用返回Errno [2]没有这样的文件或目录

1 个答案:

答案 0 :(得分:1)

subprocess.call的第一个参数不正确。它应该是一个列表,而不是一个字符串。比较:

>>> 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

使用:

>>> subprocess.call(['echo', 'hello'])
hello
0

如果您确实要将shell命令传递给subprocess.call,则需要设置shell=True

>>> subprocess.call('echo hello', shell=True)
hello
0

使用列表版本通常会更好,因为这样您无需担心命令字符串中shell元字符的意外影响。