python:os.system(r'cd foo') & os.chdir()

python:os.system(r'cd foo') & os.chdir()

我有一个 doubt.When 我试过了 os.system(r'cd F:\') 我还在我开始 interpreter.But `os.chdir()' 工作的目录中 fine.I 将在下面显示我的代码:

>>> import os
>>> os.system('F:')
0

通过运行 os.system('dir') 发现我还在目录C:\python34.

然后我试了这个:

>>> os.chdir('F:')

通过 运行 os.system('dir') 我发现它运行良好。

为什么 os.system('F:') 不起作用? 我很乐意得到帮助。

os.system('F:') 生成子 shell 进程(即 %ComSpec% shell,通常是 cmd.exe)并更改其工作目录。它不会(也不能)更改父进程的工作目录。

请注意,工作目录不是按线程存储的,即它不是存储在线程环境块 (TEB) 中,而是存储在进程环境块 (PEB) 中的进程范围内。通常避免修改多线程应用程序中的工作目录。而是使用相对路径或完全限定路径。


奖金琐事:DOS 仿真

除了进程当前工作目录之外,Windows(实际上是 C 运行时)在隐藏的环境变量(例如 =C: 中跟踪每个 DOS 驱动器(例如 C:) 上的工作目录.初始的 '=' 字符防止这些变量被 shell 的 set 命令显示,并且它还将它们从 Python 使用的 C 运行时 environ 中过滤掉对于 os.environ。如果您将空字符串传递给 set 命令,则命令提示符中的错误将显示这些隐藏变量,例如set ""。或者在 Python 中使用 ctypes 调用 GetEnvironmentVariable:

>>> from ctypes import *                            
>>> kernel32 = WinDLL('kernel32')
>>> kernel32.GetEnvironmentVariableW('=C:', None, 0)
8
>>> path = create_unicode_buffer(8)
>>> kernel32.GetEnvironmentVariableW('=C:', path, 8)
7
>>> path.value
'C:\Temp'

Windows 使用 这些隐藏变量(如果存在)来解析驱动器相对路径。也就是说,C 运行时 _chdir function is actually what creates/modifies them. A Windows program that only calls SetCurrentDirectory instead of POSIX chdir won't remember the per-drive working directory. Python's home-grown implementation of chdir on Windows has to implement this magic. See win32_chdir(3.4.3 源代码,Modules/posixmodule.c,第 1398 行)。