[Tutor] PYTHONPATH (Mac OS X)

David Rock david at graniteweb.com
Fri Jan 13 15:57:43 CET 2012


* Stayvoid <stayvoid at gmail.com> [2011-12-30 16:11]:
> >You don't have any option.
> >You either type in the full path or you get the user to tell you
> >in some way - either with a prompt or via an input argument.
> 
> OK, now I get it.
> 
> How can I tell this to the end-user?
> Should I write a README file or what?
> 
> I've tried to run lengthcounter_lutz from the file's folder and this worked out.
> cd /Users/Username/Python_modules/
> python /Users/Username/Python_modules/lengthcounter_lutz.py
> ('Lines:', 12, 'Chars:', 285)
> 
> 
> But I can't understand what's wrong with the second one:
> def countLines(name):
>     file = open(name.__file__)
>     return len(file.readlines())
> 
> def countChars(name):
>     return len(open(name.__file__).read())
> 
> def test(name):
>     return "Lines:", countLines(name), "Chars:", countChars(name)
> 
> if __name__ == '__main__':
>     import lengthcounter
>     print test(lengthcounter)
> 
> >>> import lengthcounter
> >>> lengthcounter.test(lengthcounter)
> ('Lines:', 5, 'Chars:', 885)
> 

Looking at page 1119 in the learning Python book, I might venture a
guess as to where the difference lies.  You are calling test as:
test(lengthcounter), but that is not the name of a file (the name of a
file should be in quotes). lengthcounter in this case is a variable, 
not a filename.  The behavior in this case is probably undetermined.

I suggest doing a manual check on the file named lengthcounter.pyc, and
I'll bet you will find something closer to 5 lines and 885 characters.
pyc files are the bytecode version of your file that gets generated
automatically and is the code that is actually executed.

Somehow, calling the method test inside the interpreter is different
from running it on the commandline and you are picking up the pyc file.  
In either case, this format is iffy at best:

if __name__ == '__main__':
    import lengthcounter
    print test(lengthcounter)

should really be:

if __name__ == '__main__':
    import lengthcounter
    print lengthcounter.test(lengthcounter)

to avoid ambiguous behavior.

-- 
David Rock
david at graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 190 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20120113/aed72e4e/attachment.pgp>


More information about the Tutor mailing list