相关疑难解决方法(0)

将stdout重定向到Python中的文件?

如何将stdout重定向到Python中的任意文件?

当从ssh会话中启动长时间运行的Python脚本(例如,Web应用程序)并进行后台处理,并且ssh会话关闭时,应用程序将引发IOError并在尝试写入stdout时失败.我需要找到一种方法来将应用程序和模块输出到文件而不是stdout,以防止由于IOError导致的失败.目前,我使用nohup将输出重定向到一个文件,这就完成了工作,但是我想知道是否有办法在不使用nohup的情况下完成它,出于好奇.

我已经尝试了sys.stdout = open('somefile', 'w'),但这似乎并没有阻止一些外部模块仍然输出到终端(或者sys.stdout = ...线路根本没有发射).我知道它应该使用我测试过的简单脚本,但我还没有时间在Web应用程序上进行测试.

python stdout

285
推荐指数
8
解决办法
43万
查看次数

使用可选参数创建装饰器

from functools import wraps

def foo_register(method_name=None):
    """Does stuff."""
    def decorator(method):
        if method_name is None:
            method.gw_method = method.__name__
        else:
            method.gw_method = method_name
        @wraps(method)
        def wrapper(*args, **kwargs):
            method(*args, **kwargs)
        return wrapper
    return decorator
Run Code Online (Sandbox Code Playgroud)

例如:下面的装饰my_functionfoo_register的,而不是它曾经做对decorator.

@foo_register
def my_function():
    print('hi...')
Run Code Online (Sandbox Code Playgroud)

示例:以下按预期工作.

@foo_register('say_hi')
def my_function():
    print('hi...')
Run Code Online (Sandbox Code Playgroud)

如果我希望它在两个应用程序中正常工作(一个使用method.__name__和一个传递名称),我必须检查内部foo_register是否第一个参数是装饰器,如果是,我必须:( return decorator(method_name)而不是return decorator).这种"检查它是否可以调用"似乎非常hackish.有没有更好的方法来创建这样的多用途装饰器?

PS我已经知道我可以要求装饰器被调用,但这不是一个"解决方案".我希望API感觉自然.我的妻子喜欢装饰,我不想破坏它.

python decorator wrapper

56
推荐指数
5
解决办法
2万
查看次数

如何使用可选参数构建装饰器?

我想制作一个可以使用或不使用参数的装饰器:这样的东西:

class d(object):
    def __init__(self,msg='my default message'):
        self.msg = msg
    def __call__(self,fn):
        def newfn():
            print self.msg
            return fn()
        return newfn

@d('This is working')
def hello():
    print 'hello world !'

@d
def too_bad():
    print 'does not work'
Run Code Online (Sandbox Code Playgroud)

在我的代码中,只使用带参数的装饰器工作:如何继续工作(有和没有参数)?

python decorator

34
推荐指数
5
解决办法
2万
查看次数

可以带或不带参数使用的类型装饰器

我有一个装饰器,可以在不带参数或带参数的情况下调用(所有字符串):

\n
@decorator\ndef fct0(a: int, b: int) -> int:\n    return a * b\n\n\n@decorator("foo", "bar")  # any number of arguments\ndef fct1(a: int, b: int) -> int:\n    return a * b\n
Run Code Online (Sandbox Code Playgroud)\n

尽管已阅读mypy 文档的相关部分,但我很难提供适当的类型提示,以便类型检查器能够正确验证装饰器的使用。

\n

这是我到目前为止所尝试过的:

\n
from typing import overload, TypeVar, Any, Callable\n\nF = TypeVar("F", bound=Callable[..., Any])\n\n@overload\ndef decorator(arg: F) -> F:\n    ...\n\n@overload\ndef decorator(*args: str) -> Callable[[F], F]:\n    ...\n\ndef decorator(*args: Any) -> Any:\n    # python code adapted from https://stackoverflow.com/q/653368\n\n    # @decorator -> shorthand for @decorator()\n    if len(args) == 1 and callable(args[0]):\n …
Run Code Online (Sandbox Code Playgroud)

python python-decorators mypy python-typing pyright

5
推荐指数
1
解决办法
749
查看次数

Django为decorator添加了可选参数

我有以下装饰和视图哪个工作正常.

装饰

def event_admin_only(func):
    """
    Checks if the current role for the user is an Event Admin or not
    """
    def decorator(request, *args, **kwargs):
        event = get_object_or_404(Event, slug=kwargs['event_slug'])

        allowed_roles = [role[1] for role in Role.ADMIN_ROLES]

        # get user current role
        current_role = request.session.get('current_role')

        if current_role not in allowed_roles:
            url = reverse('no_perms')
            return redirect(url)
        else:       
            return func(request, *args, **kwargs)
    return decorator
Run Code Online (Sandbox Code Playgroud)

视图

@event_admin_only
def event_dashboard(request, event_slug):
    pass
Run Code Online (Sandbox Code Playgroud)

但是我如何修改我的装饰器,以便它接受一个额外的参数,如下所示:

@event_admin_only(obj1,[...])
def event_dashboard(request, event_slug):
    pass
Run Code Online (Sandbox Code Playgroud)

python django decorator

4
推荐指数
1
解决办法
6284
查看次数