part10-1 Python common modules (sys module, os module)


Python has a strong third-party modules, these third-party modules in the practical application has been able to achieve a lot of features, usually you do not need to repeat Development Module with the same functions. In addition, Python language also built a number of modules, which have been very well, for example, a common date, time, regular expressions, JSON support, containers and others have a sound module. Then learn Python built-in module, but these modules is continually updated, more detailed module helps to see the Python library online reference manual, https: //docs.python.org/3/library/index.html.

A, sys module


sys module represents the Python interpreter, and is mainly used to obtain information related to the Python interpreter. In Python interactive interpreter (command line) is introduced into the sys module, the module can view the program element is provided, note that the module is not __all__ variables, for example:
>>> import sys
>>> [s for s in dir(sys) if not s.startswith('_')]
['api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder',
'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info',
'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks',
'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencodeerrors',
'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval',
'gettrace', 'getwindowsversion', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing',
'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform',
'prefix', 'ps1', 'ps2', 'set_asyncgen_hooks', 'set_coroutine_wrapper', 'setcheckinterval', 'setprofile',
'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version',
'version_info', 'warnoptions', 'winver']
Above all output sys module contains program unit (including variables, functions, etc.), all of these program units do not need to write down, in actual use, which modules to use Now go documentation and its corresponding reference cell phone can . Online sys module reference is https://docs.python.org/3/library/sys.html. 

The following common attributes and to understand the function of the sys module.
(1), sys.argv: get command line arguments to run Python programs. sys.argv [0] is the current Python program (file), sys.argv [1] is the first argument to the program Python, sys.argv [2] is the second parameter, to ...... forth.

(2), sys.byteorder: displaying an indicator of the native byte order. If the local byte is the big endian mode, the module returns Big; otherwise little.

(3), sys.copyright: which returns information about the copyright Python interpreter.

(4), sys.executable: This property returns the path Python interpreter stored on disk.

(5), sys.exit (): exceptions to exit the program by throwing SystemExit. It can not be prevented in a try block is performed finally block.

(6), sys.flags: This read-only property returns the specified run Python command flag.

(7), sys.getfilesystemencoding (): returns the file to save all of the characters in the current system, as utf-8, gbk like.

(8), sys.getrefcount (object) : Returns the object's reference count. When the reference object object count is 0, the object will be recovered.

(9), sys.getrecursionlimit (): Returns the Python interpreter currently supports recursion depth (default is 1000). This property can be reset by setrecursionlimit () method.

(10), sys.getswitchinterval (): Return time Python interpreter thread switching current interval (default 0.005). Available () function is changed by setswitchinterval.

(11), sys.implementation: Returns the current Python interpreter.

(12), sys.maxsize: returns the maximum integer supported by Python. On the platform 32-bit platform is 32-1,64 2 ** ** 63-1 2

(13 is), the sys.modules: module name and returns the corresponding dictionary relationship between the load module.

(14), sys.path: This attribute specifies a list of lookup module Python path. In the program may be dynamically increased load module Python path by modifying the attribute.

(15), sys.platform: Returns the identifier Python interpreter platform where the value of the windows platform is "win32".

(16), sys.stdin: return to the standard system of the input stream, a file-like object.

(17), sys.stdout: return to the standard output stream system, a file-like object.

(18), sys.stderr: returns the system error output stream, a file-like object.

(19), sys.version: Returns the current version information of the Python interpreter.

(20), sys.winver: Python interpreter returns the current major version number.

Some features sys module using the example below:
SYS Import 
# local display endian indicator being 
Print (sys.byteorder) Little # 
# display associated with the copyright information interpreter Python 
Print (sys.copyright) 
# return path Python interpreter stored on the disk 
print (sys. Executable) 
# display characters save files in the current system 
Print (sys.getfilesystemencoding ()) # UTF-8 
# to display the largest integer Python support 
Print (sys.maxsize) 
# show platform where Python interpreter 
print (sys. Platform) Win32 # 
# display version information interpreter Python 
Print (the sys.version) ...... # 3.6.5 
# Python interpreter returns the current version number of the master 
print (sys.winver) # 3.6 

running the above code, output is as follows: 
Little 
. Copyright (C) 2001-2018 the Python Software Foundation 
All Rights Reserved.

Copyright (c) 2000 BeOpen.com.
All Rights Reserved.

Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.

Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
C:\ProgramData\Anaconda3\python.exe
utf-8
9223372036854775807
win32
3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)]
3.6

1, access to operating parameters

argv sys module may acquire property run Python command line parameter file, the attribute value is a list argv, argv [0] is the file name of the Python, argv [. 1] is the second element of the argv list, the first file is run Python a parameter. Corresponding, argv [2] is the second parameter, .......

Argv below with reference to examples as described further parameters, argv_test.py now a new file, the code of the file is as follows:

from sys import argv 
length list # argv output 
print ( "argv length list is:", len (argv)) 
# traversing each element of the argv list 
for Arg in argv: 
  Print (Arg)

Code length output list argv, argv and each element of the list, the results of running the command line is as follows:

Command-line commands: python argv_test.py
output are:
the argv list length is:. 1
argv_test.py

Can be seen from the output, 1 is the length of the argv list, the first element is argv Python source file "argv_test.py". Let's continue to run at the command line:
Command-line commands: python argv_test.py hello world 
output are: 
the argv list length is: . 3 
argv_test.py 
Hello 
World
When this run behind Python source file "argv_test.py" added two parameters "hello world", the output can be seen from the length of the list is 3, from this operation can also be seen in command line operation, a space by default as the separator between the parameters, if the parameter itself contains spaces, the parameter is required ( "") enclose, a parameter is clear that, for example, run the following command as shown in double quotation marks:
Command-line commands: Python argv_test.py " Hello World " 
output is: 
the argv list length is: 2 
argv_test.py 
Hello World
Seen from the output, the length of the argv list 2, hello world can be considered as a parameter. If the command line to double quotes single quotes, hello world will not be seen as a parameter.

2, the dynamic path modification module loading

path attribute sys module can be changed dynamically load path Python module, provided that the first path is created. Since the attribute value is sys.path list, the list can be used directly append () method to be loaded dynamically added to the path, for example:

SYS Import 
# dynamically add e: \ mypymodule path as the path to the module loading 
sys.path.append ( 'E: \\ mypymodule') 
# load e: \ hello module under mypymodule path 
import hello
The code above to be able to run successfully, you need to create mypymodule directory in the E drive, and create hello.py module file in the directory.

Two, os module

os module is a module associated with the operating system, the operating system for getting information on where to run the program. Import module os Python interactive interpreter, available os .__ all__ command to view the public interface of the module, including all of the properties and functions. Properties and functions of the module there are many, only need to have common attributes and functions can be. The module's official website reference is https://docs.python.org/3/library/os.html. The following are common attributes and os module functions.

(1), os.name: Returns the name of the operating system dependent module is introduced, usually return 'posix', 'nt', one 'java' equivalent. 

(2), os.environ: return to the dictionary on the current system composed of all environment variables.

(3), os.fsencode (filename) : This function class path (path-like) encode the file name.

(4), os.fsdecode (filename) : This function class path (path-like) to decode the file name.

(5), PathLike: This is a class that represents a class path (path-like) object.

(6), os.getenv (key, default = None): Gets the value of the specified environment variable.

(7), os.getlogin (): Returns the current system login user name. Corresponding to the function has os.getuid (), os.getgroups (), os.getgid () function and the like, for acquiring a user ID, user group, the group ID, etc. These functions are usually only available on UNIX systems.

(8), os.getpid (): Get the current process ID.

(9), os.getppid (): Get the parent of the current process ID.

(10), os.putenv (key, value): This function is used to set the environment variables.

(11), os.cpu_count (): returns the number of the current system CPU.

(12), os.sep: separator return path.

(13), os.pathsep: Returns the separator between multiple paths on the current system. On windows is a semicolon (;); on UNIX systems and UNIX-colon (:).

(14), os.linesep: return newline of the current system. On Windows "\ r \ n"; on UNIX systems is "\ n"; on Mac OS X is "\ r".

(15), os.urandom (size) : Returns suitable for use as the encryption, the object of bytes up to size bytes thereof. The function returns the operating system by a specific source of randomness of random bytes, the random bytes, is generally unpredictable, for most scenes encryption.

 Partial function usage examples os module:

OS Import 
# import-dependent display module operating system name 
Print (The os.name) NT # 
# Get the value of environment variable PYTHONPATH 
Print (The os.getenv ( 'PYTHONPATH')) #; E:. \ mypymodule 
# Returns the current system log username 
print (os.getlogin ()) # Michael 
# gets the current process ID 
print (os.getpid ()) 
# get the current process of the parent process ID 
print (os.getppid ()) 
# returns the number of CPU current system of 
print ( os.cpu_count ()) #. 4 
# separator return path 
Print (os.sep) # \ 
# returns the current system a plurality of path separators 
Print (os.pathsep) #; 
# returns the current system newline 
print (os. linesep) # \ R & lt \ n- 
# returned suitable for use as the encryption, the object of bytes up to five bytes of 
print (os.urandom (5)) # b'v \ xc9! \ x11 * ' 

run code, the following output : 
NT
.;e:\mypymodule
michael
1832
10072
4
\
;


b'v\xc9!\x11*'

From the output can be seen in the Windows system Python import-dependent module operating system name is "nt"; the current logged-on user name michael system; the current process ID is 1832; the father of the current process ID is 10072; currently on the system are 4 a the CPU; the current path of the system separator is "\"; the current system of multiple paths separator is a semicolon (;); the current system is a newline "\ r \ n" (the output when converted into two blank lines).

os module has a function and the function of operating files and directories, which later part of the learning. Under os module also includes process management functions that can be used to start a new process, the process has been suspended and so on. os module functions associated with process management as follows:

 

(1), os.abort (): Generate a SIGABRT signal to the current process. On UNIX systems, the default behavior is to generate a kernel dump; on Windows systems, the process immediately returns an exit code 3. 

(2), os.execl (path, arg0, arg1, ...): This function has a similar system performance function, such os.execle (), os.execlp (), etc., these functions use the parameter list arg0, arg1, ... to execute the executable file path represented by the.

Note: os.exec * (POSIX functions are directly mapped system), so if you use this command to execute Python programs, the incoming parameters arg0 no effect. os._exit (n) for forced to exit Python interpreter. The block placed try to prevent the execution finally block.

(3), os.forkpty (): fork a child process.

(4), os.kill (pid, sig): sig signal transmitting process corresponding to the pid, to end the process.

(5), os.killpg (pgid, sig): sig sends a signal to the process group corresponding to pgid.

(6), os.popen (cmd, mode = 'r', buffering = -1): read and write pipe to open (when r is a read-only mode to pipeline cmd command, when the read-write mode is rw piping), buffering parameters and the built-in buffer open () function have the same meaning. This function returns the file object for reading and writing character string, instead of bytes.

(7), os.spawnl (mode, path, ...): This function also features a series of similar functions, such as os.spawnle (), os.spawnlp (), etc. These functions are used to perform in a new process new program.

(8), os.startfile (path [ , openation]): the use of tools associated with the file for the specified file to perform an operation corresponding openration. If you do not specify openration operation, the default implementation of open (open) operation. openration parameter must be a valid command line operation projects, such as open (open), edit (edit), print (print) and so on.

(9), os.system (command) : Specifies the command to run on the operating system.

os module functions associated with the example of process management function is as follows:

os Import, SYS 
cmd command to run on the platform # 
# os.system ( 'cmd') 
# use Excel to open the e: \ abc.xlsx file 
os.startfile ( 'e: \ abc.xlsx') 
os.spawnl (os. P_NOWAIT, r'C: \ Program files (x86) \ Geany \ bin \ geany.exe ',' ') 
# use Python command sys_test.py file 
path = sys.executable 
os.execl (path, "",' sys_test .py ',' i ')

Directly run the above code with the code editor tool, you can see the abc.xlsx use Excel to open the file after the program is running, also open Geany tool, also run sys_test.py file using python command. If os.system ( 'cmd') uncommented this line of code, you will see the program just started running cmd command-line program, it is because os.system a function to run the program, a new program where the process () It will replace the existing process.

Note: Use os.execl () function runs after a new process will replace the original process, and therefore the code above this line of code in the final.

Guess you like

Origin www.cnblogs.com/Micro0623/p/12145772.html