#!/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.
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.
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