[Tutor] PYTHONPATH (Mac OS X)
Alan Gauld
alan.gauld at btinternet.com
Fri Dec 30 15:07:06 CET 2011
On 30/12/11 13:11, Stayvoid wrote:
> 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
You should only have needed:
> python ./lengthcounter_lutz.py
the ./ tells Linux to use the current folder as startuing point.
> ('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)
Neither do I but you can debug it easily from the >>> prompt by calling
the individual lines/functions. Try:
>>> import lengthcounter as lc
>>> print lc.__file__ # to check it's using the expected file
>>> # assuming it is...
>>> print (open(lc.__name__),read()) # check the contents is what we
expect
>>> print ( len(open(lc.__name__),read()) ) # check the length result
>>> print ( len(open(lc.__name__),readlines()) ) # check the lines
> That PYTHONPATH variable has no connection with the mess above. When
> should I use it?
Python uses PYTHONPATH to find modules when you import them.
So when we do import lengthcounter above we dont need to be in the same
folder as lengthcounter.py to be able to import it.
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list