繁体   English   中英

在 Python3 中运行 linux shell 命令

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM