Summary of Several import modules in Python and several import modules in python
The module encapsulates many practical functions, and sometimes needs to be imported for external calls.There are several common methods:
1. import
>>> import sys>>> sys.path['', 'C:\\Python34\\Lib\\idlelib', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']
The most common method is to directly write the name of the module to be imported into the system.
2. from... import ..
Similar to import, it is just a more explicit method or variable to be imported, such:
>>> from sys import path>>> path['', 'C:\\Python34\\Lib\\idlelib', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']
But it may cause namespace pollution. We recommend using import.
3. Import the module with the name string
We may want to import the module as follows:
>>> import "sys"SyntaxError: invalid syntax
Python import receives a variable instead of a string. What about assigning "sys" to a variable?
>>> x="sys">>> import xTraceback (most recent call last): File "<pyshell#4>", line 1, in <module> import xImportError: No module named 'x'
This does not work either. This means importing a module named x instead of a sys module represented by x.
We need to use the exec function:
>>> x="sys">>> exec("import "+ x)>>> sys.path['', 'C:\\Python34\\Lib\\idlelib', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']
Build the import statement into a string and pass it to the exec function for execution.
The disadvantage of exec is that it needs to be compiled every time it is executed. Running it multiple times will affect the performance.
A better way is to use the _ import _ function.
>>> x="sys">>> sys = __import__(x)>>> sys.path['', 'C:\\Python34\\Lib\\idlelib', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']
This method requires a variable to save the module object for subsequent calls.
The above summary of Several import modules in Python is the full content shared by the small Editor. I hope you can give us a reference and support the help house.