IOError:文件存在时没有此类文件

2024-09-19 23:37:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个简单的脚本来更新我的CSS样式(从less到CSS),每次我更改less文件。我现在有:

import time
import hashlib
from subprocess import call


def md5_checksum(filePath):
    fh = open(filePath, 'rb')
    m = hashlib.md5()
    m.update(fh.read())
    fh.close()
    return m.hexdigest()

md5 = md5_checksum('styles.less')

while True:
    newmd5 = md5_checksum('styles.less')
    if md5 != newmd5:
        sh = open('styles.css', 'w')
        call(['lessc', 'styles.less'], stdout=sh)
        md5 = newmd5
        sh.close()
        print 'Changed'
    time.sleep(0.2)

奇怪的是,脚本已经运行了一段时间:

^{pr2}$

怎么回事?文件仍在那里100%。我做错什么了?在


Tags: 文件import脚本timeshcallcssmd5
1条回答
网友
1楼 · 发布于 2024-09-19 23:37:55

正如Martijn Pieters所指出的,当im在文本编辑器中编辑较少的文件时,会有一段时间文件不存在(在保存期间,当旧文件被新文件替换时)。在

从strace记录(strace-o原木维姆样式。少):

rename("styles.less", "styles.less~")   = 0                               = 0
open("styles.less", O_WRONLY|O_CREAT|O_TRUNC, 0644) = 3
write(3, "@text-color: #000;\n@btn-font-col"..., 1135) = 1135
fsync(3)                                = 0
getxattr("styles.less~", "security.selinux", "unconfined_u:object_r:user_home_t:s0", 255) = 37
getxattr("styles.less", "security.selinux", "unconfined_u:object_r:user_home_t:s0", 255) = 37
stat("styles.less", {st_mode=S_IFREG|0644, st_size=1135, ...}) = 0
stat("styles.less", {st_mode=S_IFREG|0644, st_size=1135, ...}) = 0
close(3)                                = 0
chmod("styles.less", 0100644)           = 0
setxattr("styles.less", "system.posix_acl_access", "\x02\x00\x00\x00\x01\x00\x06\x00\xff\xff\xff\xff\x04\x00\x04\x00\xff\xff\xff\xff \x00\x04\x00\xff\xff\xff\xff", 28, 0) = 0
stat(".../styles.less", {st_mode=S_IFREG|0644, st_size=1135, ...}) = 0
unlink("styles.less~")

因此,可能的解决方案是增加:

^{pr2}$

或者,更好的方法是使用指向那里的方法:How do I watch a file for changes?。在

相关问题 更多 >