0 votes
1 view
in Data Science by (18.3k points)

I use a sub.Popen in Python2.7

But, Python3 has timeout but, Python2.7 can't it.

it is my snippet.

proc = sub.Popen(['some command', 'some params'], stdout=sub.PIPE)    

try:

    for 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 to set timeout to it.

1 Answer

0 votes
by (36.8k points)

You need to use the thread:

from threading import Thread

from 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

Do check out Python for data science course which helps you understand from scratch 

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...