Python CLI
In this post, I would like to introduce you to the python CLI. Back in the days of early computing, if you wanted a computer to perform a task, you needed to strictly work in the terminal. With the invention of IDE's, we have a much easier time when it comes to communicating with the computer. But, for this post I want to focus on creating a Python CLI program that performs operations using the eval function that is built in Python.
Even though the eval function is not recommended, see this post here. But, since we can assume that we are the only ones using it, the eval function is perfectly fine to use. If you are unfamiliar with the eval function, make sure to visit this link. In order to properly use our CLI App, we need to access the command line arguments. This can easily be done by importing sys and accessing the arguments by sys.argv. See doc.python:sys.argv for details.
The last thing we need to create a CLI is the Argument Parser object. This will inspect the command line and convert each argument to the appropriate type so that the approprate action is invoked. See docs.python: Argparse Tutorial. Looking at the code below, we have two import statements, one for argparse and the other for sys. The argparse module will bring in the Argument Parser object. We will assign this to a variable named parser. The parser will parse the arguments and store them in a variable named args. The args variable will hold the expression and evaluate. It will be surrounded by a try except feature in Python. The result is then printed. The default data type for args is a string which is good enough for the eval() function. We will also add a help flag. This can be initiated in our command line by executing the python program without any arguments.
Python
import argparse, sys
parser = argparse.ArgumentParser()
parser.add_argument('input', help="The Input Expression Passed to Eval Function")
args = parser.parse_args()
try:
result = eval(args.input)
print(result)
except (NameError, SyntaxError):
sys.exit("Error: Not A Valid Expression")
Code copied
In conclusion, this wraps up our discussion on CLI Applications. In another post, I plan on discussing how to initialize mutiple flags that will perform different translations on the system arguments.