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

时间:2017-03-02 22:46:48

标签: python multithreading python-2.7 batch-file multiprocessing

我有两个单独的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

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

1 个答案:

答案 0 :(得分:0)

这是一个未经测试的想法,并希望得到反馈。一般的想法是根据当前时间检查要运行的程序,然后等到时间切换。

CODE:

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 error\n')
            sys.exit(1)

        #Wait until the next time switch to loop again
        time.sleep(wait_time)

如果您尝试实施,请发表评论或告诉我它是否有效。