Repository: spyder-ide/spyder

Issue:
Check : Profiler unable to find modules
I'm trying to use the profiler for the first time and have noticed that the following error comes up:

> import pymatgen as pm
> ImportError: No module named pymatgen

Is this still the same bug as #2378 ? If not how do I fix it? The code runs normally otherwise from within Spyder.
# Generic Reproduction
1. Download pymatgen
2. Write a script containing

<pre><code>import pymatgen as pm
pm.Element.from_Z(10)</code></pre>

1. You should (hopefully) get the profiler error as well.
## Versions and main components
- Spyder Version: 2.3.7
- Python Version: 2.7.10 64bit
- Operating system: 10.10.5
## Dependencies

pymatgen library [https://github.com/materialsproject/pymatgen]



Discussion:
Do you get an `ImportError` if you run the script from within Spyder without using the profiler? What about if you run the script without using Spyder?

Runs fine without the profiler as well as simply running the script without spyder. I haven't the foggiest what is causing this.

It seems like PYTHONPATH is not set when running the profiler. I have a related issue with profiling code I am developing, where the default library is loaded rather than the one in the PYTHONPATH.

I added the following piece of code to my code to be profiled:
``` python
import os
try:
    user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
except KeyError:
    user_paths = []
print(user_paths)
```

This prints `[]` so it seems like the setting of paths does not work (I have two paths in my PYTHONPATH). At least on Windows 10.

Resolving patch:
diff --git a/spyder/utils/misc.py b/spyder/utils/misc.py
--- a/spyder/utils/misc.py
+++ b/spyder/utils/misc.py
@@ -223,31 +223,38 @@ def get_common_path(pathlist):
                 return osp.abspath(common)
 
 
-def add_pathlist_to_PYTHONPATH(env, pathlist, drop_env=False,
-                               ipyconsole=False):
+def add_pathlist_to_PYTHONPATH(env, pathlist, drop_env=True):
+    """
+    Add a PYTHONPATH entry to a list of enviroment variables.
+
+    This allows to extend the environment of an external process
+    created with QProcess with our additions to PYTHONPATH.
+
+    Parameters
+    ----------
+    env: list
+        List of environment variables in the format of
+        QProcessEnvironment.
+    pathlist: list
+        List of paths to add to PYTHONPATH
+    drop_env: bool
+        Whether to drop PYTHONPATH previously found in the environment.
+    """
     # PyQt API 1/2 compatibility-related tests:
     assert isinstance(env, list)
     assert all([is_text_string(path) for path in env])
 
     pypath = "PYTHONPATH"
     pathstr = os.pathsep.join(pathlist)
-    if os.environ.get(pypath) is not None and not drop_env:
-        old_pypath = os.environ[pypath]
-        if not ipyconsole:
-            for index, var in enumerate(env[:]):
-                if var.startswith(pypath+'='):
-                    env[index] = var.replace(pypath+'=',
-                                             pypath+'='+pathstr+os.pathsep)
-            env.append('OLD_PYTHONPATH='+old_pypath)
-        else:
-            pypath =  {'PYTHONPATH': pathstr + os.pathsep + old_pypath,
-                       'OLD_PYTHONPATH': old_pypath}
-            return pypath
+    if not drop_env:
+        for index, var in enumerate(env[:]):
+            if var.startswith(pypath + '='):
+                env[index] = var.replace(
+                    pypath + '=',
+                    pypath + '=' + pathstr + os.pathsep
+                )
     else:
-        if not ipyconsole:
-            env.append(pypath+'='+pathstr)
-        else:
-            return {'PYTHONPATH': pathstr}
+        env.append(pypath + '=' + pathstr)
 
 
 def memoize(obj):


Test patch:
diff --git a/spyder/utils/tests/test_misc.py b/spyder/utils/tests/test_misc.py
--- a/spyder/utils/tests/test_misc.py
+++ b/spyder/utils/tests/test_misc.py
@@ -15,7 +15,10 @@
 import pytest
 
 # Local imports
-from spyder.utils.misc import get_common_path
+from spyder.utils.misc import (
+    get_common_path, add_pathlist_to_PYTHONPATH
+)
+
 
 def test_get_common_path():
     """Test getting the common path."""
@@ -35,5 +38,28 @@ def test_get_common_path():
                                 ]) == '/Python'
 
 
+@pytest.mark.parametrize("drop_env", [True, False])
+def test_add_pathlist_to_PYTHONPATH(drop_env):
+    """Test for add_pathlist_to_PYTHONPATH."""
+    pathlist = ['test123', 'test456']
+
+    if drop_env:
+        env = []
+        expected = ['PYTHONPATH=' + pathlist[0] + os.pathsep + pathlist[1]]
+    else:
+        env = ['PYTHONPATH=test0']
+        expected = [
+            'PYTHONPATH=' +
+            pathlist[0] +
+            os.pathsep +
+            pathlist[1] +
+            os.pathsep +
+            'test0'
+        ]
+
+    add_pathlist_to_PYTHONPATH(env, pathlist, drop_env=drop_env)
+    assert env == expected
+
+
 if __name__ == "__main__":
     pytest.main()