Python找不到结构类的DWTime属性

发布于 2025-02-13 11:35:37 字数 2357 浏览 0 评论 0 原文

在这里我的代码:

from ctypes import byref, c_uint, c_ulong, sizeof, Structure, windll
import ctypes
import random
import sys
import time
import win32api


class LASTINPUTINFO(Structure):
    """Мы импортировали необходимые модули и создали структуру LASTINPUTINFO
    для хранения временной метки (в миллисекундах), обозначающей момент
обнаружения последнего события ввода в системе. """
fields_ = [
    ('cbSize', ctypes.c_uint),
    ('dwTime', ctypes.c_ulong)
]


def get_last_input():
"""Дальше создаем функцию get_last_input, чтобы, собственно, определить этот момент."""

struct_lastinputinfo = LASTINPUTINFO()

# Обратите
# внимание на то, что прежде чем выполнять вызов, переменную cbSize 
# нужно инициализировать с использованием размера структуры.
struct_lastinputinfo.cbSize = sizeof(LASTINPUTINFO)  # 

# Затем мы
# вызываем функцию GetLastInputInfo, которая присваивает полю struct_
# lastinputinfo.dwTime временную метку.
windll.user32.GetLastInputInfo(byref(struct_lastinputinfo))

# Следующий шаг состоит в определении того,
# как долго проработала система. Для этого применяется вызов
# функции GetTickCount .
run_time = windll.kernel32.GetTickCount()  # 

# Переменная elapsed должна быть равна разности
# между временем работы системы и временем последнего ввода.
elapsed = run_time - struct_lastinputinfo.dwTime
print(f"[*] It's been {elapsed} milliseconds since the last event.")
return elapsed


# Небольшой
# фрагмент кода, размещенный в конце , позволяет выполнить простую проверку
while True:  # 
get_last_input()
time.sleep(1)

但是我收到此错误:

Trackback(最近的电话最后一次): 文件“ c:\ user \ user \ user \ pycharmprojects \ sandbox_detected \ sandbox_detect.py”,第49行,in get_last_input() 文件“ C:\ User \ User \ user \ pycharmprojects \ sandbox_detected \ sandbox_detect.py”,第41行,在get_last_input中 大量= run_time -struct_lastinputinfo.dwtime attributeError:'lastInputInfo'对象没有属性'dwtime'

对我有帮助。

upd:

@megaemailman谢谢,现在的代码不会引发异常,但是尚不清楚为什么它不能正常工作,并且仅显示此功能:

[*] It's been 0 milliseconds since the last event.
[*] It's been 0 milliseconds since the last event.
[*] It's been 0 milliseconds since the last event.
[*] It's been 0 milliseconds since the last event.
[*] It's been 0 milliseconds since the last event.
[*] It's been 0 milliseconds since the last event.

Here my code:

from ctypes import byref, c_uint, c_ulong, sizeof, Structure, windll
import ctypes
import random
import sys
import time
import win32api


class LASTINPUTINFO(Structure):
    """Мы импортировали необходимые модули и создали структуру LASTINPUTINFO
    для хранения временной метки (в миллисекундах), обозначающей момент
обнаружения последнего события ввода в системе. """
fields_ = [
    ('cbSize', ctypes.c_uint),
    ('dwTime', ctypes.c_ulong)
]


def get_last_input():
"""Дальше создаем функцию get_last_input, чтобы, собственно, определить этот момент."""

struct_lastinputinfo = LASTINPUTINFO()

# Обратите
# внимание на то, что прежде чем выполнять вызов, переменную cbSize 
# нужно инициализировать с использованием размера структуры.
struct_lastinputinfo.cbSize = sizeof(LASTINPUTINFO)  # 

# Затем мы
# вызываем функцию GetLastInputInfo, которая присваивает полю struct_
# lastinputinfo.dwTime временную метку.
windll.user32.GetLastInputInfo(byref(struct_lastinputinfo))

# Следующий шаг состоит в определении того,
# как долго проработала система. Для этого применяется вызов
# функции GetTickCount .
run_time = windll.kernel32.GetTickCount()  # 

