繁体   English   中英

如何让 Python 的 subprocess() 与 input() 交互?

[英]How to make Python's subprocess() interact with input()?

(有关更新,请参阅下面的编辑 1)

我需要与我用 Python 3 编写的菜单进行交互。
但是,无论我尝试什么,我都无法调用input()行。
(这是get_action()函数的最后一行)。

以下是我想与subprocess()交互的(简化的)脚本:

$ cat test_menu.py
#!/usr/bin/env python3

action_text = """
5. Perform addition
6. Perform subtraction
Q. Quit
"""

def get_action():
    print(action_text)
    reply = input("Which action to use? ")

if __name__ == "__main__":
    get_action()

与上面的test_menu.py交互的基于 subprocess subprocess()的代码是:

$ cat tests1.py
import subprocess

cmd = ["/usr/bin/python3","./test_menu.py"]

process = subprocess.Popen(cmd,
                           shell=False,
                           bufsize=0,
                           stdin=subprocess.PIPE,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)

for i in range(8):
    output = process.stdout.readline()
    print output.strip()

process.stdin.write('%s\n' % "5")
process.stdin.flush()

但是,当我运行tests1.py,它永远不会到达input()行:

$ python ./tests1.py

5. Perform addition [default]
6. Perform subtraction
Q. Quit

任何建议如何让subprocess()显示并与input()行交互(例如,显示Which action to use?提示)?


编辑1:

按照@Serge 的建议, subprocess subprocess()能够显示提示行,但它仍然不显示输入 (5) 我输入了 PIPE。

改变了tests1.py:

import subprocess

def terminated_read(fd, terminators):
    buf = []
    while True:
        r = fd.read(1)
        buf += r
        if r in terminators:
            break
    return ''.join(buf)

cmd = ["/usr/bin/python3","./test_menu.py"]

process = subprocess.Popen(cmd,
                           shell=False,
                           bufsize=0,
                           stdin=subprocess.PIPE,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)

for i in range(5):
    output = process.stdout.readline()
    print output.strip()

process.stdin.write("5\n")
process.stdin.flush()

for i in range(80):
    output = terminated_read(process.stdout, "?")
    print output," ",

执行:

$ python ./tests1.py

5. Perform addition [default]
6. Perform subtraction
Q. Quit

Which action to use?                                                                                                                                                                         

问题是readline读取一个流直到它找到一个换行符,并且那个input("Which action to use? ")不打印一个。

一种简单的解决方法是编写

...
reply = input("Which action to use? \n")
...

如果您不想(或不能)更改测试菜单中的任何内容,则必须执行超时读取,或一次读取一个字符,直到找到新行或? .

例如这应该工作:

...
def terminated_read(fd, terminators):
    buf = []
    while True:
        r = fd.read(1).decode()
        buf += r
        if r in terminators:
            break
    return ''.join(buf)

process = subprocess.Popen(cmd,
                           shell=False,
                           bufsize=0,
                           stdin=subprocess.PIPE,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)

for i in range(8):
    output = terminated_read(process.stdout, "\n?")
    print(output.strip())
...

将答案传递给 subprocess 很简单。 困难的部分是猜测何时回答。 在这里,您知道只要输入以? . 我更改了您的 test_menu.py 以便能够确认它正确地获取命令:

#!/usr/bin/env python3

import sys

action_text = """
5. Perform addition
6. Perform subtraction
Q. Quit
"""

def get_action():
    print(action_text)
    reply = input("Which action to use? ")
    print("Was asked ", reply) # display what was asked
    if reply == '5':
        print("subtract...")


if __name__ == "__main__":
    get_action()

包装器test1.py很简单:

import subprocess

cmd = ["/usr/bin/python3","./test_menu.py"]

def terminated_read(fd, terminators):
    buf = []
    while True:
        r = fd.read(1).decode()
        # print(r)
        buf.append(r)
        if r in terminators:
            break
    return "".join(buf)

process = subprocess.Popen(cmd,
                           shell=False,
                           bufsize=0,
                           stdin=subprocess.PIPE,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)

while True:
    output = terminated_read(process.stdout, "\n?")
    print(output.strip())
    if output[-1] == '?':
        break

