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



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

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

作为旁注,我已经看到了不使用shell=True的建议,但我基本上得到了错误OSError: [Errno 2] No such file or directory.

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

我尝试过用户输入案例:

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)                                          

感谢您的帮助,我知道我没有适当地理解这里所需的结构,因此一些"手持"答案将不胜感激。

你需要

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)

警告:如果与不受信任的输入结合使用,传递shell=True可能会造成安全隐患。有关详细信息,请参阅"常用参数"下的警告。

像这样:

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

您应该阅读Popen以及shell论点的作用,并做出决定。

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

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

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

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

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

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

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

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

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

最新更新