I have a lot of arguments to pass to my main.py
. It's easier to store them in a txt file. So, i would like to know best way of using "config" files to pass CL args.
Shell script is not what i need, unfortunatly.
If you plan to use argparse
, then fromfile_prefix_chars
is designed to solve exactly this problem.
In your launching program, put all of the arguments, one per line, into a file. Pass @file.txt
to your child program. In your child program, pass a fromfile_prefix_chars
parameter to the ArgumentParser()
constructor:
parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
argparse
takes care of the rest for you.
Here is an example:
from argparse import ArgumentParser
parser = ArgumentParser(fromfile_prefix_chars='@')
parser.add_argument('-f', '--foo')
parser.add_argument('--bar')
parser.add_argument('q', nargs='*')
ns = parser.parse_args()
print(ns)
The contents of foo.txt
:
-f
1
--bar=2
q one
q two
The command line and the output:
$ python zz.py @foo.txt
Namespace(bar='2', foo='1', q=['q one', 'q two'])
Use configparser. It uses .ini files and it's really easy to use.
Config file:
[DEFAULT]
KeepAlive = 45
ForwardX11 = yes
Example Code:
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
>>> for key in config['bitbucket.org']: print(key)
...
keepalive
forwardx11
>>> default = config['default']
>>> default['keepalive']
'45'
>>> default['ForwardX11']
'yes'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With