Python 2.6 程序退出后不带换行符打印

标签 python python-2.x

在我的代码中,我尝试在程序退出并再次打印后打印而不换行。我在例如后用逗号打印:

type_d=dict.fromkeys(totals,[0,0])
for keysl in type_d.keys():
    print type_d[keysl][0] , ",", type_d[keysl][1] , ",",
print "HI" ,

但是当程序退出并且我调用另一个程序时,在文件中的最后一个值之后输入了一个换行符。我怎样才能避免这种情况?

最佳答案

我认为这没有记录,但它是有意为之,并且与记录的行为相关。

如果你查找print在文档中:

A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line. This is the case (1) when no characters have yet been written to standard output, (2) when the last character written to standard output is a whitespace character except ' ', or (3) when the last write operation on standard output was not a print statement. (In some cases it may be functional to write an empty string to standard output for this reason.)

Python 确实会跟踪最后写入 sys.stdout 的内容是否是由 print 写入的(包括由 print >>sys.stdout 写入的) code>) 或不是(除非 sys.stdout 不是实际的文件对象)。 (请参阅 C API 文档中的 PyFile_SoftSpace。)这就是上面 (3) 的作用。

它也用来决定在关闭 stdout 时是否打印换行符。

因此,如果您不想在末尾添加换行符,则可以在程序末尾执行 (3) 中提到的相同解决方法:

for i in range(10):
    print i,
print 'Hi',
sys.stdout.write('')

现在,当你运行它时:

$ python hi.py && python hi.py
0 1 2 3 4 5 6 7 8 9 Hi0 1 2 3 4 5 6 7 8 9 Hi
<小时/>

如果您想查看责任来源:

PRINT_ITEM ceval 中的字节码处理程序是设置“软空间”标志的位置。

根据标志检查并输出换行符或不输出的代码是 Py_FlushLine (Python 的许多其他部分也使用它)。

我相信调用该检查的代码是 handle_system_exit -但请注意各种不同的 "Very High Level C API" functions在同一文件中运行 Python 代码也在最后执行相同的操作。

关于Python 2.6 程序退出后不带换行符打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51164339/

相关文章:

python - 使用一些重复元素从 CSV 文件中构建和提取多维 Python 字典中的值

python - 自动完成什么都不做。怎么了?

python - 避免在 python 中为 Long 加上 L 后缀

python - 如何在 python 中捕获所有旧式类异常?

python - 如何在类属性定义中使用类方法

python - 为什么 008 和 009 是 Python 字典的无效键?

python - 枕头 OSError : cannot identify image file <_io. BytesIO 对象在 0x02345ED8>

python - 如何在未触及的 python etree 中正确转义 XML?

python - 使用 django-allauth 在用户注册时创建用户和用户配置文件

python - 如何在 python 交互模式下撤消 True = False?