Python 3.9+astfunction
ast.main()
helper functions
The entry point of the python -m ast command line: parses a file or stdin and prints the tree with an indented dump. Available since 3.9.
Syntax
python -m ast [-m mode] [-a] [-i indent] [infile]
The function itself is not documented; the documented interface is the command python -m ast file.py, and that is what you use. main reads its arguments from sys.argv (since 3.14 an args list may be passed), prints to stdout and returns nothing. The output is the same ast.dump, so it also differs between versions; 3.14 added --feature-version, -O and --show-empty, and 3.15 colours terminal output.
Examples
import ast, contextlib, io, sys
with open('demo.py', 'w', encoding='utf-8') as f:
f.write('x = 1\n')
sys.argv = ['ast', 'demo.py']
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
ast.main()
print(buf.getvalue().splitlines()[0]) # → Module(
print('Assign(' in buf.getvalue()) # → True
See also
Open in the full glossarydocs.python.orgReport an inaccuracy