# Переменная elapsed должна быть равна разности
# между временем работы системы и временем последнего ввода.
elapsed = run_time - struct_lastinputinfo.dwTime
print(f"[*] It's been {elapsed} milliseconds since the last event.")
return elapsed


# Небольшой
# фрагмент кода, размещенный в конце , позволяет выполнить простую проверку
while True:  # 
get_last_input()
time.sleep(1)

But I get this error:

Traceback (most recent call last):
File "C:\Users\user\PycharmProjects\sandbox_detected\sandbox_detect.py", line 49, in
get_last_input()
File "C:\Users\user\PycharmProjects\sandbox_detected\sandbox_detect.py", line 41, in get_last_input
elapsed = run_time - struct_lastinputinfo.dwTime
AttributeError: 'LASTINPUTINFO' object has no attribute 'dwTime'

Help me please.

UPD:

@MegaEmailman Thank you, the code now does not throw exceptions, but it is not clear why it does not work correctly and displays only this:

[*] It's been 0 milliseconds since the last event.
[*] It's been 0 milliseconds since the last event.
[*] It's been 0 milliseconds since the last event.
[*] It's been 0 milliseconds since the last event.
[*] It's been 0 milliseconds since the last event.
[*] It's been 0 milliseconds since the last event.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淤浪 2025-02-20 11:35:39

您的代码中还有很多关键错误(除了错误的凹痕 - 我认为这是一个格式化问题):

  • 根据 [python.docs]:ctypes-结构和工会强调是我的):

    结构和工会必须源自结构 href =“ https://docs.python.org/library/ctypes.html#ctypes.union” rel =“ nofollow noreferrer”> Union> Union> Union 在 ctypes 模块。 每个子类都必须定义A _Fields _ 属性 _fields _ 必须是 2-tuples 的列表>

    所以,它是 _fields _ lundscores ))

  • 始终定义 argtypes Restype 用于通过 ctypes 调用的功能。检查 [so]:c函数从python通过ctypes返回不正确的值(@cristifati的答案)有关更多详细信息

    >

  • 不是重要的详细信息

    ,但是在使用 winapi 时,请使用定义某些类型的 wintypes 模块(实际上是别名)

我对您的代码进行了一些改进:

  • 移动了 cbsize 成员在初始化器中设置了,因此每次班级都会实例化

    时,不再需要

  • cbsize 构件设置在初始化器中,因此每次 ence 按下 时,

code00.py

#!/usr/bin/env python

import ctypes as ct
import msvcrt
import sys
import time
from ctypes import wintypes as wt


class LASTINPUTINFO(ct.Structure):
    _fields_ = (
        ("cbSize", wt.UINT),
        ("dwTime", wt.DWORD),
    )

    def __init__(self, dwTime=0):
        super().__init__(ct.sizeof(self.__class__), dwTime)


PLASTINPUTINFO = ct.POINTER(LASTINPUTINFO)


kernel32 = ct.WinDLL("Kernel32")
user32 = ct.WinDLL("User32")

GetTickCount = kernel32.GetTickCount
GetTickCount.argtypes = ()
GetTickCount.restype = wt.DWORD

GetLastInputInfo = user32.GetLastInputInfo
GetLastInputInfo.argtypes = (PLASTINPUTINFO,)
GetLastInputInfo.restype = wt.BOOL


def get_last_input():
    lii = LASTINPUTINFO()
    GetLastInputInfo(ct.byref(lii))
    run_time = GetTickCount()
    print("\nLast input time: {:d}\nTick count: {:d}\nElapsed: {:d}".format(lii.dwTime, run_time, run_time - lii.dwTime))


def main(*argv):
    while True:
        get_last_input()
        time.sleep(1)
        if msvcrt.kbhit():
            if ord(msvcrt.getch()) == 0x1B:
                break


if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.")
    sys.exit(rc)

输出(在移动鼠标和按键时运行程序):

  [cfati@cfati-5510-0:e:\ work \ dev \ stackoverflow \ q072887838]> ”
