python subprocess: check to see if the executed script is asking for user input

对着背影说爱祢 提交于 2021-02-07 13:45:03

问题


import subprocess

child = subprocess.Popen(['python', 'simple.py'], stdin=subprocess.PIPE)
child.communicate('Alice')

I know you can communicate with executed script via communicate How do you check for whether a script 'simple.py' is asking for user input?

simple.py could ask for 5-10 user inputs so simply hardcoding communicate wouldnt be enough.

[EDIT]: want to parse the stdout as the script is running and communicate back to the script

while True:
    if child.get_stdout() == '?':
       # send user input

回答1:


A simple example:

simple.py:

i = raw_input("what is your name\n")
print(i)
j = raw_input("What is your age\n")
print(j)

Read and write:

import subprocess

child = subprocess.Popen(['python2', 'simple.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

for line in iter(child.stdout.readline, ""):
    print(line)
    if "name" in line:
        child.stdin.write("foo\n")
    elif "age" in line:
        child.stdin.write("100\n")

Output:

what is your name

foo

What is your age

100


来源:https://stackoverflow.com/questions/35751295/python-subprocess-check-to-see-if-the-executed-script-is-asking-for-user-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!