Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to implement command line with parameters in Python+getopt

Shulou Source: shulou.com Published: 2022-06-01 11:20:32 10月02日 Update

Python+getopt how to achieve command line parameters, I believe that many inexperienced people do not know what to do, so this paper summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

Python+getopt implements command line with parameters

Getopt module in python, which is specifically used to handle command line arguments

Function getopt (args, shortopts, longopts = [])

The parameter args is generally sys.argv [1:], shortopts short format (-), longopts long format (- -)

Enter on the command line:

# python test.py-I 127.0.0.1-p 80 55 66

# python test.py-ip=127.0.0.1-port=80 55 66

Code:

#! / usr/bin/python

Import getopt

Import sys

Def usage ():

Print'- h help\ n'\

'- i ip address\ n'\

'- p port number\ n'\

''

If _ _ name__ = ='_ _ main__':

Try:

Options, args = getopt.getopt (sys.argv [1:], "hp:i:", ['help', "ip=", "port="])

For name, value in options:

If name in ('- hype,'--help'):

Usage ()

Elif name in ('- iTunes,'--ip'):

Print value

Elif name in ('- paired,'--port'):

Print value

Except getopt.GetoptError:

Usage ()

Rgv [1:], "hp:i:", ["help", "ip=", "port="])

"hp:i:" short format

H is not followed by a colon: it means that there are no parameters, and p: and I: are followed by a colon to indicate that parameters are required.

["help", "ip=", "port="] long format

There is no equal sign after help, which means that there are no parameters, and the other three have =, indicating that parameters are needed later.

The return value options is a list of meta-ancestors, and each meta-ancestor is the format information analyzed, for example, [('- iSequence 127.0.0.1'), ('- pawning meme80')]

Args is a list that contains parameters that do not have'-'or'- -', such as: ['55 'June' 66']

Note: when defining command line parameters, define parameters with the'- 'option first, and then define parameters without' -'.

After reading the above, have you mastered how Python+getopt implements the command line with parameters? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Tags: Parameters commands formats contents colons methods more modules problems meta-ancestors helpless for this three code information function reason this skill equal sign Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Linux MySQL MariaDB Redmi