Arguments
Command Line Interface
The command for generating Apache access logs:
$python3.4 $Visor_HOME/src/fake_log_gen/fake_log_gen.py -m access -o outputfile
The command for generating Apache error logs:
$python3.4 $Visor_HOME/src/fake_log_gen/fake_log_gen.py -m error -o outputfile
argparse
The Python argparse module provides a convenient way of writing command-line interfaces. It can save you a lot of trouble of dealing with sys.argv, and can automatically generate help messages.
$ python3.4 ../src/fake_log_gen/fake_log_gen.py -h
usage: fake_log_gen.py [-h] [-o O] [-m M]
optional arguments:
-h, --help show this help message and exit
-o O fake logfile
-m M log mode
Create Parser
Import the Python argparse module and instantiate a parser:
parser = argparse.ArgumentParser()
Add Arguments
For now, there are 2 arguments for our generator program:
- The output file
- The log mode (access log or error log)
parser.add_argument("-o", help="fake logfile")
parser.add_argument("-m", help="log mode")
The explanation after the help will be utilized by the -h messages.
Parse the Arguments
Parse the arguments via parse_args() method:
args = parser.parse_args()
parse_args() just illustrate how the program will access the arguments. Usually called with no arguments, ArgumentParser will automatically determine the command-line arguments from sys.argv.
Access the Arguments
Now, we are capable to access the parsed arguments:
mode = args.m
Pay attention that when use the . notation to access arguments, don't need to add the - before the argument name. Here, use args.m instead of args.-m.