


Python 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))
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:
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:
- When n is 0: normal exit When n is not equal to 0, abnormal exit will trigger SystemExit Exception
# 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")
- The program first Execute print("start sys")Then execute the try statement, call sys.exit(888)Then capture the system exception, the value of the captured SystemExit exception is 888Finally call the exit_function function and pass the value 888 to the exit_function function In the exit_function function, execute the statement, print the captured value value, and finally call sys.exit(0) to exit the program
上个示例的执行结果可以看到在exit_function函数中调用sys.exit(0),此时程序就会退出,不会再执行print("end sys"),而当在exit_function函数中注释掉sys.exit(0),则会继续执行最后的代码print("end sys"),即:程序中途不退出,如下所示:
3.sys.platform-获取当前Python运行平台
基本用法
print(sys.platform)
Windows下运行:
Linux下运行:
除了sys.platform外,通过platform.system()也可以获取到当前系统平台:
Windows下运行:
Linux下运行:
适用场景
我们都知道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)
适用场景
如果是在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))
执行效果如下:
② 再来看看使用sys.stdin.readline()的实现效果
print("please input a number:",)# 逗号表示不换行 nn = sys.stdin.readline() print("your input number is %s" % (nn))
执行效果如下:
sys.stdout 与 print()
在Python中, print() 等价于 sys.stdout.readline()
① 先来看看使用print()的实现效果
# sys.stdout 与 print print("hello world")
执行效果如下:
② 再来看看使用sys.stdin.write()的实现效果
sys.stdout.write("hello world")
执行效果如下:
所以综上所述,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)
执行效果如下:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
