How to use third-party modules in Python?
In Python, you can import modules in the code, and then you can use third-party modules.
import statement
To use a Python source file, just execute the import statement in another source file, the syntax is as follows:
import module1[, module2[,... moduleN]
When the interpreter encounters an import statement, it will be imported if the module is in the current search path.
The search path is a list of all directories that the interpreter will search first. If you want to import the module hello.py, you need to put the command at the top of the script:
#! /usr/bin/python
# - *- coding: UTF-8-*-
# Import module
import support
# Now you can call the functions contained in the module
support.print_func("Zara")
The output of the above example:
Hello : Zara
A module will only be imported once, no matter how many imports you perform. This prevents imported modules from being executed over and over again.
From...import statement
Python's from statement allows you to import a specified part from the module into the current namespace. The syntax is as follows:
from modname import name1[, name2[,... nameN]]
For example, to import the fibonacci function of the module fib, use the following statement:
from fib import fibonacci
This declaration will not import the entire fib module into the current namespace, it will only introduce the fibonacci in the fib into the global symbol table of the module executing this declaration.
From...import* statement
It is also possible to import all the contents of a module into the current namespace, just use the following declaration:
from modname import*
This provides an easy way to import all the items in a module. However, this statement should not be used too much.
Knowledge point expansion:
In Python, the installation of third-party modules is done through the tool setuptools. Python has two package management tools that encapsulate setuptools: easy_install and pip. Currently, pip is officially recommended.
If you are using Mac or Linux, the step of installing pip itself can be skipped.
If you are using Windows, please refer to the install Python section, make sure pip and Add python.exe to Path are checked during installation.
Try to run pip in the command prompt window. If Windows prompts that the command is not found, you can re-run the installer to add pip.
The above is the detailed content of how to introduce third-party modules in Python. For more information about the methods of introducing third-party modules in Python, please pay attention to other related articles on ZaLou.Cn!
Recommended Posts