Remember that when you import a module into a Python
program that the contents of the module are executed when the import statement is
encountered. Thus, you can't just include your test program in your module, or it will
be executed every time the module is imported. But Python provides a builtin variable called
__name__
, which will be equal to the name of a module when the module is imported,
but will be equal to the value ``__main__
'' when a program is executed directly. Thus,
we could include a test program for the strfunc module by including the following
lines in the file strfunc.py after the function definitions:
if __name__ == '__main__': import sys files = sys.argv[1:] for f in files: print 'Processing %s' % f print ' Longest line is %d characters' % lline(f) print ' File contains %d lines, %d words, and %d characters' % wcount(f) print ' The file contains %d spaces' % ccount(f,' ') printNow when the program is invoked directly (for example through the execfile function, or by typing the program's name at a shell prompt), the test program will be run, but when the module is imported into another program, the test program is ignored. Notice that in this example, since the sys module is not needed for the functions defined in the fileutil module, the import statement for that module was placed after the if statement which checks for the value of
__name__
.