import mlogging,No module named ffi,import fcntl 报错

本文解决了一个在Windows环境下使用mlogging库时遇到的fcntl模块导入错误问题,通过替换fcntl的功能为win32con等Windows特有模块,实现了文件锁定功能,使mlogging能在Windows系统上正常运行。

在import mlogging 的时候,一直报错,网上几乎没有别的办法,发现是在导入 fcntl这个包的时候出了错,经过多番搜索发现 pip安装下来的mlogging这个包应该是在linux上运行的,见 https://github.com/kieslee/mlogging , 所以ffi一直找不到
在这里插入图片描述
所以想在windows系统上用这个包需要改写一下mlogging这个包

  • 在site-packages中找到mlogging文件夹,打开编辑__init__.py文件
from logging import StreamHandler, FileHandler
from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler
import fcntl, time, os, codecs, string, re, types, cPickle, struct, shutil
from stat import ST_DEV, ST_INO, ST_MTIME
  • 看到这里import了fcntl模块,它就是报错的根源
    import fcntl
  File "D:\Apps\PyCharm 2018.2.4\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 20, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "D:\Apps\anaconda2.5.2.0\lib\site-packages\fcntl.py", line 1, in <module>
    import ffi
  File "D:\Apps\PyCharm 2018.2.4\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 20, in do_import
    module = self._system_import(name, *args, **kwargs)
ImportError: No module named ffi

在这里插入图片描述

  • 我们需要导入其他的包来替换这个功能
from logging import StreamHandler, FileHandler
from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler
import time, os, codecs, string, re, types, cPickle, struct, shutil
from stat import ST_DEV, ST_INO, ST_MTIME
import win32con, win32file, pywintypes

LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
LOCK_SH = 0 # the default
LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY
__overlapped = pywintypes.OVERLAPPED(  )

def lock(file, flags):
    hfile = win32file._get_osfhandle(file.fileno(  ))
    win32file.LockFileEx(hfile, flags, 0, 0xffff0000, __overlapped)

def unlock(file):
    hfile = win32file._get_osfhandle(file.fileno(  ))
    win32file.UnlockFileEx(hfile, 0, 0xffff0000, __overlapped)
  • 编写lock, unlock 函数,来实现下面 fcntl 的功能,如:
fcntl.flock(f.fileno(), fcntl.LOCK_EX)
emit(self, record)
flock(f.fileno(), fcntl.LOCK_UN)

可更改为以下代码,来实现锁定文件

lock(f, LOCK_EX)
FileHandler_MP.emit(self, record)
unlock(f)
大功告成

在此要感谢同事的帮助,解决了困扰我大半天的问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值