python command timeout (Advanced)

python에서 command 실행시 타임아웃 설정 (Advanced)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import subprocess as sp

class ExecuteFile:
    class TimeoutException(Exception):
        pass

    # timeout 커맨드실행
    @staticmethod
    def execute(cmd, errorKeyword=['error', 'fail', 'bad'], timeout=10):
        #pdb.set_trace()
        #popen = sp.Popen(cmd.split(), stderr=sp.STDOUT, stdout=sp.PIPE, env=os.environ)
        popen = sp.Popen(cmd, shell=True, stderr=sp.STDOUT, stdout=sp.PIPE, env=os.environ)

        # timeout 처리
        sTime = time.time()
        try:
            while True:
                if popen.poll() is not None:
                    break

                if time.time()-sTime > timeout:
                    raise ExecuteFile.TimeoutException

                time.sleep(0.1)

        except ExecuteFile.TimeoutException as e:
            popen.kill()

            return False, cmd, 'TimeoutException'

        # 에러 keyword 처리
        stdout = popen.stdout.read()

        for keyword in errorKeyword:
            if keyword in stdout:
                return False, cmd, stdout


        return True, cmd, 'SUCCESS'

댓글 1개:

  1. Best titanium flat iron rods for use with your craft
    Our titanium titanium dog teeth flat iron micro hair trimmer rods work with the best brass rods that we've found. sia titanium In our tests, we can 2021 ford escape titanium hybrid safely say race tech titanium that the best fit is very easy.

    답글삭제