On Sat, May 21, 2011 at 8:56 AM, vijay swaminathan <swavi...@gmail.com> wrote: > Hi Gurus, > > 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. > > According to the documentation > http://docs.python.org/library/subprocess.html#subprocess.call, it says, > > if you want to send data to the process’s stdin, you need to create the > Popen object with stdin=PIPE. > > so based on this, I have used the below function but it does not seem to > work. Am I missing something here? > > import subprocess > import threading > import time > > def runMonitor(command): > retcode = subprocess.Popen([command, '\k', 'dir'],
Shouldn't that be /k, not \k? > cwd= > 'C:\Python26\WorkSpace\FunctionExamples\src', Sidenote: You really should use forward-slashes in paths like this (or double-up the backslashes). > stdin = subprocess.PIPE, > creationflags=subprocess.CREATE_NEW_CONSOLE) > > retcode.wait() > > retcode.communicate('scripts_to_execute.bat') Several issues here: - .wait() waits for the subprocess to terminate; there's reason for the shell to terminate here, so your program will hang forever on the .wait() call. - It makes no sense to call .communicate() after .wait(), since the subprocess will have already terminated; you can't communicate with a dead process. - .communicate() blocks until the subprocess terminates anyway, so calling .wait() is pointless. - I would think a newline is needed in you input to the shell. When one runs a command in the shell manually, one presses Enter after typing it, no? - `retcode` seems a rather poor variable name, since it's holding a Popen object rather than an integer exit code. Putting this all together, here's an improved version: def runMonitor(command): proc = subprocess.Popen([command, '/k', 'dir'], cwd='C:/Python26/WorkSpace/FunctionExamples/src', stdin=subprocess.PIPE, creationflags=subprocess.CREATE_NEW_CONSOLE) input_data = 'scripts_to_execute.bat\n' + 'exit\n' stdout_data, stderr_data = proc.communicate(input_data) I can't test it since I don't run Windows. Cheers, Chris -- http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list