Skip to content

Commit 0a2b017

Browse files
committed
Add experiment with file options
1 parent 6817dbd commit 0a2b017

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed

source-code/command-line-arguments/ArgParse/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,4 @@ $ ./generate_gaussian.py -h
2323
./options_in_file.py --foo something @file_options.txt
2424
```
2525
1. `file_options.txt`: file containing options for `options_in_file.py`.
26+
1. `Rerun`: experiment with file options.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Rerunnable
2+
3+
Toy application to explore the possibilities created by
4+
using argparse options stored in a file.
5+
6+
7+
## What is it?
8+
1. rerunnable.py`: script to explore the possibilities.
9+
10+
11+
## How to use?
12+
13+
```bash
14+
$ ./rerunnable.py --verbose --number 5 --type bye gjb
15+
$ ./rerunnable.py @rerunnable_cla.txt
16+
```
17+
18+
This will rerun the application with all the settings specified for the
19+
previous run.
20+
21+
To override options:
22+
```bash
23+
$ ./rerunnable.py @rerunnable_cla.txt --number 3
24+
```
25+
26+
27+
## Conclusions
28+
29+
This approach works well for command line options, e.g., `--number 5`.
30+
31+
It is not flexibile for flags, e.g., `--verbose` since they can not be "unset".
32+
33+
It is not flexible either for positional arguments since they can not be modified.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#!/usr/bin/env python
2+
3+
import argparse
4+
5+
6+
def dump_options(options, pos_args=None, exclude=None):
7+
options_dict = vars(options)
8+
with open('rerunnable_cla.txt', 'w') as file:
9+
for key, value in options_dict.items():
10+
if ((exclude is None or key not in exclude) and
11+
(pos_args is None or key not in pos_args)):
12+
if isinstance(value, bool):
13+
if value:
14+
print(f'--{key}', file=file)
15+
else:
16+
print(f'--{key}\n{value}', file=file)
17+
if pos_args is not None:
18+
for key in pos_args:
19+
print(options_dict[key], file=file)
20+
21+
22+
if __name__ == '__main__':
23+
arg_parser = argparse.ArgumentParser(
24+
fromfile_prefix_chars='@',
25+
description='application that saves its command line options and can be rerun'
26+
)
27+
arg_parser.add_argument('--number', type=int, default=1,
28+
help='number of messages to write')
29+
arg_parser.add_argument('--type', choices=('hello', 'bye'), default='hello',
30+
help='message type')
31+
arg_parser.add_argument('--verbose', action='store_true',
32+
help='verbose output')
33+
arg_parser.add_argument('name', help='person to message')
34+
options = arg_parser.parse_args()
35+
dump_options(options, pos_args=('name', ))
36+
if options.verbose:
37+
print(f'printing {options.number} messages')
38+
for _ in range(options.number):
39+
print(f'{options.type} {options.name}')

0 commit comments

Comments
 (0)