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
| 23 | |
| 24 | |
| 25 | class AvoidUNCPath: |
| 26 | """A context manager to protect command execution from UNC paths. |
| 27 | |
| 28 | In the Win32 API, commands can't be invoked with the cwd being a UNC path. |
| 29 | This context manager temporarily changes directory to the 'C:' drive on |
| 30 | entering, and restores the original working directory on exit. |
| 31 | |
| 32 | The context manager returns the starting working directory *if* it made a |
| 33 | change and None otherwise, so that users can apply the necessary adjustment |
| 34 | to their system calls in the event of a change. |
| 35 | |
| 36 | Examples |
| 37 | -------- |
| 38 | :: |
| 39 | cmd = 'dir' |
| 40 | with AvoidUNCPath() as path: |
| 41 | if path is not None: |
| 42 | cmd = '"pushd %s &&"%s' % (path, cmd) |
| 43 | os.system(cmd) |
| 44 | """ |
| 45 | |
| 46 | def __enter__(self) -> Optional[str]: |
| 47 | self.path = os.getcwd() |
| 48 | self.is_unc_path = self.path.startswith(r"\\") |
| 49 | if self.is_unc_path: |
| 50 | # change to c drive (as cmd.exe cannot handle UNC addresses) |
| 51 | os.chdir("C:") |
| 52 | return self.path |
| 53 | else: |
| 54 | # We return None to signal that there was no change in the working |
| 55 | # directory |
| 56 | return None |
| 57 | |
| 58 | def __exit__( |
| 59 | self, |
| 60 | exc_type: Optional[type[BaseException]], |
| 61 | exc_value: Optional[BaseException], |
| 62 | traceback: Optional[TracebackType], |
| 63 | ) -> None: |
| 64 | if self.is_unc_path: |
| 65 | os.chdir(self.path) |
| 66 | |
| 67 | |
| 68 | def _system_body(p: subprocess.Popen[bytes]) -> int: |
no outgoing calls
no test coverage detected
searching dependent graphs…