search
HomeBackend DevelopmentPython TutorialPython commonly used standard libraries and third-party libraries 2-sys module

1. Introduction to the sys module

The os module introduced earlier is mainly for the operating system, while the sys module in this article is mainly for the Python interpreter.

The sys module is a module that comes with Python. It is an interface for interacting with the Python interpreter. The sys module provides many functions and variables to deal with different parts of the Python runtime environment.

2. Common methods of sys module

You can check which methods are included in the sys module through the dir() method:

import sys

print(dir(sys))

Python commonly used standard libraries and third-party libraries 2-sys module

1.sys.argv - Get command line parameters

sys.argv is used to transfer parameters from outside the program to the program, and it can obtain the command line parameter list. The argv list contains all parameters passed to the script:

  • sys.argv[0]: represents the program itself
  • sys.argv[1]: represents the first parameter of the program
  • sys.argv[2]: Indicates the second parameter of the program
import sys

for index, arg in enumerate(sys.argv):
print(index, arg)

Execute this script file on the Python command line (without any parameters), and obtain the second parameter One element is the script itself. The print result is:

Python commonly used standard libraries and third-party libraries 2-sys module

Execute this script file (with parameters) on the Python command line, and the first element obtained is the script itself. The rest are passed parameters. The printing result is:

Python commonly used standard libraries and third-party libraries 2-sys module

#2.sys.exit(n)-Exit the program

sys.exit() Basic Principle

sys.exit(n):

    When n is 0: normal exit
  • When n is not equal to 0, abnormal exit will trigger SystemExit Exception
Under normal circumstances, the interpreter will automatically exit when the program is executed to the end. At this time, sys.exit(0) is not called in the code, but the actual Python interpreter calls sys.exit(0) during runtime. After running, the PyCharm editor will automatically prompt "Process finished with exit code 0", as follows:

Python commonly used standard libraries and third-party libraries 2-sys module

When sys.exit(888) is called in the code, that is, a non-0 integer is passed in, the PyCharm editor will The prompt "Process finished with exit code 888" is as follows:

Python commonly used standard libraries and third-party libraries 2-sys module

And when sys.exit(n) is called in the code, it means that the program will exit, regardless of whether n is equal to 0, that is, whether it exits normally or abnormally, the subsequent statements will not be executed, that is, the sentence "print("Python sys.exit() Usage Example")" will not be executed. It can also be seen from the figure below that the statement after sys.exit(888) has been highlighted in yellow in the PyCharm editor (it will not be highlighted if the grammar is normal), and the running result does not execute sys Statement after .exit(888):

Python commonly used standard libraries and third-party libraries 2-sys module

#sys.exit() Applicable scenario - the control program exits midway

General situation Next, when the execution reaches the end of the main program, the interpreter will automatically exit. The above example has told us that if you want to exit midway, calling sys.exit() first and then calling other statements will not work, and the editor will warn you.

If you want to freely control whether the program exits midway, you can use the "sys.exit(n) catch exception" method. Among them, n can be an integer parameter or a string parameter. When n is a non-0 value, a SystemExit exception will be thrown, which can be captured in the main program:

# sys.exit()用法示例
def exit_function(value):
print("sys.exit()捕获到的value是%s" % value)
sys.exit(0)


print("start sys")

try:
sys.exit(888)
except SystemExit as value:
exit_function(value=value)

print("end sys")

① Example of program exiting midway

The execution results are as follows:

Python commonly used standard libraries and third-party libraries 2-sys module

Execution process analysis:

    The program first Execute print("start sys")
  1. Then execute the try statement, call sys.exit(888)
  2. Then capture the system exception, the value of the captured SystemExit exception is 888
  3. Finally call the exit_function function and pass the value 888 to the exit_function function
  4. In the exit_function function, execute the statement, print the captured value value, and finally call sys.exit(0) to exit the program
② Example of not exiting the program

上个示例的执行结果可以看到在exit_function函数中调用sys.exit(0),此时程序就会退出,不会再执行print("end sys"),而当在exit_function函数中注释掉sys.exit(0),则会继续执行最后的代码print("end sys"),即:程序中途不退出,如下所示:

Python commonly used standard libraries and third-party libraries 2-sys module

3.sys.platform-获取当前Python运行平台

基本用法

print(sys.platform)

Windows下运行:

Python commonly used standard libraries and third-party libraries 2-sys module

Linux下运行:

Python commonly used standard libraries and third-party libraries 2-sys module

除了sys.platform外,通过platform.system()也可以获取到当前系统平台:

Windows下运行:

Python commonly used standard libraries and third-party libraries 2-sys module

Linux下运行:

Python commonly used standard libraries and third-party libraries 2-sys module

适用场景

