以有限的执行时间运行命令

2024-04-20 04:21:23 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我要通过命令行运行一些Python,比如说:

cat <<'PYSTUFF' | python
print "Hi"
print "There"
print "Friend"
PYSTUFF

这非常有效,并输出REPL的响应。我要做的是限制这个命令的执行。例如,如果我写道:

cat <<'PYSTUFF' | python
while(True):
    print "Oh no!"
PYSTUFF

那将是不好的,最终会崩溃的东西。我如何限制执行说“如果这需要超过x的时间量,杀死它。”?我试过使用ulimit -t 2,但似乎没有达到我想要的效果。你知道吗


Tags: no命令行命令friendtrue时间hirepl
3条回答

如果要从shell控制此操作,请在后台启动python脚本,休眠一段时间,然后终止后台进程:

# a sample command that generates some output
{ while :; do date; sleep 1; done; } &

# let it run for a while, see if it's still running, and kill it if it is
sleep 10 && kill -0 $! 2>/dev/null && kill $!

limit the execution of this command.

从Python2.6+开始,您可以使用multiprocessing模块:

cat <<'PYSTUFF' | python
from multiprocessing import Process
from time import sleep

def task():
    while True:
        print "oh no!"
        sleep(0.5)

p = Process(target=task)
p.start()
p.join(1)
print "*** Aborted"
p.terminate()
PYSTUFF

多亏@Biffen使用了timeout命令,所以工作得非常好。在mac上我使用了gtimeout。我的整个命令如下:

cat <<'PYSTUFF' | gtimeout 0.5 python
while(True): print("hi")
PYSTUFF

相关问题 更多 >