[英]Run linux shell commands in Python3
我正在創建一個服務管理器來管理 apache、tomcat.. 等服務。我可以通過 srvmanage.sh enable <service_name> 在 Z2591C98B70119FE624898B1E424B 中啟用/禁用服務。 我想使用 python 腳本來做到這一點。 怎么做?
service_info = ServiceDB.query.filter_by(service_id=service_id).first()
service_name = service_info.service
subprocess.run(['/home/service_manager/bin/srvmanage.sh enable', service_name],shell=True)
這段代碼有什么問題?
我猜如果您想在 python 中執行此操作,您可能需要更多功能。 如果不是@programandoconro 答案會做。 但是,您也可以使用subprocess module
來獲得更多功能。 它將允許您使用 arguments 運行命令並返回 CompletedProcess 實例。 例如
import subprocess
# call to shell script
process = subprocess.run(['/path/to/script', options/variables], capture_output=True, text=True)
您可以通過捕獲 stderr/stdout 和返回代碼來添加其他功能。 例如:
# call to shell script
process = subprocess.run(['/path/to/script', options/variables], capture_output=True, text=True)
# return code of 0 test case. Successful run should return 0
if process.returncode != 0:
print('There was a problem')
exit(1)
子流程的文檔在這里
您可以使用os
模塊來訪問系統命令。
import os
os.system("srvmanage.sh enable <service_name>")
我解決了這個問題。
operation = 'enable'
service_operation_script = '/home/service_manager/bin/srvmanage.sh'
service_status = subprocess.check_output(
"sudo " +"/bin/bash " + service_operation_script + " " + operation + " " + service_name, shell=True)
response = service_status.decode("utf-8")
print(response)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.