首页 > 解决方案 > 如何在 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,但在我的情况下这是不可能的,因为我需要使用另一个外部程序,这只是一个基于它的最小示例。

标签: pythonpython-3.xsubprocess

解决方案


如果您对程序有固定输入(意味着输入在运行时不会改变),那么这个解决方案可能是相关的。

回答

首先创建文件。

  • 输入文件。将其命名为 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())

推荐阅读