Python 子进程输出流 stdout.read 永远挂起输入提示

问题描述 投票:0回答:1

我正在尝试使用 Popen 运行一个子进程,并且有一次它要求输入提示而没有任何

EOF
,所以
stdout.read()
会阻塞 while 循环,直到找到
EOF

我无法通过

检测到我们是否处于输入提示中
  • proc.stdout.isatty()
    它停留在 False
  • proc.stdout.writable()
    它停留在 False

main1.py

from subprocess import Popen, PIPE
import sys

proc = Popen(["python3", "main2.py"], stdin=PIPE, stdout=PIPE, stderr=PIPE)
def read_until_it_finishes():
    while proc.poll() is None:
        if proc.stdout.isatty() is True: # <-- Why this line isn't it detecting we are in a input prompt ?
            break
        if proc.stdout.writable() is True: # <-- Why this line isn't it detecting we are in a input prompt ?
            break
        line =  proc.stdout.read(1).decode(sys.stdout.encoding) # https://stackoverflow.com/a/63137801/10294022
        sys.stdout.write(line)
        sys.stdout.flush()

read_until_it_finishes()
proc.stdin.write(b"My name is Catwoman\n")
proc.stdin.flush()

main2.py

import sys

sys.stdout.write("Hello my name is Batman\n")
sys.stdout.flush()
sys.stdout.write("I am awesome\n")
sys.stdout.flush()
name = input('And you what is your name:')
sys.stdout.write(name)
sys.stdout.flush()
sys.stdout.close()

然后运行

python3 main1.py

你能帮帮我吗?

python stdout popen
1个回答
0
投票

这是一个如何在应用程序之间传递

stdin
和打印
stdout
的例子:

  • runner.py:
from subprocess import Popen, PIPE
import sys

proc = Popen(["python", "app.py"], stdin=PIPE, stdout=PIPE, stderr=PIPE)
def read_until_it_finishes():
    while proc.poll() is None:
        char = proc.stdout.read(1).decode(sys.stdout.encoding)
        sys.stdout.write(char)
        sys.stdout.flush()
        if char == '>':
            name = input('')
            proc.stdin.write(name.encode(sys.stdout.encoding))
            proc.stdin.write(b'\n')
            proc.stdin.flush()

read_until_it_finishes()
  • app.py
print('Hello, I`m a bot')

while True:
    name = input('What is your name (or print exit to exit)>')
    if name == 'exit':
        print('bye bye')
        break
    print(f'Hello {name}')
  • 输出:
Hello, I`m a bot
What is your name (or print exit to exit)>a
Hello a
What is your name (or print exit to exit)>b
Hello b
What is your name (or print exit to exit)>c
Hello c
What is your name (or print exit to exit)>exit
bye bye

这是否回答了您的问题?

© www.soinside.com 2019 - 2024. All rights reserved.