繁体   English   中英

Python中的子进程挂起

[英]subprocess in Python hangs

我正在尝试使用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()

联接语句只是打印命令,就像我在终端中输入命令一样,以仔细检查命令的质量。 那个总是可以工作的...但是在Python中,它挂在subprocess.Popen() (位于p = ...)处。

我也尝试了其他几种methods例如call()但无济于事。

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

如果您只想进行简单的输入重定向,则无需使用外壳程序。 在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()

对于list shell=True ,我不清楚为什么对perl的调用会阻塞。 当我尝试类似

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

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

subprocess.call("cat < .bashrc".split(), shell=True, stdin=open("/dev/null"))

呼叫立即返回。 在这两种情况下, cat似乎都忽略了它的进一步论点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM