


An article to help you understand Python's distributed process interface
1. Preface
Among Thread and Process, Process should be preferred because Process is more stable and Process can be distributed to multiple machines. Thread can only be distributed to multiple CPUs on the same machine at most.
Python's multiprocessing module not only supports multiple processes, but the managers submodule also supports distributing multiple processes to multiple machines. You can write a service process as a scheduler to distribute tasks to multiple other processes and rely on network communication for management.
2. Case Analysis
When doing a crawler program, crawl all the images of a website. If you use multiple processes, generally One process is responsible for grabbing the link address of the image and putting the link address into the queue. Another process is responsible for getting the link address from the queue to download and store it locally.
How to use distributed process?
The process on one machine is responsible for grabbing the link address, and the processes on other machines are responsible for storing it. The main problem encountered is to expose the queue to the network so that other machine processes can access it. The distributed process encapsulates this process. This process can be called the networking of local queues.
Example:
1.py
from multiprocessing.managers import BaseManager from multiprocessing import freeze_support, Queue # 任务个数 task_number = 10 # 收发队列 task_quue = Queue(task_number) result_queue = Queue(task_number) def get_task(): return task_quue def get_result(): return result_queue # 创建类似的queueManager class QueueManager(BaseManager): pass def win_run(): # 注册在网络上,callable 关联了Queue 对象 # 将Queue对象在网络中暴露 # window下绑定调用接口不能直接使用lambda,所以只能先定义函数再绑定 QueueManager.register('get_task_queue', callable=get_task) QueueManager.register('get_result_queue', callable=get_result) # 绑定端口和设置验证口令 manager = QueueManager(address=('127.0.0.1', 8001), authkey='qiye'.encode()) # 启动管理,监听信息通道 manager.start() try: # 通过网络获取任务队列和结果队列 task = manager.get_task_queue() result = manager.get_result_queue() # 添加任务 for url in ["ImageUrl_" + str(i) for i in range(10)]: print('url is %s' % url) task.put(url) print('try get result') for i in range(10): print('result is %s' % result.get(timeout=10)) except: print('Manager error') finally: manager.shutdown() if __name__ == '__main__': freeze_support() win_run()
Connect to the server. Please keep the port and verification password exactly the same as those in the server process to obtain the Queue from the network. Perform localization, obtain tasks from the task queue, and write the results to the result queue
2.py
#coding:utf-8 import time from multiprocessing.managers import BaseManager # 创建类似的Manager: class Manager(BaseManager): pass #使用QueueManager注册获取Queue的方法名称 Manager.register('get_task_queue') Manager.register('get_result_queue') #连接到服务器: server_addr = '127.0.0.1' print('Connect to server %s...' % server_addr) # 端口和验证口令注意保持与服务进程设置的完全一致: m = Manager(address=(server_addr, 8001), authkey='qiye') # 从网络连接: m.connect() #获取Queue的对象: task = m.get_task_queue() result = m.get_result_queue() #从task队列取任务,并把结果写入result队列: while(not task.empty()): image_url = task.get(True,timeout=5) print('run task download %s...' % image_url) time.sleep(1) result.put('%s--->success'%image_url) #结束: print('worker exit.')
The task process must be connected to the service process through the network, so To specify the IP of the service process.
The running results are as follows:
Get the image address and pass the address to 2.py.
Receive the address passed by 1.py, download the image, and the console displays the crawling results.
3. Summary
This article is based on the basics of Python. Python’s distributed process interface is simple and encapsulated Good, suitable for environments where heavy tasks need to be distributed to multiple machines. By explaining that the role of Queue is to deliver tasks and receive results.
The above is the detailed content of An article to help you understand Python's distributed process interface. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
