Detailed sys.argv[] Use of the method

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.