简体   繁体   English

防止脚本通过sys.exit()关闭

[英]Prevent script from closing by sys.exit()

I need to call 1 script(test.py) every 5 minutes, so i have used another script timer.py with following code: 我需要每5分钟调用1个script(test.py),所以我使用了另一个脚本timer.py,其代码如下:

import time
while(1==1):
    execfile("test.py")
    time.sleep(300)

This works correctly. 这可以正常工作。 But it stopped working after few iterations. 但是经过几次迭代,它停止了工作。 After debugging i found that there is a flow in test.py which uses following code: 调试后,我发现test.py中存在使用以下代码的流:

sys.exit()

So, this is causing both test.py and timer.py to stop. 因此,这导致test.py和timer.py都停止。 what changes should be done, so as to continue timer.py since i want sys.exit() to only exit test.py and not timer.py 应该做些什么更改,以便继续timer.py,因为我希望sys.exit()仅退出test.py而不是timer.py

sys.exit() doesn't do more then raising SystemExit (a BaseException subclass), which can be caught like any exception eg: sys.exit()并没有做更多的BaseException ,而是引发了SystemExit (一个BaseException子类),它可以像任何异常一样被捕获,例如:

import time
while True:
    try:
        execfile("test.py")
    except SystemExit:
        print("ignoring SystemExit")
    finally:
        time.sleep(300)

Try this: 尝试这个:

import time
import os
while True:
    os.system("python test.py") # if you are not running script from same directory then mention complete path to the file
    time.sleep(300)

You should be able to use: 您应该可以使用:

try:
  # Your call here
except BaseException as ex:
  print("This should be a possible sys.exit()")

Check out the documentation for more information. 查看文档以获取更多信息。

Use subprocess 使用子流程

import subprocess  
import time

while(1==1):
    subprocess.call(['python', './test.py'])
    time.sleep(300)

You could even remove the python word if the test.py file has a shebang comment on the first line: 如果test.py文件的第一行带有shebang注释,您甚至可以删除python单词:

#!/usr/bin/env python

This is not exactly the same, as it will start a new interpreter, but the results will be similar. 这并不完全相同,因为它将启动一个新的解释器,但是结果将是相似的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM