How to run Python functions from command line?

To run Python functions from the command line, you save the function in a .py file and then invoke it using the Python interpreter. There are several approaches − using sys.argv, the -c flag, or the argparse module.

Using sys.argv with __name__ Guard

The most common approach is to use sys.argv to read command-line arguments and the if __name__ == "__main__" guard to call your function when the script is executed directly. The first item in sys.argv is the script name, and subsequent items are the arguments passed. Note that all command-line arguments are received as strings, so you must convert them to the appropriate type inside your script.

Example: Simple String Argument

Create a file called my_functions.py with the following content ?

import sys

def greet(name):
    print(f"Hello, {name}!")

if __name__ == "__main__":
    greet(sys.argv[1])

Run it from the command line ?

~$ python my_functions.py John
Hello, John!

Example: Numeric Arguments

Since command-line arguments are strings, we convert them to integers before performing arithmetic. Create math_functions.py ?

import sys

def multiply(a, b):
    return a * b

if __name__ == "__main__":
    a = int(sys.argv[1])
    b = int(sys.argv[2])
    print(multiply(a, b))

Run it from the command line ?

~$ python math_functions.py 2 3
6

Using the -c Flag

The Python interpreter's -c option lets you run a command as a string directly from the terminal. You can import your module and call any function in it without modifying the script ?

Example

Given a file my_script.py containing ?

def greet(name):
    print("Hello, " + name + "!")

Run the function from the command line ?

~$ python -c "import my_script; my_script.greet('Alice')"
Hello, Alice!

This approach is useful for quick one-off calls without adding a __name__ guard to the file.

Using argparse for Named Options

For more complex scripts that accept multiple named arguments, the argparse module provides a clean interface with built-in help messages and type conversion. Create calc.py ?

Example

import argparse

def calculate(a, b, operation):
    if operation == "add":
        return a + b
    elif operation == "subtract":
        return a - b
    elif operation == "multiply":
        return a * b
    elif operation == "divide":
        return a / b
    else:
        raise ValueError("Invalid operation")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Simple calculator")
    parser.add_argument("a", type=float, help="First number")
    parser.add_argument("b", type=float, help="Second number")
    parser.add_argument("--op", default="add", help="Operation: add, subtract, multiply, divide")
    args = parser.parse_args()
    print(calculate(args.a, args.b, args.op))

Run it from the command line ?

~$ python calc.py 10 5 --op multiply
50.0

Conclusion

Use sys.argv with a __name__ guard for simple scripts, the -c flag for quick one-off calls, and argparse when your function needs named options or built-in help. Always remember that command-line arguments arrive as strings and must be converted to the correct type.

Updated on: 2026-03-12T21:30:33+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements