How to communicate between modules in Python
In Python, communication between modules is a very common requirement. Communication between modules can help us split and decouple functions, making code processing clearer and more flexible. This article will introduce several common methods of inter-module communication in Python and give specific code examples.
# module1.py global_variable = "Hello, World!" # module2.py from module1 import global_variable print(global_variable) # 输出:Hello, World!
# module1.py def func1(data): return data * 2 # module2.py from module1 import func1 result = func1(5) print(result) # 输出:10
# module1.py def func1(data): return data * 2 # module2.py import module1 result = module1.func1(5) print(result) # 输出:10
queue
module, which makes it easy to create and use queues. The following is an example: # module1.py import queue q = queue.Queue() def func1(): while True: data = q.get() print("Received:", data) # module2.py import module1 module1.q.put("Hello") module1.q.put("World")
In the above code, module2.py
passes to the queue q
in module1.py
Putting in data enables communication between the two modules.
Summary:
In Python, communication between modules can use methods such as global variables, function parameters, imported modules, and queues. Depending on specific needs, choosing the appropriate communication method can improve code readability and flexibility. I hope the code examples provided in this article will help you understand and use communication between modules.
The above is the detailed content of How to communicate between modules in Python. For more information, please follow other related articles on the PHP Chinese website!