为什么我的 python return 值包含以前的打印文本?
Why does my python return value include previous print text?
我创建了一个小的 python 脚本,我从另一个 shell 脚本调用它来计算文件中数据的平均值,然后我将这个平均值返回给 shell 脚本变量。这是我的代码:
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()
但是,当我打印存储在 shell 变量中的值时
echo "$avgVal"
它也显示以前的打印文本!
所有重量的平均值 = 78.22 公斤
78.22
为什么会这样?我在返回平均值的方式上犯了什么错误吗?我怎样才能在 shell 变量中得到 78.22?
shell 捕获打印到标准输出的任何内容。如果您不想在 avgVal
.
中打印该消息到标准错误
print("Average of all weights = %f kg" % avg, file = sys.stderr)
我创建了一个小的 python 脚本,我从另一个 shell 脚本调用它来计算文件中数据的平均值,然后我将这个平均值返回给 shell 脚本变量。这是我的代码:
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()
但是,当我打印存储在 shell 变量中的值时
echo "$avgVal"
它也显示以前的打印文本!
所有重量的平均值 = 78.22 公斤
78.22
为什么会这样?我在返回平均值的方式上犯了什么错误吗?我怎样才能在 shell 变量中得到 78.22?
shell 捕获打印到标准输出的任何内容。如果您不想在 avgVal
.
print("Average of all weights = %f kg" % avg, file = sys.stderr)