在中使用变量子流程.Popen命令

2024-06-06 09:30:19 发布

您现在位置:Python中文网/ 问答频道 /正文

现在我有个测试文件.dat运行hextump并将输出放入十六进制转储.dat文件。在

subprocess.Popen(['hexdump file.dat > hexdump.dat' ], shell=True)  

作为旁注,我看到了不使用shell=True的建议,但实际上我得到了错误OSError: [Errno 2] No such file or directory。在

所以,我希望能够传入一个变量或数组,文件,而不是硬编码的“文件.dat". "“文件”可以是用户输入或从上一个子进程部分生成的数组/列表。在

我尝试过用户输入案例:

^{pr2}$

还有:

p = subprocess.Popen(['hexdump',  inputs, ' > hexdump.dat' ], stdout=PIPE, stderr=STDOUT)                                          

谢谢你的帮助,我知道我不太了解这里需要的结构,所以一些“随手”的回答将不胜感激。在


Tags: 文件用户true错误数组shell建议hexdump
3条回答

Warning: Passing shell=True can be a security hazard if combined with untrusted input. See the warning under Frequently Used Arguments for details.

比如:

with open('hexdump.dat', 'wb') as f:
    p = subprocess.Popen(['hexdump', 'file.dat'], stdout=f)
    p.wait()

您应该仔细阅读^{}shell参数的作用,然后做出决定。在

您需要shell=True,否则它将查找具有该名称的可执行文件。shell=True告诉方法使用shell来执行命令,使>和朋友成为您最初想要的(重定向)。在

您发布的以下代码:

from subprocess import Popen, PIPE, STDOUT 
files = raw_input('File Name: ')                                                                                                 
p = subprocess.Popen(['hexdump files > hexdump.dat' ], stdout=PIPE, stderr=STDOUT)                                         
out,err = p.communicate(input=files)  

将不起作用,因为您只是将files传递给hexdump,如果名为files的文件不存在,您将得到一个错误(如果它确实存在,它可能仍然不是您想要的)

您需要构建正在执行的字符串:

^{pr2}$

您可以使用stdout参数重定向,而不是使用>重定向。至于文件列表,您只需将文件列表附加到包含hexdump的数组中,即

myfiles = ['file1','file2']
with open('hexdump.dat', 'w') as output:
    proc = subprocess.Popen(['hexdump'] + myfiles, stdout=output)

相关问题 更多 >