Creating Scripts
Notebooks are great for exploration. And with NBDev they’re pretty amazing for development work too! But sometimes you just want a nice command-line script so that you can run your code with some thing like:
python my_script.py --input cat.png --width 128
In this quick notebook I’ll show you my new favourite way of doing this, using fastcore.script
. The example from their docs shows how simple this can be. We write the following to a file:
from fastcore.script import *
@call_parse
def main(msg:str, # The message
bool): # Convert to uppercase?
upper:"Print `msg`, optionally converting to uppercase"
print(msg.upper() if upper else msg)
Overwriting scripts/example_script.py
Now we can run this like so:
!python scripts/example_script.py --upper 'Hello World'
HELLO WORLD
And those type hints and comments in the function definition above? They become part of the help text:
!python scripts/example_script.py -h
usage: example_script.py [-h] [--upper] msg
Print `msg`, optionally converting to uppercase
positional arguments:
msg The message
options:
-h, --help show this help message and exit
--upper Convert to uppercase? (default: False)
Pretty nifty right!
Check out the scripts/
directory for a bunch of examples which I made using this technique to go along with the course.