how can i use fork() in Python3.3

巧了我就是萌 提交于 2021-02-10 20:21:54

问题


how can i use fork() in Python3.3 **This is My code :

Input:

#!/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()

Output:

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'

回答1:


os.fork is only available in Unix-like system. You cannot use that in Windows.

os.fork()

Fork a child process. Return 0 in the child and the child’s process id in the parent. If an error occurs OSError is raised.

Note that some platforms including FreeBSD <= 6.3, Cygwin and OS/2 EMX have known issues when using fork() from a thread.

Availability: Unix.




回答2:


Since os.fork isn't available on your target, consider instead using the subprocess module or even (batteries-not-included) envoy.

These create a convenient abstraction around launching children.




回答3:


You should use the python's default multiprocessing package. It works with both Linux and 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()


来源:https://stackoverflow.com/questions/19547443/how-can-i-use-fork-in-python3-3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!