1

I have the following code and I want to use to extract the config parameter.

parser = argparse.ArgumentParser() parser.add_argument( "--config", type=str, default="src/config.yml", dest="config" ) 

My issue is that I cannot use parser.parse_args() (because I'm running the script from uvicorn and the parse_args is raising an error. Is there a way to retrieve the config parameter without the use of parse_args?


Other answers I've seen make use of parse_args.

3
  • 1
    Given that parse_args does the parsing of sys.argv and you can’t use it then presumably you’ll have to parse sys.argv yourself - have you tried to do that? Or perhaps you can adapt what is (I guess) a non-standard sys.argv to something that parse_args() can handle? To do that you’ll have to look at sys.argv. Commented Dec 30, 2020 at 17:36
  • What's the error? Commented Dec 30, 2020 at 18:46
  • 1
    What do you mean by the config parameter? Do you want the value that the parser would find in the sys.argv? Or do you want the corresponding Action object? Or its default attribute? Commented Dec 30, 2020 at 22:03

1 Answer 1

0

If you want to parse an argument array that is not passed via sys.argv, for example one that you created, simply pass an array to the parse_args() function.

my_args = ["--config", "my_value"] parsed_args = parser.parse_args(my_args) print(parsed_args.config) # Prints "my_value" 
Sign up to request clarification or add additional context in comments.

3 Comments

No, they seem to suggest that parse_args() does not support what they need, which I would guess it does when reading their question. Edit: More specifically: They say parse_args() raises an error, which I guess is due to sys.argv not being filled by uvicorn.
Then according to your code, they pass my_args = ["--config", "my_value"] in order to get "my_value". But they would already have that value so why use argparse at all?
Mine is a toy example. Presumably they get arguments from somewhere and want to use argparse to verify their validity. They can do that by passing them directly. For example, their example checks for the type (str) and has a default that is assigned if no value is given. Yes, to preempt your obvious next comment, that could be done differently. I know that, I know Python. I'm just trying to help this person with their specific issue. Why does this bother you so much? I'm puzzled.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.