无法在Python3.8.3中导入"win32com.shell.shell"来使用Python3执行管理员命令提示符命令

4
我们在项目中使用Python 2,创建了多个脚本,使用pywin32库在Windows 10上运行,并使用import win32com.shell.shell as shell执行 shell 命令,如 shell.ShellExecuteEx(lpVerb='runas', lpFile='cmd.exe', lpParameters='/c ' + commands) 其中 commands 是我们用于执行管理员提示的命令。
我们的脚本需要执行一些安装操作,我们将其作为命令传递,并且最近由于执行决策,我们必须转移到Python3。当我尝试导入import win32com.shell.shell as shell时,它无法导入。
有人能否建议如何在 Windows 10 上使用 Python 3.8.3 以管理员身份执行 shell 命令?

1
这个回答解决了你的问题吗?如何在Windows上以提升的权限运行脚本 - The Amateur Coder
3个回答

3

我知道这个可能有点过时,但是如果还有人遇到了同样的问题,您可以使用from win32comext.shell import shell,如github所述。


0

现在您可以使用PyUAC模块(适用于Windows,Python 3)。使用以下命令进行安装:

pip install pyuac
pip install pypiwin32

该包的直接使用方法是:

import pyuac

def main():
    print("Do stuff here that requires being run as an admin.")
    # The window will disappear as soon as the program exits!
    input("Press enter to close the window. >")

if __name__ == "__main__":
    if not pyuac.isUserAdmin():
        print("Re-launching as admin!")
        pyuac.runAsAdmin()
    else:        
        main()  # Already an admin here.

或者,如果您希望使用装饰器:

from pyuac import main_requires_admin

@main_requires_admin
def main():
    print("Do stuff here that requires being run as an admin.")
    # The window will disappear as soon as the program exits!
    input("Press enter to close the window. >")

if __name__ == "__main__":
    main()

实际的代码(在模块中)是:

#!/usr/bin/env python
# -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vim: fileencoding=utf-8 tabstop=4 expandtab shiftwidth=4

# (C) COPYRIGHT © Preston Landers 2010
# Released under the same license as Python 2.6.5

 
import sys, os, traceback, types
 
def isUserAdmin():
   
    if os.name == 'nt':
        import ctypes
        # WARNING: requires Windows XP SP2 or higher!
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            traceback.print_exc()
            print "Admin check failed, assuming not an admin."
            return False
    elif os.name == 'posix':
        # Check for root on Posix
        return os.getuid() == 0
    else:
        raise RuntimeError, "Unsupported operating system for this module: %s" % (os.name,)
   
def runAsAdmin(cmdLine=None, wait=True):
 
    if os.name != 'nt':
        raise RuntimeError, "This function is only implemented on Windows."
   
    import win32api, win32con, win32event, win32process
    from win32com.shell.shell import ShellExecuteEx
    from win32com.shell import shellcon
   
    python_exe = sys.executable
 
    if cmdLine is None:
        cmdLine = [python_exe] + sys.argv
    elif type(cmdLine) not in (types.TupleType,types.ListType):
        raise ValueError, "cmdLine is not a sequence."
    cmd = '"%s"' % (cmdLine[0],)
    # XXX TODO: isn't there a function or something we can call to massage command line params?
    params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
    cmdDir = ''
    showCmd = win32con.SW_SHOWNORMAL
    #showCmd = win32con.SW_HIDE
    lpVerb = 'runas'  # causes UAC elevation prompt.
   
    # print "Running", cmd, params
 
    # ShellExecute() doesn't seem to allow us to fetch the PID or handle
    # of the process, so we can't get anything useful from it. Therefore
    # the more complex ShellExecuteEx() must be used.
 
    # procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)
 
    procInfo = ShellExecuteEx(nShow=showCmd,
                              fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
                              lpVerb=lpVerb,
                              lpFile=cmd,
                              lpParameters=params)
 
    if wait:
        procHandle = procInfo['hProcess']    
        obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
        rc = win32process.GetExitCodeProcess(procHandle)
        #print "Process handle %s returned code %s" % (procHandle, rc)
    else:
        rc = None
 
    return rc
 
def test():
    rc = 0
    if not isUserAdmin():
        print "You're not an admin.", os.getpid(), "params: ", sys.argv
        #rc = runAsAdmin(["c:\\Windows\\notepad.exe"])
        rc = runAsAdmin()
    else:
        print "You are an admin!", os.getpid(), "params: ", sys.argv
        rc = 0
    x = raw_input('Press Enter to exit.')
    return rc
 
 
if __name__ == "__main__":
    sys.exit(test())

(来自这个答案


-1

如果你想升级,win32com.shell.shell作为shell必须在Python2上独自导入,那么你必须更新到一个新版本的pywin32。Github仓库发布了v225,它支持Python 3.8.3。安装这些文件后,您应该能够使用您的代码而不会出现任何导入错误。

https://github.com/CristiFati/Prebuilt-Binaries/tree/master/PyWin32/v225

如果那不起作用,另一个解决方案是使用复制模块。
pip3 install pypiwin32


import pypiwin32 

这个模块应该具备 shell 功能


1
我已经在我的电脑上安装了pywin32 build 228,但仍然遇到问题,甚至尝试了您建议的225版本,但导入问题仍然存在。 - thebadguy
如果那不起作用,我会尝试导入win32api,它是pywin32的复制品。 - Seaver Olson
请问你能否建议导入哪个模块,因为这个模块也没有 shell 模块。 - thebadguy
我目前在使用我的Macbook,无法测试这个,但我已经更新了我的答案,并提供了安装模块的指令,希望可以解决问题。 - Seaver Olson
1
错误:无法找到满足要求 pypiwin32(来自版本:none) 错误:使用安装命令时未找到匹配的分发。 - thebadguy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接