1

I noticed one of my scripts was not running because an argparse parser was not able to parse_args().

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="Save a plot to file")
    parser.add_argument('input_directory', metavar='i', type=str, default='.',
                        help='The input directory')

    parser.add_argument('output_file', metavar='o', type=str,
                        help='The output filename')

    parser.add_argument('--fix', type=str, default=None,
                        help='If FIX, the txt containing fix classification results')

    args = parser.parse_args()

    import ipdb; ipdb.set_trace()

Strangely enough, I noticed that the problem has to do with the variable called args. I cannot retrieve any information from that variable, since it always returns empty. If I change the name of the args variable to anything else, then the script works fine.

I'm asking this question because I could not find any information telling me that args is a keyword, or anything else.

I invoked my script as:

python3 plotter.py --fix $(pwd)/fix.txt $(pwd) $(pwd)/plot.png

Here's a screenshot of the funny behaviour:

weird

Note how any statement containing the word args does not return.

Any ideas of what may be happening here?

Daniel
  • 11,332
  • 9
  • 44
  • 72

3 Answers3

2

You can refer to the args variable name by prepending it with an exclamation mark:

ipdb> !args

args is actually a command used by ipdb, see here:

Explanation:

a(rgs)
Print the argument list of the current function.
ponadto
  • 702
  • 7
  • 17
1

Try using vars()

args = vars(parser.parse_args())

then retrieve using

some_val = args['some']

Also refer this stackoverflow post

Arpit Solanki
  • 9,567
  • 3
  • 41
  • 57
1

ipdb/__main__.py sets args in its main:

def main():
    ...
    opts, args = getopt.getopt(sys.argv[1:], 'hc:', ['--help', '--command='])

I don't know what's visible when run interactively, but I suspect its own use of args is interfering with what you see with

args = parser.parse_args(...)

When testing argparse, I routinely add a

print(args)

statement. Or I test it in an ipython session, where I can look at the result of parse_args without further work.

hpaulj
  • 221,503
  • 14
  • 230
  • 353