最後更新: 2015-10-12
Sys Class
This module provides access to some variables used or maintained by the interpreter
目錄
- sys.exit()
- version
- sys.argv
- getopt()
import
import sys
sys.exit()
sys.exit() # 相當於 sys.exit(0)
Exit code: 0
version
print(sys.version)
3.6.8 (default, Oct 25 2023, 15:15:22) [GCC 8.5.0 20210514 (Red Hat 8.5.0-20)]
print(sys.version_info)
sys.version_info(major=3, minor=6, micro=8, releaselevel='final', serial=0)
sys.argv
The list of command line arguments passed to a Python script. argv[0] is the script name
Code:
sys.argv.py
import sys print sys.argv print len(sys.argv)
./sys.argv.py 123 456
['./sys.argv.py', '123', '456'] 3
./sys.argv.py -n 123 -m 456
['./sys.argv.py', '-n', '123', '-m', '456'] 5
getopt
Helps scripts to parse the command line arguments in sys.argv
option, value = getopt.getopt(args, options[, long_options])
args
The argument list to be parsed
i.e.
# without the leading reference to the running program
sys.argv[1:]
options
The string of option letters that the script wants to recognize
當 options 必須帶 argument 時必須加上 colon ':'
i.e
# -f -t X -m
"ft:m"
long_options
The leading '--' characters should not be included in the option name
short & long options
short options: -fV
long options: --foo=V
Example
>>> import getopt >>> args = '-a -b -cfoo -d bar a1 a2'.split() >>> args ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2'] >>> optlist, args = getopt.getopt(args, 'abc:d:') >>> optlist [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')] >>> args ['a1', 'a2']