简体   繁体   English

从 python 脚本在后台执行 Linux 命令

[英]Executing Linux command in background from a python script

I have an ubuntu machine where kubernetes cluster is running.我有一台运行 kubernetes 集群的 ubuntu 机器。 I am basically trying to run a Kubernetes command in background from python3 script but it's not working, please help...我基本上是在尝试从 python3 脚本在后台运行 Kubernetes 命令,但它不起作用,请帮助...

Below is a part of code from a larger script, I am creating cmd4 using a formatted string and then passing cmd4 to os.system as os.system(cmd4).下面是来自较大脚本的部分代码,我正在使用格式化字符串创建 cmd4,然后将 cmd4 作为 os.system(cmd4) 传递给 os.system。 But as soon as I execute the script it starts showing logs in cmdline.但是,一旦我执行脚本,它就会开始在 cmdline 中显示日志。 I tried this using nohup as well as mentioned below but it starts populating logs in nohup.out.我尝试使用 nohup 以及下面提到的方法,但它开始在 nohup.out 中填充日志。

for podname in pod_names:
    if "smf" in podname or "pcf" in podname or "udm" in podname:
        containername = 'worker'
    else:
        containername = 'cppe'

    **cmd4 = f"kubectl logs -f -n core {podname} --container={containername} > {podname}_{containername}_log </dev/null &>/dev/null &&"**
    cmd5 = f"echo $! >> pid.txt"
    os.system(cmd4)
    os.system(cmd5)
    pid_file = open('pid.txt', 'a+')
    pid_file.write("\n")
    pid_file.close

================================= ==================================

tried with nohup as:尝试使用 nohup 为:

cmd4 = f"nohup kubectl logs -f -n core {podname} --container={containername} > {podname}_{containername}_log </dev/null &>/dev/null &&" cmd4 = f"nohup kubectl logs -f -n core {podname} --container={containername} > {podname}_{containername}_log </dev/null &>/dev/null &&"

But it gives this o/p但它给出了这个 o/p

updatedReplicas: 1更新副本:1

deployment.apps/core-pcf configured nohup: ignoring input and appending output to 'nohup.out' deployment.apps/core-pcf 配置 nohup:忽略输入并将输出附加到“nohup.out”

Have you tried using the subprocess library?您是否尝试过使用子流程库?

I think the solution for your script will be the following.我认为您的脚本的解决方案如下。

import subprocess

for podname in pod_names:
    if "smf" in podname or "pcf" in podname or "udm" in podname:
        containername = 'worker'
    else:
        containername = 'cppe'

    **cmd4 = f"kubectl logs -f -n core {podname} --container={containername} > {podname}_{containername}_log </dev/null &>/dev/null &&"**
    cmd5 = f"echo $! >> pid.txt"
    cmd4_bash = subprocess.Popen(cmd4.split(), stdout=subprocess.PIPE)
    cmd5_bash = subprocess.Popen(cmd5.split(), stdout=subprocess.PIPE) 
    pid_file = open('pid.txt', 'a+')
    pid_file.write("\n")
    pid_file.close

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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