2

I'd like to output a series of dircmp report_full_disclosure()'s to a text file. However the report_full_disclosure() format is one blob of text, it doesn't play nicely with file.write(comparison_object.report_full_disclosure()) because file.write() expects a single line to write to the file.

I've tried iterating through the report_full_disclosure() report but it doesn't work either. Has anyone else had this particular problem before? Is there a different method to write out to files?

Dylan Pierce
  • 4,313
  • 3
  • 35
  • 45

2 Answers2

2

the "report generating" methods of dircmp.filecmp don't accept a file object, they just use the print statement (or, in the Python 3 version, the print() function)

You could create a subclass of dircmp.filecmp which accepts a file argument to methods report, report_full_closure and report_partial_closure (if needed), at each print ... site writing print >>dest, .... Where report_*_closure call recursively, pass the dest argument down to the recursive call.

The lack of ability to print output to a specific file seems to me to be an oversight, so having added an optional file argument to these methods and tested it thoroughly you may wish to offer your contribution to the Python project.

If your program is single threaded, you could temporarily replace sys.stdout with your destination file before calling the report methods. But this is a dirty and fragile method, and it is probably foolish to imagine your program will be forever single threaded.

Jeff Epler
  • 502
  • 2
  • 7
  • Thanks, I was wondering why there was output to terminal when I never called print in my script. I may just have to add the subclass on my own like you said. Thanks! – Dylan Pierce Apr 30 '14 at 19:38
  • I'm following what you're saying up until "print >>dest, .... Where report_*_closure call recursively, pass the dest argument down to the recursive call." Can you explain what you mean by "print >> dest"? And how to use the output from report_*_closure recursively? – Dylan Pierce May 02 '14 at 18:13
  • This statement prints on standard output: "print 'foo'". This one prints to the open file held in the variable "dest": "print >>dest, 'foo'" – Jeff Epler May 03 '14 at 20:13
1

Answer to this question is available in another stackoerflow thread mentioned below How to redirect 'print' output to a file using python? Example which worked for me based on solution provided in above thread:

>>> import sys
>>> import filecmp
>>> d = dircmp('Documents/dir1','Documents/dir2')
>>> orig_stdout = sys_stdout
>>> orig_stdout = sys.stdout
>>> fo = open('list_of_diff.txt','a+')
>>> sys.stdout = fo
>>> d.report()
>>> sys.stdout = orig_stdout
>>> fo.close()
Tarn
  • 11
  • 1