解决 Visual Studio 代码中 Python 脚本的自动调试错误

Resolving Error in Automatic Debugging of Python Script in Visual Studio Code

我有一个有效的 Python 脚本,它通过以下代码捕获我的主显示器工作区的宽度和高度。

# First, install library win32api by executing as administrator
# the command "pip install pywin32" in PowerShell. Then,

from win32api import MonitorFromPoint, GetMonitorInfo
handle_for_primary_monitor = MonitorFromPoint((0,0))
monitor_info = GetMonitorInfo(handle_for_primary_monitor)
work_area_info = monitor_info.get("Work")
width_of_work_area = work_area_info[2]
height_of_work_area = work_area_info[3]

Visual Studio 代码错误地抛出以下两个错误:

如何获取 Visual Studio 代码以识别 class MonitorFromPoint 和方法 GetMonitorInfo 实际上在 win32api 库中?

此错误是由于 Pylint

事实上,Pylint 在分析过程中不会 运行 Python 代码,因此大多数非标准(不可推断的)构造必须通过编写自定义代码来支持。

参考:

有两种方法可以解决这个问题:

  • 添加:# pylint: disable-msg=E0611

    参考:pylint not recognizing some of the standard library

  • 使用最新版本Pylint

作为解决方法,您可以使用 ctypes.windll:

import ctypes
from ctypes.wintypes import tagPOINT
from ctypes import *
class RECT(Structure):
    _fields_ = [
        ("left", c_long),
        ("top", c_long),
        ("right", c_long),
        ("bottom", c_long),
    ]
class MONITORINFOEXA(Structure):
    _fields_ = [
        ("cbSize", c_ulong),
        ("rcMonitor", RECT),
        ("rcWork", RECT),
        ("dwFlags", c_ulong),
        ("szDevice", c_char*32),
    ]
class MONITORINFOEXW(Structure):
    _fields_ = [
        ("cbSize", c_ulong),
        ("rcMonitor", RECT),
        ("rcWork", RECT),
        ("dwFlags", c_ulong),
        ("szDevice", c_wchar*32),
    ]
point = tagPOINT(0,0)
handle_for_primary_monitor = ctypes.windll.user32.MonitorFromPoint(point,0)
print(handle_for_primary_monitor)
monitorinfo = MONITORINFOEXW()
#monitorinfo.cbSize = 72 #sizeof(MONITORINFOEXA) = 72 ;sizeof(MONITORINFOEXW) = 104
monitorinfo.cbSize = 104
monitorinfo.dwFlags = 0x01 #MONITORINFOF_PRIMARY
#ctypes.windll.user32.GetMonitorInfoW(handle_for_primary_monitor,byref(monitorinfo))
ctypes.windll.user32.GetMonitorInfoW(handle_for_primary_monitor,byref(monitorinfo))
Monitor_width =  monitorinfo.rcMonitor.right - monitorinfo.rcMonitor.left
Monitor_height =  monitorinfo.rcMonitor.bottom - monitorinfo.rcMonitor.top
Work_width = monitorinfo.rcWork.right - monitorinfo.rcWork.left
Work_height = monitorinfo.rcWork.bottom - monitorinfo.rcWork.top
print(monitorinfo.szDevice)
print(Monitor_width)
print(Monitor_height)
print(Work_width)
print(Work_height)