Detailed --sys using the Python programming module (with examples)

A. Using the sys module

sys module Python language is a system built-in module, comprising automatically after installation Python library sys, without needing to install. Just import sys can be.

We can command dir (sys) View module methods available, for example:

>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_enablelegacywindowsfsencoding', '_getframe', '_git', '_home', '_xoptions', '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_wrapp
er', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'getwindowsversion', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizin
g', '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', 'versio
n', 'version_info', 'warnoptions', 'winver']

Here mainly introduce common methods sys module:

1. sys.argv-- achieve pass parameters to the program from the external program

sys.argv variable is a string that contains a list of command-line arguments, using a command line argument passed to the program. Among them, the name of the script is always the first argument in the sys.argv list.

import sys
print(sys.argv[0])         #sys.argv[0]表示代码本身的文件路径
print("命令行参数如下:")
for i in sys.argv:
    print(i)
 
命令行输入参数如下:
D:\st13\python\1.20\python lx.py Welcome to Xian
 
运行结果:
lx.py                #sys.argv[0]
命令行参数如下:
lx.py
Welcome
to
Xian
2. sys.path

Gets the module search path list of directory names, the first item in the list is the current working directory.
That is, the name of the directory import module position in the list, the first item in the list to the current position.

>>>import sys
>>> print(sys.path)
['', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\DLLs', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\lib', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages']
3. sys.exit([arg])

Intermediate program exits, arg = 0 for the normal exit. In general, the main program execution to the end, the interpreter automatically exit, but if you need to drop out program, you can call sys.exit function (0 is normal exit, the other is abnormal)

In the following example, the first print Hello, in performing the sys.exit (1), will be passed to the function as an argument, and then print out a program exits normally does not perform the latter statement will not print the world.

在这里插入代码片
4. sys.version-- get Python version information
>>> import sys
>>> sys.version
'3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)]'
5. sys.platform-- get the current system platform, returns the name of the operating system
>>> import sys
>>> sys.platform
'win32'
6. sys.getsizeof-- get the query of space.

There can be introduced following example: for the same elements, sorting memory space as follows: Digital tuple = <string <list <set.

>>> import sys
>>> number1=5
>>> str1='5'
>>> tup1=(5)
>>> list1=[5]
>>> set1={5}
 
>>> sys.getsizeof(number1)
28
>>> sys.getsizeof(str1)
50
>>> sys.getsizeof(tup1)
28
>>> sys.getsizeof(list1)
72
>>> sys.getsizeof(set1)
224
7. sys.modules-- return module of the system lead field

sys.modules is a global dictionary that is after the start Python loaded in memory. Whenever the programmer introducing new module, sys.modules will automatically record the module. When the second re-import the module, Python directly to the dictionary lookup, thereby speeding up the program running. It has all the dictionary methods have.

>>> import sys
>>> sys.modules['os']
<module 'os' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\lib\\os.py'>
8. sys.modules.keys () - returns all modules have been introduced
>>> import sys
>>> sys.modules.keys()
dict_keys(['sys', 'builtins', '_frozen_importlib', '_imp', '_thread', '_warnings', '_weakref', 'zipimport', '_frozen_importlib_external', '_io', 'marshal', 'nt', 'winreg', 'encodings', 'codecs', '_codecs', 'encodings.aliases', 'encodings.utf_8', '_signal', '__main__', 'encodings.latin_1', 'io', 'abc', '_abc', 'site', 'os', 'stat', '_stat', 'ntpath', 'genericpath', 'os.path', '_collections_abc', '_sitebuiltins', 'atexit'])
9. sys.modules.values ​​() - returns all of the modules, including the module path
>>> import sys
>>> sys.modules.values()
dict_values([<module 'sys' (built-in)>, <module 'builtins' (built-in)>, <module '_frozen_importlib' (frozen)>, <module '_imp' (built-in)>, <module '_thread' (built-in)>, <module '_warnings' (built-in)>, <module '_weakref' (built-in)>, <module 'zipimport' (built-in)>, <module '_frozen_importlib_external' (frozen)>, <module 'io' (built-in)>, <module 'marshal' (built-in)>, <module 'nt' (built-in)>, <module 'winreg' (built-in)>, <module 'encodings' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\lib\\encodings\\__init__.py'>, <module 'codecs' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\lib\\codecs.py'>, <module '_codecs' (built-in)>, <module 'encodings.aliases' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\lib\\encodings\\aliases.py'>, <module 'encodings.utf_8' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\lib\\encodings\\utf_8.py'>, <module '_signal' (built-in)>, <module '__main__' (built-in)>, <module 'encodings.latin_1' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\lib\\encodings\\latin_1.py'>, <module 'io' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\lib\\io.py'>, <module 'abc' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\lib\\abc.py'>, <module '_abc' (built-in)>, <module 'site' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site.py'>, <module 'os' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\lib\\os.py'>, <module 'stat' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\lib\\stat.py'>, <module '_stat' (built-in)>, <module 'ntpath' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\lib\\ntpath.py'>, <module 'genericpath' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\lib\\genericpath.py'>, <module 'ntpath' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\lib\\ntpath.py'>, <module '_collections_abc' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\lib\\_collections_abc.py'>, <module '_sitebuiltins' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\lib\\_sitebuiltins.py'>, <module 'atexit' (built-in)>])
10. sys.stdout / sys.stdin / sys.stderr

sys.stdout standard output; sys.stdin standard input; sys.stderr error output

>>> import sys
>>> sys.stdout
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>
>>> sys.stdin
<_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>
>>> sys.stderr
<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>
11. sys.getdefaultencoding() / sys.getfilesmencoding()
  • sys.getdefaultencoding (): Get the default encoding interpreter;
  • sys.getfilesystemencoding (): Gets memory data saved to a file in the default encoding.
>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
>>> sys.getfilesystemencoding()
'utf-8'

II. Application sys module

1, according to the above information, we can judge the specified module, determines whether the built-in modules.

import sys
print("Name is:",sys.argv[0])
 
def dump(module):
    print(module+'---->',end='')
    if module in sys.builtin_module_names:
        print("内建模块")
    else:
        module=__import__(module)
        print(module.__file__)
       
dump("sys")
dump("json")
dump("shelve")
dump("os")
dump("string")
dump("requests")
 
结果如下:
Name is: D:\st13\test\1.py
sys---->内建模块
json---->C:\Python36\lib\json\__init__.py
shelve---->C:\Python36\lib\shelve.py
os---->C:\Python36\lib\os.py
string---->C:\Python36\lib\string.py
requests---->C:\Python36\lib\site-packages\requests\__init__.py

2. In the following example, the main application of the sys module argv achieve a transfer from an external program into the program parameters by means of specific cases so that we can sys module, can have a more in-depth understanding.

import os
#import sys   这种方法导入sys模块,需使用sys.argv
from sys import argv  #这种方法导入sys模块,可直接使用argv
def ping(net,start=1,end=85,n=1,w=3):
    for i in range(start,end+1):
        ip=net+"."+str(i)
        command="ping %s -n %d -w %d"%(ip,n,w)
        print(ip,("通","不通")[os.system(command)])  #os.system(command):运行command命令
if len(argv) not in [2,4,6]:
    print("参数输入错误!")
    print("运行示例:")
    print("note1.py 121.194.14")
    print("note1.py 121.194.14 80 90")
    print("note1.py 121.194.14 80 90 3 1")
    print("语法:note1.py net startip endip count timeout")
elif len(argv)==2:
    net=argv[1]
    ping(net)
elif len(argv)==4:
    net=argv[1]
    ping(net,start=int(argv[2]),end=int(argv[3]))
else:
    net=argv[1]
    ping(net,start=int(argv[2]),end=int(argv[3]),n=int(argv[4]),

Guess you like

Origin blog.csdn.net/weixin_45116657/article/details/91876450
Recommended