简体   繁体   中英

IOError: no such file when file exists

I've written simple script to update my CSS styles (from less to css) every time when i change less file. I have now:

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)

And what is strange, script is working for some time:

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'

Whats going on? File is still there for 100%. What am i doing wrong?

As pointed by Martijn Pieters, when im editing less file in text editor there is some time when file does not exist (during save, when old file is replaced by new file).

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

So, possible solution is to add:

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

Or, even better is to use methods pointed there: How do I watch a file for changes? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM