[英]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.