Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving python argparse file

Argparse has a feature that called fromfile-prefix-chars, that seems to do exactly half of what I am looking for. How can I create the file for this feature from the current command line arguments?

I have a complicated script with a parser that is automating part of a code build. The use-case is setting up the command line correctly the first time, and then basically re-running with the same arguments.

Using a file and loading from that seems like a great way to implement what I need. What seems to be missing is a simple way of writing out the initial command line to a file so the existing file parsing will work correctly.

like image 543
Brett Stottlemyer Avatar asked Feb 18 '17 18:02

Brett Stottlemyer


1 Answers

from argparse import ArgumentParser
import json

parser = ArgumentParser()
parser.add_argument('--seed', type=int, default=8)
parser.add_argument('--resume', type=str, default='a/b/c.ckpt')
parser.add_argument('--surgery', type=str, default='190', choices=['190', '417'])
args = parser.parse_args()

with open('commandline_args.txt', 'w') as f:
    json.dump(args.__dict__, f, indent=2)

parser = ArgumentParser()
args = parser.parse_args()
with open('commandline_args.txt', 'r') as f:
    args.__dict__ = json.load(f)

print(args)
like image 127
Fangda Han Avatar answered Oct 07 '22 08:10

Fangda Han