【问题标题】:Run linux shell commands in Python3在 Python3 中运行 linux shell 命令
【发布时间】:2021-05-11 16:31:07
【问题描述】:

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

这段代码有什么问题?

【问题讨论】:

  • 这段代码有什么问题:你遇到了什么问题?
  • 它没有启用服务。
  • 您是否尝试跟踪命令(`set -x)?你检查了它的退出代码吗?

标签: python-3.x linux shell subprocess centos7


【解决方案1】:

我猜如果您想在 python 中执行此操作,您可能需要更多功能。如果不是@programandoconro 答案就可以。但是,您也可以使用subprocess module 来获得更多功能。它将允许您运行带有参数的命令并返回 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)

子流程的文档是here

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我需要将服务名称作为变量传递。因为它可能会有所不同。
    • 这与您调用命令的方式有什么关系?您可以根据需要将尽可能多的可变性编程到其中。
    【解决方案3】:

    我解决了这个问题。

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 1970-01-01
      • 2017-12-22
      • 2019-10-25
      • 2019-11-17
      • 2021-12-31
      相关资源
      最近更新 更多