簡體   English   中英

Python - 創建超時(kill subprocess)函數的問題

[英]Python - problems in creating an timeout (kill subprocess) function

我需要在我的小程序中支持你,它創建一個子進程,這里是10次ping,應該被給定的超時值(5)殺死。 此示例未成功。 你能給我一個提示嗎?

問候。 斯特凡

輸出:

Traceback (most recent call last):
File "./nwcheck.py.work", line 146, in <module>
MyCheck().check().exit()
File "./nwcheck.py.work", line 80, in check
output = process.communicate()
File "/usr/lib/python2.6/subprocess.py", line 701, in communicate
return self._communicate(input)
File "/usr/lib/python2.6/subprocess.py", line 1199, in _communicate
rlist, wlist, xlist = select.select(read_set, write_set, [])
File "./nwcheck.py.work", line 29, in alarm_handler
raise alarm
TypeError: exceptions must be old-style classes or derived from BaseException, not   builtin_function_or_method

碼:

def check(self):

    class Alarm(Exception):
        pass

    def alarm_handler(signum, frame):
        raise alarm

    def get_process_children(pid):
        p = Popen('ps --no-headers -o pid --ppid %d' % pid, shell = True,
                   stdout = PIPE, stderr = PIPE)
        stdout, stderr = p.communicate()
        return [int(p) for p in stdout.split()]
    timeout = 5
    args2 = [
            'ping',
            'localhost',
            '-c 10',
            ]
    process = subprocess.Popen(args2, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={'LANG':'de_DE@euro'})
    processpid = process.pid
    print processpid
    if timeout != -1:
        signal(SIGALRM, alarm_handler)
        alarm(timeout)
        print 'in timeout abfrage'
    try:
        ## catch stdout and stderr
        output = process.communicate()
        if timeout != -1:
            alarm(0)
            print 'in timeout abfrage 2'
    except Alarm:
        pids = [process.pid]
        print pids
        if kill_tree:
            pids.extend(get_process_children(process.pid))
        for pid in pids:
        # process might have died before getting to this line
        # so wrap to avoid OSError: no such process
            try:
                kill(pid, SIGKILL)
            except OSError:
                pass
        return -9, '', ''

    # Return a response
    return output

您應該使用異常而不是警報:

class AlarmException(Exception): 
    pass 

...

    def alarm_handler(signum, frame):
        raise AlarmException()

另外,不要忘記管道可能會溢出 如果進程對stderr和/或stdout產生太多(在某些Linux上> 64k),程序將被阻止。

子進程可以被以下命令殺死:

import os
os.kill(process.pid, signal.SIGKILL)

或者可能:

from subprocess import Popen
Popen.kill()

要么:

from subprocess import Popen
Popen.terminate()

請參閱: http//docs.python.org/library/subprocess.html#popen-objects

您的異常名為“ Alarm ,但您正在alarm Python區分大小寫。

您可能希望將Alarm重命名為更具描述性的內容。 AlarmExceptionAlarmError這樣簡單的名稱會使代碼更清晰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM