1
p = subprocess.Popen("path to batch file")
time.sleep(30)
#do something to terminate the .exe process

I am using Popen to run a batch file. The associated program .exe opens & runs in a cmd terminal. The program can be (nicely) terminated by manually entering a 'q' argument in the terminal.

I would like to use the above python27 script to pass a 'q' string to the terminal, such that the program recognizes its native termination signal and closes out. After reading around the "os" & "subprocess" module docs & having tried several methods (.call, .terminate, .kill) I haven't had success

Edit:

The operation..

p.send_signal('q')

..seems to be what I want to do. However, 'q' raises a ValueError in the interpreter.

Matt Y.
  • 49
  • 4

2 Answers2

1

I think what you need to do is specify the standard input when creating the subprocess and then call its write method:

import time
import subprocess
p = subprocess.Popen(r"your.bat", stdin=subprocess.PIPE)
time.sleep(30)
p.stdin.write("q")
Abbas
  • 6,720
  • 4
  • 35
  • 49
  • Following this framework, Line 5 {p.stdin.write('q')} raises an IOError in the interpreter: [Errno 22] Invalid argument. – Matt Y. Apr 19 '13 at 08:27
  • Interestingly, including stdin=subprocess.PIPE in the Popen call (Line 3) causes my program to hang. My workaround is to leave the popen call as subprocess.Popen("my .bat"), and follow w a subsequent line p.stdin = sub.PIPE. – Matt Y. Apr 19 '13 at 08:30
  • Because the subprocess.Popen method has created another command line process within the same terminal window. I put all 5 lines into a .py file and then ran the script. I tested this on Python v2.7.2. – Abbas Apr 19 '13 at 08:34
0

If I understood correctly you want to pass an argument to your batch file. Simply supply a list to Popen.

p = subprocess.Popen(['path to batch file', 'arg_1', 'arg_2', etc...])

If you want to communicate with the process while it's running then you need to check this post.

Community
  • 1
  • 1
Alex
  • 1,066
  • 9
  • 13
  • My batch has all necessary arguments to initialize my program. Once it is already running, I want the script to wait some time (30s in my example) before passing the termination signal ('q') to the program, which is running in a cmd terminal. – Matt Y. Apr 18 '13 at 21:05
  • Ok understood then you need to have a look at [this](http://stackoverflow.com/a/165662/2286993). I'll update my answer. – Alex Apr 18 '13 at 21:33
  • Yes, I want to communicate w the process during runtime. I assign stdin = subprocess.PIPE as indicated in the linked response. Using p.communicate('q'), the interpreter raises an AttributeError: 'int' object has no attribute 'write.' This seems odd, because type(p) returns . – Matt Y. Apr 19 '13 at 08:32