如何处理两个Python脚本之间的切换



我有两个独立的python脚本和一个主要脚本:

scripta.py
scriptb.py
main.py

我想从凌晨5点至凌晨12点运行Scripa.py,并从凌晨12点至下午5点运行ScriptB。我想编写一个脚本来为我做这个。目前,我正在尝试通过main.py进行此操作。但是什么都没有用。我实际想要的是这样的。

if time betwee 5am and 12am:
    if scriptB running:
        stop scriptB
        execute scriptA
    else:
        execute scriptA
if time between 12:01am and 4:99:
    if scriptA running:
        stop scriptA
        execute scriptB
    else:
        execute scriptB

,如果您还有其他建议以实现上述功能,请告诉我。

这是一个未经测试的想法,可以反馈。一般的想法是检查基于当前时间运行的程序,然后等到时间切换。

代码:

from datetime import datetime 
import subprocess
import sys
def check_time():
    script_type = ''
    wait_time = None
    now = datetime.now()
    if 5 <= now.hour <= 23:
        script_type = 'ScriptA'
        end_time = now.replace(hour=23, minute=59, second=59, microsecond=999)
        wait_time = end_time-now
    elif 0 <= now.hour <= 4:
        script_type = 'ScriptB'
        end_time = now.replace(hour=3, minute=59, second=59, microsecond=999)
        wait_time = end_time-now
    return script_type,wait_time.seconds

if __name__ == '__main__':
    active_process = None
    #Loop forever
    while True:
        #If there is an active process, terminate it
        if active_process:
            active_process.terminate()
            active_process.kill()
        #Start the correct script
        script_type,wait_time = check_time()
        if script_type == 'ScriptA':
            active_process = subprocess.Popen([YOUR,COMMAND,A,HERE])
        elif script_type == 'ScriptB':
            active_process = subprocess.Popen([YOUR,COMMAND,B,HERE])
        else:
            sys.stderr.write('Some sort of errorn')
            sys.exit(1)
        #Wait until the next time switch to loop again
        time.sleep(wait_time)

请评论任何问题,或者如果您尝试实施它,请告诉我是否有效。

相关内容

  • 没有找到相关文章

最新更新