簡體   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