MCPcopy Index your code
hub / github.com/ipython/ipython / AvoidUNCPath

Class AvoidUNCPath

IPython/utils/_process_win32_controller.py:152–187  ·  view source on GitHub ↗

A context manager to protect command execution from UNC paths. In the Win32 API, commands can't be invoked with the cwd being a UNC path. This context manager temporarily changes directory to the 'C:' drive on entering, and restores the original working directory on exit. The conte

Source from the content-addressed store, hash-verified

150LocalFree.restype = HLOCAL
151
152class AvoidUNCPath:
153 """A context manager to protect command execution from UNC paths.
154
155 In the Win32 API, commands can't be invoked with the cwd being a UNC path.
156 This context manager temporarily changes directory to the 'C:' drive on
157 entering, and restores the original working directory on exit.
158
159 The context manager returns the starting working directory *if* it made a
160 change and None otherwise, so that users can apply the necessary adjustment
161 to their system calls in the event of a change.
162
163 Examples
164 --------
165 ::
166 cmd = 'dir'
167 with AvoidUNCPath() as path:
168 if path is not None:
169 cmd = '"pushd %s &&"%s' % (path, cmd)
170 os.system(cmd)
171 """
172
173 def __enter__(self) -> None:
174 self.path = os.getcwd()
175 self.is_unc_path = self.path.startswith(r"\\")
176 if self.is_unc_path:
177 # change to c drive (as cmd.exe cannot handle UNC addresses)
178 os.chdir("C:")
179 return self.path
180 else:
181 # We return None to signal that there was no change in the working
182 # directory
183 return None
184
185 def __exit__(self, exc_type, exc_value, traceback) -> None:
186 if self.is_unc_path:
187 os.chdir(self.path)
188
189
190class Win32ShellCommandController:

Callers 1

systemFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…