Sys. argv [] is used to obtain command line parameters, sys. argv [0] indicates the path of the code file. for example, enter pythontest in the CMD command line. py-help, then sys. argv [0] indicates test. py. Sys. startswith () is used to determine the beginning of an object, such as in... sys. argv [] is used to obtain command line parameters, sys. argv [0] indicates the path of the code file. for example, enter "python test. py-help ", then sys. argv [0] indicates "test. py ".
Sys. startswith () is used to determine the starting point of an object. for example, if you enter 'ABC'. startswith ('AB') in the python command line, True is returned.
For 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 (line) = 0:
Break
Print 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 here
If 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 two characters
If option = 'version ':
Print 'version 1.2'
Elif option = 'help ':
Print '''"
This program prints files to the standard output.
Any number of files can be specified.
Options include:
-- Version: Prints the version number
-- Help: Display this help '''
Else:
Print 'unknown option .'
Sys. exit ()
Else:
For filename in sys. argv [1:]:
Readfile (filename)
Execution result: # python test. py -- version help
Sys. argv [0] --------- test. py
Sys. argv [1] --------- -- version
Sys. argv [2] --------- help
Version 1.2:
Note: sys. argv [1] [2:] indicates to intercept the second parameter from the third character to the end. In this example, the result is: version.