2015-09-04 70 views
-1

我想在後臺執行第一個命令,第二個執行後面的命令。Python多線程/具有函數的子進程

import time 
loop =[ 1,100] 
start_time_loop = time.time() 
for in loop: 
    print i 
end_time_loop = time.time() 

multi() 
    start_time_func = time.time() 
    c= 5*2 
    end_time_func = time.time() 

當乘法完成時,循環應該在後臺運行。

我要證明:

start_time_loop < start_time_func 
end_time_func << end_time_loop 

任何指針將會很有幫助。

+0

可能幫助:https://stackoverflow.com/questions/23100704/running-infinite-loops-using-threads-in-python/23102874#23102874 –

+0

Python不能使用本機運行多個進程。查看線程模塊。 – Bretsky

+1

Python可以使用多個進程 - 這就是'multiprocessing'模塊的功能。 –

回答

1

你需要使用多處理來做你想做的。它基本上在後臺啓動一個新的(克隆)python副本。

import time 
from multiprocessing import Process 


def thing_1(): 
    """We'll run this in a subprocess.""" 
    for i in range(10): 
     print('thing_1: {}'.format(i)) 
     # let's make it take a bit longer 
     time.sleep(1) 


def thing_2(): 
    """We'll run this as a normal function in the current python process.""" 
    time.sleep(1) 
    c = 5 * 2 
    print('thing_2: {}'.format(c)) 
    # let's make this take a bit longer too 
    time.sleep(1) 



if __name__ == '__main__': 
    # start the first thing running "in the background" 
    p = Process(target=thing_1) 
    p.start() 
    # keep a record of when we started it running 
    start_thing_1 = time.time() 

    # let's run the other thing 
    start_thing_2 = time.time() 
    thing_2() 
    end_thing_2 = time.time() 

    # this will wait for the first thing to finish 
    p.join() 
    end_thing_1 = time.time() 

    print('thing 1 took {}'.format(end_thing_1 - start_thing_1)) 
    print('thing 2 took {}'.format(end_thing_2 - start_thing_2)) 

在最後你會看到:

thing 1 took 10.020239114761353 
thing 2 took 2.003588914871216 

因此,雖然thing_1在當地的蟒蛇可以在做其他事情進行後臺運行。

您需要使用特殊的機制來在Python的兩個副本之間傳輸任何信息。而且打印總是有點奇怪,因爲你不知道接下來要打印哪個python副本。