python notes - modules and packages

Posted by idris on Tue, 04 Jan 2022 20:32:53 +0100

Import module

Before using a module, you must import the module in the file where you write the code

Use the keyword import
Example: importing os modules

import os

Import multiple modules

# ① The module name can be followed by import, separated by English commas
import random,os,request,math

#② Each module is imported separately using the import keyword
import random
import os
import request
import math

After importing modules, view the modules imported in the current environment

import random


['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'random']

To view all the methods of the imported module, view through dir (module name)

import random

Output: all classes, methods, and properties of the module

['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_inst', '_log', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']

Import package

Package is to place many module files in the same group of folders. This folder is called package or class library. There must be at least one in each package__ file

Packages can contain sub packages. There should also be in the sub package__ file

Import entire package

import packageName

Import a module or sub package from a package

imporrt packageName .module

When importing a module or sub package into a package, the import order must follow the path information of the file

Import statement from import...

Import classes, methods, properties, etc. from the module
from followed by module name,
import is followed by the name of the class or method to be imported

Duplicate modules and packages

Rename the imported module and package, and use the keyword as to implement it
The keyword as can only name a package or a module file

import random as rd

Reload modules and packages

Without interrupting the program, when the code of the imported module or package changes, the program will not be updated in real time. Python provides the reload() method of importlib module to reload the module or package


def run():
    return 10


import a
import time
from importlib import reload
if __name__=='__main__':
    while 1:
        print("b Modular run()The return value is:",v)

After running the file, modify the return value of to 22;

b Modular run()The return value is: 10
b Modular run()The return value is: 10
b Modular run()The return value is: 22

Dynamically add modules and packages

Through built-in functions__ import__ () method implementation


__import __(name, globals, locals, fromlist, level)

The required parameter is: name. Character type: string, usually name

import os
import time
from importlib import reload

#Reload function is imported to reload the module

if __name__=='__main__':
    this_file=os.path.split(__file__)[-1]#Intercept the file name of the current file path
    while 1:
        for f in os.listdir(os.getcwd()):#Traverses the list of all files in the current folder
            if '.py' in f and f !=this_file:# The filter suffix is py and exclude the current file
                file_name = f.split('.')[0]#Intercept the file name of a file without suffix
                print("The file to import is",file_name)
                new_import = __import__(file_name)#Use__ inmport__ Function dynamic import module
                v = to call the module
                print("b Modular run()The return value is:",v)


The file to import is a 
b Modular run()The return value is: 22

__ file__ Property to view the source file path of the module

Run in module file:


Returns the file path of the current module


View the source file path of the specified module

Module name. __file__

Package / install custom modules and packages;

When some functions are developed and encapsulated into modules or packages, if you want to share these functions with others, you need to package them.

Others get your packaged module and need to install it before calling it


Built in module package setuptools can package customized modules or packages into whl documents;

Packaging steps:
1. Under the root directory of the project, add setup Py file

Add a mypack folder under the test folder, and then add a setup Py file

2. In setup Py file, specify the name, version, author and other attributes of the package
Use the built-in function setup function of the packaging module setuptools

from setuptools import setup

    name='mypackage1', #Package name
    version='1.0',    #edition
    description='This is my practice.',# Function description of packer
    py_modules=['a','b'],   #py module file to package
    packages=['mypack'],  #Packaged module or package path
  1. Run the build command in the root directory (see the online tutorial for this step, but it doesn't matter if I don't execute it)
    4. Run the package command
    On the command line, enter setup Py file, run the following command to view the help information of setuptools
python --help-commands


python sdist bdist_wheel

5. View the completed package under the generated dist directory

Packaging command

Package into wheel file

sdist bdist_wheel

Pack into a compressed package


Install custom packages

Install the package
Enter the directory where the compressed package is located to run

pip install XXXX.tar.gz

Or (install wheel file):

pip install XXx.whl

It can also be installed directly (this should be run in the root directory of the package. I haven't tried yet)

python install

View all currently installed packages through the pip list command, and you can see the packages I typed myself

Installing third-party modules and packages

pip, a Python package management tool, provides functions such as finding, downloading, installing and uninstalling modules or packages


pip help

View help information

  install                     Install packages.
  download                    Download packages.
  uninstall                   Uninstall packages.
  freeze                      Output installed packages in requirements format.
  list                        List installed packages.
  show                        Show information about installed packages.
  check                       Verify installed packages have compatible dependencies.
  config                      Manage local and global configuration.
  search                      Search PyPI for packages.
  cache                       Inspect and manage pip's wheel cache.
  wheel                       Build wheels from your requirements.
  hash                        Compute hashes of package archives.
  completion                  A helper command used for command completion.
  debug                       Show information useful for debugging.
  help                        Show help for commands.

Common methods:
Install, install package (parameter - r batch install dependency according to requirements file, - e install editable package; - t install to specified location)
download, download
Uninstall, uninstall
list to view all installed packages and modules

pip install packagesname

freeze instruction

The pip management tool provides the free instruction, which can write the information of the third-party module or package installed in the current environment into requirements txt ; Execute install requirements. In the new environment Txt file, the pip tool will batch install the packages and modules in the file

Enter the file directory to run:

pip freeze > requirements.txt

The current folder automatically generates requirements Txt file;
Copy the file to the new environment and run:

pip install -r requirements.txt

The program automatically performs the installation

Topics: Python