在指定的时间内运行2个python脚本,每个脚本单独运行

2024-04-25 10:12:48 发布

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

我有两个python脚本作为单独的文件。比如说你好,派瑞你好。我的总执行时间是100秒。所以我想你好,派瑞执行前60秒,hello1.py执行40秒。那怎么把它撒出来?你知道吗


Tags: 文件py脚本时间hello1
2条回答

让我定义两个python脚本temp4.py和temp5.py。内容:

临时4.py

def f1():
 print 'hello'

临时5.py

    def f2():
        print 'hello1'

最终脚本temp5.py。这将测量时间并相应地运行脚本。改变时代。在这里,两个脚本都将运行10秒。你知道吗

        from temp4 import f1
        from temp5 import f2
        from timeit import default_timer as timer

        start = timer()

        while (timer()-start)<10:
            f1()
            print timer()-start

        while (timer()-start)<20: #add timings here
            f2()
            print timer()-start

请把第二次加到计时器上。所以第一次是60,第二次是100。你知道吗

您可以在代码运行一段时间后使用警报来中断代码。优点是运行的代码不需要知道时间限制。缺点是它没有机会优雅地终止(尽管您可以捕获Stop异常来终止)。你知道吗

import signal
import time

def task(name):
    """Generic task   print out name once a second."""
    while True:
        print(name)
        time.sleep(1)

class Stop(Exception):
    """Raised to stop a running task."""
    pass

def onAlarm(signum, frame):
    """Alarm signal handler."""
    raise Stop

def run(function, seconds):
    """Run a function for a specified number of seconds."""

    # install our alarm handler
    savedHandler = signal.signal(signal.SIGALRM, onAlarm)

    # request an alarm after the specified numbers of seconds
    signal.setitimer(signal.ITIMER_REAL, seconds)

    # run the function
    try:
        function()
    except Stop:
        pass

    # restore the saved timeout handler
    signal.signal(signal.SIGALRM, savedHandler)

# run hello for 6 seconds
run(lambda: task("hello"), 6)

# run hello1 for 4 seconds
run(lambda: task("hello1"), 4)

相关问题 更多 >