5

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 当前目录被重置(因为我不会在下一次调用时使用相同的 Windows 命令 shell os.system())。

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

4

3 回答 3

7

subprocess模块旨在替换os.system.

Among other things, it gives you subprocess.Popen(), which takes a cwd argument to specify the working directory for the spawned process (for exactly your situation).

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

Example usage replacing os.system:

p = subprocess.Popen("yourcmd" + " yourarg", shell=True, cwd="c:/your/path")
sts = os.waitpid(p.pid, 0)[1]
于 2011-02-03T00:01:15.520 回答
1

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

os.system('start /d newPath cmd')
于 2011-02-02T23:52:14.110 回答
1

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

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

于 2011-02-02T23:53:11.893 回答