[Python] python在每个独立的进程中运行一个函数 →→→→→进入此内容的聊天室

来自 , 2020-12-31, 写在 Python, 查看 150 次.
URL http://www.code666.cn/view/e3b6fb0f
  1. #!/usr/bin/env python
  2. from __future__ import with_statement
  3.  
  4. import os, cPickle
  5. def run_in_separate_process(func, *args, **kwds):
  6.     pread, pwrite = os.pipe()
  7.     pid = os.fork()
  8.     if pid > 0:
  9.         os.close(pwrite)
  10.         with os.fdopen(pread, 'rb') as f:
  11.             status, result = cPickle.load(f)
  12.         os.waitpid(pid, 0)
  13.         if status == 0:
  14.             return result
  15.         else:
  16.             raise result
  17.     else:
  18.         os.close(pread)
  19.         try:
  20.             result = func(*args, **kwds)
  21.             status = 0
  22.         except Exception, exc:
  23.             result = exc
  24.             status = 1
  25.         with os.fdopen(pwrite, 'wb') as f:
  26.             try:
  27.                 cPickle.dump((status,result), f, cPickle.HIGHEST_PROTOCOL)
  28.             except cPickle.PicklingError, exc:
  29.                 cPickle.dump((2,exc), f, cPickle.HIGHEST_PROTOCOL)
  30.         os._exit(0)
  31.  
  32. #an example of use
  33. def treble(x):
  34.     return 3 * x
  35.  
  36. def main():
  37.     #calling directly
  38.     print treble(4)
  39.     #calling in separate process
  40.     print run_in_separate_process(treble, 4)
  41. #//python/8319

回复 "python在每个独立的进程中运行一个函数"

这儿你可以回复上面这条便签

captcha