Python modules and packages: use of sys module, os module and variable functions

module

Modularization refers to decomposing a complete program into small modules and building a complete program by combining the modules. Modularity has the advantages of convenient development, maintenance and reuse. In Python, each py file is a module.

Import external modules

There are two ways to introduce external modules into a module: import 模块名and import 模块名 as 模块别名. The latter can introduce the same module multiple times, but only one instance will be created. The import statement can be called anywhere in the program, but generally it should be written at the beginning of the program. There is an attribute inside each module __name__through which the name of the module can be obtained. __name__The module with a value __main__of is the main module and the module we execute directly through python.

Introduce some content

You can also import only part of the content in the module, the syntax is from 模块名 import 变量,变量....: You can use aliases for imported variables with the syntax from 模块名 import 变量 as 别名:

package

A package is a folder composed of multiple modules. When a module has too much code, or when a module needs to be broken down into multiple modules, you need to use packages. A file is required in the package __init__.py, and this file can contain the main content of the package.

Sample code

Here is some sample code:

# 引入test_module模块,并指定别名test
import test_module as test

# 访问模块中的变量
print(test.a, test.b)

# 创建Person的实例p
p = test.Person()
print(p.name)

# 只引入模块中的特定部分
from m import Person,test

# 引入到模块中所有内容,不推荐使用
from m import *

# 为引入的变量使用别名
from m import test2 as new_test2

# 引入包hello中的模块
from hello import a,b

print(a.c)
print(b.d)

Note: __pycache__It is the cache file of the module and can be used to improve the performance of the program.

# 模块缓存文件
__pycache__ 是模块的缓存文件。在Python中,代码在执行前需要被解析器转换为机器码,然后再执行。为了提高程序的运行性能,Python会在第一次编译后将代码保存到一个缓存文件中。下次加载该模块时,就可以直接加载缓存中编译好的代码,而不需要重新编译。

例子:
# 引入math模块
import math

# 调用math模块中的函数
print(math.sqrt(16))

# 输出结果:4.0

注意:在实际编写代码时,应该根据实际情况选择引入模块的方式,避免引入不必要的内容,以减少内存占用和提高代码的可读性。

The above is related to modules and packages. Using modularity can make code clearer, easier to maintain, and reusable. At the same time, the use of packages can decompose large programs into smaller modules, making it easier to manage and organize code. When writing modules and packages, pay attention to naming conventions and choose a reasonable way to introduce modules.

When a module is imported, Python executes all top-level code in the module (that is, code that is not in any functions, classes, or conditional statements). This is typically used for operations such as initializing variables in a module, defining functions and classes, etc.

Sample code:

# module.py
print("This is a module.")

def greet(name):
    print(f"Hello, {
      
      name}!")

class Person:
    def __init__(self, name):
        self.name = name

# main.py
import module

print("This is the main module.")

module.greet("Alice")

p = module.Person("Bob")
print(p.name)

Run main.pyoutput:

This is a module.
This is the main module.
Hello, Alice!
Bob

As you can see, when the module main.pyis imported module, the top-level code in is executed first module.py, and then main.pythe code in is continued.

In addition, you can use if __name__ == "__main__":to determine whether the current module is executed directly. This allows the module to both execute as an independent program and be imported and used by other modules.

Sample code:

# module.py
def square(x):
    return x * x

if __name__ == "__main__":
    # 当前模块被直接执行
    # 执行一些测试代码
    print(square(5))
    print(square(10))

Functions can be executed individually module.pyor imported and used in other modules square. When executed as a standalone program, the test code will be executed; when imported as a module, the test code will not be executed.

OK, I will organize this article as required and format it in Markdown format. Just a moment please.

Ready out of the box

In order to realize the idea of ​​out-of-the-box use, Python provides us with a standard library of modules. In this standard library, there are many very powerful modules that we can use directly, and the standard library will be installed together with the Python installation.

sys module

The sys module provides some variables and functions that allow us to obtain information about the Python parser or operate the Python parser through functions. We can introduce the sys module:

import sys

sys.argv

sys.argv is used to obtain the parameters contained in the command line when executing code. This property is a list that stores all parameters of the current command. For example:

print(sys.argv)

sys.modules

sys.modules is used to obtain all modules introduced in the current program. modules is a dictionary, the key of the dictionary is the name of the module, and the value of the dictionary is the module object. We can use the pprint module to format and output it. For example:

import pprint
pprint.pprint(sys.modules)

sys.path

sys.path is a list that stores the search path of the module. For example:

pprint.pprint(sys.path)

sys.platform

sys.platform represents the platform on which Python is currently running. For example:

print(sys.platform)

sys.exit()

The sys.exit() function is used to exit the program. You can add a string in parentheses as a prompt when exiting. For example:

sys.exit('程序出现异常,结束!')
print('hello')

os module

The os module allows us to access the operating system. We can introduce the os module:

import os

os.environ

The system's environment variables can be obtained through the os.environ property. For example:

pprint.pprint(os.environ['path'])

os.system()

