使用 os.system 函数时设置超时

Setting timeout when using os.system function

首先,我想说我刚开始学习python,我想在我的python脚本中执行maven命令(见下面的部分代码)

os.system("mvn surefire:test")

但不幸的是,有时这个命令会超时,所以我想知道如何设置超时阈值来控制这个命令。

也就是说,如果执行时间超过X秒,程序将跳过命令

另外,还有其他有用的解决方案可以解决我的问题吗?提前致谢!

改用子流程模块。通过使用列表并坚持使用默认值 shell=False,我们可以在超时时终止进程。

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

简单回答

os.system 不支持 timeout.

可以使用Python 3subprocess代替,它支持timeout参数

如:

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

详细说明

另外,我给大家封装成一个函数getCommandOutput

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

演示:

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

此外,您可以在终端超时中使用:

这样做:

import os

os.system('timeout 5s [Type Command Here]')

此外,您可以使用 s、m、h、d 表示秒、分、时、日。 您可以向命令发送不同的信号。如果您想了解更多信息,请参阅: https://linuxize.com/post/timeout-command-in-linux/