如何在python中获取/设置逻辑目录路径 [英] How to get/set logical directory path in python
问题描述
在python中,可以获取或设置一个逻辑目录(与绝对目录相对).
In python is it possible to get or set a logical directory (as opposed to an absolute one).
例如,如果我有:
/real/path/to/dir
我有
/linked/path/to/dir
链接到同一目录.
使用os.getcwd和os.chdir将始终使用绝对路径
using os.getcwd and os.chdir will always use the absolute path
>>> import os
>>> os.chdir('/linked/path/to/dir')
>>> print os.getcwd()
/real/path/to/dir
我发现唯一可以解决此问题的方法是在另一个进程中启动"pwd"并读取输出.但是,只有在您首次调用os.chdir时,此方法才起作用.
The only way I have found to get around this at all is to launch 'pwd' in another process and read the output. However, this only works until you call os.chdir for the first time.
推荐答案
底层操作系统/shell报告python的真实路径.
The underlying operational system / shell reports real paths to python.
因此,实际上没有办法解决,因为os.getcwd()
是对C库getcwd()
函数的包装调用.
So, there really is no way around it, since os.getcwd()
is a wrapped call to C Library getcwd()
function.
按照您已经知道的启动pwd
的精神,有一些变通办法.
There are some workarounds in the spirit of the one that you already know which is launching pwd
.
另一种可能涉及使用os.environ['PWD']
.如果设置了该环境变量,则可以创建一些遵循该变量的getcwd
函数.
Another one would involve using os.environ['PWD']
. If that environmnent variable is set you can make some getcwd
function that respects it.
下面的解决方案将两者结合在一起:
The solution below combines both:
import os
from subprocess import Popen, PIPE
class CwdKeeper(object):
def __init__(self):
self._cwd = os.environ.get("PWD")
if self._cwd is None: # no environment. fall back to calling pwd on shell
self._cwd = Popen('pwd', stdout=PIPE).communicate()[0].strip()
self._os_getcwd = os.getcwd
self._os_chdir = os.chdir
def chdir(self, path):
if not self._cwd:
return self._os_chdir(path)
p = os.path.normpath(os.path.join(self._cwd, path))
result = self._os_chdir(p)
self._cwd = p
os.environ["PWD"] = p
return result
def getcwd(self):
if not self._cwd:
return self._os_getcwd()
return self._cwd
cwd = CwdKeeper()
print cwd.getcwd()
# use only cwd.chdir and cwd.getcwd from now on.
# monkeypatch os if you want:
os.chdir = cwd.chdir
os.getcwd = cwd.getcwd
# now you can use os.chdir and os.getcwd as normal.
这篇关于如何在python中获取/设置逻辑目录路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!