Skip to content

Commit

Permalink
Store original sys.path so that user paths do not need to be removed …
Browse files Browse the repository at this point in the history
…upon update. This obviates the need for sending the old user paths with the sig_pythonpath_updated signal.
  • Loading branch information
mrclary committed Feb 29, 2024
1 parent 37e15d2 commit 79cdf37
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions spyder_kernels/console/kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@ def __init__(self, *args, **kwargs):
# Socket to signal shell_stream locally
self.loopback_socket = None

# Store original sys.path. Kernels are started with PYTHONPATH
# removed from environment variables, so this will never have
# user paths and should be clean.
self._sys_path = sys.path.copy()

@property
def kernel_info(self):
# Used for checking correct version by spyder
Expand Down Expand Up @@ -764,34 +769,34 @@ def set_special_kernel(self, special):
raise NotImplementedError(f"{special}")

@comm_handler
def update_syspath(self, old_path, new_path, prioritize):
def update_syspath(self, new_path, prioritize):
"""
Update the PYTHONPATH of the kernel.
`old_path` corresponds to the previous state of the PYTHONPATH.
`new_path` corresponds to the new state of the PYTHONPATH.
`prioritize` determines whether to prioritize PYTHONPATH in sys.path.
"""
# Remove old paths
for path in old_path:
while path in sys.path:
sys.path.remove(path)
# Add new paths
if new_path:
A copy of sys.path is made at instantiation, which should be clean,
so we can just prepend/append to the copy without having to explicitly
remove old user paths. PYTHONPATH can just be overwritten.
"""
if new_path is not None:
# Overwrite PYTHONPATH
os.environ.update({'PYTHONPATH': os.pathsep.join(new_path)})

# Add new paths to original sys.path
if prioritize:
new_path.reverse()
[sys.path.insert(0, path) for path in new_path]
sys.path[:] = new_path + self._sys_path

# Ensure current directory is always first
if '' in sys.path:
sys.path.remove('')
sys.path.insert(0, '')
else:
sys.path.extend(new_path)
sys.path[:] = self._sys_path + new_path
else:
# Restore original sys.path and remove PYTHONPATH
sys.path[:] = self._sys_path
os.environ.pop('PYTHONPATH', None)

# -- Private API ---------------------------------------------------
Expand Down

0 comments on commit 79cdf37

Please sign in to comment.