Hands-On Enterprise Automation with Python.
上QQ阅读APP看书,第一时间看更新

Package search paths

Typically, Python searches for modules in some specific system paths. You can print these paths by importing the sys module and printing the sys.path. This will actually return the strings inside the PYTHONPATH environment variable and inside the operating system; notice the result is just a normal Python list. You can add more paths to the search scope using a list function such as insert().

However, it's better to install the packages in the default search paths so the code won't break when you share it with other developers:

A simple package structure with a single module will be something like this:


The __init__ file inside each package (in the global directory or in the sub-directory) will tell the Python interpreter that this directory is a Python package, and each file ending with .py will be a module file, which could be imported inside your code. The second function of the init file is to execute any code inside it once the package is imported. However, most developers leave it empty and just use it to mark the directory as a Python package.