Python从磁盘刷新文件

时间:2015-01-07 22:13:17

标签: python io

我有一个python脚本,它调用系统程序并从文件out.txt读取输出,作用于该输出,并循环。但是,它不起作用,并且仔细调查显示python脚本只打开out.txt一次,然后继续从该旧副本读取。如何让python脚本在每次迭代时重新读取文件?我在这里看到了一个类似的问题,但它是关于一个与程序一起运行的python脚本,而不是调用它,并且该解决方案不起作用。我试图在循环回来之前关闭文件,但它没有做任何事情。

编辑: 我已经尝试过关闭和打开,它没有工作。这是代码:

import subprocess, os, sys

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

while True:
    subprocess.call(["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
        foo.write('\n'+output)
        out.close()
    else:
        break

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

3 个答案:

答案 0 :(得分:3)

您需要刷新foo,以便外部程序可以查看其最新更改。写入文件时,数据将在本地进程中缓冲,并以较大的块发送到系统。这样做是因为更新系统文件相对昂贵。在您的情况下,您需要强制刷新数据,以便minisat可以看到它。

    foo.write('\n'+output)
    foo.flush()

答案 1 :(得分:1)

我重写了它,希望有点容易理解:

import os
from shutil import copyfile
import subprocess
import sys

TEMP_CNF = "tmp.in"
TEMP_SOL = "tmp.out"
NULL = open(os.devnull, "wb")

def all_solutions(cnf_fname):
    """
    Given a file containing a set of constraints,
    generate all possible solutions.
    """
    # make a copy of original input file
    copyfile(cnf_fname, TEMP_CNF)

    while True:
        # run minisat to solve the constraint problem
        subprocess.call(["minisat", TEMP_CNF, TEMP_SOL], stdout=NULL,stderr=NULL)

        # look at the result
        with open(TEMP_SOL) as result:
            line = next(result)
            if line.startswith("SAT"):
                # Success - return solution
                line = next(result)
                solution = [int(i) for i in line.split()]
                yield solution
            else:
                # Failure - no more solutions possible
                break

        # disqualify found solution
        with open(TEMP_CNF, "a") as constraints:
            new_constraint = " ".join(str(-i) for i in sol)
            constraints.write("\n")
            constraints.write(new_constraint)

def main(cnf_fname):
    """
    Given a file containing a set of constraints,
    count the possible solutions.
    """
    count = sum(1 for i in all_solutions(cnf_fname))
    print("There are {} solutions.".format(count))

if __name__=="__main__":
    if len(sys.argv) == 2:
        main(sys.argv[1])
    else:
        print("Usage: {} cnf.in".format(sys.argv[0]))

答案 2 :(得分:0)

你接受file_var并用file_var.close()结束循环。

for ... :
    ga_file = open(out.txt, 'r')
    ... do stuff
    ga_file.close()

下面的一个实现的演示(尽可能简单,这是所有需要的Jython代码)......

__author__ = ''
import time

var = 'false'
while var == 'false':
    out = open('out.txt', 'r')
    content = out.read()
    time.sleep(3)
    print content
    out.close()

生成此输出:

2015-01-09, 'stuff added'
2015-01-09, 'stuff added'           # <-- this is when i just saved my update
2015-01-10, 'stuff added again :)'  # <-- my new output from file reads

我强烈建议您阅读错误消息。他们掌握了很多信息。

我认为应该编写完整的文件名以用于调试目的。