Thursday, March 26, 2009

Python: How to paste all your code into the python console??

A beautiful thing about python is that it eliminates the need for the language to need characters to specify blocks of code, it does this with white space.

An incredibly annoying thing about python (when you're starting out) is that it uses whitespace to denote blocks of code.

Have you ever copied and pasted python code from a web page and had to reformat it properly? And was it annoying and a bitch, and even IMPOSSIBLE to do, without knowing what the logic was in the first place?

If you're starting out at python you have probably played around quite a bit in the interrupter to learn it, but when you started writing python code in files you wrote little programs to test the functions you're writing, which is great, but more on unit testing in another post.

Alot of python scripts I write are quick, dirty and I don't care about writing unit tests, I just want it working ASAP, so I save the code to a file, and then what? What is the quickest way to test it, PASTE THE ENTIRE FILE CONTENTS INTO THE PYTHON INTERPRETER, then just run the function you want to test to your heart's content.


Here is some sample code of mine, notice the comments denoting an ending of a block, I also use tabs, which will not be preserved when you copy and paste this out of your browser, go ahead, copy and paste it into your python interpreter, I even included 2 lines of code runing the function for you at the end.


def filetolist(filename, clean = True):
result = []
f = open(filename, 'r')
for line in f.xreadlines():
removedn = False
if clean:
stripped = line.strip()
if len(stripped) > 0:
result.append(stripped)
#end if
else:
if len(line) > 0 and line.endswith('\n'):
line = line[:-1] # remove 1 char
removedn = True
#end if
result.append(line)
#end if
#end for
if not clean and removedn:
result.append('')
#end if
return result
#end def



a = filetolist('C:\\WINDOWS\\win.ini')
print a





The beautiful thing about this is you can paste an entire file into the python console, not to mention I can paste my code anywhere and not worry about html removing the visible spacing, for example I didn't include it in a pre tag here and the logic of the code is not lost due to the #end comments.


def filetolist(filename, clean = True):
result = []
f = open(filename, 'r')
for line in f.xreadlines():
removedn = False
if clean:
stripped = line.strip()
if len(stripped) > 0:
result.append(stripped)
#end if
else:
if len(line) > 0 and line.endswith('\n'):
line = line[:-1] # remove 1 char
removedn = True
#end if
result.append(line)
#end if
#end for
if not clean and removedn:
result.append('')
#end if
return result
#end def


It's still somewhat readable. As opposed to this, without the comments denoting the end of the blocks, just try to figure out what the heck is going on:



def filetolist(filename, clean = True):
result = []
f = open(filename, 'r')
for line in f.xreadlines():
removedn = False
if clean:
stripped = line.strip()
if len(stripped) > 0:
result.append(stripped)
else:
if len(line) > 0 and line.endswith('\n'):
line = line[:-1] # remove 1 char
removedn = True
result.append(line)
if not clean and removedn:
result.append('')
return result



One catch when writing code you want to paste into the python console, beware of blank lines, I purposefully left blank lines in here so you can paste it into your python interpreter and see the errors.


def filetolist(filename, clean = True):
result = []
f = open(filename, 'r')
for line in f.xreadlines():
removedn = False

if clean:
stripped = line.strip()
if len(stripped) > 0:
result.append(stripped)
#end if

else:

if len(line) > 0 and line.endswith('\n'):
line = line[:-1] # remove 1 char
removedn = True
#end if
result.append(line)
#end if
#end for

if not clean and removedn:
result.append('')
#end if

return result
#end def




You can have blank lines, but the spacing has to be correct even for the blank lines, just remember the spaces denote the blocks of code, as soon as the spaces "de-dent" (opposite of indent) the block goes with it. Of course the actual python interpretter is much better at reading files, I've seen some really poorly formatted code be read properly.

I mentioned earlier I use tabs for spacing, more on this in another post.

Here I did the blank lines properly, preserving the block.


def filetolist(filename, clean = True):
result = []
f = open(filename, 'r')
for line in f.xreadlines():
removedn = False

if clean:
stripped = line.strip()
if len(stripped) > 0:
result.append(stripped)
#end if

else:

if len(line) > 0 and line.endswith('\n'):
line = line[:-1] # remove 1 char
removedn = True
#end if
result.append(line)
#end if
#end for

if not clean and removedn:
result.append('')
#end if

return result
#end def

No comments: