1

私はコードをもっている:

function_1()
function_2()

通常、function_1()は終了するのに10時間かかります。しかし、function_1()を2時間実行し、2時間後、function_1が戻り、programがfunction_2()を続行する必要があります。function_1()が完了するのを待つべきではありません。Pythonでこれを行う方法はありますか?

4

5 に答える 5

2

Pythonの関数が実行と再開を中断できるようにするのは、「yield」ステートメントを使用することです。これにより、関数はジェネレーターオブジェクトとして機能します。このオブジェクトの「next」メソッドを呼び出して、最後のyieldの後に開始または続行します

import time
def function_1():
    start_time = time.time()
    while True:
         # do long stuff
         running_time = time.time() -start_time
         if running_time > 2 * 60 * 60: # 2 hours
              yield #<partial results can be yield here, if you want>
              start_time = time.time()



runner = function_1()
while True:
    try:
        runner.next()
    except StopIteration: 
        # function_1 had got to the end
        break
    # do other stuff
于 2012-09-06T15:00:18.917 に答える
1

モジュールGevent:スレッドで関数を開始し、しばらくしてからそのスレッドを強制終了してみてください。

次に例を示します。

import gevent

# function which you can't modify
def func1(some_arg)
    # do something
    pass

def func2()
    # do something
    pass

if __name__ == '__main__':
    g = gevent.Greenlet(func1, 'Some Argument in func1')
    g.start()
    gevent.sleep(60*60*2)
    g.kill()
    # call the rest of functions
    func2()
于 2012-09-12T12:48:12.703 に答える
1

実行を終了してもかまわない場合function_1

from threading import Thread
import time

Thread(target=function_1).start()
time.sleep(60*60*2)
Thread(target=function_2).start()
于 2012-09-06T10:09:51.713 に答える
0
from multiprocessing import Process
p1 = Process(target=function_1)
p1.start()
p1.join(60*60*2)
if p1.is_alive():p1.terminate()
function_2()

これがお役に立てば幸いです

次のコードを使用してこれをテストしました

import time
from multiprocessing import Process

def f1():
    print 0
    time.sleep(10000)
    print 1

def f2():
    print 2


p1 = Process(target=f1)
p1.start()
p1.join(6)
if p1.is_alive():p1.terminate()
f2()

出力は期待どおりです:

0
2
于 2012-09-06T13:22:35.460 に答える
0

datetimeモジュールを使用して実行の時間を計ることができます。おそらく、オプティマイザ関数のどこかにループがあります。ループ内では、関数を開始してからどれだけの時間が経過したかをテストできます。

def function_1():
    t_end = datetime.time.now() + datetime.timedelta(hours=2)

    while not converged:
        # do your thing
        if datetime.time.now() > t_end:
            return
于 2012-09-12T13:15:09.020 に答える