SoFunction
Updated on 2024-10-28

Python standard library sys module usage details

1. Introduction

"sys" means "system". The module provides interfaces for accessing variables used and maintained by the Python interpreter itself, as well as functions for deeper interaction with the interpreter.

2. Common functions

2.1

argv", short for "argument value", is a list object that stores the "command-line arguments" provided when calling a Python script from the command line. "when calling a Python script from the command line.

The first parameter in this list is the name of the script being called, that is, the "command" that invokes the Python interpreter (python ) itself is not added to this list. This is important to note because it differs from the behavior of C programs, which read command-line arguments from scratch.

For example, to create a new Python file in the current directorysys_argv_example.py , whose content is:

import sys
print("The list of command line arguments:\n", )

Run the script at the command line:

$ python sys_argv_example.py
The list of command line arguments:
 ['']

Add a couple of parameters and try it:

$ python sys_argv_example.py arg1 arg2 arg3
The list of command line arguments:
 ['', 'arg1', 'arg2', 'arg3']

The interactivity of Python scripts can be greatly enhanced by utilizing this property.

2.2

"Viewsys in the module attribute to get more detailed information about the platform on which it's running", and here we'll try it out:

>>> import sys
>>> 
'win32'

On Linux:

>>> 
'linux'

Compare. results, it is easy to see that the The information is more accurate.

2.3

"The term "byteorder" refers to whether the low byte of data is stored high or low in the memory space when data is stored inside a computer.

In "small end storage", the low bit of the data is also stored in the low address of the storage space, when the The value of the“little” . If you are not careful, you may mistype the contents stored at the small end when printing the contents in address order. CurrentMost machinesAll use small end storage.

So it should come as no surprise that the following interactive statement should be executed on your machine with the same results as mine:

>>> 
'little'

There is also a "big-end storage" order where the high byte of the data is stored at the low address of the storage space. The value of the“big”

This way seems to be very reasonable and natural, because we generally in the written representation of the low address will be written on the left, the high address is written on the right, the big end of the order of storage is very consistent with the human reading habits. But in fact, for machines, there is no difference between left and right memory addresses, and the so-called "natural" actually does not exist.

I'm sorry I don't have a machine with big-endian storage that I can use as a demo, so I can only say that if you run Python on a machine with big-endian storage, the output should look something like the following, which means that the following example is not a real run that I got, and it's just for reference:

>>> 
'big'

2.4

This attribute is a string whose value, under normal circumstances, is the absolute path to the location of the executable program corresponding to the currently running Python interpreter.

For example, Python installed on Windows using Anaconda, the value of this property is:

>>> 
'E:\Anaconda\Anaconda\'

2.5

This property is a dictionary containing a mapping of module names to module-specific locations for various loaded modules.

By modifying this dictionary manually, it is possible to reload certain modules; however, be careful not to accidentally remove basic entries, as this may render Python inoperable as a whole.

Regarding its specific value, due to too much content, I will not give an example here, the reader can check it by themselves.

2.6 sys.builtin_module_names

This attribute is a tuple of strings whose elements are the names of the built-in modules of the Python interpreter currently in use.

Note the difference cap (a poem)sys.builtin_module_names --The former keyword (keys) lists the imported module names, while the latter lists the module names built into the interpreter.

Examples of their values are shown below:

>>> sys.builtin_module_names
('_abc', '_ast', '_bisect', '_blake2', '_codecs', '_codecs_cn', '_codecs_hk', '_codecs_iso2022', '_codecs_jp', '_codecs_kr', '_codecs_tw', '_collections', '_contextvars', '_csv', '_datetime', '_functools', '_heapq', '_imp', '_io', '_json', '_locale', '_lsprof', '_md5', '_multibytecodec', '_opcode', '_operator', '_pickle', '_random', '_sha1', '_sha256', '_sha3', '_sha512', '_signal', '_sre', '_stat', '_string', '_struct', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', '_winapi', 'array', 'atexit', 'audioop', 'binascii', 'builtins', 'cmath', 'errno', 'faulthandler', 'gc', 'itertools', 'marshal', 'math', 'mmap', 'msvcrt', 'nt', 'parser', 'sys', 'time', 'winreg', 'xxsubtype', 'zipimport', 'zlib')

2.7

A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.

This attribute is a list of strings whose individual elements represent paths to Python search modules; it is initialized during program startup.

where the first element (that is, thepath[0] ) is the absolute path to the script that originally called the Python interpreter; if you're looking at it in an interactive environment, the value of value, you get an empty string.

Run the script from the command line (see example for script code)sys_path_example.py ):

$ python sys_path_example.py
The path[0] =  D:\justdopython\sys_example

Interactive environment view attribute first element:

>>> [0]
''

3. Advanced functions

3.1

