Python에서 논리 디렉토리 경로를 얻거나 설정하는 방법
문제
파이썬에서는 논리 디렉토리를 얻거나 설정할 수 있습니다 (절대 디렉토리와 반대).
예를 들어 내가 가지고있는 경우 :
/real/path/to/dir
그리고 나는 가졌다
/linked/path/to/dir
동일한 디렉토리에 연결됩니다.
os.getcwd 및 os.chdir 사용은 항상 절대 경로를 사용합니다.
>>> import os
>>> os.chdir('/linked/path/to/dir')
>>> print os.getcwd()
/real/path/to/dir
내가 이것을 둘러싼 유일한 방법은 다른 프로세스에서 'PWD'를 시작하고 출력을 읽는 것입니다. 그러나 이것은 처음으로 OS.Chdir를 호출 할 때까지만 작동합니다.
해결책
기본 운영 체제 / 쉘은 Python에 대한 실제 경로를보고합니다.
그래서, 그 주위에 실제로는 아무 방법이 없습니다. os.getcwd()
C 라이브러리로 포장 된 전화입니다 getcwd()
기능.
이미 출시중인 사람의 정신에 몇 가지 해결 방법이 있습니다. pwd
.
다른 하나는 사용과 관련이 있습니다 os.environ['PWD']
. 해당 환경 변수가 설정되면 일부를 만들 수 있습니다. getcwd
그것을 존중하는 기능.
아래 솔루션은 두 가지를 결합합니다.
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.
다른 팁
이것은 또한 나에게 트릭을 수행합니다.
import os
os.popen('pwd').read().strip('\n')
파이썬 쉘의 데모는 다음과 같습니다.
>>> import os
>>> os.popen('pwd').read()
'/home/projteam/staging/site/proj\n'
>>> os.popen('pwd').read().strip('\n')
'/home/projteam/staging/site/proj'
>>> # Also works if PWD env var is set
>>> os.getenv('PWD')
'/home/projteam/staging/site/proj'
>>> # This gets actual path, not symlinked path
>>> import subprocess
>>> p = subprocess.Popen('pwd', stdout=subprocess.PIPE)
>>> p.communicate()[0] # returns non-symlink path
'/home/projteam/staging/deploys/20150114-141114/site/proj\n'
환경 변수 PWD를 얻는 것이 항상 작동하지 않으므로 Popen 메소드를 사용합니다. 건배!
제휴하지 않습니다 StackOverflow