If you want to specify arguments when executing a python program with CLI, getopt is used. I tried various basic movements.
Reference URL: https://szarny.hatenablog.com/entry/2017/08/17/231356
Format
import getopt
opts,args = getopt.getopt(text, shortopts, longopts=[])
Example
import getopt
opts,args = getopt.getopt(
sys.args[1:],
"hle:t:cp:,
["help", "listen", "execute=","target=","command","port=" )
argument | Description |
---|---|
opts | The target for which the argument was parsed. shortopts,Targets matching longopts are set in list format |
args | The target for which the argument was parsed. shortopts,Targets that do not match longopts are set in list format |
text | The target for which the argument is parsed. Sys if the argument is given from the prompt.args[1:]OK |
shortopts | Option specification in abbreviation. Add a colon to options that require an argument. For example, h,l,c requires no arguments and e,t,p is an argument required option |
longopts | Option specification in detail. Specify in list format. Options that require arguments are equal(=)Attach. For example, execute, target,port requires argument |
In addition, shortopts and longopts correspond to each other, so you should be careful about it.
I've tried various things, so some extra code is mixed in ...
show_arg.py
import sys
import getopt
def main():
if not len(sys.argv[1:]):
print("argument is nothing")
sys.exit()
text = sys.argv[1:]
try:
opts,args = getopt.getopt(
text,
"t:p:m:h",
["target=", "port=", "message=", "hogehoge"]
)
print("Options:", opts)
print("Arguments:", args)
except getopt.GetoptError as err:
print(str(err))
main()
print("finished")
Click here for the execution result. If you specify the abbreviation, one hyphen. Two hyphens if specified in detail. The first time I tried shortopts and longopts (a pattern that does not seem to enter args) The second time I tried setting the argument so that the value is entered in args
Execution result
$ python show_arg.py -t 127.0.0.1 -p 8888 --message hello --hogehoge
('Options:', [('-t', '127.0.0.1'), ('-p', '8888'), ('--message', 'hello'), ('--hogehoge', '')])
('Arguments:', [])
finished
$ python show_arg.py -t 127.0.0.1 -p 8888 --message hello --hogehoge hoge hage hige
('Options:', [('-t', '127.0.0.1'), ('-p', '8888'), ('--message', 'hello'), ('--hogehoge', '')])
('Arguments:', ['hoge', 'hage', 'hige'])
finished
$
It was super convenient to make it available as a set with getops and sys.argv.
Recommended Posts