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

2024-09-30 00:42:14 发布

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

我有两个单独的Python脚本和一个主脚本:

在脚本.py
脚本b.py
主.py

我想跑scripA.py文件早上5点到12点,脚本从12点到下午5点。我想为我写一个剧本。目前我正试图通过主.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

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


Tags: and文件py脚本executeiftimerunning
1条回答
网友
1楼 · 发布于 2024-09-30 00:42:14

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

代码:

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)

请评论任何问题或让我知道如果你已经尝试实施它的工作。在

相关问题 更多 >

    热门问题