puddles
puddles

Reputation: 103

while debugging python in pdb, how to print output to file

Sometimes as I'm using pdb, I would like to save the output to a file, pdbSaves.txt. For example I would want to do something like pp locals() >> pdbSaves.txt, which actually gives *** NameError: name 'pdbSaves' is not defined. What is the correct way to do this?

Upvotes: 3

Views: 2799

Answers (1)

jsbueno
jsbueno

Reputation: 110166

In Python 3 the ">>" symbol is no longer usable with the regular "print" for redirecting the output.

I had not before used it from inside the PDB, but, certainly, the support for it was removed at the same time.

What you have to do is to use the regular way of output to file with the new print function - or, if you want to do pretty print (pp does that), with the pprint.pprint function.

(Pdb) from pprint import pprint as ppr
(Pdb) file = open("x.txt", "wt")
(Pdb) ppr("mystuff", stream=file)

Or, for regular printing, the parameter name for the output file is file rather than stream (the advantage is that the import statement is not needed):

(Pdb) print ("mystuff", file=file)

Also, either these methods and the Python 2 >> way require the target to be an open file, not a string with the filename:

Upvotes: 5

Related Questions