等效于 shell 'cd' 命令来更改工作目录? [英] Equivalent of shell 'cd' command to change the working directory?

查看:71
本文介绍了等效于 shell 'cd' 命令来更改工作目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

cd 是改变工作目录的 shell 命令.

如何在 Python 中更改当前工作目录?

解决方案

您可以通过以下方式更改工作目录:

import osos.chdir(路径)

使用这种方法时有两个最佳实践需要遵循:

  1. 在无效路径上捕获异常(WindowsError、OSError).如果抛出异常,不要执行任何递归操作,尤其是破坏性的操作.他们将在旧路径而不是新路径上运作.
  2. 完成后返回到旧目录.这可以通过将 chdir 调用包装在上下文管理器中以异常安全的方式完成,就像 Brian M. Hunt 在 他的回答.

更改子进程中的当前工作目录不会更改父进程中的当前工作目录.Python 解释器也是如此.您不能使用 os.chdir() 来更改调用进程的 CWD.

cd is the shell command to change the working directory.

How do I change the current working directory in Python?

解决方案

You can change the working directory with:

import os

os.chdir(path)

There are two best practices to follow when using this method:

  1. Catch the exception (WindowsError, OSError) on invalid path. If the exception is thrown, do not perform any recursive operations, especially destructive ones. They will operate on the old path and not the new one.
  2. Return to your old directory when you're done. This can be done in an exception-safe manner by wrapping your chdir call in a context manager, like Brian M. Hunt did in his answer.

Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use os.chdir() to change the CWD of the calling process.

这篇关于等效于 shell 'cd' 命令来更改工作目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