You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Ubuntu终端运行带return的Python函数无输出的问题求助

解决终端运行Python脚本无返回值的问题

Colab的交互式环境会自动打印函数调用的返回值,但在Ubuntu终端运行脚本时,函数返回值不会自动输出——这就是你执行python test.py看不到结果的原因。以下几种方法可以在保留return语句的前提下实现输出:

方法1:在脚本末尾直接打印函数结果

修改脚本,在函数调用后添加print()语句,原函数的return完全保留:

#!/usr/bin/env python

# testing a func

def hello(x):
  if x > 5:
    return "good"
  else:
    return "bad"

# 打印函数返回值
print(hello(2))

运行命令:

python test.py

输出:

bad

方法2:使用__name__ == "__main__"判断(更规范)

这种方式可以让脚本在被其他模块导入时不执行打印操作,只有直接运行脚本时才输出,适合需要复用函数的场景:

#!/usr/bin/env python

# testing a func

def hello(x):
  if x > 5:
    return "good"
  else:
    return "bad"

if __name__ == "__main__":
    print(hello(2))

方法3:不修改原脚本,通过终端命令调用并打印

如果不想改动原脚本,可在终端用python -c命令导入函数并打印结果:

python -c "from test import hello; print(hello(2))"

执行后同样会输出bad。

内容的提问来源于stack exchange,提问作者Chip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 08:15:31