2 Ways to Run Python Functions from the Command Line

This tutorial will show you 2 ways to run Python functions from the command line – using command line arguments by importing the sys module, or by using the argparse module

Python is a language that can be used in collaboration with other tools in our system. It is because of its versatility and ease that Python is changing the way we communicate with our devices. Today, we will learn how to run Python functions from the command line.

Setting Up Python

Before writing Python scripts, we need to set up Python on our desktops. First, go to the official Python documentation “https://www.python.org/downloads/” and download the latest Python release. You can refer to the following image and click on Python 3.12.1. The Python version 3.12.1 might differ.

Python_Downlaod

After your download is finished, run the file and click on “customize the installation”.Next, you will see advanced settings, tick the box for “Add Python to Environment Variable” and install Python.

Finally, search for the command line from your Windows menu. Type “Python –version” or “Python -v” to check if Python was installed correctly. Refer to the following image for support.

Check_python

Thus here we can see the Python version installed on my device. If the command line throws an error like “Python not found”, either recheck the environment variable added in the system or check the steps mentioned earlier.

Methods to Run Python Script from CMD

Let’s get right into the methods to run Python script from Windows CMD.

Command-Line Arguments

The command-line arguments are values passed to the function/program during its execution. Let’s take a script example, a file named calculator.py with a function that adds two values.

import sys
 
def add_numbers(num1, num2):
    result = num1 + num2
    print(f"The sum is: {result}")
 
if __name__ == "__main__":
      if len(sys.argv) != 3:
        print("Usage: python calculator.py <num1> <num2>")
        sys.exit(1)
 
num1 = float(sys.argv[1])
num2 = float(sys.argv[2])
 
add_numbers(num1, num2)

First, you have to make a call to the sys module that is responsible for accepting command-line arguments. Next, create a function for adding numbers that take three values: script name, number1 and number2. The sys.agrv extracts such values when given in the console.

Now head toward the command line tool and write code for accessing the file path, where our python file is stored. Type “cd” and then the path with a space.

terminal_output1

In the next line, type Python followed by the file’s name and pass the two numbers to be added.

terminal_output2

Hence the python function runs after taking values and provides the output as 12. This is how we can pass values from the command line and run Python functions smoothly.

Argparse Module

The “argparse” module improves user experience and simplifies complex codes. We will use the previous example and import the “argparse” module.

import argparse
 
def add_numbers(num1, num2):
    result = num1 + num2
    print(f"The sum is: {result}")
 
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="A simple calculator script.")
    parser.add_argument("num1", type=float, help="First number")
    parser.add_argument("num2", type=float, help="Second number")
 
    args = parser.parse_args()
 
add_numbers(args.num1, args.num2)

Like the previous example, we need to import “argparse” module. Along with the add function, we create a block that runs on a script, when directly called. Inside this block, you need to create an object with a description. The description is displayed when users request help or provide incorrect inputs. Lastly “add_argument” and “parse_Args” methods are called to take arguments from the command line.

Now to run this code from the command line, we will use the last syntax. Take reference from the following image.

terminal_output3

We can see that Python takes values 5 and 7 from the command line and prints their sum as output. One other advantage that comes with this method is the help message. This help message will be displayed, when the user provides wrong input, thus helping one understand the reasons behind errors.

What are the different modules used to run Python script from the command line?

To run Python script from the command line, we can use modules like “sys” or “argparse” that help us get inputs from the command line. The choice of method depends on the user and the system’s needs.

What is the syntax to run the Python function in the terminal?

To call the python script in the terminal, go to the directory where the python script is present by typing ” cd \path\address\directory” and then run the function by typing “python” followed by the file’s name in the terminal itself.

Summary

There are two primary ways to run Python functions from the command line – using command line arguments by importing the sys module, or by using the argparse module. The argparse module is the easiest way to run Python functions from the command line. It avoids complex code while providing useful help messages. How else can you run Python scripts from the terminal?

#python 

2 Ways to Run Python Functions from the Command Line
1.30 GEEK