0

每次更改较少的文件时,我都编写了简单的脚本来更新我的 CSS 样式(从 less 到 css)。我现在有了:

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)

奇怪的是,脚本工作了一段时间:

Changed
Changed
Changed
Changed
Traceback (most recent call last):
  File "watcher.py", line 16, in <module>
    newmd5 = md5_checksum('styles.less')
  File "watcher.py", line 7, in md5_checksum
    fh = open(filePath, 'rb')
IOError: [Errno 2] No such file or directory: 'styles.less'

这是怎么回事?文件仍然存在 100%。我究竟做错了什么?

4

1 回答 1

0

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

从 strace 记录(strace -o strace.log vim styles.less):

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~")

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

try:
    ...
catch IOError:
    continue
else:
    ...

或者,更好的是使用那里指出的方法:如何查看文件的更改?.

于 2013-05-25T07:24:14.693 回答