Search code examples
python-2.7cprofilepstats

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.


Solution

  • 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)