On 15.05.2013 17:29, Roy Smith wrote:
In article <kn00fb$8kc$1...@gwdu112.gwdg.de>,
Henry Leyh  <henry.l...@ipp.mpg.de> wrote:
On 15.05.2013 14:24, Roy Smith wrote:
In article <kmva9j$1hbk$1...@gwdu112.gwdg.de>,
   Henry Leyh <henry.l...@ipp.mpg.de> wrote:

Is there a simple way to determine which
command line arguments were actually given on the commandline, i.e. does
argparse.ArgumentParser() know which of its namespace members were
actually hit during parse_args().

I think what you're looking for is sys.argv:

$ cat argv.py
import sys
print sys.argv

$ python argv.py foo bar
['argv.py', 'foo', 'bar']

Thanks, but as I wrote in my first posting I am aware of sys.argv and
was hoping to _avoid_ using it because I'd then have to kind of
re-implement a lot of the stuff already there in argparse, e.g. parsing
sys.argv for short/long options, flag/parameter options etc.

Sorry, I missed that.

I'm not clear on exactly what you're trying to do.  You say:

Now I would also like the program to be able to _write_ a
configparser config file that contains only the parameters actually
given on the commandline.

I'm guessing what you're trying to do is parse the command line first,
then anything that was set there can get overridden by a value in the
config file?  That seems backwards.  Usually, the order is:

1) built-in default
2) config file (possibly a system config file, then a per-user one)
3) environment variable
4) command-line argument

It sounds like you're doing it in the reverse order -- allowing the
config file to override the command line.

No. The program reads a general config file in $HOME, something like ~/.programrc; then parses the command like for '-c FILE' and, if FILE is present reads it; then parses the command line remains for more arguments which overwrite everything previously set. (For the record, this split parsing is done with two argparse parsers. The first parses for '-c FILE' with parse_known_args(). If there is a FILE, its contents is used as defaults for a second parser (using set_options()) which then parses the remains that were returned by the first parser's parse_known_args().)

But now I would also like to be able to _write_ such a config file FILE that can be read in a later run. And FILE should contain only those arguments that were given on the command line.

Say, I tell argparse to look for arguments -s|--sopt STRING, -i|--iopt INT, -b|--bopt [BOOL], -C CONFFILE. Then 'prog -s bla -i 42 -C cfile' should produce a confparser compatible cfile which contains

  [my_options]
  sopt = blah
  iopt = 42

and not 'bopt = False' (if False was the program's default for bopt).

Regards,
Henry

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to