Python standard library sys
The sys module includes a set of very practical services, including many function methods and variables, used to handle Python runtime configuration and resources, so that it can interact with system environments outside the current program, such as: python interpreter.
List of common functions of the sys module (import sys):
function | illustrate |
---|---|
dir(sys) | The dir() method views the methods available in the module. Note: If you are in the editor, be sure to declare the encoding method of the code in advance, otherwise the Chinese will be garbled. |
Implement the passing of parameters from outside the program to the program | |
([arg]) | Exit in the middle of the program, arg=0 is a normal exit |
() | Get the current code of the system, generally default to ascii |
() | Set the system default encoding. You won’t see this method when executing dir(sys). If you fail to execute in the interpreter, you can execute it first. |
reload(sys), | Then execute setdefaultencoding('utf8') and set the system encoding to utf8 |
() | Get the file system encoding method, return 'mbcs' in Windows, and return 'utf-8' in Mac |
Get the string collection of the specified module search path. You can place the written module under a certain path you get and you can find it correctly when importing it in the program. | |
Get the current system platform. | |
The stdin, stdout, and stderr variables contain stream objects corresponding to standard I/O streams. If you need better control over the output and prints don't meet the requirements, they are what you need. You can also replace them, redirect output and input to other devices, or process them in a non-standard way. | |
It is a global dictionary, which is loaded in memory after python is started. Whenever a programmer imports a new module, the module will be automatically recorded. When the module is imported the second time, python will search directly into the dictionary, thereby speeding up the program's running. It has all the methods that a dictionary has. |
Python Standard Library OS
The os module is responsible for the interaction between the program and the operating system and provides an interface to access the underlying operating system.
List of common functions of the os module (import os):
Function - Description:
A dictionary contains the mapping relationship of environment variables
Show the currently used platform
Display path separator under the current platform
Give the line terminator used by the current platform
('filename') Delete a file
("oldname", "newname") Rename the file
() Show the current working path of python script
(dir) Change the current directory, note that escape is used under Windows
('dirname') Returns all files and directory names in the specified directory
(‘dirname/dirname’) can generate multi-layer delivery directory
(‘dirname’) Delete single-level directory
() Get the user login name
('key') Get environment variable configuration
('key') Set environment variables
() Run the shell command. Note: Here is to open a new shell and run the command. When the command is finished, close the shell.
Operation example:
('/tmp/xx'),("echo'hello' > /tmp/xx/"),('/tmp/xx') ('/tmp/xx/','/tmp/xx/'),('/tmp/xx/'),('/tmp/xx')
Write a simple shell in python:
#!/usr/bin/python import os, sys cmd = (); while cmd: (cmd); cmd = ();
Function-Description:
() Get the absolute path ("") == ((),"")
() is used to separate the directory part and the file name part in a directory name.
Characters representing the previous level directory under the current platform…
(path, name) Connect directory and file name.
(path) Returns the file name
(path) Returns the file path
("/root/") Returned ctime (create time) timestamp
(()) Determine whether the file exists
(()) Determine whether it is a file name, 1 is 0 is
(‘c:\Python\temp') determines whether it is a directory, 1 is 0 is not
('/home/') Whether it is a symbolic connection, it is not available under Windows
(()) Whether it is a file system installation point, it is not available under Windows
((), ‘/home’) See if the two file names refer to the same file
() Can traverse all directories and files in a given directory.
('/home/huaying', test_fun, "") Traverse all subdirectories under /home/huaying, including this directory, and the function test_fun will be called for each directory.
The difference between
Function declaration: (top, topdown=True,None)
1. Parameter top represents the path to the top-level directory that needs to be traversed.
2. The default value of parameter topdown is "True" to first return the file in the top-level directory, and then iterate over the files in the subdirectory. When the value of topdown is "False", it means that the files in the subdirectory are traversed first, and then return to the files in the top-level directory.
3. The default value of the parameter onerror is "None", indicating that the error during file traversal is ignored. If it is not empty, a custom function is provided to prompt the error message and continue to traverse or throw an exception to abort traversal.
Return value: The function returns a tuple containing three elements. These three elements are: the path name of each traversal, the subdirectory list under the path, and the file list under the directory.
Function declaration: (top, func, arg)
1. Parameter top represents the directory path that needs to be traversed.
2. The parameter func represents a callback function, that is, a function that processes the traversal path. The so-called callback function is used as a parameter of a certain function. When triggered at a certain time, the program will call the defined callback function to handle a certain task. Note: The callback function of walk must provide three parameters: the first parameter is arg, the second parameter represents the directory dirname, and the third parameter represents the file list names. Note: The file list in the callback function does not separate the subdirectory and the file from the same as () but is confused. It is necessary to determine whether it is a file or a subdirectory in the callback function.
3. The parameter arg is a tuple passed to the callback function, providing processing parameters for the callback function, and arg can be empty. The first parameter of the callback function is used to receive the incoming tuple.
Procedure: Each directory in the directory tree rooted with top (including the top itself, if it is a directory), and call the callback function function with parameters (arg, dirname, names). Parameter dirname specifies the directory to be accessed, and parameter names lists the files in the directory (get from (dirname). The callback function can modify names to change the settings of the directory accessed under dirname, for example, to avoid accessing a part of the tree. (Objects associated with names must be modified in the appropriate location, assigned with del or slice.) Note: Symbol connections to directories are not processed as a subdirectory, and therefore walk() will not access them. The directory accessing the connection must be identified by (file) and (file), and walk() must be called.
Difference: The file name list generated by () and () are not the same. () generates the directory path and file path under the directory tree, while () only generates the file path (a mixed list of subdirectories and files).
Example:
#coding=utf-8 importos #Current level directory characters on the platform..print() # (__file__) :Absolute path# Get the absolute path (directory plus current file name)print((__file__)) # (()) Used to separate the directory part and the file name part in a directory name.# Get the absolute directory (no file name)print(()); print(((__file__))[0]) # Table of contentsprint(((__file__)))# is equivalent to the previous sentence# Splice file directory and file nameprint((((__file__)), ) ) # Get the parent directory# The path name of the current directory, that is, the parent directory ((): displays the current path, and the current file name will not be displayed)print((())); print((((), )) )
For more information about the use of python standard library sys and OS, please see the related links below