python實現(xiàn)在每個獨立進程中運行一個函數(shù)的方法
更新時間:2015年04月23日 10:03:04 作者:令狐不聰
這篇文章主要介紹了python實現(xiàn)在每個獨立進程中運行一個函數(shù)的方法,涉及Python操作進程的相關技巧,需要的朋友可以參考下
本文實例講述了python實現(xiàn)在每個獨立進程中運行一個函數(shù)的方法。分享給大家供大家參考。具體分析如下:
這個簡單的函數(shù)可以同于在單獨的進程中運行另外一個函數(shù),這對于釋放內存資源非常有用
#!/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程序設計有所幫助。
相關文章
基于virtualenv創(chuàng)建python虛擬環(huán)境過程圖解
這篇文章主要介紹了基于virtualenv創(chuàng)建python虛擬環(huán)境過程圖解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-03-03Python sklearn中的.fit與.predict的用法說明
這篇文章主要介紹了Python sklearn中的.fit與.predict的用法說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06