Python subprocess question

A

Alexi Zuo

Hi everyone,

Here I have a simple program which starts a thread and the thread use
Popen to execute a shell cmd which needs a long time. I want to stop
the thread once I type "ctrl+C" (KeyboardInterrupt). But in fact this
program enters a dead loop. Can anyone tell me what is wrong?

Alex

from subprocess import *
import threading
import time

class TestThread(threading.Thread):
def run(self):
try:
while True:
p=Popen("for (( i = 0 ; i <= 100000; i++ )); do echo
hello; done", shell=True,stdin=PIPE,stdout=PIPE,stderr=PIPE,close_fds=True)
print p.stdout.readlines()
print p.stderr.readlines()
except KeyboardInterrupt:
print "got ex"
print "leave..."

a=TestThread()
a.start()
try:
a.join()
except:
print "gone"
 
R

Roger

The KeyboardInterrupt exception is being raised in your main thread which
doesn't handle it so it just terminates. Your child thread isn't marked as
a daemon thread so the program won't exit until the child thread has also
terminated.

I've been recently working with threads for the first time and I've
been unclear on the setDaemon flag though I've sifted through the
documentation for a clear answer (most likely my reading comprehension
has failed me and not the documentation). I think I had the notion of
that flag backwards. .setDaemon(True) means the thread gets destroyed
when the program exits and default .setDaemon(False) means that the
thread continues to process even when the main program is gone?
 
S

skip

Roger> .setDaemon(True) means the thread gets destroyed when the program
Roger> exits and default .setDaemon(False) means that the thread
Roger> continues to process even when the main program is gone?

Approximately. The main thread (and thus the program) will exit only when
all non-daemon threads have finished. A thread can't continue to run if the
main program has exited.
 
R

Roger

    Roger> .setDaemon(True) means the thread gets destroyed when the program
    Roger> exits and default .setDaemon(False) means that the thread
    Roger> continues to process even when the main program is gone?

Approximately.  The main thread (and thus the program) will exit only when
all non-daemon threads have finished.  A thread can't continue to run if the
main program has exited.

Gotcha. Thank you, that makes it clearer. =)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top