Python basics of sys.argv[] usage

Source: Internet
Author: User
Tags parse string readfile

Sys.argv[] is used to get command-line arguments, Sys.argv[0] represents the code itself as a file path, so the parameters start at 1 .

Arg[1] Represents the first command-line argument

Arg[1][2:] means taking the first command-line argument, but removing the top two bytes

For example, if the command line argument is "--help", remove the "--" and execute the "help" parameter.

The following code comes from a concise Python tutorial.

If there is sys.arg[0] it means
[Python]View Plaincopy
  1. #!/usr/bin/python
  2. #
  3. Import Sys
  4. def readfile (filename):
  5. ' Print a file to the standard output. '
  6. f = file (filename)
  7. While True:
  8. line = F.readline ()
  9. If Len (line) = = 0:
  10. Break
  11. Print line, # Notice comma
  12. F.close ()
  13. # Script starts from here
  14. If Len (SYS.ARGV) < 2:
  15. print ' No action specified. '
  16. Sys.exit ()
  17. If Sys.argv[1].startswith ('--'):
  18. option = sys.argv[1][2:]
  19. # take sys.argv[1] but without the first and characters, here remove "--"
  20. if option = = ' Version ':
  21. print ' Version 1.2 '
  22. elif option = = ' help ':
  23. print "\
  24. Prints files to the standard output.
  25. Any number of the files can be specified.
  26. Options include:
  27. --version:prints the version number
  28. --help:display this ""
  29. Else
  30. print ' Unknown option. '
  31. Sys.exit ()
  32. Else
  33. For filename in sys.argv[1:]:
  34. ReadFile (filename)

When you run a program, you may need to enter different command-line options to implement different functions depending on the conditions. There are currently two formats for short options and long options . The short option format is "-" plus a single letter option; The long option is "--" plus a word. The long format was introduced under Linux. These two formats are supported by a number of Linux programs. The getopt module in Python provides a good way to support both usages and is simple to use.

get command line arguments
before you use it, get the command-line arguments first. Command-line arguments can be obtained using the SYS module.
Import Sys

then, at the command line, click any parameter, such as:
python t--help cmd file1 file2

The result is:
[' ', '-o ', ' t ', '--help ', ' cmd ', ' file1 ', ' file2 ']

visible, all command-line arguments are separated by spaces and are saved in the sys.argv list . The 1th of which is the file name of the script.

the wording of the option requires
for short format, the "-" sign is followed by an option letter. If there are additional parameters for this option, they can be separated by a space or separated. Any length, you can use quotation marks. The following are correct:
-O "a B"
for long formats, the "--" sign is followed by a word. If you have additional parameters for the options, follow the "=" followed by the parameters. There must be no spaces before and after the "=" number. The following are correct:


and these are not true:
--help =file1
--help = File1
--help= file1

How to use getopt for analysis
using the Getopt module to analyze command-line parameters is broadly divided into three steps:

1.import getopt, sys module
2.parsing command-line arguments
3.Processing Results

The first step is simple and requires only:
Import getopt, sys

The second step is as follows (for example in the Python manual):
opts, args = Getopt.getopt (sys.argv[1:], "ho:", ["Help", "output="])
Except Getopt. Getopterror:
# Print Help information and exit:

1.The function used for processing is called getopt (), because it is a getopt module that is imported directly using import, so it is possible to add a qualified getopt.
2. use sys.argv[1:] to filter out the first parameter (it is the name of the execution script and should not be counted as part of the parameter).
3.use the short format to parse the string "ho:". The option character is written in the parse string when an option simply represents a switch state, that is, when no additional parameters are followed. When an optional item is followed by an additional parameter, the Write option character in the parse string is appended with a ":" Number . " ho:" means "h" is a switch option; "O:" indicates that a parameter should be followed.
4.parse the list of strings using long format: ["Help", "output="]. Long format strings can also have a switch state, which is not followed by the "=" number. If you follow an equal sign, you should have a parameter later . This long format means "help" is a switch option; "Output=" indicates that a parameter should be followed.
5.Call the Getopt function. The function returns two lists:opts and args. OPTs the format information for the analysis. Args is the remaining command-line argument that is not part of the format information. OPTs is a two-tuple list . Each element is: (option string, additional parameter). Empty string If no additional parameters are available.
6.the whole process uses exceptions to include, so that when parsing errors, you can print out usage information to inform the user how to use the program.

as explained above, a command line example is:
'-h-o file--help--output=out file1 file2 '

after the analysis is complete, the OPTs should be:
[('-H ', '), ('-O ', ' file '), ('--help ', '), ('--output ', ' out ')]

and the args are:
[' file1 ', ' file2 ']

The Third step is the analysis of the parameters of the existence of the decision, and then further processing . The main processing modes are:  
For O, the A in opts:
If O in ("-H", "--help"):
Usage ()
Sys.exit ()
If O in ("-O", "--output"):
Output = a

using a loop, each time a two-tuple is taken out of the opts, it is assigned to two variables. o Save the option parameter, A is an additional parameter. The option parameters are then processed. (Examples also use manual examples)

Python basics of sys.argv[] usage

Related Article

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: 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.