小编ran*_*let的帖子

从Python函数中抑制stdout/stderr打印

我有一个Python脚本,它使用我的雇主提供的一些闭箱Python函数(即我无法编辑这些函数).当我调用这些函数时,它们正在打印输出到我想要压制的linux终端.我尝试过重定向stdout/stderr;

orig_out = sys.stdout
sys.stdout = StringIO()
rogue_function()
sys.stdout = orig_out
Run Code Online (Sandbox Code Playgroud)

但这没有抓住输出.我认为我通过Python调用的函数(上面的rogue_function())实际上是编译C代码的包装器,它们实际上正在进行打印.

有没有人知道我可以通过函数(以及函数调用的任何子函数)对stdout/stderr的任何打印进行"深度捕获"?

更新:

我最终采用了下面选定答案中概述的方法并编写了一个上下文管理器来压制stdout和stderr:

# Define a context manager to suppress stdout and stderr.
class suppress_stdout_stderr(object):
    '''
    A context manager for doing a "deep suppression" of stdout and stderr in 
    Python, i.e. will suppress all print, even if the print originates in a 
    compiled C/Fortran sub-function.
       This will not suppress raised exceptions, since exceptions are printed
    to stderr just before a script exits, and after the context manager …
Run Code Online (Sandbox Code Playgroud)

python stdout

32
推荐指数
3
解决办法
2万
查看次数

Django通用外键过滤(v1.5和v1.6之间的区别)

我有以下概念模型:

class GenericAbstractBase(models.Model):
    name = models.CharField(max_length=255)
    staff = generic.GenericRelation(
        "Staff",
        content_type_field="content_type",
        object_id_field="object_id",
    )

    class Meta:
        abstract = True


class GenericModelA(GenericAbstractBase):
    extra_a = models.CharField(max_length=255)


class GenericModelB(GenericAbstractBase):
    extra_b = models.CharField(max_lenth=10)


class Staff(models.Model):

    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    active = models.CharField(max_length=10, choices = ACTIVE_CHOICES)

    limit = models.Q(app_label='staff', model='genericmodela') | models.Q(app_label='staff', model='genericmodelb')
    content_type = models.ForeignKey(ContentType, limit_choices_to=limit)
    object_id = models.PositiveIntegerField()
    generic_object = generic.GenericForeignKey("content_type", "object_id")
Run Code Online (Sandbox Code Playgroud)

在Django v1.4和Django v1.5中,以下查询工作正常:

>>> ctype = ContentType.objects.get_for_model(GenericModelA)
>>> Staff.objects.filter(
        content_type=ctype,
        genericmodela__name__icontains="a"
    )
>>> [<Staff: Abbott, Kaylee>, <Staff: Adams, Kay>, ... …
Run Code Online (Sandbox Code Playgroud)

django generic-relations generic-foreign-key

7
推荐指数
1
解决办法
1363
查看次数