我试图使用子进程来模拟以下bash命令:
dpkg --get-selections > a_file.txt我在Python解释器中尝试了一些东西:
1只跑dpkg
>>> args = ['dpkg','--get-selections']
>>> subprocess.call(args, shell=True)
dpkg: error: need an action option2将子进程分配给变量
>>> x = subprocess.call(args, shell=True)
dpkg: error: need an action option3将子进程输出重定向到文件
>>> args = ['dpkg','--get-selections', '>', 'a_file.txt']
>>> subprocess.call(args, shell=True)
dpkg: error: need an action option4重定向,作为数组中的一个参数。
>>> args = ['dpkg','--get-selections', '> a_file.txt']
>>> subprocess.call(args, shell=True)
dpkg: error: need an action option5不使用shell=True
>>> x = subprocess.call(args)
dpkg: no packages found matching > a_file.txt
>>> 对于在子进程中使用dpkg: error: need an action option,我似乎无法得到任何具体的信息。
bash命令工作正常,但语法似乎也没有什么问题。
干杯
发布于 2014-12-25 00:34:12
使用stdout参数call()。而且,您通常不想要shell=True --在大多数情况下,您不需要在shell中执行它,而不使用它要安全得多(还记得ShellShock吗?)
args = ['dpkg', '--get-selections']
with open('a_file.txt', 'w') as outfile:
subprocess.call(args, stdout=outfile)如果从dpkg本身得到一个错误,就意味着您传递了错误的参数。这与子进程无关。
https://stackoverflow.com/questions/27643326
复制相似问题