Python sys Module
sysis a module in the Python standard library that provides functions for interacting with the Python interpreter and its environment.
Throughsysthe library, you can access variables and functions related to the Python interpreter, such as command-line arguments, standard input/output, program exit, etc.
Import sys Library
To usesysthe library, you need to import it first. The import method is as follows:
import sys
Example
# List all attributes and methods of the os module
print(dir(os))
Common features of the sys library
1. Command-line arguments
sys.argvis a list containing command-line arguments.sys.argv[0]is the script name, and subsequent elements are arguments passed to the script.
Example code:
Example
print("Script name:", sys.argv[0])
print("Argument list:", sys.argv[1:])
How to run:
python script.py arg1 arg2
Output:
脚本名称: script.py 参数列表: ['arg1', 'arg2']
2. Program exit
sys.exit()Used to exit the program. You can pass an integer as the exit status code; usually0indicates success, while non-zero values indicate errors.
Example code:
Example
print("Program start")
sys.exit(0)
print("This line of code will not execute")
3. Standard input/output
sys.stdin、sys.stdoutandsys.stderrrepresent standard input, standard output, and standard error streams, respectively. You can redirect these streams to customize input/output behavior.
Example code:
Example
# Redirect standard output to a file
with open('output.txt', 'w') as f:
sys.stdout = f
print("This line will be written to output.txt")
# Restore standard output
sys.stdout = sys.__stdout__
print("This line will be displayed in the console")
4. Python version information
sys.versionandsys.version_infoprovides version information of the current Python interpreter.
Example code:
Example
print("Python version:", sys.version)
print("Version info:", sys.version_info)
Output:
<code>Python 版本: 3.9.7 (default, Aug 31 2021, 13:28:12) [GCC 7.5.0] 版本信息: sys.version_info(major=3, minor=9, micro=7, releaselevel='final', serial=0) </code>
5. Module search path
sys.pathis a list that contains the paths that the Python interpreter searches when importing modules. You can modify this list to add custom module search paths.
Example code:
Example
print("Module search path:", sys.path)
sys.path.append('/custom/path')
print("Updated module search path:", sys.path)
Common attributes of the sys module
| Attribute | Description |
|---|---|
sys.argv | Command-line argument list,sys.argv[0]is the script name |
sys.path | Python module search path (PYTHONPATH) |
sys.modules | dictionary of loaded modules |
sys.platform | operating system platform identifier (e.g.,'win32', 'linux', 'darwin') |
sys.version | Python interpreter version info |
sys.executable | absolute path of the Python interpreter |
sys.stdin | standard input stream (file object) |
sys.stdout | standard output stream (file object) |
sys.stderr | standard error stream (file object) |
sys.byteorder | byte order ('little'or'big') |
sys.maxsize | maximum integer value (2**31-1or2**63-1) |
Common methods of the sys module
| Method | Description |
|---|---|
sys.exit([status]) | exit the program,status=0indicates normal exit |
sys.getsizeof(obj) | returns the memory size in bytes occupied by the object |
sys.getdefaultencoding() | get default string encoding (usually'utf-8') |
sys.setrecursionlimit(limit) | set recursion depth limit (default1000) |
sys.getrecursionlimit() | get current recursion depth limit |
sys.getrefcount(obj) | return the reference count of the object |
sys.exc_info() | get current exception info ((type, value, traceback)) |
sys.settrace(tracefunc) | set debug tracing function |
sys.setprofile(profilefunc) | set profiling function |