2010-01-12 29 views
41
import subprocess 

def my_function(x): 
    return x + 100 

output = subprocess.Popen(my_function, 1) #I would like to pass the function object and its arguments 
print output 
#desired output: 101 

我只找到使用單獨腳本打開子過程的文檔。有誰知道如何傳遞函數對象,甚至是傳遞函數代碼的簡單方法嗎?是否可以在沒有線程或編寫單獨的文件/腳本的情況下在子進程中運行函數。

+1

我相信你正在尋找[multiprocessing](http://docs.python.org/3.1/library/multiprocessing.html)模塊。 – 2010-01-12 04:01:22

回答

65

我認爲你正在尋找更多的東西一樣多處理模塊:

http://docs.python.org/library/multiprocessing.html#the-process-class

的子模塊是產卵過程,並與他們的輸入/輸出做的事情 - 而不是運行功能。

這裏是一個multiprocessing版本的代碼:

from multiprocessing import Process, Queue 

def my_function(q, x): 
    q.put(x + 100) 

if __name__ == '__main__': 
    queue = Queue() 
    p = Process(target=my_function, args=(queue, 1)) 
    p.start() 
    p.join() # this blocks until the process terminates 
    result = queue.get() 
    print result 
+13

你可以使用'processify'裝飾器作爲快捷方式:https://gist.github.com/2311116 – schlamar 2012-04-05 16:58:06

+1

我認爲這克隆了Python解釋器及其子進程的所有環境? – Jens 2015-02-20 18:23:47

+0

這是一個在python 3中工作並支持生成器函數的processify分支。 https://gist.github.com/stuaxo/889db016e51264581b50 – 2016-03-29 15:14:00

14

您可以使用標準的Unix fork系統調用,如os.fork()fork()將創建一個新的進程,並運行相同的腳本。在新進程中,它將返回0,而在舊進程中它將返回新進程的進程ID。

child_pid = os.fork() 
if child_pid == 0: 
    print "New proc" 
else: 
    print "Old proc" 

對於較高水平的庫,它提供多處理支持,提供了一種便攜式的抽象用於使用多個過程,還有的multiprocessing模塊。有一篇關於IBM DeveloperWorks的文章,Multiprocessing with Python,並簡要介紹了這兩種技術。

+0

我很好奇;爲什麼downvote?我的回答有什麼問題嗎? – 2010-01-12 04:42:09

+0

多處理不僅僅是fork()的更高級別的包裝,它是一個多平臺多處理工具包(它在unix上使用fork)。這很重要,因爲這意味着它運行在Windows上,而fork()不運行。 編輯:這是downvote的原因,雖然我後來認爲它可能不值得。儘管如此,收回時間已經太晚了。 Edit2:或者相反,fork()被建議,當它不是跨平臺是原因。 – 2010-01-12 04:42:55

+1

@Devin,如果你願意的話,你總是可以收回你所做的一切。 – 2010-01-12 04:49:17

3

布賴恩·麥肯納的約多重上述職位是真正有用的,但如果你想下去螺紋路徑(相對於基於進程的),這個例子讓你開始:

import threading 
import time 

def blocker(): 
    while True: 
     print "Oh, sorry, am I in the way?" 
     time.sleep(1) 

t = threading.Thread(name='child procs', target=blocker) 
t.start() 

# Prove that we passed through the blocking call 
print "No, that's okay" 

您還可以使用setDaemon(True)功能立即爲線程提供背景。

相關問題