SoFunction
Updated on 2024-11-14

Python Ways to Write Command Line Programs with Options

When running a python program, it is sometimes necessary to pass some arguments on the command line. A common way to do this is to append a space-separated list of arguments directly after the script name (e.g. python arg0 arg1 arg2) at execution time, and then you can get all the command line arguments by in the script.

The advantage of this approach is the convenience of passing parameters and the simplicity of obtaining parameters; the disadvantage is that when executing the script, you must know the order of the parameters, and you cannot set default values, and all parameters must be passed in each time.

There is also a way to pass parameters on the command line by passing them with options (e.g. python -p0=arg0 -p1=arg1).

The advantage of this approach is that the parameters do not have to be passed in a fixed order, and for parameters with default values, you can use the default values directly without passing parameters; the disadvantage is that you need to add additional options when passing parameters.

Command line arguments with options can be parsed with python's own getopt module.

Primary methodology:

getopt(args, shortopts, longopts = []): parses the list of command line options and arguments.

args is the list of arguments excluding references to the running program, which would normally be [1:].

shortopts are the short option letters to be recognized by the script. If the short option requires a parameter, you need to add a colon ":" after the letter.

longopts are supported long options, a list of long option names. Option names do not include "-". Long options that require an argument need to be followed by an equal sign "=".

The return value consists of two lists: the first list is (option, value), and if the option has no arguments, the value is the empty string. The second list is the list of program parameters after stripping the options. Long items are preceded by "--" and short items by "-".

Also note that when parsing command line arguments, parsing with option arguments stops if a non-option argument is encountered.

simple example

#!/usr/bin/python
# -*- coding: gbk -*-
import sys
import getopt
def printUsage():
	print ('''usage:  -i <input> -o <output>
     --in=<input> --out=<output>''')
 
def main():
	inputarg=""
	outputarg=""
	try:
		opts, args = ([1:],"hi:o:",["in=","out="])
	except :
		printUsage()
		(-1)
	for opt,arg in opts:
		if opt == '-h':
			printUsage()
		elif opt in ("-i", "--in"):
			inputarg=arg
		elif opt in ("-o","--out"):
			outputarg=arg
	print ('Input:'+inputarg)
	print ('Output:'+outputarg)
	print ('Other program parameters:'+",".join(args))
if __name__=="__main__":
	main()

Above this Python write command line program with options method is all I have shared with you, I hope to give you a reference, and I hope you support me more.