【问题标题】:Error when attempting to write cProfile information to file尝试将 cProfile 信息写入文件时出错
【发布时间】:2014-05-26 22:41:16
【问题描述】:

我正在尝试加载 cProfile 配置文件,进行一些排序和微调,然后将结果输出到文件中。基于documentation,我想我可以简单地传递一个文件对象,print_stats 函数将重定向到该流。

这是我尝试使用的代码:

import sys,pstats
s = open('output.txt', 'w')
p = pstats.Stats('profile.dat', s)

这是产生的错误:

TypeError: Cannot create or construct a <class pstats.Stats at 0xbaa870> object from '<open file 'output.txt', mode 'w' at 0xb2ef60>''

我还应该补充一点,当我不将对象传递给流参数时,输出在终端中显示正常。

【问题讨论】:

    标签: python-2.7 cprofile pstats


    【解决方案1】:

    查看源代码,您必须将文件作为 stream 关键字参数传递(我不清楚为什么要这样实现...),例如:

    p = pstats.Stats('profile.dat', stream = s)
    

    见下面的内联注释和if "stream" in kwds 行。

    class Stats:
        """..."""
        def __init__(self, *args, **kwds):
            # I can't figure out how to explictly specify a stream keyword arg
            # with *args:
            #   def __init__(self, *args, stream=sys.stdout): ...
            # so I use **kwds and sqauwk if something unexpected is passed in.
            self.stream = sys.stdout
            if "stream" in kwds:
                self.stream = kwds["stream"]
                del kwds["stream"]
            if kwds:
                keys = kwds.keys()
                keys.sort()
                extras = ", ".join(["%s=%s" % (k, kwds[k]) for k in keys])
                raise ValueError, "unrecognized keyword args: %s" % extras
            if not len(args):
                arg = None
            else:
                arg = args[0]
                args = args[1:]
            self.init(arg)
            self.add(*args)
    

    【讨论】:

    • 我分配了流属性 (dpaste.com/2R8YS04) 但出现了同样的错误。
    • @tutuca 请发布您的代码,或提出新问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多