-3

I am writing code on python which is calling the log file VXT_CDR_1_1_20180816.DAT using os.system(command)

The code is here

import os
command = "cat /home/smslog/CDRS/VXT_CDR_1_1_20180816.DAT | awk -F'|' '{print $3}' |sort|uniq"  
output= os.system(command)
#data = str(output)

for d in str(output).split():
  print(d)

os.system(command) is returning integer and it str(output) doesn't convert int to string and returning 0.

Kindly help to solve this issue.

bill
  • 118
  • 5
  • 1
    How do you expect to convert an integer to a string and get a completely different result? output integer most likely just returns whether it ran successfully. – Sasha Aug 17 '18 at 08:14
  • It returns 0 because `os.system` returns the exit status. If you want to retrieve the result from your command you should look into subprocess. – Bernhard Aug 17 '18 at 08:15

2 Answers2

2

os.system() simply runs the command without connecting its standard output to Python, and merely returns a small number which indicates whether or not the command succeeded (zero means success).

If you want to make its output available to Python, you are looking for subprocess.run() or its lesser predecessors (if you need pre-2.7 Python then this gets hairy).

from subprocess import run, PIPE
# refactor to avoid useless cat
command = "awk -F'|' '{print $3}' /home/smslog/CDRS/VXT_CDR_1_1_20180816.DAT |sort|uniq"  
result = run(command, shell=True, stdout=PIPE, universal_newlines=True)
# No need to split on newlines just so you can print a newline after each line
print(result.stdout)

For earlier versions of Python, look at subprocess.check_output() or, in the worst case, reimplement it with subprocess.Popen().

We usually dissuade people from using shell=True but getting rid of that by reimplementing the shell's pipeline functionality in Python is moderately challenging in this case. But there's nothing here which Python cannot do by itself natively, so the simplest fix is to not use external tools in the first place.

with open('/home/smslog/CDRS/VXT_CDR_1_1_20180816.DAT') as input:
    values = dict()
    for line in input:
        values[line.rstrip('\n').split('|')[2]] = 1
for value in sorted(values.keys()):
    print(value)

Collecting the values in a dictionary is a common pattern for making something unique. If the value already exists in the dictionary, we are not adding anything new by overwriting it with identical information. At the end of the loop, the keys of the dictionary values are the unique inputs.

tripleee
  • 175,061
  • 34
  • 275
  • 318
0

To get command output you could use subprocess.check_output() function with shell=True kwarg passed to it.

leotrubach
  • 1,509
  • 12
  • 15