That is, Python's standard input channel. By changing this attribute to some other file-like object, it is possible to redirect the input, i.e. to replace the standard input with something else.

The so-called "standard input" is actually the characters entered via the keyboard.

In the example (sys_stdin_example.py ) in which we try to change the value of this property to an open file objecthello_python.txt , which contains the following:

Hello Python!
Just do Python, go~
Go, Go, GO!

due toinput() It is the standard input stream that is used, so by modifying the value, we use our old friendinput() function, you can also achieve the contents of the file to read, the program runs as follows:

$ python sys_stdin_example.py
Hello Python!
Just do Python, go~
Go, Go, GO!

3.2

Similar to the previous "standard input". is an attribute that represents "standard output".

By changing the value of this property to some file object, you can write to a file what would otherwise be printed to the screen.

For example, to run the sample programsys_stdout_example.py It is also very convenient to use it for temporary log generation:

import sys
# Open the file in append mode, or create a new one if it doesn't exist
with open("count_log.txt", 'a', encoding='utf-8') as f:
     = f
    for i in range(10):
        print("count = ", i)

3.3

Similar to the previous two attributes, except that this attribute identifies a standard error, which is also usually directed to the screen, and can be crudely thought of as a special standard output stream that outputs an error message. Since the properties are similar, they are not demonstrated.

In addition.sys There are also several "private" properties in the module:sys.__stdin__ sys.__stdout__ sys.__stderr__ These attributes hold the "standard input", "standard output" and "standard error" streams that were originally targeted. These properties hold the "standard input", "standard output", and "standard error" streams that are initially oriented. At the appropriate time, we can use these three attributes to convert the cap (a poem) Restore to the initial value.

3.4 () and ()

() cap (a poem)() are paired. The former gets Python's maximum number of recursions, and the latter sets the maximum number of recursions. Since you'll rarely need them in the beginning, you'll only use them for informational purposes.

3.5 ()

() function whose return value is the number of times an object has been referenced in Python.

3.6 ()

This function is similar to the Csizeof operator is similar and returns the number of bytes occupied by the role object.

For example, we can look at an integer object1 Size in memory:

>>> (1)
28

Note that in Python, the size of an object of a certain class is not set in stone:

>>> (2**30-1)
28
>>> (2**30)
32

3.7 sys.int_info and sys.float_info

These two attributes each give information about two important data types in Python.

included among thesesys.int_info The value of:

>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)

Explained in the documentation as:

causality account for
bits_per_digit number of bits held in each digit. Python integers are stored internally in base  2**int_info.bits_per_digit
sizeof_digit size in bytes of the C type used to represent a digit

refers to Python's ability to use thesys.int_info.bits_per_digit The second power is used as a base to represent integers, i.e. it is the "2's".sys.int_info.bits_per_digit The number of "subdivided bytes". Such numbers are stored in 4 bytes each in the C class.

In other words, for every "1-bit" (i.e., an integer value that increases by 2 bits), a "1-bit" (i.e., an integer value that increases by 2 bits) is added.sys.int_info.bits_per_digit (the second power), you need to allocate 4 more bytes to store a certain integer.

thus in() In the example of the2**30-1 cap (a poem)2**30 The difference between the two is only 1, but the latter takes up 4 more bytes than the former.

(indicates contrast)sys.float_info The value of is then:

>>> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)

The specific implications of each of these will not be pursued here.

4. An interesting feature

Let's relax next.

Every time we open Python's interactive interface, we're greeted with the prompt>>> . I wonder if you've thought about replacing this with something else?

I hadn't thought about it anyway haha - at least I really hadn't thought about those two attributes until I saw them in the documentation. Which two properties?

Just the two of them:sys.ps1 cap (a poem)sys.ps2

The so-called "ps" should be the abbreviation of "prompts", that is, "prompt".

Of these two attributes, thesys.ps1 represents the first-level prompt, which is the one that appears once you enter the Python interface.>>> and the secondsys.ps2 It is the second level prompt, which is the prompt at the beginning of a new line after a line break when the content of the same level has not been typed.... . Of course, both properties are strings.

Well, it's good to know what's going on.

Now we'll have one:

>>> sys.ps1 = "justdopython "
justdopython li = [1,2,3]
justdopython li[0]
1
justdopython 

The prompter has been changed, but of course, it's a bit long and not very aesthetically pleasing haha.

Let's switch:

justdopython sys.ps1 = "ILoveYou: "
ILoveYou: print("What a little wit you are!")
You're such a smart ass.!
ILoveYou:

It's kind of fun, isn't it?

Note do not forget to add a space at the end of the string, otherwise the prompt will be mixed with the contents of your input, it will be very difficult to see yo~!

Above is the Python standard library of sys module details, more information about Python sys module please pay attention to my other related articles!