能否在Vista中以管理员身份程序化地运行编译后的Python (通过py2exe编译)?
再来澄清一下。我写了一个修改windows hosts文件(c:\Windows\system32\drivers\etc\hosts)的程序,在Vista中,除非你右键单击并以管理员身份运行,否则程序将无法运行并出现异常。
你的意思是想让Windows在程序运行时提示提升吗?这可以通过在EXE的资源中添加一个UAC清单来控制。这篇博客 解释了如何创建清单以及如何将其编译成.RES文件。
我不知道py2exe有什么工具可以嵌入自定义的.RES文件,所以你可能需要使用Platform SDK中的MT.EXE工具在程序中嵌入manifest。MT.EXE不需要.RES文件,它可以直接合并.manifest文件。
按照下面的例子 Python2x\Lib\site-packages\py2exe\samples\user_access_control
只需加 uac_info="requireAdministrator"
到控制台或windows dict。
windows = [{
'script': "admin.py",
'uac_info': "requireAdministrator",
},]
根据Roger Lipscombe的评论,我在py2exe中使用了一个清单文件,但我并不知道我在做什么。 所以这个 可能 工作。
# in setup.py
# manifest copied from http://blogs.msdn.com/shawnfa/archive/2006/04/06/568563.aspx
manifest = '''
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<asmv3:trustInfo xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
<asmv3:security>
<asmv3:requestedPrivileges>
<asmv3:requestedExecutionLevel
level="asInvoker"
uiAccess="false" />
</asmv3:requestedPrivileges>
</asmv3:security>
</asmv3:trustInfo>
</assembly>
'''
setup(name='MyApp',
#...
windows=[ { #...
'other_resources':[(24, 1, manifest)],
}]
)
你可能需要做一些调整...
pyinstaller的最佳解决方案在这里找到。从Python脚本中请求UAC提升?
对exe清单文件的任何操作都不会起作用。使用if else语句从python代码中处理UAC。