1

I'm trying to use the argparse module to extract the arguments from it, but the naive implementation fails when called with the python interpreter:

  1 import argparse
  2 import sys
  3 
  4 parser = argparse.ArgumentParser(description="some test program")
  5 parser.add_argument('--some-option', action="store", dest="some_option")
  6 
  7 parsed_args = parser.parse_args(sys.argv)
  8 print(vars(parsed_args)

It fails because it detects the first argument as the name of the script - in this case "test.py":

~$: python3 ./test.py --some-option=5
usage: test.py [-h] [--some-option INPUT]
test.py: error: unrecognized arguments: ./test.py

The solution I have found at the moment is to search and remove the python scripts name from the arugments, but this seems like an unelegant hack, and will have issues if the first argument can legitimately be a python file:

  1 import argparse
  2 import sys
  3 
  4 parser = argparse.ArgumentParser(description="some test program")
  5 parser.add_argument('--some-option', action="store", dest="some_option")
  6 
  7 print(sys.argv)
  8 if sys.argv[0].find('.py') != -1:
  9     args = sys.argv[1:]
 10 else:
 11     args = sys.argv
 12 
 13 parsed_args = parser.parse_args(args)
 14 print(vars(parsed_args)

Is there a better way to get rid of that pesky python file name when using argparse

Note: I cannot get rid of the call to the intepreter because this is part of a cross-platform build system, and thus has a makefile that sets the python executable to python3 or python3.exe depending on OS.

1 Answer 1

1

sys.argv[0] is always the name of the file. So if you do parsed_args = parser.parse_args(sys.argv[1:]), you can be sure that you will always ignore the file name.

Per the python documentation:

sys.argv The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.

Sign up to request clarification or add additional context in comments.

1 Comment

You are correct. I had assumed that if you invoked the script directly it would not have the python script as an argument to sys.argv - but of course, the python designers are smart people.....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.