0

This command gives multiple values.

kapacitor list tasks | grep -i enabled

I need to iterate through and store the output of the above command. I tried

enabled = os.system("kapacitor list tasks | grep -i enabled")
print enabled

Output for this command kapacitor list tasks | grep -i enabled

Alert_ALL_metrics_cpu stream enabled true ["metrics_NWNA"."autogen" "metrics_NN"."autogen"] tAlert_ALL_metrics_memory_usage stream enabled true ["metrics_NWNA"."autogen" "metrics_NN"."autogen"] tAlert_ALL_oracle_TBS_offline stream enabled true ["oracle_NWNA"."autogen" "oracle_NN"."autogen"] tAlert_NN_WMS_endpoint-message-count_MSE stream enabled true ["metrics"."autogen"] tAlert_NN_ecom_version_check stream enabled true ["metrics_NN"."autogen"] tAlert_NN_ecom_version_check_all_farms stream enabled true ["metrics_NN"."autogen"] tAlert_NN_metrics_fileSystem stream enabled true ["metrics_NN"."autogen"] tAlert_NWNA_metrics_fileSystem stream enabled true ["metrics_NWNA"."autogen"]

Karthika
  • 11
  • 3

2 Answers2

0

Instead of using the os module, try using the subprocess module.

import subprocess

ele = subprocess.Popen(['kapacitor', 'list', 'tasks', '|', 'grep', '-i', 'enabled'] shell=True)
output, err = ele.communicate()
print(output)

This will store the output of the command ran inside the output(as a variable) then you can call it and do whatever you want with it from there

maestro.inc
  • 796
  • 1
  • 6
  • 13
0

Not sure what variable come with your "enable" but try below.

from subprocess import check_output

datas = []

data = check_output("kapacitor list tasks | grep -i enabled")

print (data)

for i, j, k in data:    # i,j,k are just three variables in example. Add more if needed.
    datas.append((i,j),(k))

print (datas[0])  # prints (i,j)

For other type of subprocess command check SO question: Linux command-line call not returning what it should from os.system?

ZF007
  • 3,708
  • 8
  • 29
  • 48
  • While executing this command kapacitor list tasks | grep -i enabled it will display the result as tAlert_ALL_metrics_cpu stream enabled true ["metrics_NWNA"."autogen" "metrics_NN"."autogen"] tAlert_ALL_metrics_memory_usage stream enabled true ["metrics_NWNA"."autogen" "metrics_NN"."autogen"] tAlert_ALL_oracle_TBS_offline stream enabled true ["oracle_NWNA"."autogen" "oracle_NN"."autogen"] – Karthika Dec 24 '19 at 10:10
  • ...should be fixed now. `os.system` just prints the output without returning it as result (in this case a list form). The latter you can use to do whatever you want to do with it. – ZF007 Dec 24 '19 at 10:51