作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我的代码中,我将一个文件写入硬盘。之后,我需要导入生成的文件,然后继续处理它。
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
循环,我正在寻找一种自动方法。
最佳答案
您可以使用time.sleep
,我希望如果您以这种方式加载模块,则需要reload
而不是import
> 第一次导入
之后。
但是,除非文件非常大,否则为什么不直接生成字符串,然后使用 eval
或 exec
呢?
注意,由于您的文件生成函数没有在线程中调用,因此它应该是阻塞的,并且只有在它认为已完成写入时才会返回 - 也许您可以通过确保文件生成来改进事情writer 以 outfile.flush()
结尾,然后以 outfile.close()
结尾,但在某些操作系统上,文件可能仍然有时不可用。
关于python - 让 Python 等待文件存在后再继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19898730/
我是一名优秀的程序员,十分优秀!