python - 如何在 Python 3 中与外部程序交互?
问题描述
使用 Python 3,我想执行一个外部程序,通过在标准输入中提供一些文本与它进行交互,然后打印结果。
例如,我创建了以下外部程序,称为test.py
:
print('Test Program')
print('1 First option, 2 Second Option')
choice = input()
if choice == '1':
second_param = input('Insert second param: ')
result = choice + ' ' + second_param
print(result)
如果我直接运行这个程序,它会按预期工作。如果我提供输入1
然后2
,结果是1 2
。
我想在另一个脚本中运行这个程序并与之交互以打印相同的结果。
在阅读了 的文档subprocess
并查看了关于 SO 的类似问题后,我得到了以下结果:
EXTERNAL_PROG = 'test.py'
p = Popen(['py', EXTERNAL_PROG], stdout=PIPE, stdin=PIPE, shell=True)
print(p.stdout.readline().decode('utf-8'))
print(p.stdout.readline().decode('utf-8'))
p.stdin.write(b'1\n')
p.stdin.write(b'2\n')
print(p.stdout.readline().decode('utf-8'))
但是,当我运行代码时,程序在打印后冻结1 First option, 2 Second Option
,我需要重新启动我的 shell。这可能是由于subprocess.stdout.readline()
期望找到换行符,而第二个参数的提示不包含换行符。
我发现 2 SO questions 谈论类似的事情,但我无法让它发挥作用。
在这里,答案建议使用该pexpect
模块。我试图使代码适应我的情况,但没有奏效。
在这里,建议是使用-u
,但添加它并没有改变任何东西。
我知道可以通过修改找到解决方案test.py
,但在我的情况下这是不可能的,因为我需要使用另一个外部程序,这只是一个基于它的最小示例。
解决方案
如果您对程序有固定输入(意味着输入在运行时不会改变),那么这个解决方案可能是相关的。
回答
首先创建文件。
- 输入文件。将其命名为 input.txt 并放入
1 2
其中
command = "python test.py < input.txt > output.txt 2>&1"
# now run this command
os.system(command)
当你运行它时,你会output.txt
在同一个目录中找到。如果您的程序成功执行,则output.txt
包含代码输出,test.py
但如果您的代码出现任何错误,则错误在output.txt
.
随心所欲地回答
main.py
变得
import sys
from subprocess import PIPE, Popen
EXTERNAL_PROG = 'test.py'
p = Popen(['python3', EXTERNAL_PROG], stdout=PIPE, stdin=PIPE, stderr=PIPE)
print(p.stdout.readline())
print(p.stdout.readline())
p.stdin.write(b'1\n')
p.stdin.write(b'2\n')
p.stdin.flush()
print(p.stdout.readline())
print(p.stdout.readline())
推荐阅读
- android - 单击时未显示警报对话框
- apache-kafka - 加入多个 Kafka 主题
- rust - 当使用 flat_map 将数据结构的三个级别展平为特征对象向量时,“闭包可能比当前函数寿命更长”
- reactjs - 模态关闭后反应选择重新聚焦
- firebase - Firestore:检查用户的 Post Like-reaction 的最佳实践
- office-js - 任务窗格在最新版本的 OfficeJS Excel 中不起作用
- typescript - TypeScript 中的对象动态属性访问
- symfony - 使用集合处理 Formbuilder 上的 OneToMany 字段
- java - 如何将二维数组或任何数组专门转换为列表
- > 在 Java 8 中?
- c# - 不一致的JArray如何计算