简体   繁体   English

从 Python 运行文本并将其传送到 a.exe 文件中

[英]Running and piping text into a .exe file from Python

I am trying to a run a.exe file from python and pipe a string into it.我正在尝试从 python 和 pipe 中运行 a.exe 文件并将字符串插入其中。 The.exe itself opens a command box and requires a series of string inputs that can be entered in one go on a series of lines (as below)该.exe 本身会打开一个命令框,需要一系列字符串输入,这些输入可以在一个 go 的一系列行中输入(如下所示)

In bash the solution would be:在 bash 中,解决方案是:

printf "test.dat\nMoreinput\nMoreinput"  | ~/Desktop/Median_filt_exes/ascxyz.exe

To recreate this in python I have tried:要在 python 中重新创建它,我尝试过:

from subprocess import Popen, PIPE
p = Popen(r"./ascxyz.exe", stdin=PIPE,text=True)
p.communicate("test.dat\nMoreinput/nMoreinput")

There's no error however it doesn't seem to be working (the.exe should create a new file when run successfully).没有错误但是它似乎没有工作(成功运行时.exe应该创建一个新文件)。 Any help into what I could do to figure out why the exe isnt running properly would be very appreciated!对于我能做些什么来弄清楚为什么 exe 不能正常运行的任何帮助将不胜感激!

The immediate problem is probably that you are not terminating the input with a newline.直接的问题可能是您没有用换行符终止输入。 But you really also don't want to do the Popen plumbing yourself.但是你真的也不想自己做Popen管道。

from subprocess import run
run(['./ascxyz.exe'], text=True,
  input="test.dat\nMoreInput\nMoreInput\n")

Notice also how we pass in a list as the first argument, to avoid the complications of shell=True .还要注意我们如何传入一个列表作为第一个参数,以避免shell=True的复杂性。

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

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