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 OverflowBest practice for Python main function definition and program start/exit - Software Engineering Stack Exchange
Passing argument to function from command line
How do you call another file's __main__, passing it command line arguments?
Argument passing in python script
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())
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.
I'd like to have my python file call the __main__ from another file. However, the other __main__ expects command-line arguments... how can I call it and wait for until it returns/exits before continuing my file's execution?