0

I am trying to a run a .exe file from python and pipe a string into it. 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)

In bash the solution would be:

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

To recreate this in python I have tried:

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). Any help into what I could do to figure out why the exe isnt running properly would be very appreciated!

tripleee
  • 175,061
  • 34
  • 275
  • 318

1 Answers1

1

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.

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.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Thank you! - I'm still not getting the file output I'm hoping to - is there a way to see the output of the exe in python? – Aidan Loasby Jul 25 '20 at 13:06
  • You can use `capture=True` and examine the object you get back from `run`; it will have `stdout` and `stderr` members. But if you don't see any output, Python won't, either. – tripleee Jul 25 '20 at 13:19
  • Thanks again. My python input is going into the script and I can see all the expected output. But the file is not being created at the end. It's as if python is closing the script prematurely after the inputs have been entered before the script can run. – Aidan Loasby Jul 26 '20 at 03:49
  • `subprocess.run()` will wait for the child process to finish. If the child process somehow demands user interaction then maybe you have to try `pexpect` or similar. Or if there's a GUI you'll probably need to hook in some GUI automation tool (what exactly does "command box" mean here?) I guess this is on Windows, so maybe it's simply broken by design. – tripleee Jul 26 '20 at 06:15
  • Yeah on windows. The .exe opens a windows console that you can type your inputs into. – Aidan Loasby Jul 26 '20 at 09:00
  • Can you try to input ctrl-Z at the end? – tripleee Jul 26 '20 at 09:11