python - 我怎么知道我的子进程是否在等待我的输入?(在 python3 中)

标签 python python-3.x subprocess

文件 sp.py:

#!/usr/bin/env python3
s = input('Waiting for your input:')
print('Data:' + s)

文件main.py

import subprocess as sp
pobj = sp.Popen('sp.py',stdin=sp.PIPE,stdout=sp.PIPE,shell=True)
print(pobj.stdout.read().decode())
pobj.stdin.write(b'something...')
print(pobj.stdout.read().decode())

main.py会阻塞在第一个pobj.stdout.read(),因为sp.py在等我。
但是如果我想先处理字符串 'Waiting for you input:',我怎么知道 sp.py 是否在等我?
换句话说,我希望 pobj.stdout.read() 在 sp.py 正在等待(或由于 time.sleep() 而休眠)时返回。

最佳答案

好的,我已经解决了。我的代码基于 Non-blocking read on a subprocess.PIPE in python (谢谢,@VaughnCato)

#!/usr/bin/env python3
import subprocess as sp
from threading import Thread
from queue import Queue,Empty
import time

def getabit(o,q):
    for c in iter(lambda:o.read(1),b''):
        q.put(c)
    o.close()

def getdata(q):
    r = b''
    while True:
        try:
            c = q.get(False)
        except Empty:
            break
        else:
            r += c
    return r

pobj = sp.Popen('sp.py',stdin=sp.PIPE,stdout=sp.PIPE,shell=True)
q = Queue()
t = Thread(target=getabit,args=(pobj.stdout,q))
t.daemon = True
t.start()

while True:
    print('Sleep for 1 second...')
    time.sleep(1)#to ensure that the data will be processed completely
    print('Data received:' + getdata(q).decode())
    if not t.isAlive():
        break
    in_dat = input('Your data to input:')
    pobj.stdin.write(bytes(in_dat,'utf-8'))
    pobj.stdin.write(b'\n')
    pobj.stdin.flush()

关于python - 我怎么知道我的子进程是否在等待我的输入?(在 python3 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12180073/

相关文章:

python - 每个进程中的管道是否独立?

python - 如何使用 POST 请求(请求和 python3)提交联系表单?

python - 使用来自另一个 pandas DF 的最小值的 id 填充 pandas 列

python - 将元组从嵌套列表分离到单独的列表中

python - 如何打开包含 utf-8 非编码字符的文件?

python - 连续绿色日

python - csv.DictReader 中的行数

python-3.x - Python - 时差(JAX 库)

Python 子进程,shell 参数的用法

python - 当传递给 selenium 时,从命令捕获的 stdout 的换行数是原来的两倍