Skip to content
Advertisement

Why does my python return value include previous print text?

I have created a small python script which I call from another shell script to calculate average value from the data in a file and I’m returning this average value back to a shell script variable. Here’s my code:

import sys

def calc():
    output = []
    file_path = sys.argv[1]
    with open(file_path, 'r') as input_stream:
        line = next(input_stream, None)
        while line is not None:
            output.append(float(line.split("t")[-1]))
            #print(output)
            line = next(input_stream, None)
        line = next(input_stream, None)
    avg = sum(output)/len(output)
    print("Average of all weights = %f kg" % avg)
    return print(avg)

calc()

However, when I print the value stored in the shell variable

echo "$avgVal"

it shows the previous print text as well!

Average of all weights = 78.22 kg

78.22

Why does this happen? Am I making any mistake in the way it’s returning the averaged value? How can I get only 78.22 in the shell variable?

Advertisement

Answer

The shell captures whatever is printed to standard output. Print that message to standard error if you don’t want it in avgVal.

print("Average of all weights = %f kg" % avg, file = sys.stderr)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement