12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

142 Chapter 14. Files>>> wc.linecount('wc.py')7So that’show you writemodules in<strong>Python</strong>.The only problem with this example is that when you import the module it executes the test codeat the bottom. Normally when you import a module, it defines new functions but it doesn’t executethem.Programs that willbe imported asmodules oftenusethe following idiom:if __name__ == '__main__':print linecount('wc.py')__name__ is a built-in variable that is set when the program starts. If the program is running as ascript, __name__ has the value __main__; in that case, the test code is executed. Otherwise, if themodule isbeing imported, thetestcode isskipped.Exercise14.4 Typethisexampleintoafilenamedwc.pyandrunitasascript. Thenrunthe<strong>Python</strong>interpreter andimport wc. What isthevalue of__name__when the module isbeing imported?Warning: If you import a module that has already been imported, <strong>Python</strong> does nothing. It does notre-read thefile, even if ithas changed.Ifyouwanttoreloadamodule,youcanusethebuilt-infunctionreload,butitcanbetricky,sothesafestthing todo isrestarttheinterpreter and then import the module again.14.10 DebuggingWhenyouarereadingandwritingfiles,youmightrunintoproblemswithwhitespace. Theseerrorscan be hard todebug because spaces, tabs and newlines arenormally invisible:>>> s = '1 2\t 3\n 4'>>> print s1 2 34The built-in function repr can help. It takes any object as an argument and returns a string representationof theobject. For strings,itrepresents whitespace characters withbackslash sequences:>>> print repr(s)'1 2\t 3\n 4'This can be helpful fordebugging.Oneotherproblemyoumightrunintoisthatdifferentsystemsusedifferentcharacterstoindicatetheendofaline. Somesystemsuseanewline,represented\n. Othersuseareturncharacter,represented\r. Some use both. If you move files between different systems, these inconsistencies might causeproblems.For most systems, there are applications to convert from one format to another. You can find them(andreadmoreaboutthisissue)atwikipedia.org/wiki/Newline. Or,ofcourse,youcouldwriteone yourself.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!