Sys.argv[] is used to get command line arguments, Sys.argv[0] represents the code itself file path, such as the cmd command line input “python test.py-help”, then sys.argv[0] is representative of “test.py”.
Sys.startswith () is used to determine what an object begins with, such as entering “ ' in a python command line ABC '. StartsWith (' ab ') ” will return True
The following example references:
#!/usr/local/bin/env pythonimport sysdef ReadFile (filename): ' Print a file to the standard output. ' f = file (filename) while true:line = F.readline () If Len (line) = = 0:break Prin T line, F.close () print "sys.argv[0"---------", sys.argv[0] print" sys.argv[1 "-------- -", sys.argv[1] print" sys.argv[2]---------", sys.argv[2]# Script starts from HEREif Len ( SYS.ARGV) < 2:print ' No action specified. ' Sys.exit () If Sys.argv[1].startswith ('--'): option = sys.argv[1][2:] # fetch SYS.ARGV[1] But without the first double char acters if option = = ' Version ': print ' version 1.2 ' elif option = = ' help ': print ' Prints files to the standard output. Any number of the files can be specified. Options include:--version:prints The version number--help:display this "else: print ' UnkNown option. ' Sys.exit () else:for filename in sys.argv[1:]: ReadFile (filename) execution result: # python test.py--version helpsys.argv[0]- --------Test.pysys.argv[1]-----------versionsys.argv[2]---------helpversion 1.2
note: sys.argv[1][2:] Represents the second argument, starting from the third character, to the end, in this case the result is: Version