Sawyer
Sawyer

Reputation: 15927

Is it possible to call a program and also obtain the input of that program in Python?

I can call another program in Python using

subprocess.call(["do_something.bat"])

I want to know if I can collect the stdin input of do_something.bat?

do_something.bat is a launcher for a Java program, the Java program will prompt the user to enter project specific information such as project name, version, and will generate a project skeleton according to the user input.

I use python to call this do_something.bat, and after it generates all the projects files, I need continue to go to a specific directory under project root, but that requires to know the project name, can I get the project name that the user previously entered?

Upvotes: 0

Views: 109

Answers (2)

Dunes
Dunes

Reputation: 40843

If you know what the exact parameters that the program will ask for and what order it will ask for them then you can collect the arguments yourself and forward them on to the subprocess.

eg.

from subprocess import Popen, PIPE

# get inputs
input1 = ...
input2 = ...

child = Popen("do_something.bat", stdin=PIPE)
# Send data to stdin. Would also return data from stdout and stderr if we set 
# those arguments to PIPE as well -- they are returned as a tuple
child.communicate("\n".join([input1, input2, ...]))

if child.returncode != 0:
    print "do_something.bat failed to execute successfully" 

Upvotes: 1

Hans Then
Hans Then

Reputation: 11322

It depends a bit on how do_something.bat prompts the user.

If it simply reads from standard input your program can act as a go-between. It can prompt the output of do_something.bat, read the user's response, and then pipe the response back to the standard input of do_something.bat.

Otherwise, I do not think it is possible without adapting do_something.bat.

Upvotes: 2

Related Questions