2

在我的代码中,我将一个文件写入我的硬盘。之后,我需要导入生成的文件,然后继续处理它。

for i in xrange(10):
    filename=generateFile()
    # takes some time, I wish to freeze the program here
    # and continue once the file is ready in the system
    file=importFile(filename)
    processFile(file)

如果我一次性运行代码片段,很可能file=importFile(filename)会抱怨该文件不存在,因为生成需要一些时间。

我曾经手动运行filename=generateFile()并等待运行前file=importFile(filename)
现在我正在使用for循环,我正在寻找一种自动方式。

4

2 回答 2

3

您可以使用time.sleep并且我希望如果您以这种方式加载模块,您将需要reload而不是import在第一个import.

eval但是,除非文件非常大,否则为什么不直接生成字符串然后exec呢?

请注意,由于您的文件生成函数没有在线程中被调用,它应该被阻塞并且只会在它认为它已经完成写入时返回 - 可能您可以通过确保文件编写器以outfile.flush()then结尾来改进事情,outfile.close()但在某些操作系统上可能仍然是文件实际上不可用的时候。

于 2013-11-11T04:26:04.543 回答
0
for i in xrange(10):
    (filename, is_finished)=generateFile()
    while is_finished:
        file=importFile(filename)
        processFile(file)
        continue;

我认为您应该使用标志来测试文件是否已生成。

于 2013-11-11T04:36:39.770 回答