示例看门狗代码显示 Python 错误

0 投票
1 回答
564 浏览
提问于 2025-04-17 19:11

我复制了一段示例代码

import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

if __name__ == "__main__":
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')
path = sys.argv[1] if len(sys.argv) > 1 else '.'
event_handler = LoggingEventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()
observer.join()

请帮帮我,我是新手,刚开始学习Python和watchdog。

我还有一些问题需要解答: 这段代码的输出是什么样的,在哪里可以看到? 我怎么在代码中更改要监控的目录?

我尝试直接运行这段代码,把它保存为一个文件test.py,然后用以下命令运行:

python C:\folder\test.py

结果出现了以下错误

C:\Python33>python c:\folder\test.py
Traceback (most recent call last):
File "c:\folder\test.py", line 4, in <module>
from watchdog.observers import Observer
File "C:\Python33\lib\site-packages\watchdog\observers\__init__.py", line 34,
in <module>
from watchdog.observers.api import BaseObserver, DEFAULT_OBSERVER_TIMEOUT
File "C:\Python33\lib\site-packages\watchdog\observers\api.py", line 62, in <module>
from watchdog.utils.bricks import OrderedSetQueue as SetQueue
File "C:\Python33\lib\site-packages\watchdog\utils\bricks.py", line 112, in <module>
if not sys.version < (2, 6, 0):
TypeError: unorderable types: str() < tuple()

1 个回答

0

这看起来像是watchdog里的一个bug。在Python 2.6和2.7中是可以正常工作的。sys.version在这两个版本中都是字符串,并且可以和元组进行比较。我觉得这听起来有点奇怪。

这种行为可能在3.x版本中发生了变化。如果没有经过充分测试,你可能会遇到更多问题。现在使用Python 2.7是最安全的,因为很多库还没有支持3.x版本。

不过,如果你真的非常想解决这个问题,可以修改watchdog\utils\bricks.py文件中的第112行:

ver = tuple([int(x) for x in sys.version.split()[0].split('.')])
if not ver < (2, 6, 0):

这真的很糟糕。还是建议使用Python 2.7。

撰写回答