I am trying to make the most basic code that shows how arge parse works so I can understand it. I tried reading tutorials on argparse but its extremely confusing.
I am trying to make a function which can take an argument as a variable. If no argument is given at the command line, then it does something else. Making the function is easy but I have no clue how to just make a simple argparse command.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--option1', help='description for option1')
parser.add_argument('--option2', help='description for option2')
parser.add_argument('--option3', help='description for option3')
def my_func():
if param
input("input your value here: ")
else:
print("we didn't use args")
my_func()
Someone told me to read this: https://docs.python.org/3/howto/argparse.html#id1 but this is super confusing. I don't need the ls I just need an example of how argparse works without a lot of extra code.
Is there any code, where I can just copy and paste an example so I can see how it works? Thanks
Here is a very simple example.
You have to save it as arg_parse.py and run it in your terminal with:
#!/usr/bin/env sh
python3 arg_parse.py -o hello_world
It will print hello_world in your terminal:
> python3 arg_parse.py -o hello_world
hello_world
#!/usr/bin/env python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--opts",)
args = parser.parse_args()
opts = args.opts
print(opts)
It takes whatever you enter in the terminal after --opts (or short -o) and saves it to variable args.opts you can use it then as you would normally in python
I finally found a very basic example of argparse that doesn't use math, classes, or bash commands for its example: https://towardsdatascience.com/a-simple-guide-to-command-line-arguments-with-argparse-6824c30ab1c3
this code here is perfect because it can be ran instantly, and you can see how it works in action:
# Import the library
import argparse
# Create the parser
parser = argparse.ArgumentParser()
# Add an argument
parser.add_argument('--name', type=str, required=True)
# Parse the argument
args = parser.parse_args()
# Print "Hello" + the user input argument
print('Hello,', args.name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With