Repository navigation
Expand file tree
/
Copy pathpython-argparse.py
More file actions
58 lines (49 loc) · 1.79 KB
/
Copy pathpython-argparse.py
File metadata and controls
58 lines (49 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
""" MARKDOWN
---
YamlDesc: CONTENT-ARTICLE
Title: Python Modules argparse
MetaDescription: Python Modules, argparse
MetaKeywords: Python Modules, argparse
Author: Venkata Bhattaram / tinitiate.com
ContentName: python-modules-argparse
---
MARKDOWN """
""" MARKDOWN
# Python Argparse
* Python Argparse is an Python Argument Parser
* Here we demonstrate handling arguments
* Handle custom error message in case an invalid argument is passed
* Test Cases for the code below
* **ERROR Scenario:** `python F:\code\tinitiate\source\python\ti-cms-md-gen.py -s 100`
* **Single Parameter -a Scenario:** `python F:\code\tinitiate\source\python\ti-cms-md-gen.py -a 100`
* **Double Parameter -a and -b Scenario:** `python F:\code\tinitiate\source\python\ti-cms-md-gen.py -a 100 -b 2000`
MARKDOWN """
# MARKDOWN ```
import argparse
import sys
# Class to handle Custom Error Messag in case an invalid argument is passed
class MyParser(argparse.ArgumentParser):
def error(self, message):
# sys.stderr.write("Hello")
print("")
self.print_help()
sys.exit(2)
# Function to handle the arguments and its values, to perform an action
def a(a=1, b=1, c="", **kwargs):
if a is not None:
print("a", a)
elif b is not None:
print("b", b)
elif b is not None:
print("c is selected")
# Function Main
if __name__ == "__main__":
parser = MyParser()
parser.set_defaults(method = a)
# Argument
parser.add_argument('-a', help="this is -a switch", default=1, type = int)
parser.add_argument('-b', help="this is -b switch", default=1, type = int)
parser.add_argument('-c', help="-c switch without parameters", action='store_true')
args = parser.parse_args()
args.method(**vars(args))
# MARKDOWN ```