我不知道如何从python运行可执行文件,然后传递它的命令一一问。我在这里找到的所有示例都是通过在调用可执行文件时直接传递参数来实现的。但是我拥有的可执行文件需要“用户输入”。它要求一个一个的值。
例:
subprocess.call(grid.exe)
>What grid you want create?: grid.grd
>Is it nice grid?: yes
>Is it really nice grid?: not really
>Grid created
您可以使用subprocess
和Popen.communicate
方法:
import subprocess
def create_grid(*commands):
process = subprocess.Popen(
['grid.exe'],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
process.communicate('\n'.join(commands) + '\n')
if __name__ == '__main__':
create_grid('grid.grd', 'yes', 'not really')
本质上,“ communicate”方法会传递输入内容,就像您在键入它一样。请确保输入的每一行都以换行符结尾。
如果要从grid.exe
控制台显示输出,请修改create_grid
为如下所示:
def create_grid(*commands):
process = subprocess.Popen(
['grid.exe'],
stdin=subprocess.PIPE)
process.communicate('\n'.join(commands) + '\n')
警告:我尚未对我的解决方案进行全面测试,因此无法确认它们在每种情况下均有效。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句