1,105,263 Community Members

Control External Program from Python Script

Member Avatar
Newbie Poster
1 post since Jun 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 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,


Member Avatar
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]

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()
This article has been dead for over three months: Start a new discussion instead
Start New Discussion
Tags Related to this Article