我应该使用哪个 Python 函数来注销当前用户。我找到了一个锁定我的电脑的例子,比如 Win+L 组合
ctypes.windll.user32.LockWorkStation()
但我需要一个类似的功能,它将注销。
This should cause the current user to logout:
ctypes.windll.user32.ExitWindowsEx(0, 1)
Ctypes should be able to convert those params to unsigned ints without problems. If it throws an error about argument types, try wrapping 0 and 1 like this: ctypes.c_ulong(0)
Documented here: ExitWindowsEx
Side note: if you make a practice of logging out active users without prompting them with a dialog (even if it has a 60 second or timer), they will likely be very unhappy.
试试os.system("shutdown -l")
。
shutdown -l
是用于注销的 windows shell 命令
您可以这样做,但只能作为以 SYSTEM 用户身份运行的服务。如果您尝试注销您正在运行的用户,您将终止您的脚本(无论您以何种方式完成此操作,当前任务将在用户环境终止时终止)。
但是,如果您编写备份以用作服务,则可以使用 win32api(通过pywin32)终止所有用户会话(这不是很好,但假设您的用户可以)然后进行备份。如果用户重新登录,就会出现问题——你必须捕获用户登录事件——但否则这是相对无痛的。