The os.system() function can be used to execute operating system commands. For example, you can execute dirthe command to view the file list of the current directory:

os.system('dir')

Variables, functions and classes in the os module

We can define variables, functions and classes in modules and use them elsewhere. For example:

a = 10
b = 20

_c = 30  # 添加了_的变量,只能在模块内部访问

def test():
    print('test')

def test2():
    print('test2')

class Person:
    def __init__(self):
        self.name = '孙悟空'

test code

We can write some test code to verify the functionality of the module. This part of the code will only be executed when the current file is used as the main module, and will not be executed when the module is introduced by other modules. We can __name__check whether the current module is the main module through properties.

if __name__ == '__main__':
    test()
    test2()
    p = Person()
    print(p.name)

Use of variables and functions in modules

Variables and functions defined in a module can be used elsewhere. For example, let's say we save the above code as a example.pymodule file called:

# example.py

a = 10
b = 20

_c = 30

def test():
    print('test')

def test2():
    print('test2')

class Person:
    def __init__(self):
        self.name = '孙悟空'

Then, in another Python script, we can import the module and use the variables and functions defined in it:

# main.py

import example

print(example.a)
print(example.b)

example.test()
example.test2()

p = example.Person()
print(p.name)

Running main.py, the following results will be output:

10
20
test
test2
孙悟空

In this way, we can encapsulate some commonly used code in modules and reuse them elsewhere.

Summarize:

  • Use sysmodules to obtain information about the Python parser and operate the Python parser.
  • Modules can be used osto access the operating system, including obtaining system environment variables and executing system commands.
  • Variables, functions, and classes defined in a module can be used elsewhere.
  • You can if __name__ == '__main__':write test code that will only be executed when the module is run as the main module.

Recommended Python boutique columns


Basic knowledge of python (0 basic introduction)

[Python basic knowledge] 0.print() function
[python basic knowledge] 1. Data types, data applications, data conversion
[python basic knowledge] 2. if conditional judgment and condition nesting
[python basic knowledge] 3.input() Functions
[Basic knowledge of python] 4. Lists and dictionaries
[Basic knowledge of python] 5. For loops and while loops
[Basic knowledge of python] 6. Boolean values ​​and four types of statements (break, continue, pass, else)
[Basic knowledge of python] 7. Practical operation - Use Python to implement the "Word PK" game (1)
[Python basic knowledge] 7. Practical operation - Use Python to implement the "Word PK" game (2)
[Python basic knowledge] 8. Programming thinking: how to Solving problems - Thinking Chapter
[Basic Knowledge of python] 9. Definition and calling of functions
[Basic Knowledge of Python] 10. Writing programs with functions - Practical Chapter
[Basic Knowledge of Python] 10. Using Python to implement the rock-paper-scissors game - Function Practice Operation Chapter
[Python Basics] 11. How to debug - Common error reasons and troubleshooting ideas - Thinking Chapter
[Python Basics] 12. Classes and Objects (1)
[Python Basics] 12. Classes and Objects (2)
[Python Basics] Knowledge] 13. Classes and objects (3)
[Basic knowledge of python] 13. Classes and objects (4)
[Basic knowledge of python] 14. Building a library management system (practical operation of classes and objects)
[Basic knowledge of python] 15. Coding basic knowledge
[Basic knowledge of python] 16. Fundamentals of file reading and writing and operations
[Basic knowledge of python] 16. Python implementation of "Ancient poem dictation questions" (File reading, writing and coding - practical operation)
[Basic knowledge of python] 17. The concept of modules and How to introduce
[python basics] 18. Practical operation - using python to automatically send mass emails
[python basics] 19. Product thinking and the use of flow charts - thinking
[python basics] 20. python implementation of "what to eat for lunch" ( Product Thinking - Practical Operation)
[Basic knowledge of python] 21. The correct way to open efficiently and lazily - Graduation
[python file processing] Reading, processing and writing of CSV files
[python file processing] Excel automatic processing (using openpyxl)
[python file processing]-excel format processing


python crawler knowledge

[python crawler] 1. Basic knowledge of crawlers
[python crawler] 2. Basic knowledge of web pages
[python crawler] 3. First experience with crawlers (BeautifulSoup analysis)
[python crawler] 4. Practical crawler operation (dish crawling)
[python crawler] 5 .Practical crawler operation (crawling lyrics)
[python crawler] 6. Practical crawler operation (requesting data with parameters)
[python crawler] 7. Where is the crawled data stored?
[python crawler] 8. Review the past and learn the new
[python crawler] 9. Log in with cookies (cookies)
[python crawler] 10. Command the browser to work automatically (selenium)
[python crawler] 11. Let the crawler report to you on time
[python crawler] 12. Build your crawler army
[python crawler] 13. What to eat without getting fat (crawler practical exercise)
[python crawler] 14. Scrapy framework explanation
[python crawler] 15. Scrapy framework practice (popular job crawling Take)
[python crawler] 16. Summary and review of crawler knowledge points

Guess you like

Origin blog.csdn.net/qq_41308872/article/details/132856258