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

执行chmod +x后直接运行Python脚本输出结果与预期不符问题

问题成因
  • 核心原因是两种执行方式调用的Python版本不一致:
    • 执行python hello.py时,你当前shell环境中python命令绑定的是Python 3,print作为内置函数接收多个参数,会将参数用空格拼接后输出,符合预期结果。
    • 直接执行./hello.py时,因为你的Python脚本首行没有指定解释器的shebang声明,系统默认调用Python 2解释执行脚本。Python 2中print是语句而非函数,你写的print ('Hello', name)会把括号内的内容识别为一个元组直接打印,因此输出带括号和引号的元组格式内容。
解决方法
  • 方法1:在hello.py文件的最顶部添加Python 3解释器声明(shebang行):
#!/usr/bin/env python3
import sys

# Define a main() function that prints a little greeting.
def main():
  # Get the name from the command line, using 'World' as a fallback.
  if len(sys.argv) >= 2:
    name = sys.argv[1]
  else:
    name = 'World'
  print ('Hello', name)

# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
  main()

添加后保存文件,直接执行./hello.py就会自动调用Python 3解释器,输出符合预期。

  • 方法2:如果不想修改脚本,直接执行时明确指定Python 3解释器即可:
python3 hello.py
  • 额外验证:你可以执行python --version和python2 --version确认当前环境的版本绑定情况,避免后续再出现版本差异导致的语法兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 11:54:03