Python3 Command Line Arguments

Python3 基础语法Python3 Basic Syntax

Python provides thegetoptsys module to get command line arguments.

$ python test.py arg1 arg2 arg3

In Python, you can also usesysofsys.argvto get command line arguments:

  • sys.argvis the list of command line arguments.

  • len(sys.argv)Counts the number of command line arguments.

Note:sys.argv[0]represents the script name.

Examples

The test.py file code is as follows:

Examples

#!/usr/bin/python3

import sys

print ('Number of arguments:', len(sys.argv), ' arguments.')
print ('Argument list:', str(sys.argv))
print ('Script name:', str(sys.argv[0]))

Executing the above code, the output is:

$ python3 test.py arg1 arg2 arg3
参数个数为: 4 个参数。
参数列表: ['test.py', 'arg1', 'arg2', 'arg3']
脚本名: test.py

getopt Module

The getopt module is a module specially designed for handling command line arguments, used to get command line options and arguments, that is,sys.argv. Command line options make program arguments more flexible. It supports short option mode-and long option mode--。

The module provides two methods and an exception handler to parse command line arguments.

getopt.getopt Method

The getopt.getopt method is used to parse a command line argument list. The syntax format is as follows:

getopt.getopt(args, options[, long_options])

Method parameter description:

  • args: The list of command line arguments to be parsed.

  • options: Defined in string format. Theoptionscolon after:indicates that the option must have an additional argument; no colon means the option does not take an argument.

  • long_options: Defined in list format. Thelong_optionsequal sign after=indicates that if the option is set, it must have an additional argument; otherwise, no argument is attached.

The return value of this method consists of two elements: the first is(option, value)a list of tuples. The second is a list of arguments, containing those without-or--options.

Next, we define a site() function, and then enter the site namenameand URL through the command line,urlabbreviations can be usednandu:

Examples

import sys
import getopt
 
 
def site():
    name = None
    url = None
 
    argv = sys.argv[1:]
 
    try:
        opts, args = getopt.getopt(argv, "n:u:")  # Short option mode
     
    except:
        print("Error")
 
    for opt, arg in opts:
        if opt in ['-n']:
            name = arg
        elif opt in ['-u']:
            url = arg
     
 
    print( name +" " + url)
 
site()

To test the above code, enter the following in the command line:

python3 test.py -n EXAMPLE -u www.example.com

The output is:

EXAMPLE www.example.com

The following example demonstrates the use of long option mode:

Examples

import sys
import getopt
 
def site():
    name = None
    url = None
 
    argv = sys.argv[1:]
 
    try:
        opts, args = getopt.getopt(argv, "n:u:",  
                                   ["name=",
                                    "url="])  # Long option mode
     
    except:
        print("Error")
 
    for opt, arg in opts:
        if opt in ['-n', '--name']:
            name = arg
        elif opt in ['-u', '--url']:
            url = arg
     
 
    print( name + " " + url)
 
site()

To test the above code, enter the following in the command line:

python3 test.py -n EXAMPLE -u www.example.com

The output is:

EXAMPLE www.example.com

Another method is getopt.gnu_getopt, which is rarely used, so we won't go into much detail here.


Exception getopt.GetoptError

This exception is triggered when no argument list is found, or when the required argument of an option is empty.

The argument of the exception is a string indicating the reason for the error. The attributemsgandoptis the error information for the related option.

Examples

Suppose we create such a script, which can pass two file names to the script file through the command line, and we also use another option to view the script usage. The script usage is as follows:

usage: test.py -i <inputfile> -o <outputfile>

The test.py file code is as follows:

Examples

#!/usr/bin/python3

import sys, getopt

def main(argv):
   inputfile = ''
   outputfile = ''
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print ('test.py -i <inputfile> -o <outputfile>')
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print ('test.py -i <inputfile> -o <outputfile>')
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg
   print ('The input file is:', inputfile)
   print ('The output file is:', outputfile)

if __name__ == "__main__":
   main(sys.argv[1:])

Executing the above code, the output is:

$ python3 test.py -h
usage: test.py -i <inputfile> -o <outputfile>

$ python3 test.py -i inputfile -o outputfile
输入的文件为: inputfile
输出的文件为: outputfile

Python3 基础语法Python3 Basic Syntax

Other Extensions