Detailed explanation of the use of sys.argv[]

高洛峰
Release: 2016-10-19 10:38:43
Original
1662 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] 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.'

  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':                                                                       : Display this help '' '

else:

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



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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!