process.stdin.write(('%s\n' % "5").encode())
cr = process.wait()
end = process.stdout.read().decode()
print("Child result >" +  end + "<")
print("Child code" + str(cr))

从 Python 3.4 或 Python 2.7 开始,输出与预期的一样:

5. Perform addition
6. Perform subtraction
Q. Quit

Which action to use?
Child result > Was asked  5
subtract...
<
Child code0

以下应该可以工作(主要区别在于它在遇到菜单末尾时停止读取标准输出):

测试1.py:

#!/usr/bin/env python
import subprocess

cmd = ['./test_menu.py']

p = subprocess.Popen(cmd, shell=False, bufsize=0
                     stdin=subprocess.PIPE, 
                     stdout=subprocess.PIPE)
menu = ''
while True:
    output = p.stdout.read(1)
    if output:
        menu += output
    else:
        break
    if menu.endswith('#: '):
        break
print(p.communicate(raw_input(menu))[0])

测试菜单.py:

#!/usr/bin/env python
import sys
action_text = '''
5. Perform addition
6. Perform subtraction
Q. Quit
#: '''
sys.stdout.write(action_text); sys.stdout.flush()
inp = sys.stdin.read()
print(inp)

用法:

[ 12:52 me@yourbase ~/test ]$ ./test1.py 

5. Perform addition
6. Perform subtraction
Q. Quit
#: 5
5

[ 12:52 me@yourbase ~/test ]$ ./test1.py 

5. Perform addition
6. Perform subtraction
Q. Quit
#: 12345
12345

不确定您打算做什么,但以下内容将接受输入,您可以在get_action中使用它做任何您想做的事情:

action_text = """5. Perform addition
6. Perform subtraction
Q. Quit"""

def get_action():
    print(action_text)
    inp = input("Which action to use?\n")
    print(inp)
    print("Now do whatever")

if __name__ == "__main__":
    get_action()



import subprocess

cmd = ["/usr/bin/python3","./test_menu.py"]

process = subprocess.Popen(cmd,
                           shell=False,
                           bufsize=0,
                           stdin=subprocess.PIPE,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)


for  line in iter(process.stdout.readline, ""):
    print(line)
    if line.rstrip() == "Which action to use?":
        r = raw_input()
        process.stdin.write(r+"\n")

示例运行:

5. Perform addition

6. Perform subtraction

Q. Quit

Which action to use?

6
6

Now do whatever

添加几个函数:

def add():
    return 4+ 6

def sub():
    return 4 - 6

def get_action():
    print(action_text)
    inp = input("Which action to use?\n")
    if inp == "5":
        print(add())
    elif inp == "6":
        print(sub())
    else:
        print("Goodbye")


if __name__ == "__main__":
    get_action()

输出:

5. Perform addition

6. Perform subtraction

Q. Quit

Which action to use?

6
-2

添加:

5. Perform addition

6. Perform subtraction

Q. Quit

Which action to use?

5
10

还要别的吗:

5. Perform addition

6. Perform subtraction

Q. Quit

Which action to use?

q
Goodbye

如果您想在不接受用户任何输入的情况下进行编写,请忘记 r 并直接写入标准输入:

for line in iter(process.stdout.readline, ""):
    print(line)
    if line.rstrip() == "Which action to use?":
        process.stdin.write("5\n")

输出:

5. Perform addition

6. Perform subtraction

Q. Quit

Which action to use?

10

如果您使用的是 linux 系统,则只需运行以下程序即可:

printf "5" | python3 "tests1.py"

如果您有一个包含多个问题的 python 脚本,只需在每个问题之间添加一个“\n”字符即可。 例如:

printf "1\n2\n3\n4\n5" | (The command to run your script)

将用“1”回答第一个问题,用“2”回答第二个问题,依此类推。

此解决方案适用于以任何语言编写的提示符下的任何交互式脚本。 有关如何使用 bash 与脚本交互的更多信息,我从中学到了这篇文章:

https://www.baeldung.com/linux/bash-interactive-prompts

(这是我在 Stack Overflow 中的第一个答案,所以格式可能有点奇怪。无论如何,希望我能帮助任何像我一样解决这个问题的人。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM