SYS module's function
SYS is a more commonly used module in Python, and provides operations on the environment where the Python script runs.
SYS function:
1 sys.argv #将python脚本运行时的脚本名以及参数作为一个list, and output.
#test_py.py File#/usr/bin/python3ImportSYSPrint('The script name is:', sys.argv[0])ifLen (SYS.ARGV) > 1: Print("there is", Len (SYS.ARGV)-1,"arguments:")#use Len (SYS.ARGV)-1 to collect the number of parameters-1 for minus [0] script name forArginchSys.argv[1:]:#output all parameters except [0] Print(ARG)Else: Print("there is no arguments!") [[email protected]~]#python3 test_py.py hahaThe script name is: Test_py.pythere is1Arguments:haha
View Code
2 Sys.path #返回一个list, the list is the PATH environment variable (PYTHONPATH) for the current script
>>> sys.path['/usr/local/python/lib/python34.zip' /usr/local/python/lib/python3.4'/usr/local/python/lib/python3.4/ Plat-linux'/usr/local/python/lib/python3.4/lib-dynload' '/usr/local/python/lib/python3.4/site-packages']
View Code
If we want to add or remove Pythonpath, we can use the Insert or pop function of list.
ImportOs,sysPrint(Sys.path) New_path=os.path.dirname (Os.path.dirname (Os.path.abspath (__file__)))Print(New_path) Sys.path.insert (0,new_path)Print(Sys.path)#Results:['C:\\users\\capital-d\\pycharmprojects\\untitled\\test\\atm\\fun','c:\\users\\capital-d\\pycharmprojects\\untitled','C:\\windows\\system32\\python34.zip','C:\\python34\\dlls','C:\\python34\\lib','C:\\python34','c:\\python34\\lib\\site-packages']c:\users\capital-d\pycharmprojects\untitled\test\atm['C:\\USERS\\CAPITAL-D\\PYCHARMPROJECTS\\UNTITLED\\TEST\\ATM','C:\\users\\capital-d\\pycharmprojects\\untitled\\test\\atm\\fun','c:\\users\\capital-d\\pycharmprojects\\untitled','C:\\windows\\system32\\python34.zip','C:\\python34\\dlls','C:\\python34\\lib','C:\\python34','c:\\python34\\lib\\site-packages']
View Code
3 Sys.platform #返回当前平台
Import Sys,os Print (Sys.platform) # Results:Win32
View Code
4 sys.stdout Sys.stdin #标准输出/input
Print 'Dive in' #Standard OutputSaveout = Sys.stdout#save stdout before redirection, so you can then set it back to normalFsock = open ('Out.log','W')#opens a new file for writing. If the file does not exist, it will be created. If the file exists, it will be overwritten. Sys.stdout = Fsock#all subsequent output will be redirected to the new file that was just opened. Print 'This message would be logged instead of displayed' #This will only "print" the output to the log file, and the output will not be visible on the screen.Sys.stdout= Saveout#before we mess up the stdout, let's set it back to the original way. fsock.close ()#close the log file.
View Code
5 Sys.stderr #错误输出
Using the same method as above
The Sys module of the Python-based module