Python 3.9.9(标签/v3.9.9:CCB0E6A,2021,18:08:50)[MSC V.1929 64 BIT(AMD64)] 064BIT


最后输入时间:392676796
刻度计数:392676921
过去:125

最后输入时间:392676921
刻度计数:392677937
过去:1016

最后输入时间:392676921
刻度计数:392678953
过去:2032

最后输入时间:392676921
刻度计数:392679968
过去:3047

最后输入时间:392676921
刻度计数:392680968
过去:4047

最后输入时间:392681421
刻度计数:392681984
过去:563

最后输入时间:392682812
刻度计数:392682984
过去:172

最后输入时间:392683937
刻度计数:392684000
过去:63

最后输入时间:392684078
刻度计数:392685000
过去:922

最后输入时间:392685687
刻度计数:392686015
经过:328

最后输入时间:392686828
刻度计数:392687031
过去:203

最后输入时间:392688046
刻度计数:392688046
过去:0

最后输入时间:392688484
刻度计数:392689062
过去:578

完毕。
 

There are a bunch of critical errors in your code (besides the wrong indentation - which I consider a formatting issue):

I modified your code with some improvements:

  • Moved the cbSize member set in the initializer, so it is no longer necessary every time the class gets instantiated

  • Exit when Esc is pressed

code00.py:

#!/usr/bin/env python

import ctypes as ct
import msvcrt
import sys
import time
from ctypes import wintypes as wt


class LASTINPUTINFO(ct.Structure):
    _fields_ = (
        ("cbSize", wt.UINT),
        ("dwTime", wt.DWORD),
    )

    def __init__(self, dwTime=0):
        super().__init__(ct.sizeof(self.__class__), dwTime)


PLASTINPUTINFO = ct.POINTER(LASTINPUTINFO)


kernel32 = ct.WinDLL("Kernel32")
user32 = ct.WinDLL("User32")

GetTickCount = kernel32.GetTickCount
GetTickCount.argtypes = ()
GetTickCount.restype = wt.DWORD

GetLastInputInfo = user32.GetLastInputInfo
GetLastInputInfo.argtypes = (PLASTINPUTINFO,)
GetLastInputInfo.restype = wt.BOOL


def get_last_input():
    lii = LASTINPUTINFO()
    GetLastInputInfo(ct.byref(lii))
    run_time = GetTickCount()
    print("\nLast input time: {:d}\nTick count: {:d}\nElapsed: {:d}".format(lii.dwTime, run_time, run_time - lii.dwTime))


def main(*argv):
    while True:
        get_last_input()
        time.sleep(1)
        if msvcrt.kbhit():
            if ord(msvcrt.getch()) == 0x1B:
                break


if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.")
    sys.exit(rc)

Output (run the program while moving mouse and pressing keys):

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q072887838]> "e:\Work\Dev\VEnvs\py_pc064_03.09_test0\Scripts\python.exe" ./code00.py
Python 3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64 bit (AMD64)] 064bit on win32


Last input time: 392676796
Tick count: 392676921
Elapsed: 125

Last input time: 392676921
Tick count: 392677937
Elapsed: 1016

Last input time: 392676921
Tick count: 392678953
Elapsed: 2032

Last input time: 392676921
Tick count: 392679968
Elapsed: 3047

Last input time: 392676921
Tick count: 392680968
Elapsed: 4047

Last input time: 392681421
Tick count: 392681984
Elapsed: 563

Last input time: 392682812
Tick count: 392682984
Elapsed: 172

Last input time: 392683937
Tick count: 392684000
Elapsed: 63

Last input time: 392684078
Tick count: 392685000
Elapsed: 922

Last input time: 392685687
Tick count: 392686015
Elapsed: 328

Last input time: 392686828
Tick count: 392687031
Elapsed: 203

Last input time: 392688046
Tick count: 392688046
Elapsed: 0

Last input time: 392688484
Tick count: 392689062
Elapsed: 578

Done.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文