Pythonでのosとsysの役割と違い



Role Difference Between Os



OSモジュール

自動テストでは、多くの場合、構成ファイルの検索(したがって構成ファイルの読み取り)、テストレポートの検索(したがってテストレポートメッセージの送信)などの操作ファイルを見つける必要があり、多くの場合、多数のファイルを処理します。ファイルと多数のパスの。 osモジュールに依存するため、今日より一般的に使用されている方法。インターネットにもたくさんの情報があります。整理するたびに、モジュールの使い方を深めるために学んだ知識を整理するだけです。



#OS The #os module is to operate the operating system. To use the module, you must first import the module: import os #getcwd() Get the current working directory (the current working directory defaults to the folder where the current file is located) result = os.getcwd() print(result) #chdir()Change the current working directory os.chdir('/home/sy') result = os.getcwd() print(result) open('02.txt','w') # If you write a complete path, you do not need to consider the default working directory, follow the actual writing path Open('/home/sy/Download/02.txt', 'w') #listdir() Get the list of names of all the contents in the specified folder result = os.listdir('/home/sy') print(result) #mkdir() Create a folder #os.mkdir('girls') #os.mkdir('boys',0o777) #makedirs() Recursively create a folder #os.makedirs('/home/sy/a/b/c/d') #rmdir() Delete empty directory #os.rmdir('girls') #removedirs Recursive deletion of folders must be empty directories #os.removedirs('/home/sy/a/b/c/d') #rename() Renaming a file or folder #os.rename('/home/sy/a','/home/sy/alibaba' #os.rename('02.txt','002.txt') #stat() Get information about a file or folder #result = os.stat('/home/sy/PycharmProject/Python3/10.27/01.py) #print(result) #system() Execute system command (dangerous function) #result = os.system('ls -al') #Get hidden files #print(result) # ''' An environment variable is a collection of commands The environment variable of the operating system is the set of directories in which the operating system searches for commands when executing system commands. ''' #getenv() Get the environment variables of the system result = os.getenv('PATH') print(result.split(':')) #putenv() Add a directory to the environment variable (temporary addition is only valid for the current script) #os.putenv('PATH','/home/sy/Download') #os.system('syls') #exit() Exit terminal command Common values ​​in the #os module #curdir indicates the current folder. Indicates the current folder. Generally, it can be omitted. print(os.curdir) #pardir indicates the folder above. .. indicates that the folder above is not to be omitted! print(os.pardir) #os.mkdir('../../../man')#relative path Find from the current directory #os.mkdir('/home/sy/man1')#Absolute path Find from the root directory #name Get the name string representing the operating system Print(os.name) #posix -> linux or unix system nt -> window system #sep Get system path interval symbol window -> linux ->/ print(os.sep) #extsep Get the interval symbol between the file name and the suffix window & linux -> . print(os.extsep) #linesep Get the line break of the operating system window -> linux/unix -> print(repr(os.linesep)) #import os module import os # is the contents of the os.path submodule #abspath() Convert a relative path to an absolute path Path = './boys'#relative result = os.path.abspath(path) print(result) #dirname() Get the directory part of the full path & basename() to get the body part of the full path path = '/home/sy/boys' result = os.path.dirname(path) print(result) result = os.path.basename(path) print(result) #split() Cut a complete path into a directory part and a body part path = '/home/sy/boys' result = os.path.split(path) print(result) #join() Combine 2 paths into one var1 = '/home/sy' var2 = '000.py' result = os.path.join(var1,var2) print(result) #splitext() Cuts a path into a file suffix and two other parts, mainly used to get the suffix of the file. path = '/home/sy/000.py' result = os.path.splitext(path) print(result) #getsize() Get the size of the file #path = '/home/sy/000.py' #result = os.path.getsize(path) #print(result) #isfile() Check if it is a file path = '/home/sy/000.py' result = os.path.isfile(path) print(result) #isdir() Check if it is a folder result = os.path.isdir(path) print(result) #islink() Check if it is a link path = '/initrd.img.old' result = os.path.islink(path) print(result) #getctime() Get the creation time of the file get create time #getmtime() Get the modification time of the file get modify time #getatime() Get the access time of the file get active time import time Filepath = '/home/sy/download/chls' result = os.path.getctime(filepath) print(time.ctime(result)) result = os.path.getmtime(filepath) print(time.ctime(result)) result = os.path.getatime(filepath) print(time.ctime(result)) #exists() Check if a path exists Filepath = '/home/sy/download/chls' result = os.path.exists(filepath) print(result) #isabs() Check if a path is an absolute path path = '/boys' result = os.path.isabs(path) print(result) #samefile() Check if 2 paths are the same file Path1 = '/home/sy/download /001' Path2 = '../../../Download /001' result = os.path.samefile(path1,path2) print(result) #os.environ Used to get and set the built-in value of system environment variables import os #Get system environment variable getenv() effect print(os.environ['PATH']) # System environment variable putenv() Os.environ['PATH'] += ':/home/sy/download' os.system('chls')

SYSモジュール

