Python and sub-process

Status
Not open for further replies.

Drizzt321

Ars Legatus Legionis
34,922
Subscriptor++
So, before I start trying to piece something together from random internet tutorials and the python user guide.

TL;DR: What's a fairly simple way to spin of a sub-process (basically, another application with parameters), and then interrupt (^C) when necessary to have it close itself and end the sub-process.

Longer form:
I'm doing a RPi app that will, using rtl_sdr, tune into FM radio. I'm doing a Python application that reads from LCDProc (as I'm using a character display with buttons) to start/stop/change channel, etc. I suppose I could use pyrtlsdr, and pyalsa to send the data out to play the audio...but that sounds like even more work than just spawning a sub-process, and when I need to change the channel or stop playing the radio just send a ^C to kill it off and spawn another one as needed. This should be pretty simple to do, right?
 
Code:
import subprocess

try:
    cmd = subprocess.Popen(['/bin/sleep', '60'])

except KeyboardInterrupt:
    cmd.poll()
    if cmd.returncode is not None:
        cmd.kill()
        # or
        cmd.terminate()
        # or 
        cmd.send_signal(SIGNAL)

Using the subprocess.Popen class directly (instead one of the wrappers like subprocess.call()) allows you to interact with the object *while* the command runs. If you use a wrapper, it won't give you control until the command finishes.

Note: In this overly simplistic example, you would need something to keep the program within that try block, or else your program will be somewhere else when you KeyboardInterrupt (^C).
 

Drizzt321

Ars Legatus Legionis
34,922
Subscriptor++
Thanks!

Although I think you mis-understand slightly my original send ^C to the process. I won't be hitting ^C on the keyboard, the program will encounter a condition (input from LCDProc), and it will then send ^C to the sub process. Basing this off of your code, I think this is actually what I want.

Code:
import subprocess

cmd = subprocess.Popen(['/bin/sleep', '60'])

# do bunches of stuff, monitor LCDProc, etc
# receive the stop radio condition

# send the signal to terminate
cmd.terminate()

# do waiting until it's done, or if we have waited too long, force kill it
completed = False
for i in range(10):
	try:
		# wait a few milliseconds, if we get by it, the cmd is terminated, otherwise the TimeoutExpired is thrown
		cmd.wait(10)
		completed = True
		break;
	except TimeoutExpired:
		poll

# if for some reason the command hasn't completed yet, forcefully kill it
if not completed:
	cmd.kill()

# cmd is now stopped/done
 
Status
Not open for further replies.