This looks correct to me, and yes if you're looking to use this as a module you would import main. Though, it would probably be better to name it in a more descriptive way.

To clarify how __main__ and the function main() works. When you execute a module it will have a name which is stored in __name__. If you execute the module stand alone as a script it will have the name __main__. If you execute it as part of a module ie import it into another module it will have the name of the module.

The function main() can be named anything you would like, and that wouldn't affect your program. It's commonly named main in small scripts but it's not a particularly good name if it's part of a larger body of code.

In terms letting a user to input arguments when running as a script I would look into either using argparse or click

An example of how argparse would work.

if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(description='Create a ArcHydro schema')
    parser.add_argument('--workspace', metavar='path', required=True,
                        help='the path to workspace')
    parser.add_argument('--schema', metavar='path', required=True,
                        help='path to schema')
    parser.add_argument('--dem', metavar='path', required=True,
                        help='path to dem')
    args = parser.parse_args()
    main(workspace=args.workspace, schema=args.schema, dem=args.dem)
Answer from Jonathan on Stack Overflow
🌐
Stanford CS
cs.stanford.edu › people › nick › py › python-main.html
Python main() - Command Line Arguments
However many command line arguments the user typed in, they will populate the args list. Note that the args in the list are always strings. The code in main() can use a simple series of if-statements to detect the different options, such as -affirm, and run the appropriate code for each option. For example, consider a run of the program with the -affirm option like this:
Discussions

