Repository: spyder-ide/spyder

Issue:
"import sys" doesn't seem to work at console startup
<!--- **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

* [✅] Searched the [issues page](https://github.com/spyder-ide/spyder/issues?q=is%3Aissue) for similar reports
* [✅] 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)
* [✅] Tried basic troubleshooting (if a bug/error)
    * [✅] Restarted Spyder
    * [✅] 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
* [✅] Completed the **Problem Description**, **Steps to Reproduce** and **Version** sections below


## Problem Description

When putting `import sys` in the IPython Console startup tab in "Run code," sys doesn't seem to be imported. You can put in multiple statements separated by semicolon, like `import os; import sys` (which is suggested in the annotation for this tab), but somehow, after doing this, you get

```
os
Out[1]: <module 'os' from '/usr/local/Caskroom/miniconda/base/envs/spyder-env/lib/python3.9/os.py'>

sys
Traceback (most recent call last):

  File "<ipython-input-2-7a51ce427d93>", line 1, in <module>
    sys

NameError: name 'sys' is not defined
```

Somehow, strangely, doing `import sys as asdf` works, in that you get

```
asdf
Out[3]: <module 'sys' (built-in)>
```

And somehow, doing *anything* with the name `sys` in the startup code yields this error - for instance, if you type `sys = 12345` in the startup code, you still get `NameError: name 'sys' is not defined`. This suggests that somewhere, Spyder is calling `del sys` after the startup code is called and prior to giving the user the ability to type in the console.


### What steps reproduce the problem?

1. Go to Preferences -> IPython console -> Startup
2. In "Lines," type `import sys`, or even `sys = 12345`, or do anything with sys
3.  Start a console and type "sys"; name "sys" will be undefined
4. This only seems to happen with the name "sys"

### What is the expected output? What do you see instead?

`NameError: name 'sys' is not defined`


### Paste Traceback/Error Below (if applicable)
<!--- Copy from error dialog or View > Panes > Internal Console --->

```python-traceback

Traceback (most recent call last):

  File "<ipython-input-1-7a51ce427d93>", line 1, in <module>
    sys

NameError: name 'sys' is not defined

```

## 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.0.0
* Python version: 3.9.4
* Qt version: 5.9.7
* PyQt version: 5.9.2
* Operating System name/version: Darwin 17.7.0

### Dependencies
<!--- Please go to the menu entry Help > Dependencies,
press the Copy to clipboard button and paste below --->

```

# Mandatory:
applaunchservices >=0.1.7     :  0.2.1 (OK)
atomicwrites >=1.2.0          :  1.4.0 (OK)
chardet >=2.0.0               :  4.0.0 (OK)
cloudpickle >=0.5.0           :  1.6.0 (OK)
cookiecutter >=1.6.0          :  1.7.2 (OK)
diff_match_patch >=20181111   :  20200713 (OK)
intervaltree >=3.0.2          :  3.1.0 (OK)
IPython >=7.6.0               :  7.22.0 (OK)
jedi =0.17.2                  :  0.17.2 (OK)
jsonschema >=3.2.0            :  3.2.0 (OK)
keyring >=17.0.0              :  23.0.1 (OK)
nbconvert >=4.0               :  6.0.7 (OK)
numpydoc >=0.6.0              :  1.1.0 (OK)
parso =0.7.0                  :  0.7.0 (OK)
pexpect >=4.4.0               :  4.8.0 (OK)
pickleshare >=0.4             :  0.7.5 (OK)
psutil >=5.3                  :  5.8.0 (OK)
pygments >=2.0                :  2.9.0 (OK)
pylint >=1.0                  :  2.7.4 (OK)
pyls >=0.36.2;<1.0.0          :  0.36.2 (OK)
pyls_black >=0.4.6            :  0.4.6 (OK)
pyls_spyder >=0.3.2           :  0.3.2 (OK)
qdarkstyle =3.0.2             :  3.0.2 (OK)
qstylizer >=0.1.10            :  0.1.10 (OK)
qtawesome >=0.5.7             :  1.0.2 (OK)
qtconsole >=5.0.3             :  5.0.3 (OK)
qtpy >=1.5.0                  :  1.9.0 (OK)
rtree >=0.8.3                 :  0.9.7 (OK)
setuptools >=39.0.0           :  52.0.0.post20210125 (OK)
sphinx >=0.6.6                :  4.0.1 (OK)
spyder_kernels >=2.0.1;<2.1.0 :  2.0.1 (OK)
textdistance >=4.2.0          :  4.2.1 (OK)
three_merge >=0.1.1           :  0.1.1 (OK)
watchdog >=0.10.3;<2.0.0      :  1.0.2 (OK)
zmq >=17                      :  20.0.0 (OK)

# Optional:
cython >=0.21                 :  0.29.23 (OK)
matplotlib >=2.0.0            :  3.3.4 (OK)
numpy >=1.7                   :  1.20.1 (OK)
pandas >=1.1.1                :  1.2.4 (OK)
scipy >=0.17.0                :  1.6.2 (OK)
sympy >=0.7.3                 :  1.8 (OK)
```



Discussion:
Hey @battaglia01, thanks for reporting. You're right, this is a strange bug and we haven't noticed it before. Fortunately the fix is simple, so I'll include it in our next version (5.0.4), to be released shortly.

Resolving patch:
diff --git a/external-deps/spyder-kernels/spyder_kernels/console/start.py b/external-deps/spyder-kernels/spyder_kernels/console/start.py
--- a/external-deps/spyder-kernels/spyder_kernels/console/start.py
+++ b/external-deps/spyder-kernels/spyder_kernels/console/start.py
@@ -98,16 +98,20 @@ def kernel_config():
     if not PY2:
         spy_cfg.IPCompleter.use_jedi = jedi_o
 
+    # Clear terminal arguments input.
+    # This needs to be done before adding the exec_lines that come from
+    # Spyder, to avoid deleting the sys module if users want to import
+    # it through them.
+    # See spyder-ide/spyder#15788
+    clear_argv = "import sys;sys.argv = [''];del sys"
+    spy_cfg.IPKernelApp.exec_lines = [clear_argv]
+
     # Run lines of code at startup
     run_lines_o = os.environ.get('SPY_RUN_LINES_O')
     if run_lines_o is not None:
-        spy_cfg.IPKernelApp.exec_lines = [x.strip() for x in run_lines_o.split(';')]
-    else:
-        spy_cfg.IPKernelApp.exec_lines = []
-
-    # Clean terminal arguments input
-    clear_argv = "import sys;sys.argv = [''];del sys"
-    spy_cfg.IPKernelApp.exec_lines.append(clear_argv)
+        spy_cfg.IPKernelApp.exec_lines += (
+            [x.strip() for x in run_lines_o.split(';')]
+        )
 
     # Load %autoreload magic
     spy_cfg.IPKernelApp.exec_lines.append(


Test patch: