[英]How can i stop and start windows services using subprocess with admin permissions?
我正在构建一个python工具来更新应用程序。 为此,我必须停止apache服务,执行一些与更新相关的工作,然后在更新ist完成后再次启动它。
我目前在Windows 10上使用python 3.7.2。
我试图通过使用这些问题作为参考来建立工作流程:
在python中使用subprocess.run以管理员身份运行进程
Windows在subprocess.call()上找不到文件
def stopApache():
processName = config["apacheProcess"]
#stopstr = f'stop-service "{processName}"'
# the line abpove should be used once im finished, but for testing
# purposes im going with the one below
stopstr = 'stop-service "Apache2.4(x64)"'
print(stopstr)
try:
subprocess.run(stopstr, shell=True)
#subprocess.run(stopstr)
# the commented line here is for explanatory purposes, and also to
# show where i started.
except:
print('subprocess failed', sys.exc_info())
stopExecution()
根据到目前为止的经验, shell=TRUE
选项是必须的,因为python不检查PATH。 鉴于我试图做的事情的性质,我希望这项服务能够停止。 实际上,控制台错误如下所示:
stopstr = get-service "Apache2.4(x64)"
Der Befehl "get-service" ist entweder falsch geschrieben oder
konnte nicht gefunden werden.
大致翻译为:命令“ stop-service”的拼写错误或找不到。
如果我直接在Powershell中运行相同的命令,则会收到类似的错误。 如果我以管理员身份打开外壳程序,然后再次运行我,则一切正常。
但是,如果我使用完全相同的管理外壳来运行python代码,那么我将回到正题。
我在这里想念的是什么,显然权限有问题,但是我无法解决这个问题
在MS Windows中停止服务的命令是net stop [servicename]
因此将stopstr
更改为'net stop "Apache2.4(x64)"'
您将需要以管理员身份运行脚本。
shell=True
针对cmd(而非powershell)运行命令。
Powershell与常规命令行不同。 因此,要使stop-service
正常工作,您必须将其传递给powershell实例。
stopstr = 'stop-service \\"Apache2.4(x64)\\"'
subprocess.run(['powershell', stopstr], shell=True)
正如您在评论中指出的那样,必须在服务名称周围转义"
,因为第一个python将取消转义它们,然后powershell将使用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.