簡體   English   中英

運行Python子進程

[英]Running a Python Subprocess

所有,

我已經閱讀了幾個有關如何在python中運行子進程的線程,但似乎都沒有幫助。 可能是因為我不知道如何正確使用它們。 我有幾種方法可以同時運行,而不是依次運行,我認為子流程模塊可以為我做到這一點。

def services():
     services = [method1(),
            method2(),
            method3(),  
            mrthod4(),
            method5()]
     return services

def runAll():
    import subprocess
    for i in services():
        proc = subprocess.call(i,shell=True)

這種方法的問題在於method1()啟動,而method2()在1完成之前不會啟動。 我嘗試了幾種方法,包括在我的服務方法中使用subprocess.Popen []都沒有碰到運氣。 誰能幫我同時運行方法1-5?

謝謝亞當

根據Python文檔, subprocess.call()等待命令完成。 您應該直接使用subprocess.Popen對象,它將為您提供所需的靈活性。

您需要使用&異步執行它們。 這是一個例子:

 subprocess.call("./foo1&", shell=True)
 subprocess.call("./foo2&", shell=True)

這就像普通的unix shell。

編輯:盡管有多種更好的方法來做到這一點。 有關其他示例,請參見其他答案。

Python線程更適合您要查找的內容: http : //docs.python.org/library/threading.html甚至是多處理模塊: http : //docs.python.org/library/multiprocessing.html#module -multiprocessing

通過說method1() ,您正在調用該函數並等待其返回。 (這是一個函數,而不是方法。)

如果您只想並行運行一堆重型函數並收集其結果,則可以使用joblib

from joblib import Parallel, delayed

functions = [fn1, fn2, fn3, fn4]

results = Parallel(n_jobs=4)(delayed(f)() for f in functions)

subprocess.call()阻塞,直到過程完成。

multiprocessing聽起來更適合您的工作。

例如:

from multiprocessing import Process

def f1():
    while True:
        print 'foo'

def f2():
    while True:
        print 'bar'

def f3():
    while True:
        print 'baz'

if __name__ == '__main__':
    for func in (f1, f2, f3):
        Process(target=func).start()

在python 3.2.x中,並發的Futures模塊使這種事情變得非常容易。

子流程不會使流程異步。 您可以嘗試使用多線程或多處理模塊來實現。

我最近有一個類似的問題,並像這樣解決了它:

from multiprocessing import Pool
def parallelfuncs(funcs, args, results, bad_value = None):
    p = Pool()
    waiters = []
    for f in funcs:
        waiters.append(p.apply_async(f, args, callback = results.append))
    p.close()
    for w in waiters:
        if w.get()[0] == bad_value:
            p.terminate()
    return p

令人高興的是,函數funcs在args上並行執行( 類似於 map的反向操作),並返回結果。 多處理池使用所有處理器並處理作業執行。

w.get塊(如果不清楚)。

對於您的用例,您可以致電

results = []
parallelfuncs(services, args, results).join()
print results

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM