views:

38

answers:

2
+1  Q: 

Process closing

Hello, can I use Popen from python subprocess to close started process? For example, from popen I run some application. In some part of my code I have to close that ran app. For example, from console in Linux I do:

./some_bin
... It works and logs stdout here ...
Ctrl + C and it breaks

I need something like Ctrl + C but in my program code.

+1  A: 

Use the subprocess module.

import subprocess

# all arguments must be passed one at a time inside a list
# they must all be string elements
arguments = ["sleep", "3600"] # first argument is the program's name

process = subprocess.Popen(arguments)
# do whatever you want
process.terminate()
zneak
Are you shure in `subprocess.terminate()`? Maybe `process.terminate()`?
Ockonal
Damn! I meant `process.terminate()`, indeed. I'll fix that.
zneak
+2  A: 
from subprocess import Popen
process = Popen(['slow', 'running', 'program'])
while process.poll():
    if raw_input() == 'Kill':
        if process.poll(): process.kill()

kill() will kill a process. See more here: Python subprocess module

Blue Peppers
You sure you didn't mix up two conditions? Shouldn't it rather be `while process.poll(): if raw_input() == 'Kill'` ?
zneak
Your version will still block on the `raw_input()`, just the same as mine, except mine checks that the process is running just before we try and kill it, were as yours checks before the blocking `raw_input()`, meaning the process could have ended before we try and kill it.
Blue Peppers
It's not a question of blocking, it's a question of looping. Your loop won't loop at all. If you type in "Kill", it stops. And if you don't type in "Kill", it also stops. Except that in that case the process is still running. On the other hand, the solution I suggest will, indeed, loop.
zneak
Good point. So both methods have errors. I have updated the snippet above. Check for process alive in loop, but also check after blocking `raw_input()`. Thank you.
Blue Peppers