How to Run a Python Function from the Command Line?

Recently, in a Python workshop, someone asked me about calling a function in Python from the command line. This is very useful, and there are different methods to achieve this. In this tutorial, I will show you how to run a Python function from the command line using various methods and examples.

To run a Python function from the command line using the -c option, you can pass a command as a string to the Python interpreter. For example, if you have a function greet in a file named hello.py, you can execute it by using the command python -c "import hello; hello.greet()".

Run a Python Function from the Command Line

While working with Python functions, you will get the requirement to run a Python function from the command line.

Let me show you different methods to run a Python function from the command line.

Method 1: Using the -c Option

The simplest way to run a Python function from the command line is by using the -c option. This allows you to pass a command as a string to the Python interpreter.

Let me show you the syntax:

Syntax:

python -c "import your_module; your_module.your_function()"

Example:

Here is an example for you. Suppose you have a Python file named hello.py with the following content:

def greet():
    print("Hello, New York!")

You can run the greet function from the command line like this:

python -c "import hello; hello.greet()"

This command imports the hello module and calls the greet function, printing “Hello, New York!” to the terminal.

Check out How to Call a Function in Python?

Method 2: Using the sys Module

Another method to run a function in Python using the command line is by using the sys module to pass command-line arguments to your script. This is particularly useful when you need to pass parameters to your function.

Syntax:

import sys

def your_function(arg):
    print(f"Argument received: {arg}")

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

Example:
Save the above script as example.py. You can then run it from the command line and pass an argument:

python example.py "Hello from command line"

This will output:

Argument received: Hello from command line

Method 3: Using argparse for Complex Arguments

For more complex argument parsing, the argparse module is the best to call the function from the command line. It allows you to define multiple arguments and options that your script can accept.

Syntax:

import argparse

def your_function(arg1, arg2):
    print(f"Arguments received: {arg1}, {arg2}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Run a function from the command line")
    parser.add_argument("arg1", type=str, help="First argument")
    parser.add_argument("arg2", type=str, help="Second argument")
    args = parser.parse_args()

    your_function(args.arg1, args.arg2)

Example:
Save this script as complex_example.py. You can run it from the command line like this:

python complex_example.py "Hello" "World"

This will output:

Arguments received: Hello, World

Check out Python Function Examples with Parameters

Method 4: Using subprocess for External Scripts

If you need to call a Python function from another script, you can use the subprocess module to execute a Python script from within another Python script.

Syntax:

import subprocess

subprocess.run(["python", "your_script.py", "arg1", "arg2"])

Example:
Assume you have a script external_script.py with the following content:

import sys

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

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

You can call this script from another Python script:

import subprocess

subprocess.run(["python", "external_script.py", "Alice"])

This will output:

Hello, Alice!

Conclusion

In this tutorial, I have explained how to run Python functions from the command line using various examples. We also saw examples for each method, like the —c option, sys for simple arguments, argparse for complex parsing, or subprocess for integrating scripts.

You may also like:

Leave a Comment