Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to pass command line arguments via file in python

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.

like image 736
Ladenkov Vladislav Avatar asked Oct 15 '25 18:10

Ladenkov Vladislav


2 Answers

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'])
like image 116
Robᵩ Avatar answered Oct 18 '25 08:10

Robᵩ


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'
like image 38
Josh Abraham Avatar answered Oct 18 '25 07:10

Josh Abraham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!