Skip to content

Commit 832e864

Browse files
bpo-38049: Add command-line interface for the ast module. (GH-15724)
1 parent b9f65f0 commit 832e864

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

Doc/library/ast.rst

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,42 @@ and classes for traversing abstract syntax trees:
340340
Added the *indent* option.
341341

342342

343+
.. _ast-cli:
344+
345+
Command-Line Usage
346+
------------------
347+
348+
.. versionadded:: 3.9
349+
350+
The :mod:`ast` module can be executed as a script from the command line.
351+
It is as simple as:
352+
353+
.. code-block:: sh
354+
355+
python -m ast [-m <mode>] [-a] [infile]
356+
357+
The following options are accepted:
358+
359+
.. program:: ast
360+
361+
.. cmdoption:: -h, --help
362+
363+
Show the help message and exit.
364+
365+
.. cmdoption:: -m <mode>
366+
--mode <mode>
367+
368+
Specify what kind of code must be compiled, like the *mode* argument
369+
in :func:`parse`.
370+
371+
.. cmdoption:: -a, --include-attributes
372+
373+
Include attributes such as line numbers and column offsets.
374+
375+
If :file:`infile` is specified its contents are parsed to AST and dumped
376+
to stdout. Otherwise, the content is read from stdin.
377+
378+
343379
.. seealso::
344380

345381
`Green Tree Snakes <https://greentreesnakes.readthedocs.io/>`_, an external documentation resource, has good

Lib/ast.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -550,3 +550,27 @@ def __new__(cls, *args, **kwargs):
550550
bytes: 'Bytes',
551551
type(...): 'Ellipsis',
552552
}
553+
554+
555+
def main():
556+
import argparse
557+
558+
parser = argparse.ArgumentParser(prog='python -m ast')
559+
parser.add_argument('infile', type=argparse.FileType(mode='rb'), nargs='?',
560+
default='-',
561+
help='the file to parse; defaults to stdin')
562+
parser.add_argument('-m', '--mode', default='exec',
563+
choices=('exec', 'single', 'eval', 'func_type'),
564+
help='specify what kind of code must be parsed')
565+
parser.add_argument('-a', '--include-attributes', action='store_true',
566+
help='include attributes such as line numbers and '
567+
'column offsets')
568+
args = parser.parse_args()
569+
570+
with args.infile as infile:
571+
source = infile.read()
572+
tree = parse(source, args.infile.name, args.mode, type_comments=True)
573+
print(dump(tree, include_attributes=args.include_attributes, indent=3))
574+
575+
if __name__ == '__main__':
576+
main()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Added command-line interface for the :mod:`ast` module.

0 commit comments

Comments
 (0)