- Системные вызовы fcntl и ioctl в Python
- Метод fcntl.fcntl (fd, op [, arg])
- Метод fcntl.ioctl (fd, op [, arg [, mutate_flag]])
- Метод fcntl.flock (fd, op)
- Метод fcntl.lockf (fd, операция [, длина [, начало [, откуда]]])
- fcntl — The fcntl and ioctl system calls¶
- замена fcntl на Windows
- 3 ответов:
- ModuleNotFoundError: No module named ‘fcntl’ on Windows #10
- Comments
- CT83 commented Dec 4, 2019 •
- Steps to Reproduce
- What I think the problem is?
- Obvious Solution — Windows Sub-System for Linux
- References
- seeravikiran commented Dec 4, 2019
- CT83 commented Dec 4, 2019
- savingoyal commented Dec 4, 2019
- ImportError: No module named fcntl under windows
- 2 Answers 2
- Not the answer you’re looking for? Browse other questions tagged python windows-10 or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
Системные вызовы fcntl и ioctl в Python
Для управления файлами и ввода-вывода, мы должны использовать модуль fcntl. Это в основном один интерфейс для подпрограмм Unix fcntl() и ioctl().
Все методы в этом модуле принимают одно целое или дескриптор файла io.IOBase в качестве первого аргумента.
Чтобы использовать этот модуль, мы должны импортировать его, используя.
Есть несколько модулей модуля fcntl, это —
Метод fcntl.fcntl (fd, op [, arg])
Этот метод используется для выполнения операции над файлом с использованием файлового дескриптора. Операция определяется оп. Третий аргумент не является обязательным. Это может быть либо целочисленное значение типа, либо значение строкового типа. Если аргумент имеет целочисленный тип, возвращаемое значение будет значением вызова C fcntl(). Когда это строка, она представляет двоичную структуру. Когда эта функция дает сбой, она вызывает ошибку IOError.
Метод fcntl.ioctl (fd, op [, arg [, mutate_flag]])
Этот метод идентичен методу fcntl(), но в этом случае обработка аргументов является более сложной. В аргументе, если передается изменяемый буфер, его поведение будет зависеть от mutate_flag. Когда это правда, буфер может быть изменяемым, иначе он будет действовать как буфер только для чтения.
Метод fcntl.flock (fd, op)
Этот метод используется для выполнения операции блокировки файла с помощью file_descriptor. В некоторых системах этот метод можно эмулировать с помощью метода fcntl().
Метод fcntl.lockf (fd, операция [, длина [, начало [, откуда]]])
Этот метод используется как оболочка для блокировки вызовов. Аргумент операции передается для блокировки или разблокировки файла. Существуют разные значения работы.
- LOCK_UN — чтобы разблокировать файл
- LOCK_SH — Shared Lock
- LOCK_EX — Эксклюзивная блокировка
- LOCK_UN — чтобы разблокировать файл
- LOCK_SH — Shared Lock
fcntl — The fcntl and ioctl system calls¶
This module performs file control and I/O control on file descriptors. It is an interface to the fcntl() and ioctl() Unix routines. For a complete description of these calls, see fcntl(2) and ioctl(2) Unix manual pages.
All functions in this module take a file descriptor fd as their first argument. This can be an integer file descriptor, such as returned by sys.stdin.fileno() , or an io.IOBase object, such as sys.stdin itself, which provides a fileno() that returns a genuine file descriptor.
Changed in version 3.3: Operations in this module used to raise an IOError where they now raise an OSError .
Changed in version 3.8: The fcntl module now contains F_ADD_SEALS , F_GET_SEALS , and F_SEAL_* constants for sealing of os.memfd_create() file descriptors.
Changed in version 3.9: On macOS, the fcntl module exposes the F_GETPATH constant, which obtains the path of a file from a file descriptor. On Linux(>=3.15), the fcntl module exposes the F_OFD_GETLK , F_OFD_SETLK and F_OFD_SETLKW constants, which working with open file description locks.
The module defines the following functions:
Perform the operation cmd on file descriptor fd (file objects providing a fileno() method are accepted as well). The values used for cmd are operating system dependent, and are available as constants in the fcntl module, using the same names as used in the relevant C header files. The argument arg can either be an integer value, or a bytes object. With an integer value, the return value of this function is the integer return value of the C fcntl() call. When the argument is bytes it represents a binary structure, e.g. created by struct.pack() . The binary data is copied to a buffer whose address is passed to the C fcntl() call. The return value after a successful call is the contents of the buffer, converted to a bytes object. The length of the returned object will be the same as the length of the arg argument. This is limited to 1024 bytes. If the information returned in the buffer by the operating system is larger than 1024 bytes, this is most likely to result in a segmentation violation or a more subtle data corruption.
If the fcntl() fails, an OSError is raised.
Raises an auditing event fcntl.fcntl with arguments fd , cmd , arg .
fcntl. ioctl ( fd, request, arg=0, mutate_flag=True ) В¶
This function is identical to the fcntl() function, except that the argument handling is even more complicated.
The request parameter is limited to values that can fit in 32-bits. Additional constants of interest for use as the request argument can be found in the termios module, under the same names as used in the relevant C header files.
The parameter arg can be one of an integer, an object supporting the read-only buffer interface (like bytes ) or an object supporting the read-write buffer interface (like bytearray ).
In all but the last case, behaviour is as for the fcntl() function.
If a mutable buffer is passed, then the behaviour is determined by the value of the mutate_flag parameter.
If it is false, the buffer’s mutability is ignored and behaviour is as for a read-only buffer, except that the 1024 byte limit mentioned above is avoided – so long as the buffer you pass is at least as long as what the operating system wants to put there, things should work.
If mutate_flag is true (the default), then the buffer is (in effect) passed to the underlying ioctl() system call, the latter’s return code is passed back to the calling Python, and the buffer’s new contents reflect the action of the ioctl() . This is a slight simplification, because if the supplied buffer is less than 1024 bytes long it is first copied into a static buffer 1024 bytes long which is then passed to ioctl() and copied back into the supplied buffer.
If the ioctl() fails, an OSError exception is raised.
Raises an auditing event fcntl.ioctl with arguments fd , request , arg .
fcntl. flock ( fd, operation ) В¶
Perform the lock operation operation on file descriptor fd (file objects providing a fileno() method are accepted as well). See the Unix manual flock(2) for details. (On some systems, this function is emulated using fcntl() .)
If the flock() fails, an OSError exception is raised.
Raises an auditing event fcntl.flock with arguments fd , operation .
fcntl. lockf ( fd, cmd, len=0, start=0, whence=0 ) В¶
This is essentially a wrapper around the fcntl() locking calls. fd is the file descriptor (file objects providing a fileno() method are accepted as well) of the file to lock or unlock, and cmd is one of the following values:
LOCK_UN – unlock
LOCK_SH – acquire a shared lock
LOCK_EX – acquire an exclusive lock
When cmd is LOCK_SH or LOCK_EX , it can also be bitwise ORed with LOCK_NB to avoid blocking on lock acquisition. If LOCK_NB is used and the lock cannot be acquired, an OSError will be raised and the exception will have an errno attribute set to EACCES or EAGAIN (depending on the operating system; for portability, check for both values). On at least some systems, LOCK_EX can only be used if the file descriptor refers to a file opened for writing.
len is the number of bytes to lock, start is the byte offset at which the lock starts, relative to whence, and whence is as with io.IOBase.seek() , specifically:
0 – relative to the start of the file ( os.SEEK_SET )
1 – relative to the current buffer position ( os.SEEK_CUR )
2 – relative to the end of the file ( os.SEEK_END )
The default for start is 0, which means to start at the beginning of the file. The default for len is 0 which means to lock to the end of the file. The default for whence is also 0.
Raises an auditing event fcntl.lockf with arguments fd , cmd , len , start , whence .
Examples (all on a SVR4 compliant system):
Note that in the first example the return value variable rv will hold an integer value; in the second example it will hold a bytes object. The structure lay-out for the lockdata variable is system dependent — therefore using the flock() call may be better.
замена fcntl на Windows
Я получил проект Python (который, оказывается, является проектом Django, если это имеет значение), который использует fcntl модуль из стандартной библиотеки, которая, кажется, доступны только в Linux. Когда я пытаюсь запустить его на моей машине Windows, прекращается с ImportError , потому что этот модуль не существует здесь.
есть ли способ для меня, чтобы сделать небольшое изменение в программу, чтобы заставить его работать на Windows?
3 ответов:
замена fcntl окна win32api звонки. Использование совершенно другое. Это не какой-то переключатель, который вы можете просто перевернуть.
другими словами, портирование a fcntl -тяжелый пользовательский модуль для windows не является тривиальным. Он требует от вас проанализировать, что именно каждый fcntl вызов делает, а затем найти эквивалент win32api код, если таковые имеются.
есть также возможность, что какой-то код с помощью fcntl не имеет эквивалента windows, что потребует от вас изменить модуль api и, возможно, структура / парадигма программы с использованием модуля, который вы портируете.
если вы предоставите более подробную информацию о fcntl звонки люди могут найти эквиваленты windows.
модуль fcntl просто используется для блокировки файла закрепления, поэтому, если вы не пытаетесь использовать множественный доступ, это может быть приемлемым обходным путем. Поместите этот модуль в свой sys.path , и он должен просто работать как официальный модуль fcntl.
попробуйте использовать модуль для целей разработки/тестирования только в Windows.
хотя это не поможет вам сразу, есть альтернатива, которая может работать как с Unix (fcntl), так и с Windows (вызовы win32 api), называется: portalocker
Он описывает себя как кросс-платформенный (posix/nt) API для блокировки файлов в стиле flock для Python. Он в основном сопоставляет fcntl с вызовами win32 api.
ModuleNotFoundError: No module named ‘fcntl’ on Windows #10
Comments
CT83 commented Dec 4, 2019 •
Steps to Reproduce
- pip install metaflow
- metaflow
What I think the problem is?
The module fctnl is not available on Windows systems, which makes it impossible to run metaflow on Windows.
I am open to suggestions. 🤔
Obvious Solution — Windows Sub-System for Linux
This is what I ended up doing, I used Ubuntu with WSL
References
The text was updated successfully, but these errors were encountered:
seeravikiran commented Dec 4, 2019
Thanks for reporting this. This was also reported to us via the gitter channel and I came to the same finding as you.
The other user was open to running it in a Linux environment. Other options that come to mind are perhaps leveraging docker for windows.
In the immediate horizon, we don’t have an easy resolution for our windows users. But happy to look around if other suggestions to run in a Linux like environment don’t work for you.
CT83 commented Dec 4, 2019
Nah, using Docker seems like a doable fix for now. I updated the issue to issue include the alternative I used.
savingoyal commented Dec 4, 2019
Closing this issue — we don’t have active plans for windows support.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
ImportError: No module named fcntl under windows
I am trying to test simple script to get Wi-Fi information. I installed the python-Wi-Fi module to use it, but once I run the script I get this message error:
import fcntl ImportError: No module named fcntl
2 Answers 2
If you read the description from python-wifi on pip you’ll see the Operating System it’s POSIX & Linux, that’s why you’re having problems in the first place, they didn’t write portable code and just stick to linux.
Therefore, either you make work that library on windows following the comment’s duplicated posts (which could take you time) or you just find something more suitable for windows like this one.
On Windows, it may be better to use win32api calls. However, this will take this time because you need to take each and every function call and find the equivalent to win32api for each of them based on what you want the call to do. Some calls may not even have an equivalent.
If it doesn’t have a windows equivalent, you would need to change the api of the module and structure of the program.
Source: nosklo’s answer at this question
Not the answer you’re looking for? Browse other questions tagged python windows-10 or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.