运行 linux shell Python3 中的命令

Run linux shell commands in Python3

我正在创建一个服务管理器来管理诸如 apache、tomcat 等服务。 我可以通过 srvmanage.sh 在 shell 中启用 来 enable/disable 服务。 我想使用 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)

这段代码有什么问题?

您可以使用os模块访问系统命令。

import os

os.system("srvmanage.sh enable <service_name>")

我猜如果您想在 python 中执行此操作,您可能需要更多功能。如果不是@programandoconro 答案就可以了。但是,您也可以使用 subprocess module 来获得更多功能。它将允许您 运行 带有参数的命令和 return CompletedProcess 实例。例如

import subprocess

# call to shell script
process = subprocess.run(['/path/to/script', options/variables], capture_output=True, text=True)

您可以通过捕获 stderr/stdout 和 return 代码来添加其他功能。例如:

# 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)

子流程的文档是 here

我解决了这个问题。

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)