-2

I am using python 2.7, and currently, I have a python code that prints to screen. I have been piping the output from the python code to a file by using >> command in linux until now. I would like to know if there is a simple method of printing out the output to a file without having to change every print function. Is this possible in python?

def print1():
  print "something1"

def print2():
  print "something2"

...

def printN():
   print "somethingN"


def main():
   print1()
   print2()
   ...
   printN()

   //I would like all the output to be in a file
Mikan
  • 89
  • 8
  • Do you want to print the output in the shell and write it to a file too? – Vignesh SP Jul 15 '19 at 21:21
  • What's the problem with with using shell redirection? – Moira Jones Jul 15 '19 at 21:21
  • @VigneshSP I no longer need to print the output in the shell. I now need to just write it in to a file. – Mikan Jul 15 '19 at 21:22
  • 2
    Possible duplicate of https://stackoverflow.com/questions/7152762/how-to-redirect-print-output-to-a-file-using-python – Kartikeya Sharma Jul 15 '19 at 21:23
  • @MoiraJones I used shell redirection for quicker testing purposes. For the users, the results need to be out putted to a specific file. – Mikan Jul 15 '19 at 21:23
  • If you search in your browser for "Python write to file", you'll find references that can explain this much better than we can manage here. Stack overflow is not a tutorial or coding resource. – Prune Jul 15 '19 at 21:29
  • 1
    Check out Python's [logging](https://docs.python.org/3/library/logging.html) package, which may be a better long term solution for your project. – Stephen B Jul 15 '19 at 21:39
  • If you solved it, I would suggest adding your edit as an answer and accepting it. Just for completness sake... :) – Tomerikoo Jul 15 '19 at 21:45

1 Answers1

0

Found a solution on : How to redirect 'print' output to a file using python?

Below works for my code:

import sys

orig_stdout = sys.stdout
f = open('out.txt', 'w')
sys.stdout = f

main()

sys.stdout = orig_stdout
f.close()
Mikan
  • 89
  • 8