在 Windows 中请求对 Python 函数的管理员访问权限 [英] Ask for admin access for a Python function in Windows

查看:23
本文介绍了在 Windows 中请求对 Python 函数的管理员访问权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Python 函数将文件列表复制到 Windows 系统目录 (C:\Windows).

I want to copy a list of files to the Windows system directory (C:\Windows) using a Python function.

我有一个功能:

import shutil

def copy_list(src_list, dst):
    for file in src_list:
        shutil.copy(file, dst)

我想这样称呼它:

def copy_as_admin():
    #... some code to obtain user elevation ...

    copy_list(files_list, "C:\\Windows\")

我怎样才能做到这一点?PS:我使用的是 Python3,我在这个线程中尝试了解决方案,如何在 Windows 上以提升的权限运行 python 脚本但这些解决方案适用于 Python 版本 2.

How can I achieve this? PS: I'm using Python3, I tried solutions in this thread, How to run python script with elevated privilege on windows but those solutions are for Python version 2.

推荐答案

以下示例基于 Cyrbil 的出色工作.特别是,引入了两个枚举.第一个允许轻松指定如何打开提升的程序,第二个在需要轻松识别错误时提供帮助.请注意,如果您希望将所有命令行参数传递给新进程,sys.argv[0] 可能应该替换为函数调用:subprocess.list2cmdline(sys.argv).

The following example builds on Cyrbil's excellent work. In particular, two enumerations are introduced. The first allows for easy specification of how an elevated program is to be opened, and the second helps when errors need to be easily identified. Please note that if you want all command line arguments passed to the new process, sys.argv[0] should probably be replaced with a function call: subprocess.list2cmdline(sys.argv).

#! /usr/bin/env python3
import ctypes
import enum
import sys


# Reference:
# msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx


class SW(enum.IntEnum):

    HIDE = 0
    MAXIMIZE = 3
    MINIMIZE = 6
    RESTORE = 9
    SHOW = 5
    SHOWDEFAULT = 10
    SHOWMAXIMIZED = 3
    SHOWMINIMIZED = 2
    SHOWMINNOACTIVE = 7
    SHOWNA = 8
    SHOWNOACTIVATE = 4
    SHOWNORMAL = 1


class ERROR(enum.IntEnum):

    ZERO = 0
    FILE_NOT_FOUND = 2
    PATH_NOT_FOUND = 3
    BAD_FORMAT = 11
    ACCESS_DENIED = 5
    ASSOC_INCOMPLETE = 27
    DDE_BUSY = 30
    DDE_FAIL = 29
    DDE_TIMEOUT = 28
    DLL_NOT_FOUND = 32
    NO_ASSOC = 31
    OOM = 8
    SHARE = 26


def bootstrap():
    if ctypes.windll.shell32.IsUserAnAdmin():
        main()
    else:
        hinstance = ctypes.windll.shell32.ShellExecuteW(
            None, 'runas', sys.executable, sys.argv[0], None, SW.SHOWNORMAL
        )
        if hinstance <= 32:
            raise RuntimeError(ERROR(hinstance))


def main():
    # Your Code Here
    print(input('Echo: '))


if __name__ == '__main__':
    bootstrap()

这篇关于在 Windows 中请求对 Python 函数的管理员访问权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