简体   繁体   中英

Python 2.6 print with no newline after program exits

In my code I am trying to print without a new line after the program exits and print again. I am printing with a comma after for example:

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

But when the program exits and I call on another one there is a newline inputted after the last value in the file. How can I avoid this?

I believe that this is not documented, but it's intentional, and related to behavior that is documented.

If you look up print in the docs:

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

And Python does keep track of whether the last thing written to sys.stdout was written by print (including by print >>sys.stdout ) or not (unless sys.stdout is not an actual file object). (See PyFile_SoftSpace in the C API docs.) That's how it does (3) above.

And it's also what it uses to decide whether to print a newline when closing stdout .

So, if you don't want that newline at the end, you can just do the same workaround mentioned in (3) at the end of your program:

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

Now, when you run it:

$ 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

If you want to see the source responsible:

The PRINT_ITEM bytecode handler in ceval is where the "soft space" flag gets set.

The code that checks and outputs a newline or not depending on the flag is Py_FlushLine (which is also used by many other parts of Python).

The code that calls that check is, I believe, handle_system_exit —but notice that the various different "Very High Level C API" functions for running Python code in the same file also do the same thing at the end.

You can try to use the code below, it will eliminate the new line:

import sys
sys.stdout.write("HI")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM