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.

David Masip
  • 2,146
  • 1
  • 26
  • 46
  • 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. – DisappointedByUnaccountableMod Dec 30 '20 at 17:36
  • What's the error? – wjandrea Dec 30 '20 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? – hpaulj Dec 30 '20 at 22:03

1 Answers1

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"
vauhochzett
  • 2,732
  • 2
  • 17
  • 40
  • 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. – vauhochzett Feb 03 '21 at 13:29
  • 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? – Tomerikoo Feb 03 '21 at 13:52
  • 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. – vauhochzett Feb 03 '21 at 20:34