python - How to timeout when I use subprocess -


this question has answer here:

i use sub.popen in python2.7

but, python3 has timeout but, python2.7 can't it.

it snippet.

proc = sub.popen(['some command', 'some params'], stdout=sub.pipe)      try:     row in proc.stdout:         print row.rstrip()   # process here         result = str(row.rstrip())         count += 1         if count > 10:             break except:     print 'tcpdump error'     proc.terminate() 

how set timeout it.

based on this blog post code couple of changes can use threading.thread:

from threading import thread subprocess import pipe, popen   def proc_timeout(secs, *args):     proc = popen(args, stderr=pipe, stdout=pipe)     proc_thread = thread(target=proc.wait)     proc_thread.start()     proc_thread.join(secs)     if proc_thread.is_alive():         try:             proc.kill()         except oserror:             return proc.returncode         print('process #{} killed after {} seconds'.format(proc.pid, secs))     return proc 

you should catch specific exceptions in try/except, don't try catch them all.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -