Swapna Sarit
Swapna Sarit

Reputation: 21

Why does the Python script still run after truncating the file as it is being interpreted?

If i write a python script (named as , say, test.py), in which I write code for opening test.py and truncating it, how does the interpreter still runs the script?

I read in the book "How to think like a computer scientist?" that

An interpreter reads a high-level program and executes it, meaning that it does what the program says. It processes the program a little at a time, alternately reading lines and performing computations.

Then how does the interpreter run the script even after truncating it a few moments ago?

Here is the code :

from sys import argv

script, filename = argv

print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")

print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file Goodbye!"
target.truncate()

print "Now I'm going to ask you for three lines"

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."
target.write(line1 + "\n" + line2 + "\n" + line2 + "\n")

Upvotes: 0

Views: 51

Answers (1)

Amadan
Amadan

Reputation: 198324

Very few modern interpreters work that way. In particular, Python actually compiles source Python into bytecode, then executes that bytecode without ever looking back on the Python source itself.

Upvotes: 3

Related Questions