The following small series will bring you an implementation method for referencing other file functions in the script in Python. I think this is quite good. now I will share it with you and give you a reference. Let's take a look at the small Editor. when importing a file, Python only searches for the directory where the current script is located, loads (entry-point) the entry script running directory and sys. path contains the path such as the package installation address. Therefore, to reference other files in the current script, in addition to placing the files in the same directory as the script, there are also the following methods,
1. add the file location to sys. path.
import syssys.path.insert(0, '/path/to/application/app/folder') # or sys.path.append('/path/to/application/app/folder')import file
2. create the _ init _. py file in the file directory and then call the file
from application.app.folder.file import func_name
Init. py file
A) functions of the. init. py file
The main function of this file is to initialize the Python package. If the directory contains the file, the Python interpreter treats the directory as a package. Next, you can use the import statement to reference the file under the Directory in other. py scripts. The structure of a standard Python module is as follows:
package/ __init__.py file.py file2.py subpackage/ __init__.py submodule1.py submodule2.py
B) the. _ init _ file can be empty but can be used to create a package requirement. In general, the classes and functions in this file need to be imported to the package level for convenient reference. For example, if the file. py File contains a File Class, you need to reference the file class when nothing is written in the init. py File:
from package.file import File
If you import file into the package in the _ init _. py File, you can directly reference the file class at the package level:
# in your __init__.pyfrom file import File# in your scriptfrom package import File
In addition, note the all variable in the _ init _. py file.
If the interpreter is in _ init __. the _ all _ variable is observed in the py file. when running from package import *, only the modules listed in the _ all _ variable will be introduced.
For example, if you want to introduce only the submodule1 module in the above structure, you can go to subpackage/_ init __. in the py file, define _ all _ = ['sublele1']. when the subpackage is referenced, the from subpackage import * introduces only the submodule1 module.
3. add the directory where the file is located to the python environment variable
export PYTHONPATH=$HOME/pathToYourScripts/:#PYTHONPATH
The above is all the implementation methods for referencing other file functions in the script in Python provided by Xiaobian. I hope you can support the script ~