Python 从磁盘刷新文件

Python refresh file from disk

我有一个 python 脚本,它调用系统程序并从文件 out.txt 中读取输出,对该输出进行操作,然后循环。然而,它不起作用,仔细调查表明 python 脚本只打开 out.txt 一次,然后继续从旧副本读取。如何让 python 脚本在每次迭代时重新读取文件?我在 SO 上看到了一个类似的问题,但它是关于一个 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."

您使用 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

我强烈建议阅读错误消息。他们掌握着相当多的信息。

我认为为了调试目的应该写完整的文件名。

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

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

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

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]))