Vedaad Shakib
Vedaad Shakib

Reputation: 729

Python Compilation in Terminal

I am participating in a CodeForces competition tomorrow, and the rules say that Python is compiled with the following line (where %1 is the filename):

python -c "compile(open('%1').read(), '%1', 'exec')"

I tried to compile a test file with this line, but it does not do anything at all:

import sys
a = sys.stdin.readline()
sys.stdout.write(a)

However, the program works when I compile with python test.py

How can I make this test file work with the compilation line above?

EDIT: I am using terminal on a mac.

Upvotes: 1

Views: 569

Answers (1)

Ned Deily
Ned Deily

Reputation: 85025

You can see what is happening if you try it in the interactive interpreter:

>>> compile(open('test.py').read(), 'read.py', 'exec')
<code object <module> at 0x10b916130, file "read.py", line 1>

The compile built-in compiles the source lines into a code object. To actually run the code object, you need to exec it:

>>> codeobj = compile(open('test.py').read(), 'read.py', 'exec')
>>> exec(codeobj)
Hello, world!
Hello, world!
>>>

Note that there are some differences here between Python 2 and Python 3, primarily that exec is a statement in Py2 but a built-in function in Py3. The above should work in either.

Upvotes: 4

Related Questions