このモジュールは、インタプリタによって使用または維持されるいくつかの変数、およびインタプリタと強力に相互作用する関数へのアクセスを提供します。いつでもご利用いただけます



#!/usr/bin/env python # coding=utf-8 __author__ = 'Luzhuo' __date__ = '2017/5/8' # sys_demo.py sys interpreter related function # This module contains some variables of the interpreter and functions that interact with the interpreter import sys def sys_demo(): #default encoding print(sys.getdefaultencoding()) # Python version print(sys.version) # Add module path to search path sys.path.append('./module') # (function) print exception information try: 1 / 0 except: Types, value, back = sys.exc_info() # catch exception Sys.excepthook(types, value, back) # print exception #Input and output sys.stdout.write('>> ') sys.stdout.flush() strs = sys.stdin.readline()[:-1] Sys.stderr.write('The input is: {}'.format(strs)) sys.stderr.flush() def sys_func(): Lists = sys.argv # list of command line arguments passed to the Python script => python p.py -> ['p.py'] / python p.py a 1 -> ['p.py', 'a', '1'] / In-program execution -> [''] Strs = sys.getdefaultencoding() # default character set name Strs = sys.getfilesystemencoding() # system file name character set name Num = sys.getrefcount(object) # Returns the reference count of the object (1 more than the actual number) Dicts = sys.modules # loaded module, can be modified, but cannot be modified by modifying the returned dictionary Lists = sys.path # module search path Sys.path.append('./test') # Dynamically add module search path Strs = sys.platform # platform identifier (system identity for detailed checking, recommended) Linux: 'linux' / Windows: 'win32' / Cygwin: 'cygwin' / Mac OS X: 'darwin' Strs = sys.version # python interpreter version Lists = sys.thread_info # thread information Num = sys.api_version # Interpreter C API version Types, value, back = sys.exc_info() # Capture exceptions See exceptions The second part of the excep() code block of the article (http://blog.csdn.net/rozol/article/details/69313164) Sys.excepthook(types, value, back) # print exception types = sys.last_type value = sys.last_value back = sys.last_traceback # sys.exit([arg]) // Raises SystemExit exception to exit Python (can try), range [0,127], None==0, 'string'==1 sys.exit(0) Num = sys.getrecursionlimit() # maximum recursion number (stack maximum depth), see function article (http://blog.csdn.net/rozol/article/details/69242050) Sys.setrecursionlimit(5000) # modify the maximum number of recursions Fnum = sys.getswitchinterval() # Get thread switching interval Sys.setswitchinterval(0.005) # Set the thread switching interval, in seconds Num = sys.getcheckinterval() # Interpreter check interval Sys.setcheckinterval(100) # Set the interpreter check interval, execute (default) 100 virtual instructions to perform a check, check the value of each virtual instruction when the value is >') sys.stdout.flush() # sys.stderr // Annotate the error stream sys.stderr.write('>>') # --- Lists = sys.builtin_module_names # All modules (Note: non-imported modules) Path = sys.base_exec_prefix # Python installation path Path = sys.base_prefix # with base_exec_prefix Path = sys.exec_prefix # with base_exec_prefix Path = sys.prefix # with base_exec_prefix Path = sys.executable # absolute path to the Python interpreter Strs = ys.byteorder # native byte order indicator, big-endian (most significant byte first) value is 'big', little-endian (least significant byte first) value is 'little ' Strs = sys.copyright # python copyright Num = sys.hexversion # hexadecimal version number Lists = sys.implementation # Information about the currently running interpreter Num = sys.getallocatedblocks() # The number of memory blocks currently allocated by the interpreter Boolean = sys.dont_write_bytecode # Whether to try to import the source module is to write the .pyc file (False will write to the .pyc file) # sys.getsizeof(object[, default]) // Returns the size bit of the object, only calculates its own memory consumption, does not calculate the memory consumption of the reference object, calls the object's __sizeof__(), default does not get the default return value num = sys.getsizeof(object) Boolean = sys.is_finalizing() # Whether the interpreter is being shut down Num = sys.maxsize # maximum integer value (2 ** 31 -1), related to the system Num = sys.maxunicode # integer Unicode value integer (1114111) Strs = sys.ps1 # interpreter master prompt Strs = sys.ps2 # interpreter secondary prompt Sys.call_tracing(func, ('arg',)) # call function Sys._clear_type_cache() # clear internal type cache Sys._debugmallocstats() # Print low-level information about the state of the CPython memory allocator Sys.setprofile(profilefunc) # Set profile function, default None Sys.getprofile() # Get the profile function Sys.settrace(tracefunc) # Set the trace function, def tracefunc(frame, event, and arg): Sys.gettrace() # Get the trace function, default None Sys.set_coroutine_wrapper(wrapper) # Set the wrapper def wrapper(coro): Sys.get_coroutine_wrapper() # wrapper, default None if __name__ == '__main__': sys_demo() # sys_func() --------------------- Author: brucewong0516 Source: CSDN Original: https://blog.csdn.net/brucewong0516/article/details/78993697 Copyright statement: This article is the original article of the blogger, please attach the blog post link!