【发布时间】:2019-03-03 05:37:19
【问题描述】:
我有一个Windows python3.7 函数,它使用ctypes 成功调用kernel32.dll GetSystemPowerStatus 函数来询问电源状态,以查看我的笔记本电脑是使用交流电源还是电池供电。这是一个纯python解决方案。
我想将此功能移植到cygwin python3.7。开箱即用,python3 的cygwin 的ctypes 似乎不允许调用 Windows dll。我更喜欢纯 Python 解决方案,但如有必要,我可以使用 C/C++。有没有人有如何做到这一点的例子?
编辑添加代码(第 63-67 行)和错误消息:
elif _os.name == 'posix' and _sys.platform == 'cygwin':
# c:\Windows\System32\kernel32.dll
kernel32_name = '/proc/cygdrive/c/Windows/System32/kernel32.dll'
kernel32 = CDLL(kernel32_name)
_GetSystemPowerStatus = kernel32.GetSystemPowerStatus
$ python3.7 GetSystemPowerStatus.py
Traceback (most recent call last):
File "GetSystemPowerStatus.py", line 82, in <module>
result, systemPowerStatus = GetSystemPowerStatus()
File "GetSystemPowerStatus.py", line 66, in GetSystemPowerStatus
kernel32 = CDLL(kernel32_name)
File "/usr/lib/python3.7/ctypes/__init__.py", line 356, in __init__
self._handle = _dlopen(self._name, mode)
OSError: Invalid argument
python2.7 给出了同样的错误,但在第 366 行。
解决了。请参阅下面我自己的答案。
【问题讨论】:
-
请给出您在 cygwin 中运行工作 Windows 代码时收到的错误消息
-
'$ python3.7 GetSystemPowerStatus.py⏎ Traceback(最近一次调用最后):⏎文件“GetSystemPowerStatus.py”,第69行,在
⏎结果中,systemPowerStatus = GetSystemPowerStatus()⏎文件“GetSystemPowerStatus.py”,第 57 行,在 GetSystemPowerStatus⏎ GetSystemPowerStatus = cdll.kernel32.GetSystemPowerStatus⏎ 文件“/usr/lib/python3.7/ctypes/__init_.py”,第 426 行,在 getattr__⏎ dll = self._dlltype(name)⏎ 文件“/usr/lib/python3.7/ctypes/__init.py”,第 356 行,在 __init__⏎ self._handle = _dlopen(self._name , mode)⏎ OSError: No such file or directory⏎' -
使用其他格式化信息编辑问题。评论显然是一团糟。
-
非常令人费解,实际上这对我有用:
ctypes.CDLL("/cygdrive/c/windows/system32/user32.dll")但不适用于kernel32.dll。我得到完全相同的错误。所以可以从 cygwin 加载一个 windows 库,但是 not kernel32 :( -
谢谢。很有意思。我猜必须挖掘 ctypes 的来源。
标签: python windows dll cygwin ctypes