Setting timeout when using os.system function

痴心易碎 提交于 2021-02-16 20:14:38

问题


Firstly, I'd like to say I just begin to learn python, And I want to execute maven command inside my python script (see the partial code below)

os.system("mvn surefire:test")

But unfortunately, sometimes this command will time out, So I wanna to know how to set a timeout threshold to control this command.

That is to say, if the executing time is beyond X seconds, the program will skip the command.

What's more, can other useful solution deal with my problem? Thanks in advance!


回答1:


use the subprocess module instead. By using a list and sticking with the default shell=False, we can just kill the process when the timeout hits.

p = subprocess.Popen(['mvn', 'surfire:test'])
try:
    p.wait(my_timeout)
except subprocess.TimeoutExpired:
    p.kill()



回答2:


Simple answer

os.system not support timeout.

you can use Python 3's subprocess instead, which support timeout parameter

such as:

yourCommand = "mvn surefire:test"
timeoutSeconds = 5
subprocess.check_output(yourCommand, shell=True, timeout=timeoutSeconds)

Detailed Explanation

in further, I have encapsulate to a function getCommandOutput for you:

def getCommandOutput(consoleCommand, consoleOutputEncoding="utf-8", timeout=2):
    """get command output from terminal


    Args:
        consoleCommand (str): console/terminal command string
        consoleOutputEncoding (str): console output encoding, default is utf-8
        timeout (int): wait max timeout for run console command
    Returns:
        console output (str)
    Raises:
    """
    # print("getCommandOutput: consoleCommand=%s" % consoleCommand)
    isRunCmdOk = False
    consoleOutput = ""
    try:
        # consoleOutputByte = subprocess.check_output(consoleCommand)


        consoleOutputByte = subprocess.check_output(consoleCommand, shell=True, timeout=timeout)


        # commandPartList = consoleCommand.split(" ")
        # print("commandPartList=%s" % commandPartList)
        # consoleOutputByte = subprocess.check_output(commandPartList)
        # print("type(consoleOutputByte)=%s" % type(consoleOutputByte)) # <class 'bytes'>
        # print("consoleOutputByte=%s" % consoleOutputByte) # b'640x360\n'


        consoleOutput = consoleOutputByte.decode(consoleOutputEncoding) # '640x360\n'
        consoleOutput = consoleOutput.strip() # '640x360'
        isRunCmdOk = True
    except subprocess.CalledProcessError as callProcessErr:
        cmdErrStr = str(callProcessErr)
        print("Error %s for run command %s" % (cmdErrStr, consoleCommand))


    # print("isRunCmdOk=%s, consoleOutput=%s" % (isRunCmdOk, consoleOutput))
    return isRunCmdOk, consoleOutput

demo :

isRunOk, cmdOutputStr = getCommandOutput("mvn surefire:test", timeout=5)


来源:https://stackoverflow.com/questions/41094707/setting-timeout-when-using-os-system-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!