python 脚本输出末尾的百分号

Percent sign at the end of the output of python script

为什么 python 脚本输出的末尾有一个百分号?

$ 回声 "TEST TEST" | trim
测试测试%

#!/usr/bin/env python
import sys

if __name__ == "__main__":
    for line in sys.stdin:
        sys.stdout.write(''.join(line.split()))

您看到的 % 实际上可能是您的 shell 提示符,而不是程序输出的一部分。您没有在输出后写新行,因此 shell 提示出现在最后一条命令输出的最后。

可能的解决方案:

  1. 使用print代替sys.stdout.write
  2. 使用 + "\n"
  3. 在输出的末尾附加一个换行符
  4. 在程序末尾添加 print()