python如何设置路径点_如何在python中获取/设置逻辑目录路径

In python is it possible to get or set a logical directory (as opposed to an absolute one).

For example if I have:

/real/path/to/dir

and I have

/linked/path/to/dir

linked to the same directory.

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

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.

解决方案

The underlying operational system / shell reports real paths to python.

So, there really is no way around it, since os.getcwd() is a wrapped call to C Library getcwd() function.

There are some workarounds in the spirit of the one that you already know which is launching pwd.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值