python实现在每个独立进程中运行一个函数的方法

yipeiwu_com6年前Python基础

本文实例讲述了python实现在每个独立进程中运行一个函数的方法。分享给大家供大家参考。具体分析如下:

这个简单的函数可以同于在单独的进程中运行另外一个函数,这对于释放内存资源非常有用

#!/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程序设计有所帮助。

相关文章

Python实现多属性排序的方法

Python实现多属性排序的方法

多属性排序: 把需要排序的属性拿出来作为一个 tuple,主要的放前面,次要的放后面。 假如某对象有n个属性,那么先按某规则对属性a进行排序,在属性a相等的情况下再按某规则对属性b进行排...

Python模拟登录之滑块验证码的破解(实例代码)

模拟登录之滑块验证码的破解,具体代码如下所示: # 图像处理标准库 from PIL import Image # web测试 from selenium import webdri...

Python实现二叉树结构与进行二叉树遍历的方法详解

Python实现二叉树结构与进行二叉树遍历的方法详解

二叉树的建立 使用类的形式定义二叉树,可读性更好 class BinaryTree: def __init__(self, root): self.key = ro...

Python实现合并同一个文件夹下所有txt文件的方法示例

Python实现合并同一个文件夹下所有txt文件的方法示例

本文实例讲述了Python实现合并同一个文件夹下所有txt文件的方法。分享给大家供大家参考,具体如下: 一、需求分析 合并一个文件夹下所有txt文件 二、合并效果 三、pyth...

树莓派4B+opencv4+python 打开摄像头的实现方法

树莓派4B+opencv4+python 打开摄像头的实现方法

在树莓派自带得python IDE Thonny中写如下代码,并在树莓派上插上usb摄像头 import cv2 cap=cv2.VideoCapture(0) #调用摄像头‘0'一...