René G René G - 1 year ago 101
Python Question

Python refresh file from disk

I have a python script that calls a system program and reads the output from a file

, acts on that output, and loops. However, it doesn't work, and a close investigation showed that the python script just opens
once and then keeps on reading from that old copy. How can I make the python script reread the file on each iteration? I saw a similar question here on SO but it was about a python script running alongside a program, not calling it, and the solution doesn't work. I tried closing the file before looping back but it didn't do anything.

I already tried closing and opening, it didn't work. Here's the code:

import subprocess, os, sys

filename = sys.argv[1]
file = open(filename,'r')
foo = open('foo','w')
foo = open('foo','a')
crap = open(os.devnull,'wb')
numSolutions = 0

while True:["minisat", "foo", "out"], stdout=crap,stderr=crap)
out = open('out','r')
if out.readline().rstrip() == "SAT":
numSolutions += 1
clause = out.readline().rstrip()
clause = clause.split(" ")
print clause
clause = map(int,clause)
clause = map(lambda x: -x,clause)
output = ' '.join(map(lambda x: str(x),clause))
print output

print "There are ", numSolutions, " solutions."

Answer Source

You need to flush foo so that the external program can see its latest changes. When you write to a file, the data is buffered in the local process and sent to the system in larger blocks. This is done because updating the system file is relatively expensive. In your case, you need to force a flush of the data so that minisat can see it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download