Yongfeng
Yongfeng

Reputation: 345

Setting timeout when using os.system function

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!

Upvotes: 7

Views: 19257

Answers (3)

WitBlack
WitBlack

Reputation: 37

Also, you can use in terminal timeout:

Do like that:

import os

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

Also, you can use s, m, h, d for second, min, hours, day. You can send different signal to command. If you want to learn more, see at: https://linuxize.com/post/timeout-command-in-linux/

Upvotes: 3

crifan
crifan

Reputation: 14328

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)

Upvotes: 3

tdelaney
tdelaney

Reputation: 77377

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()

Upvotes: 8

Related Questions