Python subprocess: How can I pass a text file as input?

Question:

I am in charge of updating some old code with Python. I was originally given a batch file to run it in windows as follows:

copy .datarandomdata.txt     tape20
copy .InputPROGM.INP                            .

progm_64.exe < PROGM.INP > PROGM.OUT

The goal is to not use the batch file, and instead use only python forgoing the need for writing the input file into the directory.
I am unable to recreate the last line’s functionality.

As I am using subprocess.Popen(), i tried the following:

p = Popen(['progm_64.exe',PROGM_INP], cwd=os.getcwd(), )
stdout, stderr = p.communicate()

where PROGM_INP is a string variable holding the text the input file would have held.

Asked By: isentr

||

Answers:

So after a while trying to figure it out I asked chatGPT for a solution and he gave me something that didn’t really work but was close, after some modifications I ended up with this:
from subprocess include Popen, PIPE

p = Popen('njoy.exe', cwd=os.getcwd(),stdin=PIPE,text=True)
p.stdin.write(input_text) #input in string form
p.stdin.flush()   
stdout,stderr=p.communicate()

This fixes the issue

Answered By: isentr
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.