Problem in using subprocess module and communicate()

Tim Golden mail at timgolden.me.uk
Mon May 23 04:38:13 EDT 2011


On 21/05/2011 16:56, vijay swaminathan wrote:
> I'm having some problem in using the communicate() along with the
> subprocess.I would like to invoke a command prompt and pass  on a .bat
> file to execute. I went through the subprocess module and understood
> that using communicate, we can send the send data to stdin.

I'm afraid you're running the risk of giving us too little information
here, Vijay. You've pointed to the docs you've read and provided code,
which is A Good Thing. Unfortunately, the code you've provided is
clearly not what you'll ultimately be running (unless you're in the
game for a convoluted means of getting a directory listing) and, as
Chris touched on in his response, is probably not even what you're
running now, as you're passing the wrong kind of "/k" to cmd.exe.

OK, let's see if I've understood correctly from this and from your
previous posts:

* You have a set of batch scripts you want to launch from Python

* You want to launch them in parallel (possibly different scripts, not 
sure) so you're setting up threads.

You seem to be trying to meet these requirements by opening a
command shell with an arbitrary command, leaving it open and
feeding its stdin with the batch script name so that it runs,
and then polling it until it finishes.

In short, you're making a mountain out of a molehill. If you
need to run batch scripts from a command shell, then use
subprocess.call with the name of the batch script and shell=True
(the last isn't always necessary; it seems to depend on the
C runtime, but it won't harm to have it there):

<code>
import subprocess

result = subprocess.call ("name-of-script.bat", shell=True)

</code>

If you want to run that in a thread:

<code>
import subprocess
import threading

def run_script (path_to_script):
   subprocess.call (path_to_script, shell=True)

t = threading.Thread (target=run_script, args=("name-of-script.bat,"))
t.start ()

while True:
   # do stuff
   if t.isAlive ():
     print "still running"

</code>

You might, as you have above, want to launch a new console with each
subprocess or the output could get quite messy. There are lots of
variations on this theme: you could use a Queue to get the success or
failure back from the threads.

It's not clear whether you actually need to feed input into your
batch scripts, as the only reason you're using .communicate above
is to actually *run* the batch scripts.

I could go on guessing what your use-case is, assuming that it doesn't
involve a command shell with the output from a "dir" command, but it'll
be easier if you can describe how closely what I've written above
matches your need.

TJG



More information about the Python-list mailing list