command line
function
programming
scripting
terminal

Run function from the command line

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

You usually cannot call an arbitrary function directly from the shell unless some program exposes that function as a command-line entry point. The practical solution is to wrap the function in a script, module, or executable that accepts arguments from the command line. In other words, the shell runs programs, and the program decides which function to call.

The Core Idea: Add A CLI Entry Point

Suppose you have a Python function:

python
def greet(name: str) -> str:
    return f"Hello, {name}!"

The terminal cannot invoke greet by name on its own. You need a small command-line wrapper.

python
1import argparse
2
3
4def greet(name: str) -> str:
5    return f"Hello, {name}!"
6
7
8def main() -> None:
9    parser = argparse.ArgumentParser()
10    parser.add_argument("name")
11    args = parser.parse_args()
12    print(greet(args.name))
13
14
15if __name__ == "__main__":
16    main()

Save that as app.py, then run:

bash
python app.py Alice

This is the normal pattern in scripting languages: the shell launches a program, and the program routes command-line arguments into the function.

Call A Specific Function By Name

If you want one file to expose several functions, add a command argument that selects the function.

python
1import argparse
2
3
4def greet(name: str) -> str:
5    return f"Hello, {name}!"
6
7
8def add(a: int, b: int) -> int:
9    return a + b
10
11
12def main() -> None:
13    parser = argparse.ArgumentParser()
14    subparsers = parser.add_subparsers(dest="command", required=True)
15
16    greet_parser = subparsers.add_parser("greet")
17    greet_parser.add_argument("name")
18
19    add_parser = subparsers.add_parser("add")
20    add_parser.add_argument("a", type=int)
21    add_parser.add_argument("b", type=int)
22
23    args = parser.parse_args()
24
25    if args.command == "greet":
26        print(greet(args.name))
27    elif args.command == "add":
28        print(add(args.a, args.b))
29
30
31if __name__ == "__main__":
32    main()

Usage:

bash
python app.py greet Alice
python app.py add 3 5

This is much more robust than trying to expose internal function names directly without validation.

A Lightweight One-Liner Option

For quick experiments, some languages let you evaluate code from the command line.

Example with Python:

bash
python -c "print((lambda x: x * 2)(21))"

Or import a module and call a function:

bash
python -c "from app import greet; print(greet('Alice'))"

This is convenient for ad hoc use, but it is a poor long-term interface. Once the command becomes part of normal workflow, write a proper CLI wrapper.

Shell Functions Are Different

In a Unix shell, you can define a shell function and run it directly, but that function exists only inside the shell session or a sourced script.

bash
1say_hello() {
2  echo "Hello, $1"
3}
4
5say_hello Alice

This is not the same as calling a Python, JavaScript, or Java function from the terminal. It is just running a shell-defined function in the shell process.

That distinction matters because many "run function from command line" questions mix these two ideas.

For Reusable Tools, Prefer A Real Command

If the function will be used repeatedly by humans or automation, turn it into a proper executable command. In Python, that often means:

  • a main() function
  • argument parsing with argparse
  • optional installation as a console script entry point

A real command gives you:

  • validation of inputs
  • predictable help text
  • better error messages
  • a stable interface for scripts and CI jobs

Security And Safety

Do not build a command-line interface that blindly takes a function name from user input and executes it with globals() or eval(). That pattern is fragile and unsafe.

A safer model is explicit routing:

  • parse a known command
  • map it to an allowed function
  • validate each argument

That is more work than dynamic execution, but it prevents a large class of avoidable bugs.

Common Pitfalls

  • Expecting the shell to know about functions that only exist inside source code.
  • Using python -c or similar one-liners as a permanent interface instead of building a proper CLI.
  • Executing functions by unchecked string name through eval() or globals().
  • Forgetting argument parsing and type conversion, which leads to brittle commands.
  • Confusing shell functions with functions defined in another programming language.

Summary

  • The shell runs programs, not arbitrary in-memory language functions.
  • To run a function from the command line, wrap it in a script or CLI entry point.
  • For multiple functions, expose explicit subcommands instead of dynamic execution.
  • One-liners such as python -c are fine for quick tests but weak as long-term interfaces.
  • Shell functions are a different mechanism from calling functions in Python, JavaScript, or other languages.

Course illustration
Course illustration

All Rights Reserved.