I would like to know how I can call a program ('example.exe') which runs as a batch process in a new command prompt and control the inputs and outputs from within a python script. I have tried the following code:

import subprocess

p = subprocessPopen('example.exe', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
#this line opens the example code in a new command prompt
#i now need to send input into the example code.

But this only ends up hanging up without any information being sent into the command prompt. How can I control the data being sent into a command prompt using python.

Thanks in advance,


This is an example on how to run Python code externally ...

# pipe the output of calendar.prmonth() to a string:
import subprocess

code_str = \
import calendar
calendar.prmonth(2006, 3)

# save the code
filename = "mar2006.py"
fout = open(filename, "w")

# execute the .py code and pipe the result to a string
test = "python " + filename
process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE)
# important, wait for external program to finish
print process.returncode  # 0 = success, optional check
# read the result to a string
month_str = process.stdout.read()
print month_str

More general ...

import subprocess

# put in the corresponding strings for
# "mycmd" --> external program name
# "myarg" --> arg for external program
# several args can be in the list ["mycmd", "myarg1", "myarg2"]
# might need to change bufsize
p = subprocess.Popen(["mycmd", "myarg"], bufsize=2048, shell=True,
    stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)

# write a command to the external program
p.stdin.write("some command string here")

# allow external program to work

# read the result to a string
result_str = p.stdout.read()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.