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

Python 2.6 print with no newline after program exits

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

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

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

您可以尝试使用下面的代码,它将消除新行:

import sys
sys.stdout.write("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)写的(除非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

如果您想查看负责的来源:

ceval 中的 PRINT_ITEM 字节码处理程序是设置 "soft space" 标志的地方。

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

调用该检查的代码是,我相信,handle_system_exit—but notice that the various different "Very High Level C API" functions for 运行ning Python 同一文件中的代码最后也会做同样的事情。