How do I disassemble a Python script from the command line?
Question:
With gcc you can use -S to stop compilation after your code has been compiled into assembly. Is there a similar feature with Python/bytecode? I know of ways like:
import dis
x = compile('print(1)', '', 'eval')
dis.dis(x)
Which prints:
1 0 LOAD_NAME 0 (print)
2 LOAD_CONST 0 (1)
4 CALL_FUNCTION 1
6 RETURN_VALUE
But I’m thinking of something more along the lines of:
> python3 -{SOME FLAG HERE} output my_script.py
Which outputs a file containing the scripts bytecode in a readable format.
Answers:
If what you are looking for is the output of the disassembler, then you can run the module as a script:
python -m dis myscript.py
And the disassembler output will be printed to the standard output. You can use the appropriate shell tools to redirect that to some file. E.g. on *nix:
python -m dis myscript.py > output.txt
Caution: this use of dis
is not documented as far as I am aware, and checking the source code it may not be a stable part of the module, but it does work for current CPython.
With gcc you can use -S to stop compilation after your code has been compiled into assembly. Is there a similar feature with Python/bytecode? I know of ways like:
import dis
x = compile('print(1)', '', 'eval')
dis.dis(x)
Which prints:
1 0 LOAD_NAME 0 (print)
2 LOAD_CONST 0 (1)
4 CALL_FUNCTION 1
6 RETURN_VALUE
But I’m thinking of something more along the lines of:
> python3 -{SOME FLAG HERE} output my_script.py
Which outputs a file containing the scripts bytecode in a readable format.
If what you are looking for is the output of the disassembler, then you can run the module as a script:
python -m dis myscript.py
And the disassembler output will be printed to the standard output. You can use the appropriate shell tools to redirect that to some file. E.g. on *nix:
python -m dis myscript.py > output.txt
Caution: this use of dis
is not documented as far as I am aware, and checking the source code it may not be a stable part of the module, but it does work for current CPython.