Domanda

Sto tentando di caricare un profilo cprofile, eseguire un po 'di ordinamento e affiliazione, quindi emettere i risultati in un file.Sulla base del Documentazione , pensavo di poter semplicemente passareUn oggetto file e la funzione print_stats si reindirizzano a quel flusso.

Ecco il codice che sto tentando di utilizzare:

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

Ed Ecco l'errore risultante:

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

Dovrei anche aggiungere che quando non passerò un oggetto al parametro del flusso, l'uscita appare normale nel terminale.

È stato utile?

Soluzione

Guardando il codice sorgente, dovrai passare il file come argomento della parola chiave stream (non mi ha chiarito perché è stato impensato come quello ...), come:

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

Vedi sotto il commento in linea e la linea 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)
.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top