Saving python argparse file

The file format is documented quite clearly:

Arguments read from a file must by default be one per line [...]

and the code example in the documentation shows that they write a file with newlines in between:

>>> with open('args.txt', 'w') as fp:
...     fp.write('-f\nbar')

If you want to save your current command line, just write sys.argv[1:] to a file, with newlines between the arguments:

with open('commandline_args.txt', 'w') as f:
    f.write('\n'.join(sys.argv[1:]))

Demo:

>>> from argparse import ArgumentParser
>>> import sys
>>> parser = ArgumentParser(fromfile_prefix_chars='@')
>>> parser.add_argument('--foo')
_StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('bar', nargs='?')
_StoreAction(option_strings=[], dest='bar', nargs='?', const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> sys.argv[1:] = ['--foo', 'spam', 'barbaz']
>>> parser.parse_args()
Namespace(bar='barbaz', foo='spam')
>>> with open('commandline_args.txt', 'w') as f:
...     f.write('\n'.join(sys.argv[1:]))
...
17
>>> parser.parse_args(['@commandline_args.txt'])
Namespace(bar='barbaz', foo='spam')
>>> sys.argv[1:] = ['--foo=spam', 'barbaz']  # using alternate syntax
>>> parser.parse_args()
Namespace(bar='barbaz', foo='spam')
>>> with open('commandline_args.txt', 'w') as f:
...     f.write('\n'.join(sys.argv[1:]))
...
17
>>> parser.parse_args(['@commandline_args.txt'])
Namespace(bar='barbaz', foo='spam')

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)