Now Place:2uzhan.com » Control External Program from Python Script

Control External Program from Python Script

Software Development @ June 20, 2009   Views:0


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()

I'm attempting to simplify my fundraising page, and would like to show exactly how much each donation would help us out. I've listed the options below, but I would like ...

Write a java program that asks a person for his height (in meters) and weight (in kilograms) and
outputs one of the messages: underweight, normal, or obese, using the BMI ...

Before I get into the specific issues, I want to provide some other details:

  • Normally, I work on a live, paid server (even in dev); I realize that is ...
© 2018 2uzhan.com Contact