无法在python3.8.3中“import win32com.shell.shell”以使用python3执行管理命令提示符命令

ki1q1bka  于 2023-05-19  发布在  Python
关注(0)|答案(3)|浏览(362)

我们在项目中使用python 2,我们使用pywin32 lib创建了各种在Windows 10上工作的脚本,并使用import win32com.shell.shell as shell,然后执行shell命令,如shell.ShellExecuteEx(lpVerb='runas', lpFile='cmd.exe', lpParameters='/c ' + commands),其中命令是我们用来作为管理提示符执行的命令。
我们的脚本需要做一些安装,我们作为命令传递,最近由于行政决定,我们必须转移到python3,当我试图导入import win32com.shell.shell as shell时,它无法导入它。
有人能建议我们如何在Windows 10上的Python 3.8.3中以管理员身份执行shell命令吗?

5n0oy7gb

5n0oy7gb1#

我知道这是旧的,但如果有人仍然有同样的问题,你可以使用from win32comext.shell import shell,因为它在这里提到的github

ut6juiuv

ut6juiuv2#

你现在可以使用the PyUAC module(对于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())

(from this answer

nkoocmlb

nkoocmlb3#

win32com.shell.shell ,因为shell将只在python2上导入,如果你想升级,你必须更新到一个新版本的pywin32。一个github repo发布了v225,它支持Python 3.8.3安装文件,你应该能够使用你的代码而不会有任何导入错误
https://github.com/CristiFati/Prebuilt-Binaries/tree/master/PyWin32/v225
如果这不起作用,则替代解决方案是使用副本模块

pip3 install pypiwin32

import pypiwin32

此模块应具有 shell 功能

相关问题