我们都知道Python是跨平台语言,只要操作系统安装了Python环境,那么同一份Python代码就可以既运行在Linux上,也可以运行在Windows上,亦或是Mac上。

而使用sys.platform或platform.system()获取到当前系统平台名称后,我们就可以针对性地作出不同操作,例如:

linux_content = "111111"
windows_content = "222222"

# 平台为Linux,执行逻辑1、发送文本1到指定邮件
if platform.system() == "Linux":
send_email(linux_content)
# 平台为Windows,执行逻辑2、发送文本2到指定邮件
elif platform.system() == "Windows":
send_email(windows_content)

4.sys.path-返回Python相关路径

基本用法

sys.path是Python的搜索模块的路径集,供Python从中查找模块,返回一个list。

print(sys.path)

Python commonly used standard libraries and third-party libraries 2-sys module

适用场景

如果是在IDE中执行Python程序,编译器会自动把当前项目的根目录加入到包查找路径中,可以理解为添加到环境变量下,所以直接执行是没有问题的。但是在cmd或是Terminal控制台中直接使用Python相关命令来执行程序,则不会自动将当前项目加入到PYTHONPATH环境变量下,如果涉及到import其他文件夹下的变量就会报类似"ModuleNotFoundError: No module named 'xxxx'"这样的错误。

解决方法:通过sys.path.append()方法将当前项目的根目录添加到系统环境变量中:

import sys

root_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(root_path)

5.sys.stdin与sys.stdout

  • Stdin:标准输入
  • Stdout:标准输出
  • Stderr:错误流

sys.stdin 与 input()

在Python中, input() 等价于 sys.stdin.readline()

① 先来看看使用input()的实现效果

# sys.stdin 与 input
number = input("please input a number:")
print("your input number is %s" % (number))

执行效果如下:

Python commonly used standard libraries and third-party libraries 2-sys module

② 再来看看使用sys.stdin.readline()的实现效果

print("please input a number:",)# 逗号表示不换行
nn = sys.stdin.readline()
print("your input number is %s" % (nn))

执行效果如下:

Python commonly used standard libraries and third-party libraries 2-sys module

sys.stdout 与 print()

在Python中, print() 等价于 sys.stdout.readline()

① 先来看看使用print()的实现效果

# sys.stdout 与 print
print("hello world")

执行效果如下:

Python commonly used standard libraries and third-party libraries 2-sys module

② 再来看看使用sys.stdin.write()的实现效果

sys.stdout.write("hello world")

执行效果如下:

Python commonly used standard libraries and third-party libraries 2-sys module

所以综上所述,input()+print() 结合的代码语句即可使用sys.stdin.readline()+sys.stdin.write()代替,如下:

sys.stdout.write("please input a number: n")
number = sys.stdin.readline()
sys.stdout.write("your input number is %s" % number)

执行效果如下:

Python commonly used standard libraries and third-party libraries 2-sys module

6 Other uses of the .sys module

  • sys.version: Get the Python interpreter version
  • sys.exc_info(): Return the exception information triplet
  • sys.getdefaultencoding(): Get the current encoding of the system, the default is utf-8
  • sys.setdefaultencoding(): Set the default encoding of the system
  • sys.getfilesystemencoding(): Get the file system Use the encoding method, the default is utf-8
  • sys.modules: Return all imported modules in the current Python environment in the form of a dictionary
  • sys.copyright: The current Python copyright information
  • sys.getrefcount(object): Returns the number of references to the object
  • sys.getrecursionlimit(): Returns the maximum recursion depth of Python, the default is 1000
  • sys.getsizeof(object[, default ]): Return the size of the object
  • sys.getwindowsversion(): Return the version information of the current windwos system

Summary

The sys module is a module that comes with Python , mainly used for interacting with the Python interpreter. It comes with many methods or attributes, among which:

1.sys.argv is used to transfer parameters from outside the program to the program, and it can obtain the command line parameter list. The argv list contains all parameters passed to the script:

  • sys.argv[0]: represents the program itself
  • sys.argv[1]: represents the first parameter of the program
  • sys.argv[2]: Indicates the second parameter of the program

2.sys.exit(n) is used to exit the program:

  • When n is 0: normal exit
  • When n is not equal to 0, abnormal exit will cause SystemExit exception

sys.exit(n) often captures SystemExit Used together with exceptions to control whether the program exits midway freely;

3.sys.platform is used to obtain the current Python running platform, similar to platform.system(), and is often used to target different operating systems. Make different operation logic;

4.sys.path is the path set of Python’s search module. Add the root directory of the current project to the system environment variable through the sys.path.append() method. You can use To solve the error report that the module cannot be found;

5. In Python, input() is equivalent to sys.stdin.readline(), and print() is equivalent to sys.stdout.readline().

The above is the detailed content of Python commonly used standard libraries and third-party libraries 2-sys module. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),