Python built-in module (SYS)--033

Source: Internet
Author: User

The SYS module provides a series of variables and functions for the Python runtime environment.

Common usage

First, SYS.ARGV
You can use SYS.ARGV to get the list of parameters for the command line arguments that are currently executing.

Variable

Explain

SYS.ARGV[0]

Current program Name

SYS.ARGV[1]

First parameter

SYS.ARGV[2]

A second parameter

Reference code:

# encoding:utf-8# Filename:argv_test.pyimport sys# Get script name print ' The name of this program is:%s '% (Sys.argv[0]) # get parameter list P Rint ' The command line arguments is: ' For I in SYS.ARGV:    print i# statistic parameter number print ' There is%s arguments. '% ( Len (SYS.ARGV)-1)

  

Operation Result:

E:\p>python argv_test.py arg1 arg2 arg3the name of this program is:argv_test.pyThe command line arguments are:argv_tes T.pyarg1arg2arg3there is 3 arguments.

Get the parameters in the script:

  

Import Sysprint ("script name is%s"% (Sys.argv[0])) #获取当前正在执行的命令行参数的参数列表 (list) print (SYS.ARGV) #获取脚本传入的第一个参数sys. argv[1], Get the second parameter Sys.argv[2]print (sys.argv[1],sys.argv[2]) #遍历所有传入脚本的参数for i in range (1,len (SYS.ARGV)):    print (i)

Operation Result:

E:\python-project>c:\python-3.5\python.exe os_test.py 1 2 3 The script name is os_test.py[' os_test.py ', ' 1 ', ' 2 ', ' 3 ']1 2123

  

Second, Sys.platform

Gets the platform for the current execution environment, such as Win32, which is the Windows 32bit operating system, LINUX2 represents the Linux platform;

# Linux >>> import sys>>> sys.platform ' linux2 ' # windows>>> import sys>>> Sys.platform ' Win32 '

  

Third, Sys.path

Path is a directory listing from which Python looks for third-party extensions. When Python starts, Sys.path is initialized according to the built-in rules, pythonpath variables.

>>> sys.path[", ' e:\\python27\\lib\\idlelib ', ' C:\\Windows\\ System32\\python27.zip ', ' e:\\python27\\dlls ', ' e:\\python27\\lib ', ' E:\\python27\\lib\\plat-win ', ' E:\\Python27\\ Lib\\lib-tk ', ' e:\\python27 ', ' e:\\python27\\lib\\site-packages '] sometimes in order for Python to find our own defined modules, we need to modify the contents of the Sys.path, such as: # Insert Test>>> sys.path.insert (0, ' test ') at the beginning of path >>> sys.path[' test ', ', ' e:\\python27\\lib\\ Idlelib ', ' c:\\windows\\system32\\python27.zip ', ' e:\\python27\\dlls ', ' e:\\python27\\lib ', ' E:\\Python27\\lib\\ Plat-win ', ' e:\\python27\\lib\\lib-tk ', ' e:\\python27 ', ' e:\\python27\\lib\\site-packages ']# can be successfully import test> >> Import test# cannot find other this module >>> import othertraceback (most recent call last): File "<pyshell#10>" , line 1, <module> import otherimporterror:no module named other# need to add path>>> sys.path.insert (0, ' oth Er ') >>> import other can also use Sys.path.append ("Mine module Path") to add a custom module. 

  

Iv. Sys.builtin_module_names

Sys.builtin_module_names returns a list containing the names of the built-in modules. Such as:

>>> Import sys>>> Print sys.builtin_module_names (' __builtin__ ', ' __main__ ', ' _ast ', ' _bisect ', ' _ Codecs ', ' _codecs_cn ', ' _codecs_hk ', ' _codecs_iso2022 ', ' _codecs_jp ', ' _codecs_kr ', ' _codecs_tw ', ' _collections ', ' _ CSV ', ' _functools ', ' _heapq ', ' _hotshot ', ' _io ', ' _json ', ' _locale ', ' _lsprof ', ' _md5 ', ' _multibytecodec ', ' _random ', ' _s ' Ha ', ' _sha256 ', ' _sha512 ', ' _sre ', ' _struct ', ' _subprocess ', ' _symtable ', ' _warnings ', ' _weakref ', ' _winreg ', ' array ', ' a ' Udioop ', ' binascii ', ' cpickle ', ' Cstringio ', ' Cmath ', ' datetime ', ' errno ', ' exceptions ', ' future_builtins ', ' GC ', ' Imageop ', ' imp ', ' itertools ', ' Marshal ', ' math ', ' mmap ', ' MSVCRT ', ' nt ', ' operator ', ' parser ', ' signal ', ' strop ', ' sys ', ' Thread ', ' time ', ' xxsubtype ', ' zipimport ', ' zlib ')

code example:

# encoding:utf-8# find_module.pyimport sys# print sys.builtin_module_namesdef find_module (module):    if module in sys . Builtin_module_names:        print module, "= =", "__builtin__"    else:        print module, "= =", __import__ ( module). __file__find_module (' OS ') find_module (' sys ') find_module (' Strop ') find_module (' zlib ') find_module (' String ' )

  

# Run Result:

>>> ======================== restart:e:/p/find_module.py ========================os =  E:\Python27 \lib\os.pycsys  = __builtin__strop  = __builtin__zlib  = __builtin__string = >  E:\PYTHON27\LIB\STRING.PYC

  

V. Sys.exit (n)

Calling Sys.exit (n) can exit the program halfway, and when the argument is not 0 o'clock, a Systemexit exception is thrown, allowing the exception to be caught in the main program.

Look at the code:

# encoding:utf-8import Sysprint ' running ... ' try:    sys.exit (1) except Systemexit:    print ' systemexit exit 1 ' Print ' Exited '

  

Operation Result:

>>> ======================= restart:e:/p/sys_exit_test.py =======================running ... Systemexit Exit 1exited

  

You can also customize the Exitfunc method to call before the program exits and perform some cleanup actions.

Refer to Python sys.exitfunc Examples for details

Python built-in module (SYS)--033

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.