Context manager that keeps directory state when executing commands. Any calls to `run`, `sudo`, within the wrapped block will implicitly have a string similar to ``"cd && "`` prefixed in order to give the sense that there is actually statefulness involved.
(self, path: Union[PathLike, str])
| 358 | |
| 359 | @contextmanager |
| 360 | def cd(self, path: Union[PathLike, str]) -> Generator[None, None, None]: |
| 361 | """ |
| 362 | Context manager that keeps directory state when executing commands. |
| 363 | |
| 364 | Any calls to `run`, `sudo`, within the wrapped block will implicitly |
| 365 | have a string similar to ``"cd <path> && "`` prefixed in order to give |
| 366 | the sense that there is actually statefulness involved. |
| 367 | |
| 368 | Because use of `cd` affects all such invocations, any code making use |
| 369 | of the `cwd` property will also be affected by use of `cd`. |
| 370 | |
| 371 | Like the actual 'cd' shell builtin, `cd` may be called with relative |
| 372 | paths (keep in mind that your default starting directory is your user's |
| 373 | ``$HOME``) and may be nested as well. |
| 374 | |
| 375 | Below is a "normal" attempt at using the shell 'cd', which doesn't work |
| 376 | since all commands are executed in individual subprocesses -- state is |
| 377 | **not** kept between invocations of `run` or `sudo`:: |
| 378 | |
| 379 | c.run('cd /var/www') |
| 380 | c.run('ls') |
| 381 | |
| 382 | The above snippet will list the contents of the user's ``$HOME`` |
| 383 | instead of ``/var/www``. With `cd`, however, it will work as expected:: |
| 384 | |
| 385 | with c.cd('/var/www'): |
| 386 | c.run('ls') # Turns into "cd /var/www && ls" |
| 387 | |
| 388 | Finally, a demonstration (see inline comments) of nesting:: |
| 389 | |
| 390 | with c.cd('/var/www'): |
| 391 | c.run('ls') # cd /var/www && ls |
| 392 | with c.cd('website1'): |
| 393 | c.run('ls') # cd /var/www/website1 && ls |
| 394 | |
| 395 | .. note:: |
| 396 | Space characters will be escaped automatically to make dealing with |
| 397 | such directory names easier. |
| 398 | |
| 399 | .. versionadded:: 1.0 |
| 400 | .. versionchanged:: 1.5 |
| 401 | Explicitly cast the ``path`` argument (the only argument) to a |
| 402 | string; this allows any object defining ``__str__`` to be handed in |
| 403 | (such as the various ``Path`` objects out there), and not just |
| 404 | string literals. |
| 405 | """ |
| 406 | path = str(path) |
| 407 | self.command_cwds.append(path) |
| 408 | try: |
| 409 | yield |
| 410 | finally: |
| 411 | self.command_cwds.pop() |
| 412 | |
| 413 | |
| 414 | class MockContext(Context): |
no test coverage detected