在 subprocess.Popen 命令中使用变量

Using a variable in a subprocess.Popen command

现在我有一个测试file.dat,我运行 hexdump 并将输出放入hexdump.dat 文件。

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

附带说明一下,我看到了不使用 shell=True 的建议,但我基本上得到了错误 OSError: [Errno 2] No such file or directory

所以,我希望能够传入变量或数组、文件,而不是硬编码 "file.dat"。 "files" 可以是用户输入或从先前的子流程部分生成的 array/list。

我试过用户输入案例:

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)        

还有:

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

感谢您的帮助,我知道我没有正确理解此处所需的结构,因此不胜感激 "handholdy" 的回答。

首先,关于找不到文件,您可能需要指定当前工作目录。

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

关于将数组作为参数传递,通常是这样的:

args = [ 'hexdump', ] + inputs
subprocess.Popen( args, cwd='/foo/bar' )

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

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

您需要 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 的文件不存在,您将得到一个错误(并且如果它确实存在,它仍然可能不是你想要的。)

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

file = "input.dat"
p = subprocess.Popen("hexdump " + file + " > hexdump.dat", shell=True)

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

您应该仔细阅读 Popenshell 参数的作用,然后做出决定。

我发现使用 python 和变量进行 shell 重定向的最简单方法如下:

subprocess.check_output('svnadmin load %s < %s' % (repo, fname), shell=True)

它可以处理非常大的文件。