Decompose command arguments in one line in Python

Source

#!/usr/bin/env python

import sys

com = { i:j for i,j in [ (i[1][1:], sys.argv[i[0]+1] if len(sys.argv)>i[0]+1 and sys.argv[i[0]+1][0]!='-' else True ) for i in enumerate(sys.argv) if i[1][0]=='-'] }

print com

If you give an argument to the above program and execute it, it will be as follows. (File name is test.py)

$ ./test.py -a hoge -b gaga
{'a': 'hoge', 'b':'gaga'}
$ ./test.py -a hoge -b gaga -c
{'a': 'hoge', 'c': True, 'b': 'gaga'}

After that, you can do something like a switch-case, and you can carry around this dict object as it is.

Commentary

First, add line breaks and comments to make it easier to understand.

com = { i:j for i,j in  #Creating a dictionary
        [ (i[1][1:], sys.argv[i[0]+1] if len(sys.argv)>i[0]+1 and sys.argv[i[0]+1][0]!='-' else True ) #Creating tuples
            for i in enumerate(sys.argv) if i[1][0]=='-' #Indexing
        ]
      }

The explanation is from the back. First, create an index. If you pull out only the last part

optIndex = [ i for i in enumerate(sys.argv) if i[1][0] == '-' ]

Assign a number to sys.argv that stores command arguments using enumerate, and extract only those command arguments whose first character is-in the if statement. When you print it, it looks like this.

$ ./test.py -a hoge -b gaga -c
optIndex: [(1, '-a'), (3, '-b'), (5, '-c')]

Then, using the index and option information tuple ʻiobtained here, create a tuple of option characters and values. In other words, what you are doing in the[]on the 2nd and 3rd lines is like[(key, value) for i in optIndex]`. The key is easier

[ i[1][1:] for i in optIndex ]

Can be taken as. It feels like everything after the second character of the location of the optIndex value. (Well, you can put - from the first character separately) Next is the value, and if you normally take only the value, do as follows.

[ sys.argv[i[0] + 1] for i in optIndex ]

Just specify the next value of the index information. However, in this case, all options have to take values, and you cannot do something like ls -a. Therefore, it is determined whether the value of value does not start with-and whether the value pointed to by the index is in the middle of the argument. If you get caught in the judgment, insert True.

values = [ sys.argv[i[0]+1 if len(sys.argv) > i[0]+1 and sys.argv[i[0]+1][0]!='-' else True ]

The second line just tuples these two. The first line just converts the tupled values into a dictionary. In other words, just do {i: j for i, j in optTuple}. As I explained at the beginning to put all this together

com = { i:j for i,j in [ (i[1][1:], sys.argv[i[0]+1] if len(sys.argv)>i[0]+1 and sys.argv[i[0]+1][0]!='-' else True ) for i in enumerate(sys.argv) if i[1][0]=='-'] }

Is completed.

Summary

Even if you don't understand at first glance, you can understand it by disassembling it and chasing it from behind. There is no such thing as "Isn't it a library without doing this?"

Recommended Posts

Decompose command arguments in one line in Python
How to receive command line arguments in Python
Fizzbuzz in Python (in one line)
Make python segfault in one line
CGI server (1) python edition in one line
[Python] Invert bool value in one line
python Note: Determine if command line arguments are in the list
One liner in Python
Template for creating command line applications in Python
Make a rock-paper-scissors game in one line (python)
[Introduction to Udemy Python3 + Application] 67. Command line arguments
Get options in Python from both JSON files and command line arguments
Specify a subcommand as a command line argument in Python
Execute external command in python
Try LINE Notify in Python
External command execution in Python
Allow brew install of command line tools made in Python
How to specify command line arguments when debugging in PyCharm
[Python] Read command line arguments from file name or stdin
Hit a command in Python (Windows)
Included notation in Python function arguments
Run shell command / python in R
Prime number enumeration in one line
I tried Line notification in Python
[Introduction] Insert line breaks in Python 3
Implemented in 1 minute! LINE Notify in Python
[Python] [3D line graph] Multiple data in one graph, axis values in characters
Create another version of Python conda environment with one command line
[LLDB] Create your own command in Python
Line graphs and scale lines in python
Learn the design pattern "Command" in Python
Read the file line by line in Python
Read the file line by line in Python
One liner webServer (with CGI) in python
[Python / Tkinter] How to pass arguments to command
Combine python function arguments into one variable
[Python] Read the specified line in the file
A note I looked up to make a command line tool in Python
Quadtree in Python --2
Python in optimization
CURL in python
[Python] How to test command line parser click
One liner that outputs multiplication tables in Python
Geocoding in python
SendKeys in Python
Automatically register function arguments to argparse in Python
How to implement Discord Slash Command in Python
Meta-analysis in Python
Try implementing two stacks in one array in Python
Unittest in python
One liner to 100% CPU1 core usage in Python
Epoch in Python
Discord in Python
Summary of tools used in Command Line vol.8
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Load and execute command from yml in python