意外的 Python 输出 Chmod 命令行

Unexpected Python output Chmod Command Line

提前感谢您的反馈!

我有一个简单的 hello.py 文件,我正在命令行中探索它。

当我运行以下命令时:

python hello.py

我得到了预期的输出:

Hello World

但是当我 运行 使用执行位命令时

chmod +x hello.py
./hello.py

我得到以下输出:

('Hello', 'World')

我不明白为什么第二个输出被括在括号中并显示为单独引用的字符串。我的 python 版本是 Python 3.8.5。如果重要的话,我的 shell 是 zsh。

这是 hello.py 文件:

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()

为了能够 运行 仅使用脚本名称的脚本,文件需要有一个有效的 shebang 行。你没有展示你的,但显然你的脚本有一个,否则 shell 会尝试 运行 它作为 shell 脚本。不幸的是,您的 shebang 指向 Python 2,而您希望它指向 Python 3.

在许多 Linux 系统上,#!/usr/bin/python(或道德上等同但更灵活的 #!/usr/bin/env python)将 运行 Python 2,而 #!/usr/bin/python3(或#!/usr/bin/env python3)将运行 Python 3.

命令行中的python是否运行s Python3大体上无关紧要;这可能是您的 shell 设置的交互式别名,但它 可以交互式工作。