2

In some codes like MCMC it lasts for hours and maybe days to finish. Now I am wondering how can see the outputs which are saving in a text file while Python is running. Because in my code checking the whole outputs in txt file is possible only after finishing the Python's work

def ....():
   return
def ....():
   return
......
with open('outputs/p.txt', 'w') as f:
 .....
   f.write("{0}\t{1}\n".format(A,B))

with this code, I can only see the outputs after finishing the python running. But it is beneficial if we can check it every time we want.

Ma Y
  • 696
  • 8
  • 19
  • If you multi-thread your program, one thread will wait for input and the other will do the work with the saving. When you input some string like "show" or something like that, delay the save and close the file, then reopen the file with an append, then continue saving where you left off. This should allow you to see what has been saved – SPYBUG96 Oct 25 '18 at 15:52
  • @SPYBUG96 To be honest I dont know how. But does it make slow the code? – Ma Y Oct 25 '18 at 15:52
  • 1
    It shouldn't because you would be running on two different cores, but when you do the show it will delay the completion of the program for a few seconds, an easier solution would be to have the python code print everything to console or after every write close the file and reopen it with an append, both will slow down the python program – SPYBUG96 Oct 25 '18 at 15:57
  • @SPYBUG96 Thank you. After adding `f.close` I can see the out puts after every couple of secs. – Ma Y Oct 25 '18 at 16:08
  • 1
    I'm glad it works for you! – SPYBUG96 Oct 25 '18 at 16:11
  • @SPYBUG96 yes, I thought you are saying to add another line for reopening the file. – Ma Y Oct 25 '18 at 16:14
  • I wasn't sure if you had a loop going, or if you had a huge piece of data in a single string – SPYBUG96 Oct 25 '18 at 16:16

1 Answers1

1
#the a+ appends the file at the end with your new data, or creates the file if it doesn't exist
with open('outputs/p.txt', 'a+') as f:

    f.write("{0}\t{1}\n".format(A,B))

    f.close()
SPYBUG96
  • 1,089
  • 5
  • 20
  • 38
  • just what is different between `w`w and `a+`. for me both are identical I think – Ma Y Oct 25 '18 at 16:19
  • @MaY This gives a good explanation https://stackoverflow.com/questions/1466000/python-open-built-in-function-difference-between-modes-a-a-w-w-and-r – SPYBUG96 Oct 25 '18 at 16:21
  • thank you. Of course I see the `f.close()` makes the code a little bitter slower. still good. another things. I want to ask in a new post. just here want to know: do you know anything about pause and resume a code? exactly similar to `internet download manager` software which we can start downloading after turning of the PC or crashing the windows or etc – Ma Y Oct 25 '18 at 16:24
  • @MaY I don't, I've never needed to do something like that – SPYBUG96 Oct 25 '18 at 16:25