Repository: spyder-ide/spyder

Issue:
PYTHONPATH manager just closes after upgrade to 5.4.3 in the Mac app
<!--- **PLEASE READ:** When submitting here, please ensure you've completed the following checklist and checked the boxes to confirm. Issue reports without it may be closed. Thanks! --->

### Issue Report Checklist

* [x] Searched the [issues page](https://github.com/spyder-ide/spyder/issues?q=is%3Aissue) for similar reports
* [x] Read the relevant sections of the [Spyder Troubleshooting Guide](https://github.com/spyder-ide/spyder/wiki/Troubleshooting-Guide-and-FAQ) and followed its advice
* [ ] Reproduced the issue after updating with ``conda update spyder`` (or ``pip``, if not using Anaconda)
* [ ] Could not reproduce inside ``jupyter qtconsole`` (if console-related)
* [x] Tried basic troubleshooting (if a bug/error)
    * [x] Restarted Spyder
    * [x] Reset preferences with ``spyder --reset``
    * [ ] Reinstalled the latest version of [Anaconda](https://www.anaconda.com/download/)
    * [ ] Tried the other applicable steps from the Troubleshooting Guide
* [x] Completed the **Problem Description**, **Steps to Reproduce** and **Version** sections below


## Problem Description

After upgrading to Spyder 5.4.3 (from 5.4.2), the PYTHONPATH manager window just closes without updating when I want to add a folder. The list remains empty when I reopen the PYTHONPATH manager.

My custom modules can no longer be imported. Instead, I get a `ModuleNotFoundError`. Some (hopefully useful hints):

- I get the correct PYTHONPATH with `echo $PYTHONPATH` on the macOS Terminal. 
- I set the Python interpreter to '/Users/<username>/opt/miniconda3/bin/python'
- On the Spyder IPython console, `os.environ['PYTHONPATH']` throws a `KeyError`

### What steps reproduce the problem?

I don' know

### What is the expected output? What do you see instead?

The "system wide" PYTHONPATH should be used (as it was in 5.4.2?). The PYTHONPATH manager should add folders.

### Paste Traceback/Error Below (if applicable)
<!--- Copy from error dialog or View > Panes > Internal Console --->

```python-traceback

Uncaught ReferenceError: spyder_terminal is not defined
Uncaught ReferenceError: spyder_terminal is not defined
Uncaught ReferenceError: spyder_terminal is not defined
Uncaught TypeError: Cannot read property 'fit' of undefined
_distutils_hack/__init__.pyc:18: UserWarning: Distutils was imported before Setuptools, but importing Setuptools also replaces the `distutils` module in `sys.modules`. This may lead to undesirable behaviors or errors. To avoid these issues, avoid using distutils directly, ensure that setuptools is installed in the traditional way (e.g. not an editable install), and/or make sure that setuptools is always imported before distutils.
_distutils_hack/__init__.pyc:33: UserWarning: Setuptools is replacing distutils.

```

## Versions
<!--- You can get this information from Help > About Spyder...
or (if Spyder won't launch) the "conda list" command
from the Anaconda Prompt/Terminal/command line. --->

* Spyder version: 5.4.3 b6abc3d30 (standalone)
* Python version: 3.9.14 64-bit
* Qt version: 5.15.2
* PyQt5 version: 5.15.9
* Operating System: Darwin 22.3.0

### Dependencies
<!--- Please go to the menu entry Help > Dependencies,
press the Copy to clipboard button and paste below --->

```
# Mandatory:
atomicwrites >=1.2.0                             :  1.4.1 (OK)
chardet >=2.0.0                                  :  5.1.0 (OK)
cloudpickle >=0.5.0                              :  2.2.1 (OK)
cookiecutter >=1.6.0                             :  2.1.1 (OK)
diff_match_patch >=20181111                      :  20200713 (OK)
intervaltree >=3.0.2                             :  3.1.0 (OK)
IPython >=7.31.1,<9.0.0,!=8.8.0,!=8.9.0,!=8.10.0 :  8.12.0 (OK)
jedi >=0.17.2,<0.19.0                            :  0.18.2 (OK)
jellyfish >=0.7                                  :  0.11.2 (OK)
jsonschema >=3.2.0                               :  4.17.3 (OK)
keyring >=17.0.0                                 :  23.13.1 (OK)
nbconvert >=4.0                                  :  7.3.0 (OK)
numpydoc >=0.6.0                                 :  1.5.0 (OK)
parso >=0.7.0,<0.9.0                             :  0.8.3 (OK)
pexpect >=4.4.0                                  :  4.8.0 (OK)
pickleshare >=0.4                                :  0.7.5 (OK)
psutil >=5.3                                     :  5.9.4 (OK)
pygments >=2.0                                   :  2.14.0 (OK)
pylint >=2.5.0,<3.0                              :  2.17.2 (OK)
pylint_venv >=2.1.1                              :  None (OK)
pyls_spyder >=0.4.0                              :  0.4.0 (OK)
pylsp >=1.7.2,<1.8.0                             :  1.7.2 (OK)
pylsp_black >=1.2.0                              :  1.2.1 (OK)
qdarkstyle >=3.0.2,<3.2.0                        :  3.1 (OK)
qstylizer >=0.2.2                                :  0.2.2 (OK)
qtawesome >=1.2.1                                :  1.2.3 (OK)
qtconsole >=5.4.2,<5.5.0                         :  5.4.2 (OK)
qtpy >=2.1.0                                     :  2.3.1 (OK)
rtree >=0.9.7                                    :  1.0.1 (OK)
setuptools >=49.6.0                              :  67.6.1 (OK)
sphinx >=0.6.6                                   :  5.1.1 (OK)
spyder_kernels >=2.4.3,<2.5.0                    :  2.4.3 (OK)
textdistance >=4.2.0                             :  4.5.0 (OK)
three_merge >=0.1.1                              :  0.1.1 (OK)
watchdog >=0.10.3                                :  3.0.0 (OK)
zmq >=22.1.0                                     :  25.0.2 (OK)

# Optional:
cython >=0.21                                    :  0.29.34 (OK)
matplotlib >=3.0.0                               :  3.7.1 (OK)
numpy >=1.7                                      :  1.24.2 (OK)
pandas >=1.1.1                                   :  2.0.0 (OK)
scipy >=0.17.0                                   :  1.10.1 (OK)
sympy >=0.7.3                                    :  1.11.1 (OK)

# Spyder plugins:
spyder_terminal.terminalplugin 1.2.2             :  1.2.2 (OK)```




Discussion:
Hi @MarkusSchwarz1980 thank you for the feedback! Could it be possible for you to run Spyder in debug mode and check the debugging log? For that go to `File > Restart in debug mode > Verbose` and then try again to use the PYTHONPATH manager. Then please post here the logs generated, you will find them at the `.spyder-py3` dir in your home directory (or accessing them through `Tools > Debug logs`).

Any new info that could help us understand what could be happening here is appreciated. Let us know!

Pinging @ccordoba12 and @mrclary maybe they know other ways to check what is happening here?
@dalthviz @ccordoba12 @MarkusSchwarz1980, I know what is going on here; three things:
1. There is a bug in `spyder.utils.environ.get_user_environment_variables` that affects only the macOS standalone application in which the user's environment variables are not retrieved resulting in the missing system `PYTHONPATH` in the PYTHONPATH Manager. I'll submit a pull request to fix this.
2. Upon adding a directory to the PYTHONPATH Manager, the window loses focus in favor of Spyder's main window. The PYTHONPATH Manager window remains open but is actually _behind_ the main window.
3. When clicking the PYTHONPATH Manager icon in the toolbar, the window is brought to focus and any changes are lost.

@MarkusSchwarz1980, I'm sorry for the inconvenience caused by these issues. Until Spyder 5.4.4 is released, you will have to manually add the system PYTHONPATH paths to the PYTHONPATH Manager, as you have already attempted, but note that the window has not actually closed, refrain from clicking the toolbar icon again, and cycle to the window (``cmd-` ``).

Resolving patch:
diff --git a/spyder/plugins/pythonpath/container.py b/spyder/plugins/pythonpath/container.py
--- a/spyder/plugins/pythonpath/container.py
+++ b/spyder/plugins/pythonpath/container.py
@@ -105,13 +105,16 @@ def update_active_project_path(self, path):
 
     def show_path_manager(self):
         """Show path manager dialog."""
-        # Set main attributes saved here
-        self.path_manager_dialog.update_paths(
-            self.path, self.not_active_path, get_system_pythonpath()
-        )
-
-        # Setup its contents again
-        self.path_manager_dialog.setup()
+        # Do not update paths or run setup if widget is already open,
+        # see spyder-ide/spyder#20808
+        if not self.path_manager_dialog.isVisible():
+            # Set main attributes saved here
+            self.path_manager_dialog.update_paths(
+                self.path, self.not_active_path, get_system_pythonpath()
+            )
+
+            # Setup its contents again
+            self.path_manager_dialog.setup()
 
         # Show and give it focus
         self.path_manager_dialog.show()
diff --git a/spyder/plugins/pythonpath/widgets/pathmanager.py b/spyder/plugins/pythonpath/widgets/pathmanager.py
--- a/spyder/plugins/pythonpath/widgets/pathmanager.py
+++ b/spyder/plugins/pythonpath/widgets/pathmanager.py
@@ -482,6 +482,13 @@ def add_path(self, directory=None):
                       "."),
                     QMessageBox.Ok)
 
+        # Widget moves to back and loses focus on macOS,
+        # see spyder-ide/spyder#20808
+        if sys.platform == 'darwin':
+            self.activateWindow()
+            self.raise_()
+            self.setFocus()
+
         self.refresh()
 
     @Slot()


Test patch: