简体   繁体   English

在 Python3 中运行 linux shell 命令

[英]Run linux shell commands in Python3

I am creating a service manager to manage services such as apache, tomcat.. etc. I can enable/disable services by srvmanage.sh enable <service_name> in shell.我正在创建一个服务管理器来管理 apache、tomcat.. 等服务。我可以通过 srvmanage.sh enable <service_name> 在 Z2591C98B70119FE624898B1E424B 中启用/禁用服务。 I want to do this using python script.我想使用 python 脚本来做到这一点。 How to do it?怎么做?

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)

what is the problem with this code?这段代码有什么问题?

I'm guessing if you want to do this in python you may want more functionality.我猜如果您想在 python 中执行此操作,您可能需要更多功能。 If not @programandoconro answer would do.如果不是@programandoconro 答案会做。 However, you could also use the subprocess module to get more functionality.但是,您也可以使用subprocess module来获得更多功能。 It will allow you to run a command with arguments and return a CompletedProcess instance.它将允许您使用 arguments 运行命令并返回 CompletedProcess 实例。 For example例如

import subprocess

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

You can add in additional functionality by capturing the stderr/stdout and return code.您可以通过捕获 stderr/stdout 和返回代码来添加其他功能。 For example:例如:

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

Docs for subprocess is here子流程的文档在这里

You can use os module to access system commands.您可以使用os模块来访问系统命令。

import os

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

I fixed this issue.我解决了这个问题。

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