Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when attempting to write cProfile information to file

I am attempting to load a cProfile profile, do some sorting and finessing, then output the results to a file. Based on the documentation, I thought I could simply pass a file object and the print_stats function would redirect to that stream.

Here is the code I am attempting to use:

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

and here is the resulting error:

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

I should also add that when I do not pass an object to the stream parameter, the output appears as normal in the terminal.

like image 756
the_e Avatar asked Oct 01 '22 01:10

the_e


1 Answers

Looking at the source code, you'd have to pass the file as a stream keyword argument (not clear to me why it was implented like that...), like:

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

See below the inline comment, and the if "stream" in kwds line.

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)
like image 128
shx2 Avatar answered Oct 12 '22 11:10

shx2