Windows 上的 fcntl 替代品

我收到了一个使用标准库中的 fcntl模块的 Python 项目(如果需要的话,这个项目恰好是 Django 项目) ,这个模块似乎只能在 Linux 上使用。当我尝试在我的 Windows 机器上运行它时,它以 ImportError结束,因为这个模块在这里不存在。

有没有什么方法可以让我对程序做一个小小的改动,使它能在 Windows 上运行?

128265 次浏览

The substitute of fcntl on windows are win32api calls. The usage is completely different. It is not some switch you can just flip.

In other words, porting a fcntl-heavy-user module to windows is not trivial. It requires you to analyze what exactly each fcntl call does and then find the equivalent win32api code, if any.

There's also the possibility that some code using fcntl has no windows equivalent, which would require you to change the module api and maybe the structure/paradigm of the program using the module you're porting.

If you provide more details about the fcntl calls people can find windows equivalents.

Although this does not help you right away, there is an alternative that can work with both Unix (fcntl) and Windows (win32 api calls), called: portalocker

It describes itself as a cross-platform (posix/nt) API for flock-style file locking for Python. It basically maps fcntl to win32 api calls.

The original code at http://code.activestate.com/recipes/65203/ can now be installed as a separate package - https://pypi.python.org/pypi/portalocker

The fcntl module is just used for locking the pinning file, so assuming you don't try multiple access, this can be an acceptable workaround. Place this module in your sys.path, and it should just work as the official fcntl module.

Try using this module (source) for development/testing purposes only in windows.

def fcntl(fd, op, arg=0):
return 0
        

def ioctl(fd, op, arg=0, mutable_flag=True):
if mutable_flag:
return 0
else:
return ""
    

def flock(fd, op):
return
        

def lockf(fd, operation, length=0, start=0, whence=0):
return

Of course, then you need to place the fcntl.py module in your site-packages directory for the Python interpreter that you want to use. For example, %LOCALAPPDATA%\Programs\Python\Python310\lib\site-packages\fcntl\. This is where my site-packages live. Check Tutorialspoint to find where yours is located.