Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Program entry point

A module run as a script or with python -m receives the name `__main__` for its top-level code.

Version: Python 3.14; repository image, production runtime not attested

Syntax

if __name__ == '__main__':
    raise SystemExit(main())

A module run as a script or with python -m receives the name __main__ for its top-level code.

An ordinary import gives the module its import name, so the guard skips the main call. Other top-level code still executes. SystemExit with integer zero signals successful process termination.

main sums two numbers and prints 7. Its zero exit status is separate from standard output.

import os,runpy,tempfile
code="hits=[]\nif __name__=='__main__': hits.append('run')"
with tempfile.TemporaryDirectory() as d:
    path=os.path.join(d,'entry.py')
    with open(path,'w',encoding='utf-8') as f: f.write(code)
    assert runpy.run_path(path,run_name='example')['hits']==[]
    assert runpy.run_path(path,run_name='__main__')['hits']==['run']

Examples

def main(values):
    print(sum(int(v) for v in values))
    return 0

if __name__ == "__main__":
    raise SystemExit(main(["2", "5"]))

Result

7

main sums two numbers and prints 7. Its zero exit status is separate from standard output.

Sources