Python 3.x 在Python3中运行linux shell命令

Python 3.x 在Python3中运行linux shell命令,python-3.x,linux,shell,subprocess,centos7,Python 3.x,Linux,Shell,Subprocess,Centos7,我正在创建一个服务管理器来管理apache、tomcat等服务。。等 我可以在shell中通过srvmanage.sh enable启用/禁用服务。 我想使用python脚本来实现这一点。怎么做 service_info = ServiceDB.query.filter_by(service_id=service_id).first() service_name = service_info.service subprocess.run(['/home/service_manag

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

导入操作系统
操作系统(“srvmanage.sh启用”)

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

import os

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

导入操作系统
操作系统(“srvmanage.sh启用”)

我猜如果您想在python中实现这一点,您可能需要更多的功能。如果不是@programandoconro,则回答即可。但是,您也可以使用
子流程模块
获得更多功能。它将允许您使用参数运行命令并返回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)

子流程的文档是

我猜如果您想在python中实现这一点,您可能需要更多的功能。如果不是@programandoconro,则回答即可。但是,您也可以使用
子流程模块
获得更多功能。它将允许您使用参数运行命令并返回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)
子流程的文档是

我解决了这个问题

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)
我解决了这个问题

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)

我需要将服务名称作为变量传递。因为它可以不同。这与您调用命令的方式有什么关系?这取决于您对它进行尽可能多的可变性编程。我需要将服务名称作为变量传递。因为它可以不同。这与您调用命令的方式有什么关系?这段代码有什么问题:您遇到了什么问题?它无法启用服务。您是否尝试跟踪该命令(`set-x)?您是否检查了它的退出代码?此代码有什么问题:您遇到了什么问题?它没有启用服务。您是否尝试跟踪命令(`set-x)?你查过它的出口代码了吗?