为什么通信会杀死我的进程?我想要一个交互式过程,但通信做了一些事情,这样我就不能再在我的过程中接受 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
有帮助吗?

解决方案

communicatewait 的方法 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):

与进程交互:将数据发送到标准输入。从标准输出读取数据并
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

注意双换行符:一个来自 '\r\n' 另一个来自 print 在子进程的脚本中声明本身。

输出显示子进程成功接收到三个输入行('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='')

它产生相同的输出。


如果您想根据子进程的响应提供不同的输入,请使用 pexpect 模块或其类似物以避免中提到的问题 为什么不直接使用管道(popen())?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top