我怎么知道我的子进程是否正在等待我的输入?(在 python3 中) [英] How can I know whether my subprocess is waiting for my input ?(in python3)

查看:35
本文介绍了我怎么知道我的子进程是否正在等待我的输入?(在 python3 中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文件 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() 而休眠)时返回.>

main.py will block in the first pobj.stdout.read(), because sp.py is waiting for me.
But if I want to process the string 'Waiting for you input:' first, how can I know whether sp.py is waiting for me ?
In other words, I want the pobj.stdout.read() to return when sp.py is waiting (or sleeping because of time.sleep()).

推荐答案

好的,我已经解决了.我的代码基于 非阻塞读取 subprocess.PIPE在 python 中(谢谢,@VaughnCato)

Okay, I've worked it out. My code is based on Non-blocking read on a subprocess.PIPE in python (Thanks, @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()

这篇关于我怎么知道我的子进程是否正在等待我的输入?(在 python3 中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