【问题标题】:Get output of `perl file.pl < some_file.txt` shell command获取 `perl file.pl < some_file.txt` shell 命令的输出
【发布时间】:2015-11-10 17:37:24
【问题描述】:
output = cStringIO.StringIO()
output.write('string') # this emulates some_file.txt

p = subprocess.Popen(['perl', 'file.pl'], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
line, _ = p.communicate(output.getvalue())
print line
output.close()

这会打印出Can't open perl script "file.pl": No such file or directory。 python脚本和perl文件在同一目录下!

我希望line 成为perl file.pl &lt; some_file.txt 的输出

如何做到这一点?

【问题讨论】:

  • file.pl 在当前工作目录中吗?
  • @ChadS.是的,它在同一个目录中。我已经更新了问题。
  • 您的问题似乎与subprocesscStringIO 无关。尝试指定file.pl 的绝对路径。
  • 它在同一个目录中并没有真正回答@ChadS。关于它是否在当前工作目录中的问题。您可以尝试os.path.join(os.path.dirname(__file__), 'file.pl') 明确查看脚本目录。
  • 你为什么使用shell=True?我认为这里不需要。如果不确定,请不要使用 shell=True。

标签: python subprocess


【解决方案1】:

我希望 line 是 perl file.pl &lt; some_file.txt 的输出

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

with open('some_file.txt', 'rb', 0) as file:
    line = check_output(['perl', 'file.pl'], stdin=file)

要修复 Can't open perl script "file.pl": No such file or directory,请将完整路径传递给 file.pl,例如,如果它与您的 Python 脚本位于同一目录中,那么您可以使用 get_script_dir() function 来获取路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 2013-08-21
    • 2012-02-07
    • 1970-01-01
    • 2017-12-10
    • 2020-01-24
    • 1970-01-01
    相关资源
    最近更新 更多