Imagine a program that needs an input path in order to operate. Let's examine how using this might look with argparse
and input
.
First, argparse
#! /usr/bin/env python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("inputfile")
args = parser.parse_args()
print(args.inputfile)
You might use it like this:
$ ./myscript.py /path/to/file.txt
/path/to/file.txt
If I wasn't 100% sure of the path, I could use my shell's tab-completion to help me out
$ ./myscript.py /path/<TAB>
(selects the "to" directory)
$ ./myscript.py /path/to/<TAB>
(selects the "file.txt" file)
$ ./myscript.py /path/to/file.txt
/path/to/file.txt
That was helpful!! If I want to execute this again, I can just press the "up" arrow and it's right there on my command prompt to be executed again!
Now, let's look at using input
#! /usr/bin/env python3
inputfile = input("Inputfile? ")
print(inputfile)
You might use it like this
$ ./myscript.py
Inputfile? /path/to/file.txt
What if I didn't know the path? Could I use tab completion?
$ ./myscript.py
Inputfile? /path/<TAB>
Oh no! It just inserted a tab into the filename - I get no help.
What if I want to execute the same command again? I press up, and then have to re-type the file path before running. Imagine you are debugging this script and need to run it over and over again - re-typing the path will get old very fast.
input
is really only useful if you want to force a script to be interactive, like if you want to say "Are you sure you want to proceed? [y/N]". Otherwise, it's best to accept runtime parameters on the command line to take full advantage of what the shell has to offer as well as make it so that re-execution (and using your script in another script) is much simpler.