1

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.

3 Answers 3

3

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()
2
  • 1
    Are you shure in subprocess.terminate()? Maybe process.terminate()?
    – Max Frai
    Commented Jul 10, 2010 at 21:54
  • 1
    Damn! I meant process.terminate(), indeed. I'll fix that.
    – zneak
    Commented Jul 10, 2010 at 22:41
2
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

4
  • You sure you didn't mix up two conditions? Shouldn't it rather be while process.poll(): if raw_input() == 'Kill' ?
    – zneak
    Commented Jul 10, 2010 at 21:50
  • 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. Commented Jul 10, 2010 at 21:53
  • 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
    Commented Jul 10, 2010 at 22:43
  • 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. Commented Jul 10, 2010 at 22:47
0

Some time ago I needed a 'gentle' shutdown for a process by sending CTRL+C in Windows console.

Here's what I have:

import win32api
import win32con
import subprocess
import time
import shlex

cmdline = 'cmd.exe /k "timeout 60"'
args = shlex.split(cmdline)
myprocess = subprocess.Popen(args)
pid = myprocess.pid
print(myprocess, pid)
time.sleep(5)
win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, pid)
# ^^^^^^^^^^^^^^^^^^^^  instead of myprocess.terminate()

Not the answer you're looking for? Browse other questions tagged or ask your own question.