Skip to content
Snippets Groups Projects

merge Aj argparse branch into master

Merged Wasiu Akanni requested to merge Aj_argparse into master
+ 276
221
@@ -73,32 +73,7 @@ keypoints:
> Pair up and discuss with a partner.
{: .challenge}
> ## Options & Arguments Revisited
> In an earlier exercise,
> you filled in the blanks in code designed to
> parse options and arguments from the command line using `sys.argv`.
> Use what you've learned about `argparse` to write a parser to replace that
> code.
>
> As a reminder, after the changes you made earlier,
> the program should take
> **one (and _only_ one) of three modes** (`--sum`, `--product`, `--mean`)
> to determine which function will be used in the body of the script,
> **an arbitrary number of input files**,
> and, **optionally, an output file name**.
> Also include the possibility to provide shorthand, single-letter flags
> (`-s`, `-p`, and `-m`)
> for each of the modes.
>
> Once you've got this parser up and running, try it out.
> Start by running the script with only the `-h` flag,
> then try providing the expected user input,
> before finally providing some incorrect/incompatible options and/or arguments
> and observe the result in each case.
> Do you think this is better than the approach we used before?
> If so, do you consider the improvement sufficient to be worth the effort?
>
{: .challenge }
> ## Carry the Zero
>
@@ -114,213 +89,293 @@ keypoints:
{% include links.md %}
##argparse
### What
- standard module
- easy and neat processing of options and arguments
- auto generation of program usage and inbuilt help functions
- Interfaces with the python system module to grab arguments from the command line
### Why
- Easy, and comes standard with python
- Great way to streamline your program for professional use
- Saves you time by, construction and formatting of help and usage outputs
- Allows dynamic programming through dynamic data input
### How
- Q1 : Try the following code and make it print the default help message for our little program
~~~
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
args = parser.parse_args()
~~~
{: .language-python }
- Anwser Q1 : python parsing_tut.py -h
> ##argparse
#### Positional arguments
>> ### What
>> standard module
>> easy and neat processing of options and arguments
>> auto generation of program usage and inbuilt help functions
>> Interfaces with the python system module to grab arguments from the command line
~~~
>> ### Why
>> Easy, and comes standard with python
>> Great way to streamline your program for professional use
>> Saves you time by, construction and formatting of help and usage outputs
>> Allows dynamic programming through dynamic data input
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("number1", help=" first number")
parser.add_argument("number2", help=" second number")
{: .keypoints}
args = parser.parse_args()
print(args.number1)
print(args.number2)
~~~
{: .language-python }
- run the script
- python parsing_tut.py 7 3
- what happens when you run
- python parsing_tut.py 7 3 add
- what happened to the 'add' argument
- Q2 : add a operations positional argument to handle the 'add' argument
> ## Help message
> Try the following code and make it print the default help message for our little program
>
> ~~~
> import argparse
>
> if __name__ == "__main__":
> parser = argparse.ArgumentParser()
> args = parser.parse_args()
>
> ~~~
> {: .language-python }
>
>> ## Solution
>>
>> python parsing_tut.py -h
>> {: .output}
> {: .solution}
{: .challenge}
- Anwser Q2 :
~~~
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("number1", help=" first number")
parser.add_argument("number2", help=" second number")
parser.add_argument("operation", help=" operation")
args = parser.parse_args()
print(args.number1)
print(args.number2)
print(args.operation)
~~~
{: .language-python }
- run the following
- python parsing_tut.py 7 3 add
- Q3 : what is the drawback of using positional arguements
- Anwser Q3 :They are mandatory. You can not skip any arguments
- Q3a : Convert your number argument to an integer.
- Answer Q3a :
~~~
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("number1", type=int, help=" first number")
parser.add_argument("number2", type=int, help=" second number")
parser.add_argument("operation", help=" operation")
args = parser.parse_args()
print(args.number1)
print(args.number2)
print(args.operation)
~~~
{: .language-python }
#### Optional arguments
- Allows us to skip arguments, there is no longer a need for fix positions and we know exactly which arguments we are passing to the program
~~~
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--number1", help=" first number")
parser.add_argument("--number2", help=" second number")
parser.add_argument("--operation", help=" operation")
args = parser.parse_args()
print(args.number1)
print(args.number2)
print(args.operation)
~~~
{: .language-python }
- Q4 : run the above code with the following argument 5, 8, multiply
- Answer Q4: python parsing_tut.py number1 5 number2 3 operation multiply
- Q5 : make the program work with "python parsing_tut.py -n1 5 -n2 3 -op multiply"
- Anwser Q5
~~~
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-n1", "--number1", help=" first number")
parser.add_argument("-n2", "--number2", help=" second number")
parser.add_argument("-op", "--operation", help=" operation")
args = parser.parse_args()
print(args.number1)
print(args.number2)
print(args.operation)
~~~
{: .language-python }
#### restricting what users can give for an argument
~~~
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-n1", "--number1", help=" first number")
parser.add_argument("-n2", "--number2", help=" second number")
parser.add_argument("-op", "--operation", help=" operation", \
choices=['add','substract','multiply'])
args = parser.parse_args()
print(args.number1)
print(args.number2)
print(args.operation)
~~~
{: .language-python }
- Q6 : what happens when you run the program with an invalid choices and then add your choices to the program
#### statements
- we can also use conditional statements with args, allowing us to set flags
~~~
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-n1", "--number1", help=" first number")
parser.add_argument("-n2", "--number2", help=" second number")
parser.add_argument("-op", "--operation", help=" operation", \
choices=['add','substract','multiply'])
parser.add_argument("-d", "--debug", help=" print out the given argument", action="store_true")
args = parser.parse_args()
if args.debug:
print(args.number1)
print(args.number2)
print(args.operation)
~~~
{: .language-python }
> ## Positional arguments
>
> ~~~
> import argparse
> if __name__ == "__main__":
> parser = argparse.ArgumentParser()
> parser.add_argument("number1", help=" first number")
> parser.add_argument("number2", help=" second number")
>
> args = parser.parse_args()
> print(args.number1)
> print(args.number2)
> ~~~
> {: .language-python }
>
> run the script
> - python parsing_tut.py 7 3
>
> - what happens when you run
> - python parsing_tut.py 7 3 add
>
> - What happened to the 'add' argument
> - Add a operations positional argument to handle the 'add' argument
>
>> ## Solution
>> ~~~
>> import argparse
>> if __name__ == "__main__":
>> parser = argparse.ArgumentParser()
>> parser.add_argument("number1", help=" first number")
>> parser.add_argument("number2", help=" second number")
>> parser.add_argument("operation", help=" operation")
>> args = parser.parse_args()
>>
>> print(args.number1)
>> print(args.number2)
>> print(args.operation)
>> ~~~
>> {: .output }
> {: .solution}
{: .challenge}
#### Mutually exclusive arguments
> ## Skip positional arguments
> run the following code
> - python parsing_tut.py 7 3 add
> - Q3 : what is the drawback of using positional arguements
>
>> ## Solution
>>
>> They are mandatory. You can not skip any arguments
> {: .solution}
{: .challenge}
- This allows us further fine grain control of the programs by limiting the options that can be used together
## Convert options argument to an integer.
>
> update the code from the previous task to convert your numbers to integer
>
>> Solution
>>
>> ~~~
>>import argparse
>> parser = argparse.ArgumentParser()
>> parser.add_argument("number1", type=int, help=" first number")
>> parser.add_argument("number2", type=int, help=" second number")
>> parser.add_argument("operation", help=" operation")
>> args = parser.parse_args()
>>
>> print(args.number1)
>> print(args.number2)
>> print(args.operation)
>> ~~~
>> {: .language-python }
> ## Optional arguments
>
> - Allows us to skip arguments, there is no longer a need for fix positions and we know exactly which arguments we are passing to the program
>
> ~~~
> import argparse
> if __name__ == "__main__":
> parser = argparse.ArgumentParser()
> parser.add_argument("--number1", help=" first number")
> parser.add_argument("--number2", help=" second number")
> parser.add_argument("--operation", help=" operation")
> args = parser.parse_args()
>
> print(args.number1)
> print(args.number2)
> print(args.operation)
> ~~~
> {: .language-python }
>
> - Q1: run the above code with the following argument 5, 8, multiply
>
> - Answer Q4: python parsing_tut.py number1 5 number2 3 operation multiply
>
> - Q2 : make the program work with "python parsing_tut.py -n1 5 -n2 3 -op multiply"
>
>> ## Solution
>> - Anwser Q2
>> ~~~
>> import argparse
>> if __name__ == "__main__":
>> parser = argparse.ArgumentParser()
>> parser.add_argument("-n1", "--number1", help=" first number")
>> parser.add_argument("-n2", "--number2", help=" second number")
>> parser.add_argument("-op", "--operation", help=" operation")
>> args = parser.parse_args()
>>
>> print(args.number1)
>> print(args.number2)
>> print(args.operation)
>> ~~~
>> {: .output}
> {: .solution}
{: .challenge}
- This is done with a group and an output is auto generated, telling the user you can ony pick one if they try 2 or more from the group together
> ## restricting what users can give for an argument
>
> ~~~
> import argparse
> if __name__ == "__main__":
> parser = argparse.ArgumentParser()
> parser.add_argument("-n1", "--number1", help=" first number")
> parser.add_argument("-n2", "--number2", help=" second number")
> parser.add_argument("-op", "--operation", help=" operation", \
> choices=['add','substract','multiply'])
> args = parser.parse_args()
>
> print(args.number1)
> print(args.number2)
> print(args.operation)
> ~~~
> {: .language-python }
>
> - Q1 : what happens when you run the program with an invalid choices and then add your choices to the program
>
{: .discussion}
~~~
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-n1", "--number1", help=" first number")
parser.add_argument("-n2", "--number2", help=" second number")
parser.add_argument("-op", "--operation", help=" operation", \
choices=['add','substract','multiply'])
parser.add_mutually_exclusive_group()
parser.add_argument("-v", "--verbose", action="store_true")
parser.add_argument("-q", "--quiet", action="store_true")
> ## statements
>
> - we can also use conditional statements with args, allowing us to set flags
>
> ~~~
> import argparse
> if __name__ == "__main__":
> parser = argparse.ArgumentParser()
> parser.add_argument("-n1", "--number1", help=" first number")
> parser.add_argument("-n2", "--number2", help=" second number")
> parser.add_argument("-op", "--operation", help=" operation", \
> choices=['add','substract','multiply'])
> parser.add_argument("-d", "--debug", help=" print out the given argument", action="store_true")
> args = parser.parse_args()
>
> if args.debug:
> print(args.number1)
> print(args.number2)
> print(args.operation)
> ~~~
> {: .language-python }
>
> - Run and discuss the above code
{: .discussion}
args = parser.parse_args()
> ## Mutually exclusive arguments
>
> - This allows us further fine grain control of the programs by limiting the options that can be used together
>
> - This is done with a group and an output is auto generated, telling the user you can ony pick one if they try 2 or more from the group together
>
> ~~~
> import argparse
> if __name__ == "__main__":
> parser = argparse.ArgumentParser()
> parser.add_argument("-n1", "--number1", help=" first number")
> parser.add_argument("-n2", "--number2", help=" second number")
> parser.add_argument("-op", "--operation", help=" operation", \
> choices=['add','substract','multiply'])
> group = parser.add_mutually_exclusive_group()
> group.add_argument("-v", "--verbose", action="store_true")
> group.add_argument("-q", "--quiet", action="store_true")
>
> args = parser.parse_args()
>
> if args.verbose:
> print(args.number1)
> print(args.number2)
> print(args.operation)
>
> if args.quiet:
> print("Schush\n")
> ~~~
> {: .language-python }
>
> - Run and discuss the above code
{: .discussion}
if args.debug:
print(args.number1)
print(args.number2)
print(args.operation)
> ## Handling variable number of arguments (nargs)
> argparse can also handle a variable number of argument/input into one optional arguments
> update the above code to take a variable amount of numbers into a single 'numbers' argument
>
>> ## Solution
>>
>> import argparse
>> if __name__ == "__main__":
>> parser = argparse.ArgumentParser()
>> parser.add_argument("-n", "--numbers", nargs='+', help=" first number")
>> parser.add_argument("-op", "--operation", help=" operation", choices=['add','substract','multiply'])
>> group = parser.add_mutually_exclusive_group()
>> group.add_argument("-v", "--verbose", action="store_true")
>> group.add_argument("-q", "--quiet", action="store_true")
>>
>> args = parser.parse_args()
>>
>> if args.verbose:
>> for i in args.numbers:
>> print(i)
>> print(args.operation)
>> if args.quiet:
>> print("Schush\n")
>> ~~~
>> {: .output }
> {: .solution}
{: .challenge}
if args.quiet:
print("Schush\n")
~~~
{: .language-python }
> ## Options & Arguments Revisited
> In an earlier exercise (),
> you filled in the blanks in code designed to
> parse options and arguments from the command line using `sys.argv`.
> Use what you've learned about `argparse` to write a parser to replace that
> code.
>
> As a reminder, after the changes you made earlier,
> the program should take
> **one (and _only_ one) of three modes** (`--sum`, `--product`, `--mean`)
> to determine which function will be used in the body of the script,
> **an arbitrary number of input files**,
> and, **optionally, an output file name**.
> Also include the possibility to provide shorthand, single-letter flags
> (`-s`, `-p`, and `-m`)
> for each of the modes.
>
> Once you've got this parser up and running, try it out.
> Start by running the script with only the `-h` flag,
> then try providing the expected user input,
> before finally providing some incorrect/incompatible options and/or arguments
> and observe the result in each case.
> Do you think this is better than the approach we used before?
> If so, do you consider the improvement sufficient to be worth the effort?
>
{: .challenge }
\ No newline at end of file
Loading