尝试将 cProfile 信息写入文件时出错
-
21-12-2019 - |
题
我正在尝试加载 cProfile 配置文件,进行一些排序和处理,然后将结果输出到文件中。基于 文档, ,我想我可以简单地传递一个文件对象和 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>''
我还应该补充一点,当我不将对象传递给流参数时,输出会在终端中正常显示。
解决方案
查看源代码,您必须将文件作为 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)
不隶属于 StackOverflow