为什么 python 不将输出发送到标准输出?

Why doesn't python send output to stdout?

这是一个最小工作示例 (MWE),另存为 mwe.py:

import sys

def f(n):
    print("Testing print()...")
    sys.stdout.write("Calculating f({})...".format(n))

当从命令行 运行 时,我没有得到任何输出:

username@hostname:~/mydir$ python mwe.py 'f(99)'
username@hostname:~/mydir$ 

当 运行 来自 python 我得到输出(删除了一些信息):

username@hostname:~/mydir$ python
Python 3.5.4 (default, DATE, HH:MM:SS)
[GCC X.X.X Compatible Apple LLVM X.X.X (clang-X.X.X)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from mwe import f
>>> f(99)
Testing print()...
Calculating f(99)...
>>>

为什么这些输出语句在 python 中有效,但在命令行中 无效

这:python mwe.py 'f(99)' 应该行不通。在这种情况下,'f(99)' 只是作为参数传递给程序。

请尝试使用 python -c 'import mwe; mwe.f(99)。 (还可以通过键入 python -h 阅读有关 python 的命令行用法的更多信息)

python mwe.py 'f(99)' 并不意味着 "run the f function from mwe.py with argument 99"。如果您想从命令行执行此操作,您可以执行

python -c 'import mwe; mwe.f(99)'

python mwe.py 'f(99)' 表示 "run the script mwe.py with sys.argv[1] set to the string "f(99)""。脚本 mwe.py 根本不检查 sys.argv 或打印任何东西;它只是定义一个函数并结束。