底層操作系統/ shell報告python的真實路徑。
所以,真的沒有辦法解決它,因爲os.getcwd()
是C庫getcwd()
功能的封裝調用。
有一些你已經知道啓動pwd
的精神的一些解決方法。
另一個涉及使用os.environ['PWD']
。如果該環境變量已設置,則可以創建一些尊重該變量的函數。
該解決方案如下結合了:
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.
謝謝! getcwd()需要一個自我論證 - 除了它完美的工作! – Moe 2008-09-23 21:50:47