help is an example of an optional argument.
Note that –help is the only optional argument you get for free, but you can make more.
Optional arguments are created just like positional arguments except that they have a '–' double dash at the start of their name (or a'-' single dash and one additional character for the short version).
For example, you can create an optional argument with parser.
The following larger example shows how to create and reference an optional argument.
Note that we specify the type int for an integer in this example.
You could also specify other valid Python variable types.
pyimport argparseparser = argparse.
ArgumentParser(description='My example explanation')parser.
add_argument( '–my_optional', default=2, help='provide an integer (default: 2)')my_namespace = parser.
my_optional)Note that the argument specified with '–my_optional' becomes this namespaced variable without the dashes: 'my_namespace.
Also note that the optional argument can have a default value.
Here we specify a default of 2.
Running python my_example.
py outputs 2.
The optional argument value can be set at run time from the command line like this: python my_example.
The program then outputs 3.
IntegersYou can do even more with argparse.
For example, you can have arguments gathered into lists with nargs='*’.
You can also check for ranges of values with choices.
See the argparse docs for all you can do.
When Else Might I Use argparse?You can also use argparse with programs running in Docker containers.
If you want to pass command line arguments to your scripts when building your image you can do so with RUN.
If you want to pass arguments to your script at run time you can do so with CMD or ENTRYPOINT.
Learn more about Dockerfiles in my series on Docker:Learn Enough Docker to be UsefulPart 3: A Dozen Dandy Dockerfile Instructionstowardsdatascience.
comWrapNow you’ve seen the basics of argparse.
You’ve seen how to get positional and optional arguments into your programs from the command line.
You’ve also seen how to set default optional arguments.
If you want to go deeper, check out the official docs.
More mountains through the mistHere are a few more suggestions to help you step out of the Jupyter Notebook.
Environment variables are useful variables that get set outside a program.
Here’s a nice, clear intro.
This article from DataCamp blog focuses on the PATH variable.
You can convert repos with Jupyter notebooks into Docker Images with Repo2Docker.
Will Koehrsen wrote a good guide on the tool here.
I plan to write more articles about interacting with the file system and scripting.
Follow me to make sure you don’t miss them!.????I hope you found this intro useful.
If you did, share it on your favorite forums and social media.
Data scientists and programmers who don’t know argparse will thank you!Thanks for reading!????.