Custom Actions for argparse Documentation

Custom Actions for argparse
Documentation
Release 0.4
Hai Vu
October 26, 2015
Contents
1
Introduction
1
2
Information
2.1 Folder Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2 IP Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.3 Dictionary Action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3
3
3
4
3
Examples
3.1 Extending the Custom Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.2 More Ideas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5
5
6
4
Samples
4.1 extend_action.py . . . .
4.2 folder_exists.py . . . . .
4.3 proper_ip.py . . . . . .
4.4 dict_action_example.py
7
7
7
7
7
5
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Indices and tables
9
Python Module Index
11
i
ii
CHAPTER 1
Introduction
The package argparse_actions provides a number of custom actions for use with the argparse module.
1
Custom Actions for argparse Documentation, Release 0.4
2
Chapter 1. Introduction
CHAPTER 2
Information
• Source Location: bitbucket
• Package Location: pypi
• Latest Document: latestdoc
2.1 Folder Actions
The folder actions implement folder-related actions.
class argparse_actions.FolderExistsAction(option_strings, dest, nargs=None, const=None,
default=None, type=None, choices=None, required=False, help=None, metavar=None)
Custom action: verify the argument to be a folder (directory). If not, raise a NonFolderError exception.
The action will strip off trailing slashes from the folder’s name.
class argparse_actions.FolderCreateAction(option_strings, dest, nargs=None, const=None,
default=None, type=None, choices=None, required=False, help=None, metavar=None)
Custom action: create a new folder if not exist. If the folder already exists, do nothing.
The action will strip off trailing slashes from the folder’s name.
2.2 IP Actions
Below are custom actions which deal with IPv4 addresses
class argparse_actions.ProperIpFormatAction(option_strings, dest, nargs=None, const=None,
default=None, type=None, choices=None, required=False, help=None, metavar=None)
A custom action, used in conjunction with argparse to validate an IP address.
validate_ip(ipvalue)
Validate an IP address, generate exception if need be.
3
Custom Actions for argparse Documentation, Release 0.4
2.3 Dictionary Action
class argparse_actions.DictAction(option_strings, dest, **kwargs)
The DictAction class enables parsing the command line as a dictionary. One application is to handle defines
such as those offered by g++
4
Chapter 2. Information
CHAPTER 3
Examples
The following example, taken from samples/folder_actions.py demonstrates the use of a custom action to verify the
existence of a folder, specified from the command line:
import argparse
import argparse_actions
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Custom Actions')
parser.add_argument('directory',
action=argparse_actions.FolderExistsAction)
try:
args = parser.parse_args()
print 'Directory exists: {0}'.format(args.directory)
except argparse_actions.NonFolderError as e:
print 'Directory does not exist'
print e
In the next example from samples/proper_ip.py, we use the ProperIpFormatAction custom action to verify if an IP
address from command line is properly formatted:
import argparse
import argparse_actions
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Custom Actions')
parser.add_argument('ip',
action=argparse_actions.ProperIpFormatAction)
try:
args = parser.parse_args()
print 'IP is properly formatted: {0}'.format(args.ip)
except argparse_actions.InvalidIp as e:
print 'IP is invalid: {0}'.format(e.ip)
# This will display similar output:
# print e
3.1 Extending the Custom Actions
If you find a custom action that almost do what you want, you can
5
Custom Actions for argparse Documentation, Release 0.4
1. Write your own from scratch
2. Submit an enhancement request
3. Extend the existing custom action
I am not commenting on option 1–it is your choice. For option 2, I will be gladly to accept any reasonable request, but
sometimes life happens and I might not response quickly enough. That leaves you with the third option of extending
the custom action yourself. Don’t worry, it is not that hard. In the next example, I will take the ProperIpFormatAction
custom action and extend it to include ‘localhost’ as one of the proper IP format:
import argparse
import argparse_actions
class IpAndLocalhostAction(argparse_actions.ProperIpFormatAction):
def __call__(self, parser, namespace, values, option_string=None):
# Do our check: allow for 'localhost'
if values == 'localhost':
setattr(namespace, self.dest, values)
else:
# Super class to perform its check
parent = super(IpAndLocalhostAction, self)
parent.__call__(parser, namespace, values, option_string)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Custom Actions')
parser.add_argument('ip', action=IpAndLocalhostAction)
try:
args = parser.parse_args()
print 'IP is valid: {0}'.format(args.ip)
except argparse_actions.InvalidIp as e:
print e
Discussion:
• The first step is to create a new class (IpAndLocalhostAction), based on an existing custom action (argparse_actions.ProperIpFormatAction, which is really a class itself)
• Define the function __call__ to override the base custom action with your own logic.
3.2 More Ideas
Here are a few ideas I have in mind, which I might implement:
• Extend ProperIpFormatAction to determine if and IP...
– Is reachable
– Provides some services such as HTTP or FTP
– Belongs to a particular list, such as the banned IP list
• Extend FolderExistsAction to determine if the folder is...
– Writable
– Empty
– A symbolic link
6
Chapter 3. Examples
CHAPTER 4
Samples
4.1 extend_action.py
This sample demonstrates how to extend the existing custom action to add functionality. In this example, we will
extend the ProperIpFormatAction class to accept ‘localhost’ as a proper IP address.
Examples:
python extend_action.py 10.0.1.2
python extend_action.py localhost
4.2 folder_exists.py
This sample demonstrate the FolderExistsAction custom action.
Examples:
python folder_exists /tmp
python folder_exists /foo/bar
4.3 proper_ip.py
This sample demonstrate the ProperIpFormatAction custom action.
Examples:
python proper_ip.py 10.0.1.2
python proper_ip.py 10.0.1.256
4.4 dict_action_example.py
Simulate a g++ define command line
Examples:
python dict_action_example -D log_level=DEBUG warning_as_error
python dict_action_example -Dverbose -D strict
7
Custom Actions for argparse Documentation, Release 0.4
8
Chapter 4. Samples
CHAPTER 5
Indices and tables
• genindex
• modindex
• search
9
Custom Actions for argparse Documentation, Release 0.4
10
Chapter 5. Indices and tables
Python Module Index
_
__init__, 3
a
argparse_actions, 3
d
dict_action, 3
dict_action_example, 7
e
extend_action, 7
f
folder_actions, 3
folder_exists, 7
i
ip_actions, 3
p
proper_ip, 7
11
Custom Actions for argparse Documentation, Release 0.4
12
Python Module Index
Index
Symbols
__init__ (module), 3
A
argparse_actions (module), 3
D
dict_action (module), 3
dict_action_example (module), 7
DictAction (class in argparse_actions), 4
E
extend_action (module), 7
F
folder_actions (module), 3
folder_exists (module), 7
FolderCreateAction (class in argparse_actions), 3
FolderExistsAction (class in argparse_actions), 3
I
ip_actions (module), 3
P
proper_ip (module), 7
ProperIpFormatAction (class in argparse_actions), 3
V
validate_ip()
(argparse_actions.ProperIpFormatAction
method), 3
13