python memo --Specify options with getopt

Introduction

If you want to specify arguments when executing a python program with CLI, getopt is used. I tried various basic movements.

Basic usage

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.

Implementation example

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
$ 

in conclusion

It was super convenient to make it available as a set with getops and sys.argv.

Recommended Posts

python memo --Specify options with getopt
Specify options when running python
Specify python version with virtualenv
python memo
Input / output with Python (Python learning memo ⑤)
Set python compile options with pyenv
Python memo
python memo
Python memo
"Scraping & machine learning with Python" Learning memo
Python memo
[Memo] Tweet on twitter with python
Python memo
Convert memo at once with Python 2to3
Specify options when running flake8 with flycheck
Memo to ask for KPI with python
"System trade starting with Python3" reading memo
A memo with Python2.7 and Python3 on CentOS
[Python] Memo dictionary
FizzBuzz with Python3
Scraping with Python
python beginner memo (9.2-10)
Statistics with python
Scraping with Python
Python with Go
python beginner memo (9.1)
Twilio with Python
Integrate with Python
Play with 2016-Python
AES256 with python
Tested with Python
★ Memo ★ Python Iroha
python starts with ()
with syntax (Python)
[Python] EDA memo
Python 3 operator memo
Bingo with python
Zundokokiyoshi with python
[My memo] python
Python3 metaclass memo
[Python] Basemap memo
Python beginner memo (2)
Excel with Python
[Python] Numpy memo
Microcomputer with Python
Cast with python
[Personal memo] julia --Using Python library with julia using PyCall
Specify the Python executable to use with virtualenv
How to specify attributes with Mock of python
A memo when creating a python environment with miniconda
Reading and writing fits files with Python (memo)
Memo for editing scenes with Blender python (W.I.P.)
Serial communication with Python
Zip, unzip with python
Django 1.11 started with Python3.6
Primality test with Python
Socket communication with Python
Data analysis with python 2
Python class (Python learning memo ⑦)
Try scraping with Python.
Learning Python with ChemTHEATER 03