Python サブプロセス通信によりプロセスが強制終了されます
-
21-12-2019 - |
質問
通信によってプロセスが強制終了されるのはなぜですか?インタラクティブなプロセスが必要ですが、通信で何らかの処理が行われるため、プロセス内で raw_input を受け取ることができなくなります。
from sys import stdin
from threading import Thread
from time import sleep
if __name__ == '__main__':
print("Still Running\n")
x = raw_input()
i = 0
while ('n' not in x ) :
print("Still Running " + str(i) + " \r\n")
x = raw_input()
i += 1
print("quit")
print(aSubProc.theProcess.communicate('y'))
print(aSubProc.theProcess.communicate('y'))
例外!
self.stdin.write(input)
ValueError: I/O operation on closed file
解決
communicate
そして wait
の方法 Popen
オブジェクトを閉じます。 PIPE
プロセスが戻った後。プロセスとの通信を維持したい場合は、次のようなことを試してください。
import subprocess
proc = subprocess.Popen("some_process", stdout=subprocess.PIPE, stdin=subprocess.PIPE)
proc.stdin.write("input")
proc.stdout.readline()
他のヒント
なぜ私のプロセスを殺すのですか?
Popen.communicate(input=None, timeout=None)
:
プロセスと対話する:Stdinにデータを送信します。 stdoutからデータを読み取ると
ファイルの終わりに達するまでStderrに達する。 の終了を待ちます。 鉱山を強調する
.communicate()
を一度だけ呼び出すことができます。それはあなたがすべての入力を一度に提供するべきです:
#!/usr/bin/env python
import os
import sys
from subprocess import Popen, PIPE
p = Popen([sys.executable, 'child.py'], stdin=PIPE, stdout=PIPE)
print p.communicate(os.linesep.join('yyn'))[0]
.
出力
Still Running
Still Running 0
Still Running 1
quit
.
2倍の改行:'\r\n'
からの1つ、および子プロセスのスクリプト内のprint
ステートメントから別のもの。
出力は、子プロセスが3つの入力行を正常に受信した('y'
、'y'
、および'n'
)。
subprocess.check_output()
'■input
パラメータを使用した類似コードです。 Python3.4から:
#!/usr/bin/env python3.4
import os
import sys
from subprocess import check_output
output = check_output(['python2', 'child.py'], universal_newlines=True,
input='\n'.join('yyn'))
print(output, end='')
.
同じ出力を生成します。
子プロセスからの応答に応じて別の入力を提供したい場合は、パイプを使うだけではない(popen())?
所属していません StackOverflow