Home > Backend Development > Python Tutorial > Detailed explanation of how to use sys.argv[]

Detailed explanation of how to use sys.argv[]

高洛峰
Release: 2017-03-27 16:59:03
Original
5183 people have browsed it

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] means "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

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(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)
执行结果:# python test.py --version help
sys.argv[0]--------- test.py
sys.argv[1]--------- --version
sys.argv[2]--------- help
Version 1.2
Copy after login

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

The above is the detailed content of Detailed explanation of how to use sys.argv[]. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template