Best practice for Python main function definition and program start/exit - Software Engineering Stack Exchange
A console_scripts function must be callable without any arguments. So, as long as all parameters have default values you’re fine. For longer running scripts consider explicitly handling KeyboardInterrupt to print a nice message when the user aborts with Ctrl+C. In the end the relevant part of your your_package/your_module.py might look something like this: def main(cli_args: List[str] = None) -> int: """ `cli_args` makes it possible to call this function command-line-style from other Python ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
Passing argument to function from command line
My son wrote a command line program in ruby for me. I want to convert it to python. To run the program he has done this on the command line; “./myProgram.rb ‘argument’”. Then the 'argument ’ is passed into the program to be processed. I want to do the same in python. More on discuss.python.org
🌐 discuss.python.org
8
0
June 25, 2025
How do you call another file's __main__, passing it command line arguments?
You shouldn't call main from another file generally. The whole point of it is to allow you to start a program externally. The only logic that really should be inside in your main is argument parsing and possibly so other basic setup. You can move whatever code you're trying to call into another function and call that from main instead. Then you can both call your program externally through main and by calling the function you created from other python files. More on reddit.com
🌐 r/learnpython
12
2
September 3, 2020
Argument passing in python script
Hey, I’m working with the invoke python method in UIPaths I want to pass 3 arg to python fuction 2 string and one python obj how can I do that?? More on forum.uipath.com
🌐 forum.uipath.com
14
0
September 22, 2023
🌐
DEV Community
dev.to › xowap › the-ultimate-python-main-18kn
The Ultimate Python main() - DEV Community
May 12, 2021 - There is two main things you want to handle: SIGINT — When the user does a CTRL+C in their terminal, which raises a KeyboardInterrupt · SIGTERM — When the user kindly asks the program to die with a TERM signal, which can be handled (as opposed to SIGKILL) but we'll see that later ... #!/usr/bin/env python3 from argparse import ArgumentParser from time import sleep from typing import Sequence, Optional, NamedTuple from sys import stderr class Args(NamedTuple): what: str def parse_args(argv: Optional[Sequence[str]] = None) -> Args: parser = ArgumentParser() parser.add_argument("-w", "--what", default="hello, world") return Args(**parser.parse_args(argv).__dict__) def main(argv: Optional[Sequence[str]] = None): args = parse_args(argv) sleep(100) print(args.what) if __name__ == "__main__": try: main() except KeyboardInterrupt: stderr.write("ok, bye\n") exit(1)
🌐
Medium
medium.com › @jordan.l.edmunds › how-to-main-like-a-boss-dcc6dfb16223
How to __main__ like a boss. Using entry points in your python… | by Jordan Edmunds Chetty, PhD | Medium
December 2, 2023 - For example, suppose you are writing a command-line tool to square a numbe. I put the parsing of command-line options inside the __main__ entry point directly, and then pass those into the main() function as arguments:
🌐
W3Schools
w3schools.com › python › python_arguments.asp
Python Function Arguments
Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
Top answer
1 of 2
9

Your doing it in the past way is probably fine for quick& dirty scripts or for mini tools used by other developers. There’s often no need to be fancy. On the contrary, Python’s default traceback output can be an appropriate or even desired form of error reporting. A script falling off its end exits with code 0, an unhandled exception exits the script with a non-zero code, so you’re covered there, too:

def main() -> None:
    # here would be code raising exceptions on error
    # note the `None` return type

if __name__ == '__main__':
    main()

When you need something more fancy working with sys.exit() explicitly is a good idea. That’s basically your future approach. But don’t only think of scripts called directly, also think of installed packages. Setuptools has a cross-platform mechanism to define functions as entry points for scripts. If you have this in your setup.py:

setuptools.setup(
        ...
        entry_points={
            'console_scripts': ['your_script=your_package.your_module:main'],
    },
)

and install that package you can run your_script from the command line.

A console_scripts function must be callable without any arguments. So, as long as all parameters have default values you’re fine. For longer running scripts consider explicitly handling KeyboardInterrupt to print a nice message when the user aborts with Ctrl+C. In the end the relevant part of your your_package/your_module.py might look something like this:

def main(cli_args: List[str] = None) -> int:
    """
    `cli_args` makes it possible to call this function command-line-style
    from other Python code without touching sys.argv.
    """
    try:
        # Parsing with `argparse` and additional processing 
        # is usually lenghty enough to extract into separate functions.
        raw_config = _parse_cli(
            sys.argv[1:] if cli_args is None else cli_args)
        config = _validate_and_sanitize(raw_config)

        # Same exception raising idea as the simple approach
        do_real_work(config.foo, config.bar)

    except KeyboardInterrupt:
        print('Aborted manually.', file=sys.stderr)
        return 1

    except Exception as err:
        # (in real code the `except` would probably be less broad)
        # Turn exceptions into appropriate logs and/or console output.

        # non-zero return code to signal error
        # Can of course be more fine grained than this general
        # "something went wrong" code.
        return 1

    return 0  # success

# __main__ support is still here to make this file executable without
# installing the package first.
if __name__ == '__main__':
    sys.exit(main())
2 of 2
1

I have worked on this template and use-case a bit more and here's the more refined structure for files containing a main function that I currently use:

#!/usr/bin/env python3

import sys
from argparse import ArgumentParser, Namespace
from typing import Dict, List

import yaml  # just used as an example here for loading more configs, optional


def parse_arguments(cli_args: List[str] = None) -> Namespace:
    parser = ArgumentParser()
    # parser.add_argument()
    # ...
    return parser.parse_args(args=cli_args)  # None defaults to sys.argv[1:]


def load_configs(args: Namespace) -> Dict:
    try:
        with open(args.config_path, 'r') as file_pointer:
            config = yaml.safe_load(file_pointer)

        # arrange and check configs here

        return config
    except Exception as err:
        # log errors
        print(err)
        if err == "Really Bad":
            raise err

        # potentionally return some sane fallback defaults if desired/reasonable
        sane_defaults = []
        return sane_defaults


def main(args: Namespace = parse_arguments()) -> int:
    try:
        # maybe load some additional config files here or in a function called here
        # e.g. args contains a path to a config folder; or use sane defaults
        # if the config files are missing(if that is your desired behavior)
        config = load_configs(args)
        do_real_work(args, config)

    except KeyboardInterrupt:
        print("Aborted manually.", file=sys.stderr)
        return 1

    except Exception as err:
        # (in real code the `except` would probably be less broad)
        # Turn exceptions into appropriate logs and/or console output.

        # log err
        print("An unhandled exception crashed the application!", err)

        # non-zero return code to signal error
        # Can of course be more fine grained than this general
        # "something went wrong" code.
        return 1

    return 0  # success


# __main__ support is still here to make this file executable without
# installing the package first.
if __name__ == "__main__":
    sys.exit(main(parse_arguments()))

Having the parse_arguments function makes integration tests much more readable, as you then can just call that function to generate the desired namespace object for you, using the same string you'd use on the cli. Then as suggested in the accepted answer handle errors to give the output you'd want and pass the arguments to the function(s) doing the work. I also load and arrange configs in this context, as necessary.

🌐
Python.org
discuss.python.org › python help
Passing argument to function from command line - Python Help - Discussions on Python.org
June 25, 2025 - My son wrote a command line program in ruby for me. I want to convert it to python. To run the program he has done this on the command line; “./myProgram.rb ‘argument’”. Then the 'argument ’ is passed into the program to be processed. I want to do the same in python.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › args-kwargs-python
*args and **kwargs in Python - GeeksforGeeks
Python · def multiply(*args): ... result *= num: multiply each number with result. **kwargs syntax allows a function to accept any number of keyword arguments....
Published   June 11, 2026
🌐
Esri Community
community.esri.com › t5 › python-questions › how-to-pass-arguments-to-main-function-in-module › td-p › 133211
Solved: How to pass arguments to main function in module? - Esri Community
December 11, 2021 - Any help in how to correctly construct my input arguments that the user will pass, which will then be passed onto the main function will be appreciated. As mentioned I'm trying to be able to use the following as a script when used directly or imported as a module into my other code and run from there. If I import it as a module would I call the main() function when importing it?
🌐
Great Learning
mygreatlearning.com › blog › it/software development › python main function and examples with code
Python Main Function and Examples with Code
May 31, 2023 - After reading this article, you are now able to illustrate many important aspects, such as what the main() function in Python is, how it can be used, and how, with the help of the main() function in Python, a ton of functionalities can be executed as and when needed, how the flow of execution can be controlled, etc.
🌐
CloudxLab
cloudxlab.com › home › how to handle command line arguments in python? | cloudxlab blog
How to handle Command Line Arguments in Python? | CloudxLab Blog
June 28, 2021 - When you are running python programs from the command line, you can pass various arguments to the program and your program can handle it. Here is a quick snippet of code that I will be explaining later: import sys if __name__ == "__main__": print("You passed: ", sys.argv)
🌐
YouTube
youtube.com › watch
What is Python's Main Function Useful For? - YouTube
In this video, we learn what the Python main function is useful for and how to use it.◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾📚 Programming Books & Merch 📚🐍 The Python Bible Boo...
Published   September 9, 2021
🌐
UiPath Community
forum.uipath.com › help › activities
Argument passing in python script - Activities - UiPath Community Forum
Hey, I’m working with the invoke python method in UIPaths I want to pass 3 arg to python fuction 2 string and one python obj how can I do that??
Published   September 22, 2023
🌐
freeCodeCamp
freecodecamp.org › news › python-function-examples-how-to-declare-and-invoke-with-parameters-2
Python Function Examples – How to Declare and Invoke with Parameters
August 24, 2021 - Number does matter, though, since each keyword argument corresponds with each parameter in the function's definition. Default arguments are entirely optional. You can pass in all of them, some of them, or none at all. If you are interested in going more in-depth and learning more about the Python programming language, freeCodeCamp has a free Python certification.
🌐
freeCodeCamp
freecodecamp.org › news › args-and-kwargs-in-python
How to Use *args and **kwargs in Python
March 23, 2022 - Simple, we can modify the function to accept three arguments and return their sum as: def add(x, y, z): return x+y+z print(add(2, 3, 5)) ... Wasn't that quite simple? Yes, it was! But what if we're again required to add two numbers only? Will our modified function help us get the sum? Let's see: ... Traceback (most recent call last): File "D:\Quarantine\Test\Blog-Codes\args-kwargs\main.py", line 14, in <module> print(add(2, 3)) TypeError: add() missing 1 required positional argument: 'z'
🌐
Python Course
python-course.eu › python-tutorial › passing-arguments.php
25. Passing Arguments | Python Tutorial | python-course.eu
November 8, 2023 - If you pass immutable arguments like integers, strings or tuples to a function, the passing acts like call-by-value. The object reference is passed to the function parameters. They can't be changed within the function, because they can't be changed at all, i.e.
🌐
OpenSourceOptions
opensourceoptions.com › how-to-pass-arguments-to-a-python-script-from-the-command-line
How to Pass Arguments to a Python Script from the Command Line – OpenSourceOptions
August 21, 2023 - The script will have the possibility ... this script myscript2.py. This script will consist of two parts. The first part is a function (myfunc) that will take the arguments (argv) as an input....
🌐
Opensource.com
opensource.com › article › 19 › 5 › how-write-good-c-main-function
How to write a good C main function | Opensource.com
Learn how to structure a C file and write a C main function that handles command line arguments like a champ. I know, Python and JavaScript are what the kids are writing all their crazy "apps" with these days. But don't be so quick to dismiss C—it's a capable and concise language that has ...
🌐
Codegrepper
codegrepper.com › code-examples › python › python+main+with+parameters
python main with parameters Code Example
May 28, 2020 - import sys #run on cmd - python argument1 argument2 print(len(sys.argv)) #2 print(sys.argv[1]) #argument1