[Tutor] PYTHONPATH (Mac OS X)

Alan Gauld alan.gauld at btinternet.com
Mon Dec 26 18:12:17 CET 2011


On 26/12/11 12:23, Stayvoid wrote:
>> Simply that python is saying it cannot find the file.
>> So it is probably in a different folder ...
> Those files are in the same folder:
> /Users/Username/Python_modules/

And is that where you are running the code from? That is the critical 
factor.

By just providing the filename Python assumes its in the same folder 
that you ran the program from. If you run it from somewhere else you 
*must* provide the full (or relative() path to the file. There is no 
option for Python to search for it.

> I don't want to write a full path here:
> if __name__ == '__main__':
>     print test('lengthcounter_lutz.py')

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.


> I have a slightly different copy of this file:
>
> 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)
>
> I've tried to run it in the interactive shell:
>
> import lengthcounter as lc
> lc.test(lengthcounter)

Are you sure it is your version that's being picked up?
Try renaming it to something guaranteed to be unique. See if the results 
are the same.

Also I would expect the prompt to complain because you are passing 
lengthcounter as a name to the test function, but you imported 
lengthcounter as lc, so python should not know about lengthcounter 
unless you had already imported it (or another file?)
eg.

 >>> import random as r
 >>> random.__file__
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'random' is not defined
 >>>

Try starting a fresh interpreter session and repeating the test.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list