0

我编写了一个既作为上下文管理器又作为函数运行的函数。

我的函数可以追溯到 Python 2.6 并针对此测试:

@cd('/')
def test_cd_decorator():
    assert os.getcwd() == '/'

def test_cd():
    old = os.getcwd()
    with cd('/'):
        assert os.getcwd() == '/'
    assert os.getcwd() == old
    test_cd_decorator()
    assert os.getcwd() == old

test_cd()

什么是最 Pythonic 的解决方案?

4

1 回答 1

2

I don't know there is such library that does what you need. So I created one.

import functools
import os

class cd:
    def __init__(self, path):
        self.path = path
    def __enter__(self):
        self.old = os.getcwd()
        os.chdir(self.path)
        return self
    def __exit__(self, exc_type, exc_value, tb):
        os.chdir(self.old)
    def __call__(self, func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            with self:
                return func(*args, **kwargs)
        return wrapper
于 2013-10-18T09:55:00.683 回答