We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,924 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Control External Program from Python Script

Hello,

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
p.stdin.write('hello')
#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,

Surge

2
Contributors
1
Reply
18 Hours
Discussion Span
3 Years Ago
Last Updated
2
Views
Surge591
Newbie Poster
1 post since Jun 2009
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

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")
fout.write(code_str)
fout.close()

# 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
process.wait()
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
p.wait()

# read the result to a string
result_str = p.stdout.read()
vegaseat
DaniWeb's Hypocrite
Moderator
6,466 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,608
Skill Endorsements: 36

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0548 seconds using 2.63MB