https://stackoverflow.com/questions/40001892/reading-named-command-arguments
33
Can I use argparse
to read named command line arguments that do not need to be in a specific order? I browsed through the documentation but most of it focused on displaying content based on the arguments provided (such as --h
).
Right now, my script reads ordered, unnamed arguments:
myscript.py foo-val bar-val
using sys.argv
:
foo = sys.argv[1]
bar = sys.argv[2]
But I would like to change the input so that it is order agnostic by naming arguments:
myscript.py --bar=bar-val --foo=foo-val
- cannot find a good duplicate, but check here for some examples: stackoverflow.com/questions/11415570/… – Jean-François Fabre♦ Oct 12 '16 at 15:01
42
You can use the Optional Arguments like so:
import argparse, sys
parser=argparse.ArgumentParser()
parser.add_argument('--bar', help='Do the bar option')
parser.add_argument('--foo', help='Foo the program')
args=parser.parse_args()
print args
print sys
Then if you call it with ./prog --bar=bar-val --foo foo-val
it prints:
Namespace(bar='bar-val', foo='foo-val')
['Untitled 14.py', '--bar=bar-val', '--foo', 'foo-val']
Or, if the user wants help argparse builds that too:
$ ./prog -h
usage: Untitled 14.py [-h] [--bar BAR] [--foo FOO]
optional arguments:
-h, --help show this help message and exit
--bar BAR Do the bar option
--foo FOO Foo the program
- I did not know that it was possible to use the
--opt=val
syntax. This is wonderful :) – Tryph Oct 12 '16 at 15:29 - 1
- 4Use
args.bar
to read--bar
It will returnNone
if not included in the command. You can also use a default instead. – dawg Oct 12 '16 at 15:33 - Using python 3.5.1, and when not included it doesn't return
None
; it gives an error. So as an alternative,d = vars(args)
gives a dictionary (maps named arguments to values) – DZack Nov 13 '17 at 18:12
'C Lang > Python Program Diary' 카테고리의 다른 글
What is Serializable? 직렬화란 무엇인가? (0) | 2019.09.02 |
---|---|
파이썬 로깅의 모든것 (0) | 2019.08.30 |
nginx - gunicorn - supervisor로 파이썬 디플로이하기 (0) | 2019.08.16 |
python에서 dict형은 순서를 보장하는가? (0) | 2019.08.13 |
How To Setup Autorun a Python Script Using Systemd (0) | 2019.08.13 |