【问题标题】:Python: Is it possible to change the Windows command line shell current directory without changing the actual current directory?Python:是否可以在不更改实际当前目录的情况下更改 Windows 命令行 shell 当前目录?
【发布时间】:2023-04-02 15:28:01
【问题描述】:

我正在使用 os.system() 执行 Windows 命令行 shell 执行。我想更改 Windows cmd 当前目录。这是一种方法:

os.chdir('newPath')

但是chdir() 也会改变实际的 Python 当前工作目录。我不想更改实际的 Python 工作目录,因为我希望脚本的其他部分在原始当前工作目录中运行。我要更改的只是 Windows cmd 当前工作目录。换句话说:我希望os.system() 命令在一个当前工作目录(Windows cmd 当前工作目录)中运行,而其他任何东西都应该在另一个当前工作目录(实际的 Python 当前工作目录)中运行。

这是另一个尝试更改 Windows cmd 当前目录:

os.system('cd newPath')

但是,这显然不起作用,因为在执行 cd newPath 命令后,Windows cmd 当前目录被重置(因为我不会在下次调用 os.system() 时使用相同的 Windows 命令外壳) .

是否可以为 Windows cmd shell 提供一个单独的当前工作目录? (与实际的当前工作目录分开)。

【问题讨论】:

  • I would like to keep the current working directory while only change the Windows cmd current working directory - 什么?
  • @BlueRaja:你是对的。我不清楚。刚刚编辑了问题以使其更清楚。

标签: python cmd working-directory


【解决方案1】:

subprocess 模块旨在替换 os.system

除其他外,它还为您提供subprocess.Popen(),它采用cwd 参数来指定生成进程的工作目录(适合您的具体情况)。

见:http://docs.python.org/library/subprocess.html

替换os.system的示例用法:

p = subprocess.Popen("yourcmd" + " yourarg", shell=True, cwd="c:/your/path")
sts = os.waitpid(p.pid, 0)[1]

【讨论】:

  • 谢谢。你能在os.waitpid()这件事上加几句吗?
  • @snak waitpid 在文档中进行了描述。你甚至可以猜到它的作用。
  • retcode = subprocess.call(["yourcmd","arg1","arg2"], shell=True, cwd="c:/your/path")
【解决方案2】:

如果它只需要在 Windows 上运行,一种方法可能是:

os.system('start /d newPath cmd')

【讨论】:

  • 为什么不直接'start cd mypath'?然而,考虑到 zigdon 和其他人指出的内容,这个问题的去向还不太清楚
  • 我猜同样的解决方案也适用于Linux。
【解决方案3】:

当您使用os.system 时,您不会重复使用相同的命令shell,而是为每个请求生成一个新的命令shell。这意味着您实际上不能期望它的更改会在调用之间传播。

您可以编写一个包装器,它总是会在启动命令之前更改为您想要的目录。

【讨论】:

  • 谢谢,但我知道我没有重复使用同一个 shell。我要问的是如何克服这个问题并在不更改实际当前目录的情况下更改 windows 当前目录。
猜你喜欢
  • 2010-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-05
  • 1970-01-01
  • 2010-10-05
  • 1970-01-01
相关资源
最近更新 更多