每次更改文件时,我都会编写简单的脚本来更新我的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%。我做错了什么?
答案 0 :(得分: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:
...
或者,更好的是使用指向那里的方法:How do I watch a file for changes?。