python實現(xiàn)在每個獨立進程中運行一個函數(shù)的方法
更新時間:2015年04月23日 10:03:04 作者:令狐不聰
這篇文章主要介紹了python實現(xiàn)在每個獨立進程中運行一個函數(shù)的方法,涉及Python操作進程的相關技巧,需要的朋友可以參考下
本文實例講述了python實現(xiàn)在每個獨立進程中運行一個函數(shù)的方法。分享給大家供大家參考。具體分析如下:
這個簡單的函數(shù)可以同于在單獨的進程中運行另外一個函數(shù),這對于釋放內(nèi)存資源非常有用
#!/usr/bin/env python
from __future__ import with_statement
import os, cPickle
def run_in_separate_process(func, *args, **kwds):
pread, pwrite = os.pipe()
pid = os.fork()
if pid > 0:
os.close(pwrite)
with os.fdopen(pread, 'rb') as f:
status, result = cPickle.load(f)
os.waitpid(pid, 0)
if status == 0:
return result
else:
raise result
else:
os.close(pread)
try:
result = func(*args, **kwds)
status = 0
except Exception, exc:
result = exc
status = 1
with os.fdopen(pwrite, 'wb') as f:
try:
cPickle.dump((status,result), f, cPickle.HIGHEST_PROTOCOL)
except cPickle.PicklingError, exc:
cPickle.dump((2,exc), f, cPickle.HIGHEST_PROTOCOL)
os._exit(0)
#an example of use
def treble(x):
return 3 * x
def main():
#calling directly
print treble(4)
#calling in separate process
print run_in_separate_process(treble, 4)
希望本文所述對大家的Python程序設計有所幫助。
相關文章
使用Pandas對數(shù)據(jù)進行篩選和排序的實現(xiàn)
這篇文章主要介紹了使用Pandas對數(shù)據(jù)進行篩選和排序的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07
解決Python3 控制臺輸出InsecureRequestWarning問題
這篇文章主要介紹了解決Python3 控制臺輸出InsecureRequestWarning的問題 ,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07

