'How to include code attribute in parse_arg?
I have the following code:
import argparse
parser = argparse.ArgumentParser(description = "Gobblet game")
parser.add_argument("code", metavar = "CODE", type=str, help= "Player code")
parser.add_argument("-l", "--lister", action="store_true", help= "Lists existing games")
attrib = parser.parse_args()
When I do print(attrib), an error prompt tells me that the the CODE argument is required. Where does this argument need to be placed in my code for this to create a Namespace of the player's code?
Solution 1:[1]
You've added mandatory positional argument to your code with this line:
parser.add_argument("code", metavar = "CODE", type=str, help= "Player code")
That means your script needs to be called with at least one non-option argument. That is, if your script is called myscript.py, you would need to call it like this:
python myscript.py <player_code_goes_here>
Or:
python myscript.py --lister <player_code_goes_here>
If you call parser.parse_args() and your command line doesn't have a non-option argument, it will fail as you've described.
If you intended code to be an option (like --code), you would need:
parser.add_argument("--code", metavar = "CODE", type=str, help= "Player code")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | larsks |
