Python:如何以管理员权限启动进程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4645909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:44:21  来源:igfitidea点击:

Python: How to start a process with Administrator Permissions?

pythonwindows-7uacprocess-management

提问by pat

I am starting the following script from a Windows 7 command line with administrator permissions:

我从具有管理员权限的 Windows 7 命令行启动以下脚本:

import win32com.client
import time
import SendKeys
import os
from ctypes import *

shell = win32com.client.Dispatch("WScript.Shell")

os.startfile("C:\...exe")

I have also assigned the feature 'Run this programme as an administrator' to python.exe under Properties > Compatibility > Privilege Level. This did not change anything.

我还在“属性”>“兼容性”>“权限级别”下将“以管理员身份运行此程序”功能分配给了 python.exe。这并没有改变任何东西。

The programme still behaves differently when opened this way to how it behaves when I just open it via a double click on screen. Am I missing some important bit here? Will the process invoked in this way not be run as if started with administrator privileges?

以这种方式打开该程序时,该程序的行为仍然与我通过双击屏幕打开它时的行为不同。我在这里遗漏了一些重要的东西吗?以这种方式调用的进程会不会像以管理员权限启动一样运行?

Thanks for your help in advance!

提前感谢您的帮助!

Cheers -

干杯——

Pat

回答by Chinmay Kanchi

I don't have access to Vista or Windows 7, but you shouldbe able to use the runascommand.

我无法访问 Vista 或 Windows 7,但您应该可以使用该runas命令。

import subprocess
subprocess.call(['runas', '/user:Administrator', 'C:/my_program.exe'])

回答by pat

OK ... I figured out what the problem was. It actually had nothing to do with permissions, contrary to my initial suspicion. Sorry about that!

好的......我想出了问题所在。与我最初的怀疑相反,它实际上与权限无关。对于那个很抱歉!

The reason why the application did not work correctly was because the Python script was located and invoked in another directory. For that reason, some of the application's dependencies were not referenced correctly and it couldn't find some of the files it needs to run properly. Moving the python script into the same directory as the invoked application was one way to fix that.

应用程序无法正常工作的原因是因为 Python 脚本在另一个目录中定位和调用。出于这个原因,应用程序的某些依赖项没有被正确引用,并且无法找到正常运行所需的一些文件。将 python 脚本移动到与调用的应用程序相同的目录中是解决该问题的一种方法。

Sorry again for the misleading initial interpretation of what seemed to be the matter.

再次抱歉对似乎是什么问题的误导性初步解释。