1

I have been following "Learn python the hard way" for learning python. The following script is directly taken from the Exercise 16 of the book:

#Exercise 16: Reading and Writing Files
from sys import argv
script, filename = argv
print "We're going to erase %r." %filename
print "If you don't want that, hit (^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("line1: ")
line2 = raw_input("line2: ")
line3 = raw_input("line3: ")

print "I'm going to write these to the file."

target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")

Suppose the file storing the above script is 'ex1.py'.I decided to run the script file with the following command in the Ubuntu terminal

$ python ex1.py ex1.py

To my surprise, I was successful in writing to the same file storing the script. Why does this work? Is the script loaded into the terminal before interpretation starts?

P.S. I am mainly asking this question because it was my idea that python is interpreted and not compiled. So the object file for the code is never created. I thought that no compiled version of the script is ever created.

Edit: I think that the second part of the question is already discussed in this stackoverflow question.

Community
  • 1
  • 1
Colorless Photon
  • 399
  • 1
  • 3
  • 19
  • possible duplicate of [If Python is interpreted, what are .pyc files?](http://stackoverflow.com/questions/2998215/if-python-is-interpreted-what-are-pyc-files) – Colorless Photon Jun 08 '14 at 22:48

2 Answers2

1

This is why computers have memory. When you load an program, it is read from the persistent storage (hard-drive, ssd) and into memory, where it is much faster for the CPU to work with.

For small programs, it doesn't matter that you overwrite the sourcecode while the program is running.

For larger programs, the CPU will need to copy multiple "pages" of the code from the hard-drive into memory, and here you may run into trouble, when a specific page of your source code is requested quite some time after your program has launched and it is no longer available.

Edit: As cchristelis mentioned, Python files are compiled into .pyc. Again, this pyc file is kept in memory and if the .pyc is written to disk it's so that it doesn't ever have to be compiled again from .py the next time you launch your program.

Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
0

Your python code is actually complied into byte code before it is executed. Have you every noticed a .pyc file? That file contains the complied version of the code.

So once the program is running the bytecode is in RAM. At that point the original source code is no longer needed. Only you can't re-run it if it is gone...

cchristelis
  • 1,985
  • 1
  • 13
  • 17