PYTHONPATH when calling from ipython

Peter Otten __peter__ at web.de
Sat May 23 12:09:01 EDT 2015


Cecil Westerhof wrote:

> Op Saturday 23 May 2015 15:25 CEST schreef Peter Otten:
> 
>> Cecil Westerhof wrote:
>>
>>> Op Saturday 23 May 2015 11:12 CEST schreef Mark Lawrence:
>>>
>>>> On 22/05/2015 06:20, Cecil Westerhof wrote:
>>>>> I am looking into using ipython instead of bash. But when I call
>>>>> a python program from ipython PYTHONPATH is not set. So
>>>>> pythonscripts that need a module through PYTHONPATH will not
>>>>> work.
>>>>>
>>>>> I could do something like:
>>>>> !PYTHONPATH=~/Python/PythonLibrary python2 …
>>>>>
>>>>> But I find that a little bit cumbersome. Is there a better way to
>>>>> do it?
>>>>>
>>>>
>>>> What makes you think this?  Have you tried:-
>>>>
>>>>>>> import os
>>>>>>> os.environ['PYTHONPATH']
>>>> 'C:\\Users\\Mark\\Documents\\Cash\\Python;C:
>> \\Users\\Mark\\Documents\\MyPython'
>>>>
>>>> That might be from the command line interpreter but it also works
>>>> the same from iPython for me on Windows 8.1.
>>>
>>> That does not change anything. The modules are not found. Also not
>>> when using %run.
>>
>>
>> That may be because ~ is not expanded.
>>
>> Try
>>
>> os.environ["PYTHONPATH"] =
>> os.path.expanduser("~/Python/PythonLibary")
> 
> That is not the problem:
>     os.environ['PYTHONPATH']
> gives:
>     .:/home/cecil/Python'
> 
> As I interpret it is that the very handy shell variable is not used in
> ipython.
> 

I can't confirm that finding. For test purposes I created foo/bar/hello.py.
Then I verified that the hello.py module is not found when invoking the 
python3 interpreter from within ipython3.
Once I update os.environ["PYTHONPATH"] the module is successfully imported.
The complete session:

$ mkdir -p foo/bar
$ echo 'print("hello from foo/bar")' > foo/bar/hello.py
$ ipython3
Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
Type "copyright", "credits" or "license" for more information.

IPython 1.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import hello.py
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-d9db4361d25a> in <module>()
----> 1 import hello.py

ImportError: No module named 'hello'

In [2]: import os

In [3]: !python3 -c 'import hello'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named 'hello'

In [4]: os.environ["PYTHONPATH"] = "foo/bar"

In [5]: !python3 -c 'import hello'
hello from foo/bar


If that's not what you want please explain in similar detail what you want 
to achieve and what you actually tried. Thank you.




More information about the Python-list mailing list