【问题标题】:subprocess in Python hangsPython中的子进程挂起
【发布时间】:2014-06-13 15:25:52
【问题描述】:

我正在尝试使用 Python 和子进程从 Perl 脚本中检索一些信息:

command = ["perl","script.perl","arg1.txt","<","arg2.txt"]
print " ".join(command)
p = subprocess.Popen(command,stdout=subprocess.PIPE,shell=True)
text = p.stdout.read()

join-statement 只是打印命令,就像我在终端中输入它以仔细检查命令的质量一样。那个总是有效的......但在 Python 中,它挂在 subprocess.Popen() (在 p= ... )。

我还尝试了其他几个methods,例如call(),但无济于事。

它只输出一行文本,所以我不知道这可能是什么问题。

【问题讨论】:

  • 您可以尝试使用strace -ff 运行 Python,以确切了解是什么操作导致它挂起。

标签: python perl command buffer subprocess


【解决方案1】:

如果您只需要简单的输入重定向,则无需涉及 shell。在 Python 中打开文件,并通过 stdin 参数将文件句柄传递给 Popen

with open("arg2.txt") as infile:
     command = ["perl", "script.perl", "arg1.txt"]
     p = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=infile)
     text = p.stdout.read()

command = "perl script.perl arg1.txt < arg2.txt"
p = subprocess.Popen(command,stdout=subprocess.PIPE,shell=True)
text = p.stdout.read()

使用列表 shell=True,我不清楚为什么它会调用perl 阻塞。当我尝试类似

subprocess.call("cat < .bashrc".split(), shell=True)

它会阻塞,就好像它仍在尝试从继承的标准输入中读取一样。如果我使用

向它提供输入
subprocess.call("cat < .bashrc".split(), shell=True, stdin=open("/dev/null"))

调用立即返回。无论哪种情况,cat 似乎都忽略了它的进一步论点。

【讨论】:

    猜你喜欢
    • 2017-02-28
    • 2012-09-07
    • 2015-07-07
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    相关资源
    最近更新 更多