Python reference module and search module path, python reference module path
Independent reference between modules is the basic capability of any programming language. The term "module" may be different in various programming languages, but we can simply think that a program file is a module, which contains the definition of classes or methods. For compiled languages, such as one in C. cs file, one in Java. java or compiled. the class file can be considered as a module (but often not expressed as a module). It is more intuitive for interpreted languages, such as PHP. PHP file, which is in Python. the py file can be considered as a module. There is a "package" on top of the "module" to facilitate the organization and management of the module. For example, after compiling in C. dll file (but often not expressed as Package, but Library), Java will. class package. jar file, PHP. A phar file (similar to a Java Package). In Python, a specially defined folder is a package and can be packaged as an egg file. However, the interpreted language "package" is not compiled into a low-level language and then packaged, but it is more convenient for modularity and Management Module dependencies. Each programming language has certain conventions for modules and package management. If you do not understand these conventions, it will bring obstacles to learning this language. Next I want to sort out these Python conventions.
1. Path of the Python search Module
Run the Python application or reference the Python module. The Python interpreter must have a search process. You can add a search path to Python by setting an environment variable PYTHONPATH to facilitate searching for related Python modules. (the settings of environment variables vary slightly with operating systems. The default values are WIndows ), this is the same as setting a system environment variable for many applications. In the command line, you can set it through the following command:
C: \ Users \ Administrator> set PYTHONPATH = E:/Project/Python/ModuleAndPackage/
After entering the Python environment, you can use the sys. path attribute of Python to obtain the current search path configuration. You can see that the previously set path is already in the current search path.
C:\Users\Administrator>pythonPython 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> import sys>>> sys.path['', 'E:\\Project\\Python\\ModuleAndPackage', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python\\DLLs', 'C:\\Python\\lib', 'C:\\Python\\lib\\plat-win', 'C:\\Python\\lib\\lib-tk', 'C:\\Python', 'C:\\Python\\lib\\site-packages']>>>
You can also use the append method of the sys module to add a search path to the Python environment.
>>> sys.path.append("E:\\Project\\Python\\ModuleAndPackage2")>>> sys.path['', 'E:\\Project\\Python\\ModuleAndPackage', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python\\DLLs', 'C:\\Python\\lib', 'C:\\Python\\lib\\plat-win', 'C:\\Python\\lib\\lib-tk', 'C:\\Python', 'C:\\Python\\lib\\site-packages', 'E:\\Project\\Python\\ModuleAndPackage2']>>>
Ii. modules and packages in Python
Each. the py file can be considered as a Python module ,. the py file can contain classes, methods, variables, and constants (Python does not strictly define constants, but it only conventions that uppercase variables are used as constants ), you can directly write all logical statements in the file and execute them directly from the top to the bottom during loading. This is similar to other explanatory languages. For example, if you choose to create a text file "person. py" in the ModuleAndPackage folder, a simple Python module is created. Its content is as follows:
# -*- coding: utf-8 -*-ID = 1name = "This person"print namedef say(something):print name,'says', something
Then we can execute person. py in the Python environment. We can directly execute person. py like executing a batch file, and input the following in the cmd command line:
Python E:/Project/Python/ModuleAndPackage/person.py
Essentially, the entry module of any Python application is executed like this (such as the main function in C # and Java). However, to reference a module, you must establish a Context Environment for running it. Set an environment variable PYTHONPATH so that the Python interpreter can find the person. py module and import the person module to access the methods or variables.
C:\Users\Administrator>pythonPython 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> import personThis person>>> person.say("hello")This person says hello>>> print person.nameThis person>>>
Python needs to go through some fixed paths to find the Python module, which we set in ModuleAndPackage. But these paths also have directory levels. How does Python find modules in subdirectories? In particular, when referencing a third-party package, we also need to know a certain level of relationship. In fact, Python builds a package structure through directories and files, and packages are nested layer by layer, which is the same as Directory layer nesting, thus forming the access path (or namespace, it can also be said that the namespace Of The Python application corresponds to its directory and file structure. It seems that it lacks some flexibility, but it is also simpler ). For example, in the ModuleAndPackage folder, create an animal folder, which creates a text file pet. py with the following content:
# -*- coding: utf-8 -*-ID = 2name = "This pet"print namedef run(somewhere):print name,'runs', somewhere
So how can we reference the pet. py module? According to the Python conventions, you need to create an empty text file named _ init _. py in the animal folder to identify the animal folder as a package. If the animal folder contains folders as packages, it must also contain the _ init _. py file. In this way, the access path is identified layer by layer.
>>> import animal.petThis pet>>> print animal.pet.nameThis pet>>> animal.pet.run("everywhere")This pet runs everywhere>>>
You can also use the from keyword to directly import attributes or methods in the module:
>>> from animal.pet import name,run>>> print nameThis pet>>> run("everywhere")This pet runs everywhere>>>
Iii. Reference between Python modules
Simply put, as long as the Python module is in the search path configured in its execution environment and its location is part of the package structure, we can reference this module. The basic example of module reference is provided above. The import Statement is written in the module File during inter-module reference. We modify the Code of the person. py module.
1. from, import, and
# -*- coding: utf-8 -*-ID = 1name = "This person"print namedef say(something):print name,'says', somethingfrom animal.pet import name as pet_name, run as pet_rundef have():print name,'has', pet_name
The import statement can be written anywhere in the document, or even in the if statement, to better control module reference. You can also use the as statement to reference another variable name to avoid variable name conflicts.
>>> import personThis personThis pet>>> print person.nameThis person>>> print person.pet_nameThis pet>>> person.have()This person has This pet>>>
2. * wildcard characters
The preceding import Code clarifies the referenced variable name, but if you want to reference all the variables in the module, you can use the * wildcard to rewrite the preceding import Statement as follows:
from animal.pet import *
However, this may cause a variable name conflict. The following name variable conflict overwrites the value of the person's own name variable:
>>> import personThis personThis pet>>> print person.nameThis pet
If you want to use the * wildcard and do not want to reference all the variables in the module, you can use the Variable _ all _ in the module to modify the pet. only two variable names, ID and run, are referenced.
# -*- coding: utf-8 -*-__all__ = ['ID','run']ID = 2name = "This pet"print namedef run(somewhere):print name,'runs', somewhere
Because the name variable in the pet module is not referenced, the name variable value of person is not changed, but run can be called.
>>> import personThis personThis pet>>> print person.nameThis person>>> person.run("nowhere")This pet runs nowhere>>>
3. Reference package
The above references specific animal. pet modules, but this is troublesome for a package with relatively independent modules and numerous modules. Can I directly import animal? The answer is yes, but Python is not like C # referencing dll or java to referencing jar. After referencing the module in the package, you can directly access it through the namespace (under the access control license ). By default, Python still needs to import specific modules in the package, but there is a work und: Use _ init _ in the package __. py file, prepare the variables in each module to be referenced in the package in advance, similar to exposing the interface in the package to the external reference. The code of the _ init _. py file is executed when the package or package module is referenced. Therefore, you can perform initialization in the package. Modify _ init _ in the animal folder __. the py file is as follows, where the module can use the absolute path and relative path, a period in the relative path. indicates the directory of the same level, with two periods .. represents the parent directory.
print "__init__"from pet import name as pet_name, run as pet_run#from animal.pet import name as pet_name, run as pet_run #from .pet import name as pet_name, run as pet_run
Modify person. py to directly reference the anmial package:
# -*- coding: utf-8 -*-ID = 1name = "This person"print namedef say(something):print name,'says', somethingimport animaldef have():print name,'has', pet_name
Reference the person module in the Python environment. person references animal and automatically runs the _ init _ code to load related variables. You can view the variables in the module through the dir method, each module contains variables starting with two underscores. These variables have special functions and are pre-defined by Python.
>>> import personThis person__init__This pet>>> dir(person)['ID', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'have','name', 'pet', 'pet_name', 'pet_run', 'say']>>> print person.pet_nameThis pet>>> person.pet_run("nowhere")This pet runs nowhere>>>
For more information about the Python reference module and the Python search module path, I hope to help you!
Articles you may be interested in:
- Python Method for importing modules by path
- How to Use the glob module in Python to find the file path