【问题标题】:Process a perl script within a python script在 python 脚本中处理 perl 脚本
【发布时间】:2015-09-11 16:18:48
【问题描述】:

我正在尝试在另一个 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

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

【问题讨论】:

  • 尝试以下方法,如此 SO stackoverflow.com/questions/25079140/…
  • 什么意思,什么都没发生?就输出而言,您 communicate 使用该进程,但您不会在 Python 脚本中打印或以其他方式对通信结果(进程的标准输出)执行任何操作。根据the documentation:“communicate() 返回 一个元组(stdoutdata,stderrdata)。” (强调我的。)
  • 您正在使用 shell 重定向运算符作为输入字符串的一部分。因此,子进程将尝试运行类似perl /path/to/perl/script/script.pl '&lt; /path/to/file1/arg1 &gt;' /path/to/file2/ 的东西。也就是说,&lt;&gt; 成为输入文件名的一部分。
  • @Evert 非常感谢!我让它工作了。是的,它的 shell 重定向,我用标准输入和标准输出替换它,它现在应该正常工作。

标签: python perl subprocess


【解决方案1】:

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。第 2 和第 3 个示例不使用 shell。

【讨论】:

    猜你喜欢
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2013-07-30
    • 2016-09-30
    • 2013-11-16
    相关资源
    最近更新 更多