Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 825
Yongfeng Avatar asked Dec 12 '16 05:12

Yongfeng


1 Answers

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()
like image 197
tdelaney Avatar answered Oct 20 '22 20:10

tdelaney