Reputation: 285
This is more of a 'toy question' than a real one, but can you compile a single line of Python code from the command line using the py_compile
module?
My first attempt was python -m py_compile "print 'Hello, Compile!'"
but that resulted in an IOError
because my_compile
thought that I was trying to compile a file named "print 'Hello, Compile!'".
Any ideas?
Note: python -c "CODE"
runs the code, it does not produce a *.pyc file with the bytecode.
Upvotes: 0
Views: 1211
Reputation: 25954
Not really. py_compile
and compileall
are meant to be used on files. You could use some tempfiles of course but that's unnecessary.
Instead: are you just trying to use dis
? You can read from stdin interactively (or from a pipe) by specifying -
:
ben@nixbox:~$ echo "print 'hello'" | python -m dis -
1 0 LOAD_CONST 0 ('hello')
3 PRINT_ITEM
4 PRINT_NEWLINE
5 LOAD_CONST 1 (None)
8 RETURN_VALUE
Upvotes: 1
Reputation: 140445
You don't need the py_compile
module to compile things -- the CPython interpreter always compiles to bytecode before execution.
The real question here is, what do you want it to do with the bytecode after you've compiled it?
Here's one possible thing you might have in mind:
$ python -c '
def f():
print "Hello, World"
import dis
dis.dis(f)'
2 0 LOAD_CONST 1 ('Hello, World')
3 PRINT_ITEM
4 PRINT_NEWLINE
5 LOAD_CONST 0 (None)
8 RETURN_VALUE
I don't think this is possible as a true "single line" (with no newlines embedded in the command), because of Python's syntax, but you see the idea.
Upvotes: 0