如何使用 Python 自动化外部 .exe,在 Windows 命令行上以交互方式获取多个用户输入?

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

我有一个可执行文件,可以从 Windows 命令行以交互方式运行。工作流程如下:

C:\Users\Me> my_executable.exe  # Running the executable from CMD

Welcome! Please choose one:
0: Exit
1: Sub-task 1
2: Sub-task 2
Enter your input: 2             # I entered this interactively

Sub-task 2 chosen.
Please choose next option:
0: Return to previous menu
1: Connect to server
2: Disconnect from server
3: Call server API 1
4: Call server API 2
Enter your input: 1             # I entered this interactively

完整的工作流程很复杂,需要多次传递(一次通过子任务 1,然后通过子任务 2 等)。

我想使用 Python 自动化此操作。我一直在尝试使用 subprocess 模块来实现这一目标。然而,我似乎在 .Popen 阶段本身失败了。

这是 StackOverflow 上类似的问题。我尝试使用相同的方法使用 .Popen。这是我看到的:

C:\Users\Me> python
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from subprocess import Popen, PIPE
>>> p = Popen('my-executable.exe', stdin=PIPE)
Traceback (most recent call last):
    file "<stdin>", line 1 in <module>
TypeError: unsupported operand type(s) for -:'Popen' and 'Popen'
>>> Welcome! Please choose one:
0: Exit
1: Sub-task 1
2: Sub-task 2
Enter your input: 2       # I am forced to enter this input here.
2                         # Python echoes 2 before returning to prompt
>>>                       # Back to Python prompt

有人可以帮我解决我做错的事情吗?

python cmd subprocess stdin
1个回答
0
投票

我不知道正确的解决方案,但我可以说以下内容。

通常,当使用外部进程处理某些输入或执行某些任务时,所有选项都应作为行参数输入。

像这样:

my-task.exe arg1 arg2...

拥有需要用户进一步输入的子流程是一种不好的做法。

如果你是编写exe进程的人,最好按照前面提到的那样重写它。

但是使用适当的 IPC 交换数据是完全可以接受的,即发送输入并接收输出。 (就像使用套接字一样)

镜头中永远不要让子流程直接要求用户输入。

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