在 python 脚本中处理 perl 脚本

Process a perl script within a python script

我正在尝试在另一个 python 脚本中执行 perl 脚本。我的代码如下:

command = "/path/to/perl/script/" + "script.pl"
input = "< " + "/path/to/file1/" + sys.argv[1] + " >"
output = "/path/to/file2/" + sys.argv[1]

subprocess.Popen(["perl", command, "/path/to/file1/", input, output])

执行python脚本时,返回:

No info key.

通往 perl 脚本和文件的所有路径都是正确的。

我的 perl 脚本使用以下命令执行:

perl script.pl /path/to/file1/ < input > output

非常感谢对此的任何建议。

shell命令的类比:

#!/usr/bin/env python
from subprocess import check_call

check_call("perl script.pl /path/to/file1/ < input > output", shell=True)

是:

#!/usr/bin/env python
from subprocess import check_call

with open('input', 'rb', 0) as input_file, \
     open('output', 'wb', 0) as output_file:
    check_call(["perl", "script.pl", "/path/to/file1/"],
               stdin=input_file, stdout=output_file)

为了避免冗长的代码,你可以use plumbum to emulate a shell pipeline:

#!/usr/bin/env python
from plumbum.cmd import perl $ pip install plumbum

((perl["script.pl", "/path/to/file1"] < "input") > "output")()

注意:只有带有 shell=True 的代码示例运行 shell。第二个和第三个例子没有使用 shell.