web123456

0 Basic learning Python path (27) sys module

Detailed explanation of Python sys module

1. Introduction

"sys" means "system", which means "system". This module provides some interfaces for accessingPython interpreterVariables for use and maintenance, and a portion of the module is also provided in thefunction, can be withInterpreterConduct a more in-depth interaction.

2. Common functions

2.1

"argv" is the abbreviation of "argument value", which is a list object that stores "command line parameters" provided when calling Python scripts on the command line.

The first parameter in this list is the name of the script being called, that is, the "command" that calls the Python interpreter (python) itself is not added to this list. Pay attention to this point, because this is different from the behavior of C programs, which start from scratch when reading command line parameters.

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

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

Run the script on the command line:

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

Try adding a few parameters:

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

Taking advantage of this property can greatly enhance the interactivity of Python scripts.

2.2

ChecksysIn the moduleProperties can get more detailed information about running the platform

  1. >>> import sys
  2. >>>
  3. 'win32'

existLinuxsuperior:

  1. >>> sys.platform
  2. 'linux'

CompareThe result is not difficult to find.The information is more accurate.

2.3

"byte order" means "endian order", which refers to the high or low bits of the data being stored in the storage space when storing data internally bytes of the data.

When "little-end storage", the low bit of the data is also stored in the low bit address of the storage space.The value of“little”. If you are not careful, when printing content in the order of address, the content stored in the little endian may be mis-printed. currentMost machinesAll are used for small-endian storage.

So if nothing unexpected happens, the following interactive statements on your machine should be the same as my results:

  1. >>>
  2. 'little'

There is also a storage order that is "big-end storage", that is, the high-bit bytes of the data are stored at the low-bit address of the storage space.The value of“big”

This method seems very reasonable and natural, because when we usually express it in writing, we write the low address on the left and the high address on the right. The order of storage in the big-end is very consistent with human reading habits. But in fact, for machines, there is no difference between memory addresses, and the so-called "natural" does not actually exist.

Sorry, I don't have a machine that uses big-endian storage to use as a demonstration, so I can only say that if Python is running on a machine with big-endian storage, the output should be like the following, which means that the following example is not the real running result I got, for reference only:

  1. >>>
  2. 'big'

2.4

This property is a string, and under normal circumstances, its value is the absolute path to the executable program corresponding to the currently running Python interpreter.

For exampleWindowsPython installed using Anaconda, the value of this property is:

  1. >>>
  2. 'E:\\Anaconda\\Anaconda\\'

2.5

This property is a dictionary that contains mappings from module names to module specific locations of various loaded modules.

By manually modifying this dictionary, you can reload certain modules; but be careful not to accidentally delete some basic items, otherwise it may cause Python to fail to run.

Regarding its specific value, due to too much content, no example is given here, and readers can view it themselves.

2.6 sys.builtin_module_names

This property is a string tuple, and the elements are the built-in module names of the Python interpreter currently in use.

Pay attention to the differenceandsys.builtin_module_names——The former keyword (keys) list the imported module name, while the latter is the built-in module name of the interpreter.

Examples of its values ​​are as follows:

  1. >>> sys.builtin_module_names
  2. ('_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 property is a list of strings, where each element represents the path to the Python search module; it is initialized during program startup.

The first element (that is,path[0]) value is the absolute path where the script that originally called the Python interpreter is located; if viewed in an interactive environmentThe value of , and an empty string will be obtained.

Run the script on the command line (see example for script codesys_path_example.py):

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

Interactive environment to view the first element of the attribute:

  1. >>> [0]
  2. ''

3. Advanced functions

3.1

That is, Python's standard input channel. By changing this property to other file-like objects, input redirection can be achieved, that is, other content can be replaced with standard input content.

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

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

  1. Hello Python!
  2. Just do Python, go~
  3. Go, Go, GO!

becauseinput()The standard input stream is used, so it is modifiedWe use old friendsinput()Functions can also realize the reading of file contents, and the program running effect is as follows:

  1. $ python sys_stdin_example.py
  2. Hello Python!
  3. Just do Python, go~
  4. Go, Go, GO!

3.2

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

By modifying the value of this property to a file object, the content that was originally printed to the screen can be written to the file.

For example, run the sample programsys_stdout_example.py, it is also very convenient to temporarily generate logs:

  1. import sys
  2. # Open the file in additional mode, if it does not exist, create a new one
  3. with open("count_log.txt", 'a', encoding='utf-8') as f:
  4. = f
  5. for i in range(10):
  6. print("count = ", i)

3.3

Similar to the previous two attributes, except that this attribute identifies a standard error, which is usually directed to the screen, and can be roughly considered as a special standard output stream that outputs error messages. Due to the similar nature, no demonstration is made.

also,sysThere are also several "private" properties in the module:sys.__stdin__sys.__stdout__sys.__stderr__. What these properties hold are the initially directed "standard input", "standard output" and "standard error" streams. At the right time, we can use these three attributes toandRevert to the initial value.

3.4 () and ()

()and()It's paired. The former can get the maximum Pythonrecursionnumber, the latter can set the maximum recursive number. Because it is rarely used in the beginner stage, I only need to understand it.

3.5 ()

existPython QuotationsThis function has actually been used in the first instance, and its return value is the number of times an object in Python is referenced. For knowledge about "citations", you can go back and read this article.

3.6 ()

The function of this function is similar to that in C languagesizeofThe operator is similar, returning the number of bytes occupied by the object.

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

  1. >>> (1)
  2. 28

Note that in Python, the size of a certain type of object is not static:

  1. >>> (2**30-1)
  2. 28
  3. >>> (2**30)
  4. 32

3.7 sys.int_info and sys.float_info

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

insys.int_infoThe value is:

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

The explanation in the documentation is:

property explain
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 with 2sys.int_info.bits_per_digitTo the power of the integer is represented by the basis, that is, it is "2"sys.int_info.bits_per_digit"The power of the number is ". Each such number is stored in 4 bytes in class C.

In other words, every "1 bit" (i.e., the integer value is increased by 2sys.int_info.bits_per_digitTo the power), you need to allocate 4 more bytes to save an integer.

Therefore, in()In the example, we can see2**30-1and2**30Although it is only 1 different, the latter occupies 4 more bytes than the former.

andsys.float_infoThe value is:

  1. >>> sys.float_info
  2. 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 meanings of these will not be continued here

4. An interesting feature

Let's relax next.

Every time we open the interactive interface of Python, we will see a prompt>>>. I wonder if you have ever thought about changing this thing to something else?

Anyway, I haven't thought about it - at least I didn't think about it before seeing these two properties in the documentation. Which two attributes?

Just these two:sys.ps1andsys.ps2

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

Among these two properties,sys.ps1It represents a first-level prompt, which is the one that will appear after entering the Python interactive interface.>>>; and the second onesys.ps2It is a second-level prompt, which is a prompt at the beginning of the new line after the new line is not entered at the same level..... Of course, both properties are strings.

OK, it's easy to do if you know what's going on.

Now let's have one:

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

The prompt has been changed, of course, it is a bit long and not very beautiful haha.

Let's change it:

  1. justdopython sys.ps1 = "ILoveYou: "
  2. ILoveYou: print("You are such a clever little guy!")
  3. You are such a clever little guy!
  4. ILoveYou: