我如何在Python中使用fork()

时间:2013-10-23 16:38:31

标签: python windows

我如何在Python3.3中使用fork() **这是我的代码:

输入:

#!/usr/bin/env python
import os

def Child_process():
    print("We are in Child_Process")
    print("My PID: %d"%os.getpid())
    print("Child_Process is exiting")

def Parent_process():
    print("-------Parent_process---------")
    wpid = os.fork()
    if wpid==0:
        print("wpid is 0 means We are in Child_process")
        print("Child :%d"%wpid)
        Child_process()
    else:
        print("Execute Parent_process")
        print("Parent_process %d"%wpid)
        Parent_process()

Parent_process()

输出:

C:\Python33\python.exe C:/Users/Iem-Prog/Desktop/Py/Fork

Traceback (most recent call last):

  File "C:/Users/Iem-Prog/Desktop/Py/Fork", line 21, in <module>
-------Parent_process---------
    Parent_process()
  File "C:/Users/Iem-Prog/Desktop/Py/Fork", line 11, in Parent_process
    wpid = os.fork()

AttributeError: 'module' object has no attribute 'fork'

3 个答案:

答案 0 :(得分:8)

os.fork仅适用于类Unix系统。你不能在Windows中使用它。

  

os.fork()

     

分叉子进程。在孩子和孩子的进程ID中返回0   在父母。如果发生错误,则引发OSError。

     

请注意,某些平台包括FreeBSD&lt; = 6.3,Cygwin和OS / 2 EMX   从线程中使用fork()时会出现已知问题。

     

可用性:Unix。

答案 1 :(得分:2)

由于您的目标无法使用os.fork,请考虑使用subprocess module或甚至(不包括电池)envoy

这些创造了围绕发射儿童的方便抽象。

答案 2 :(得分:1)

您应该使用python的默认multiprocessing package。它可与Linux和Windows一起使用。

from multiprocessing import Process, Array

def split_work_receiver(import_type, process_no, i, shared_arr):
   creds= login()

    if creds is not None:
        process_submissions(browser, i, import_type, process_no, shared_arr)
    else:
        print("Failed login.")
    return

def split_work(base_path, i, connection_url, database_name):
    shared_arr = Array('i', range(0)) # Used to send data across processeses
    processes = [
        Process(target=split_work_receiver, args=("arg1", base_path, i, shared_arr)),
        Process(target=split_work_receiver, args=("arg1", base_path, i, shared_arr)),
        Process(target=split_work_receiver, args=("arg1", base_path, i, shared_arr))]

    #Run processes
    for p in processes:
        p.start()

    while True:
        sleep(600)

    #Exit the completed processes
    for p in processes:
        print('Closed process: '+ str(p))
        p.join()