Home > Article > Backend Development > Detailed explanation of the use of sys.argv[]
sys.argv[] is used to obtain command line parameters, sys.argv[0] represents the file path of the code itself; for example, enter "python test.py -help" on the CMD command line, then sys.argv[0] stands for "test.py".
sys.startswith() is used to determine what an object starts with. For example, entering "'abc'.startswith('ab')" on the python command line will return True
For reference to the following examples:
# !/usr/local/bin/env python
import sys
def readfile(filename):
'''Print a file to the standard output.'''
f = file(filename)
while True:
line = f.readline()
if len ( argv[0] . --------", sys.argv[2]
# Script starts from here
if len(sys.argv) print 'No action specified.'
if sys.argv[1].startswith(' --'):
option = sys.argv[1][2:]
# fetch sys.argv[1] but without the first two characters
if option == 'version': print 'Version 1.2'
elif option == 'help': : Display this help '' '
Print' unknown option.'
sys.exit ()
Le Filename in sys.argv [1:]:
Readfile (FILENAME)
execute results:# python T EST .py --version help
sys.argv[0]--------- test.py
sys.argv[1]--------- --version
sys.argv[2 ]--------- help
Version 1.2
Note: sys.argv[1][2:] means intercepting from the second parameter, starting from the third character to the end. The result in this example is :version