标签归档:printing

在Python的同一行上有多个打印

问题:在Python的同一行上有多个打印

我想运行一个脚本,该脚本基本上显示如下输出:

Installing XXX...               [DONE]

目前,我Installing XXX...先打印,然后再打印[DONE]

不过,我现在想打印Installing xxx...[DONE]在同一行。

有任何想法吗?

I want to run a script, which basically shows an output like this:

Installing XXX...               [DONE]

Currently, I print Installing XXX... first and then I print [DONE].

However, I now want to print Installing xxx... and [DONE] on the same line.

Any ideas?


回答 0

您可以使用该print语句执行此操作,而无需导入sys

def install_xxx():
   print "Installing XXX...      ",

install_xxx()
print "[DONE]"

行尾的逗号会print阻止print发出新行(您应注意,输出末尾会有多余的空格)。

Python 3解决方案
由于上述内容在Python 3中不起作用,因此您可以改为这样做(同样,不导入sys):

def install_xxx():
    print("Installing XXX...      ", end="", flush=True)

install_xxx()
print("[DONE]")

打印功能接受end默认值为的参数"\n"。将其设置为空字符串可防止它在该行的末尾发出新行。

You can use the print statement to do this without importing sys.

def install_xxx():
   print "Installing XXX...      ",

install_xxx()
print "[DONE]"

The comma on the end of the print line prevents print from issuing a new line (you should note that there will be an extra space at the end of the output).

The Python 3 Solution
Since the above does not work in Python 3, you can do this instead (again, without importing sys):

def install_xxx():
    print("Installing XXX...      ", end="", flush=True)

install_xxx()
print("[DONE]")

The print function accepts an end parameter which defaults to "\n". Setting it to an empty string prevents it from issuing a new line at the end of the line.


回答 1

您可以简单地使用:

print 'something',
...
print ' else',

和输出将是

something else

无需过度杀伤import sys。注意末尾的逗号符号。

Python 3+ print("some string", end="");删除结尾处的换行符。阅读更多help(print);

You can simply use this:

print 'something',
...
print ' else',

and the output will be

something else

no need to overkill by import sys. Pay attention to comma symbol at the end.

Python 3+ print("some string", end=""); to remove the newline insert at the end. Read more by help(print);


回答 2

您应使用退格键’ \ r ‘或(’ \ x08 ‘)char返回控制台输出中的上一个位置

Python 2+:

import time
import sys

def backspace(n):
    sys.stdout.write((b'\x08' * n).decode()) # use \x08 char to go back   

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    sys.stdout.write(s)                     # just print
    sys.stdout.flush()                      # needed for flush when using \x08
    backspace(len(s))                       # back n chars    
    time.sleep(0.2)                         # sleep for 200ms

Python 3:

import time   

def backline():        
    print('\r', end='')                     # use '\r' to go back


for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print(s, end='')                        # just print and flush
    backline()                              # back to the beginning of line    
    time.sleep(0.2)                         # sleep for 200ms

此代码将在一行中从0%到100%计数。最终值将是:

> python test.py
100%

在这种情况下,有关刷新的其他信息在这里:为什么包含’end =’参数的python打印语句在while循环中的行为不同?

You should use backspace ‘\r‘ or (‘\x08‘) char to go back on previous position in console output

Python 2+:

import time
import sys

def backspace(n):
    sys.stdout.write((b'\x08' * n).decode()) # use \x08 char to go back   

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    sys.stdout.write(s)                     # just print
    sys.stdout.flush()                      # needed for flush when using \x08
    backspace(len(s))                       # back n chars    
    time.sleep(0.2)                         # sleep for 200ms

Python 3:

import time   

def backline():        
    print('\r', end='')                     # use '\r' to go back


for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print(s, end='')                        # just print and flush
    backline()                              # back to the beginning of line    
    time.sleep(0.2)                         # sleep for 200ms

This code will count from 0% to 100% on one line. Final value will be:

> python test.py
100%

Additional info about flush in this case here: Why do python print statements that contain ‘end=’ arguments behave differently in while-loops?


回答 3

使用sys.stdout.write('Installing XXX... ')sys.stdout.write('Done')。这样,"\n"如果要重新创建打印功能,则必须手动添加新行。我认为可能不必为此专门使用诅咒。

Use sys.stdout.write('Installing XXX... ') and sys.stdout.write('Done'). In this way, you have to add the new line by hand with "\n" if you want to recreate the print functionality. I think that it might be unnecessary to use curses just for this.


回答 4

没有一个答案对我有用,因为它们都暂停了,直到遇到新的一行。我写了一个简单的助手:

def print_no_newline(string):
    import sys
    sys.stdout.write(string)
    sys.stdout.flush()

要测试它:

import time
print_no_newline('hello ')
# Simulate a long task
time.sleep(2)
print('world')

“ hello”将首先打印出来,然后在睡眠前冲洗到屏幕。之后,您可以使用标准打印。

None of the answers worked for me since they all paused until a new line was encountered. I wrote a simple helper:

def print_no_newline(string):
    import sys
    sys.stdout.write(string)
    sys.stdout.flush()

To test it:

import time
print_no_newline('hello ')
# Simulate a long task
time.sleep(2)
print('world')

“hello ” will first print out and flush to the screen before the sleep. After that you can use standard print.


回答 5

sys.stdout.write 将打印而无需回车

import sys
sys.stdout.write("installing xxx")
sys.stdout.write(".")

http://en.wikibooks.org/wiki/Python_Programming/Input_and_output#printing_without_commas_or_newlines

sys.stdout.write will print without return carriage

import sys
sys.stdout.write("installing xxx")
sys.stdout.write(".")

http://en.wikibooks.org/wiki/Python_Programming/Input_and_output#printing_without_commas_or_newlines


回答 6

最简单的:

Python 3

    print('\r' + 'something to be override', end='')

这意味着它将把光标返回到开始处,而不是打印一些内容并在同一行结束。如果处于循环中,它将在开始的位置开始打印。

Most simple:

Python 3

    print('\r' + 'something to be override', end='')

It means it will back the cursor to beginning, than will print something and will end in the same line. If in a loop it will start printing in the same place it starts.


回答 7

这个简单的示例将在同一行上打印1-10。

for i in range(1,11):
    print (i, end=" ")

This simple example will print 1-10 on the same line.

for i in range(1,11):
    print (i, end=" ")

回答 8

Print有一个可选end参数,它是最终输出的内容。默认值为换行符,但您可以将其更改为空字符串。例如print("hello world!", end="")

Print has an optional end argument, it is what printed in the end. The default is a newline, but you can change it to empty string. e.g. print("hello world!", end="")


回答 9

如果你想覆盖前一行(而不是不断地增加它),你可以结合\r使用 print(),,在打印语句的结束。例如,

from time import sleep

for i in xrange(0, 10):
    print("\r{0}".format(i)),
    sleep(.5)

print("...DONE!")

将计数0到9,替换控制台中的旧数字。的"...DONE!"将打印在同一行作为最后的反击,9。

对于OP,这将允许控制台将安装的完成百分比显示为“进度条”,您可以在其中定义开始和结束字符位置,并在其间更新标记。

print("Installing |XXXXXX              | 30%"),

If you want to overwrite the previous line (rather than continually adding to it), you can combine \r with print(), at the end of the print statement. For example,

from time import sleep

for i in xrange(0, 10):
    print("\r{0}".format(i)),
    sleep(.5)

print("...DONE!")

will count 0 to 9, replacing the old number in the console. The "...DONE!" will print on the same line as the last counter, 9.

In your case for the OP, this would allow the console to display percent complete of the install as a “progress bar”, where you can define a begin and end character position, and update the markers in between.

print("Installing |XXXXXX              | 30%"),

回答 10

这里是@ Vadim-Zin4uk从3.0版本派生的2.7兼容版本:

Python 2

import time

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print '{0}\r'.format(s),                # just print and flush

    time.sleep(0.2)

为此,提供的3.0解决方案看起来有些looks肿。例如,退格方法不使用整数参数,可能完全可以使用。

Python 3

import time

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print('{0}\r'.format(s), end='')        # just print and flush

    time.sleep(0.2)                         # sleep for 200ms

两者都已经过测试和工作。

Here a 2.7-compatible version derived from the 3.0 version by @Vadim-Zin4uk:

Python 2

import time

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print '{0}\r'.format(s),                # just print and flush

    time.sleep(0.2)

For that matter, the 3.0 solution provided looks a little bloated. For example, the backspace method doesn’t make use of the integer argument and could probably be done away with altogether.

Python 3

import time

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print('{0}\r'.format(s), end='')        # just print and flush

    time.sleep(0.2)                         # sleep for 200ms

Both have been tested and work.


回答 11

这是一个非常古老的线程,但是这里有一个非常详尽的答案和示例代码。

\r是ASCII字符集的回车的字符串表示形式。与八进制015[ chr(0o15)]或十六进制0d[ chr(0x0d)]或十进制13[ chr(13)]相同。请参阅man ascii无聊的阅读。它(\r)是一种可移植的表示形式,足以让人们阅读。这很简单,就是在不推进纸张的情况下将打字机上的笔架一直移动到起点。这是CR一部分CRLF,这意味着回车和换行

print()是Python 3中的函数。在Python 2(您可能会感兴趣的任何版本)中,print可以通过从__future__模块中导入函数的定义来强制使用该函数。该print功能的好处在于,您可以指定在\n结尾处打印的内容,而不是在每次print()调用结束时打印换行符的默认行为。

sys.stdout.flush告诉Python刷新标准输出的输出,print()除非您另外指定,否则发送标准输出的位置。您还可以通过运行python -u或设置环境变量来获得相同的行为PYTHONUNBUFFERED=1,从而跳过import syssys.stdout.flush()调用。通过这样做,您获得的收益几乎完全为零,并且如果您方便地忘记了必须在应用程序正常运行之前执行该步骤,那么调试起来就不太容易。

和一个样本。请注意,这可以在Python 2或3中完美运行。

from __future__ import print_function

import sys
import time

ANS = 42
FACTORS = {n for n in range(1, ANS + 1) if ANS % n == 0}

for i in range(1, ANS + 1):
    if i in FACTORS:
        print('\r{0:d}'.format(i), end='')
        sys.stdout.flush()
        time.sleep(ANS / 100.0)
else:
    print()

This is a very old thread, but here’s a very thorough answer and sample code.

\r is the string representation of Carriage Return from the ASCII character set. It’s the same as octal 015 [chr(0o15)] or hexidecimal 0d [chr(0x0d)] or decimal 13 [chr(13)]. See man ascii for a boring read. It (\r) is a pretty portable representation and is easy enough for people to read. It very simply means to move the carriage on the typewriter all the way back to the start without advancing the paper. It’s the CR part of CRLF which means Carriage Return and Line Feed.

print() is a function in Python 3. In Python 2 (any version that you’d be interested in using), print can be forced into a function by importing its definition from the __future__ module. The benefit of the print function is that you can specify what to print at the end, overriding the default behavior of \n to print a newline at the end of every print() call.

sys.stdout.flush tells Python to flush the output of standard output, which is where you send output with print() unless you specify otherwise. You can also get the same behavior by running with python -u or setting environment variable PYTHONUNBUFFERED=1, thereby skipping the import sys and sys.stdout.flush() calls. The amount you gain by doing that is almost exactly zero and isn’t very easy to debug if you conveniently forget that you have to do that step before your application behaves properly.

And a sample. Note that this runs perfectly in Python 2 or 3.

from __future__ import print_function

import sys
import time

ANS = 42
FACTORS = {n for n in range(1, ANS + 1) if ANS % n == 0}

for i in range(1, ANS + 1):
    if i in FACTORS:
        print('\r{0:d}'.format(i), end='')
        sys.stdout.flush()
        time.sleep(ANS / 100.0)
else:
    print()

回答 12

print()具有内置参数“ end”,默认情况下设置为“ \ n”。调用print(“ This is America”)实际上是调用print(“ This is America”,end =“ \ n”)。一种简单的方法是调用print(“ This is America”,end =“”)

print() has a built in parameter “end” that is by default set to “\n” Calling print(“This is America”) is actually calling print(“This is America”, end = “\n”). An easy way to do is to call print(“This is America”, end =””)


回答 13

以防万一您已将值预先存储在数组中,可以按以下格式调用它们:

for i in range(0,n):
       print arr[i],

Just in case you have pre-stored the values in an array, you can call them in the following format:

for i in range(0,n):
       print arr[i],

回答 14

Python附加换行符作为打印结束。对于print3的python3使用end =”来添加空格而不是换行符。对于python2,请在打印语句末尾使用逗号。

print("Foo",end=' ')
print('Bar')

Python appends newline as an end to print. Use end=’ ‘ for python3 for print method to append a space instead of a newline. for python2 use comma at end of print statement.

print("Foo",end=' ')
print('Bar')


回答 15

找到此Quora帖子,并找到适用于我的示例(python 3),该示例更接近于我需要的示例(即,删除了前一行)。

他们提供的示例:

def clock():
   while True:
       print(datetime.now().strftime("%H:%M:%S"), end="\r")

如其他人所建议,要在同一行上打印,只需使用 end=""

Found this Quora post, with this example which worked for me (python 3), which was closer to what I needed it for (i.e. erasing the whole previous line).

The example they provide:

def clock():
   while True:
       print(datetime.now().strftime("%H:%M:%S"), end="\r")

For printing the on the same line, as others have suggested, just use end=""


回答 16

我找到了这个解决方案,并且可以在Python 2.7上运行

# Working on Python 2.7 Linux

import time
import sys


def backspace(n):
    print('\r', end='')                     # use '\r' to go back


for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    sys.stdout.write(string)
    backspace(len(s))                       # back for n chars
    sys.stdout.flush()
    time.sleep(0.2)                         # sleep for 200ms

I found this solution, and it’s working on Python 2.7

# Working on Python 2.7 Linux

import time
import sys


def backspace(n):
    print('\r', end='')                     # use '\r' to go back


for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    sys.stdout.write(string)
    backspace(len(s))                       # back for n chars
    sys.stdout.flush()
    time.sleep(0.2)                         # sleep for 200ms

在Python中打印多个参数

问题:在Python中打印多个参数

这只是我的代码的一部分:

print("Total score for %s is %s  ", name, score)

但我希望它打印出来:

“(姓名)的总分是(分数)”

其中name是列表中的变量,score是整数。如果有帮助的话,这就是Python 3.3。

This is just a snippet of my code:

print("Total score for %s is %s  ", name, score)

But I want it to print out:

“Total score for (name) is (score)”

where name is a variable in a list and score is an integer. This is Python 3.3 if that helps at all.


回答 0

有很多方法可以做到这一点。要使用%-formatting 修复当前代码,您需要传入一个元组:

  1. 将其作为元组传递:

    print("Total score for %s is %s" % (name, score))

具有单个元素的元组看起来像('this',)

这是其他一些常见的实现方法:

  1. 将其作为字典传递:

    print("Total score for %(n)s is %(s)s" % {'n': name, 's': score})

还有一种新型的字符串格式,可能更容易阅读:

  1. 使用新型的字符串格式:

    print("Total score for {} is {}".format(name, score))
  2. 使用带有数字的新型字符串格式(可用于重新排序或多次打印相同的字符):

    print("Total score for {0} is {1}".format(name, score))
  3. 使用具有显式名称的新型字符串格式:

    print("Total score for {n} is {s}".format(n=name, s=score))
  4. 连接字符串:

    print("Total score for " + str(name) + " is " + str(score))

我认为最清楚的两个是:

  1. 只需将值作为参数传递:

    print("Total score for", name, "is", score)

    如果您不希望print在上面的示例中自动插入空格,请更改sep参数:

    print("Total score for ", name, " is ", score, sep='')

    如果您使用的是Python 2,将不能使用最后两个,因为print这不是Python 2中的函数。不过,您可以从__future__以下方式导入此行为:

    from __future__ import print_function
  2. f在Python 3.6中使用新的-string格式:

    print(f'Total score for {name} is {score}')

There are many ways to do this. To fix your current code using %-formatting, you need to pass in a tuple:

  1. Pass it as a tuple:

    print("Total score for %s is %s" % (name, score))
    

A tuple with a single element looks like ('this',).

Here are some other common ways of doing it:

  1. Pass it as a dictionary:

    print("Total score for %(n)s is %(s)s" % {'n': name, 's': score})
    

There’s also new-style string formatting, which might be a little easier to read:

  1. Use new-style string formatting:

    print("Total score for {} is {}".format(name, score))
    
  2. Use new-style string formatting with numbers (useful for reordering or printing the same one multiple times):

    print("Total score for {0} is {1}".format(name, score))
    
  3. Use new-style string formatting with explicit names:

    print("Total score for {n} is {s}".format(n=name, s=score))
    
  4. Concatenate strings:

    print("Total score for " + str(name) + " is " + str(score))
    

The clearest two, in my opinion:

  1. Just pass the values as parameters:

    print("Total score for", name, "is", score)
    

    If you don’t want spaces to be inserted automatically by print in the above example, change the sep parameter:

    print("Total score for ", name, " is ", score, sep='')
    

    If you’re using Python 2, won’t be able to use the last two because print isn’t a function in Python 2. You can, however, import this behavior from __future__:

    from __future__ import print_function
    
  2. Use the new f-string formatting in Python 3.6:

    print(f'Total score for {name} is {score}')
    

回答 1

有很多打印方法。

让我们看另一个例子。

a = 10
b = 20
c = a + b

#Normal string concatenation
print("sum of", a , "and" , b , "is" , c) 

#convert variable into str
print("sum of " + str(a) + " and " + str(b) + " is " + str(c)) 

# if you want to print in tuple way
print("Sum of %s and %s is %s: " %(a,b,c))  

#New style string formatting
print("sum of {} and {} is {}".format(a,b,c)) 

#in case you want to use repr()
print("sum of " + repr(a) + " and " + repr(b) + " is " + repr(c))

EDIT :

#New f-string formatting from Python 3.6:
print(f'Sum of {a} and {b} is {c}')

There are many ways to print that.

Let’s have a look with another example.

a = 10
b = 20
c = a + b

#Normal string concatenation
print("sum of", a , "and" , b , "is" , c) 

#convert variable into str
print("sum of " + str(a) + " and " + str(b) + " is " + str(c)) 

# if you want to print in tuple way
print("Sum of %s and %s is %s: " %(a,b,c))  

#New style string formatting
print("sum of {} and {} is {}".format(a,b,c)) 

#in case you want to use repr()
print("sum of " + repr(a) + " and " + repr(b) + " is " + repr(c))

EDIT :

#New f-string formatting from Python 3.6:
print(f'Sum of {a} and {b} is {c}')

回答 2

使用方法.format()

print("Total score for {0} is {1}".format(name, score))

要么:

// Recommended, more readable code

print("Total score for {n} is {s}".format(n=name, s=score))

要么:

print("Total score for" + name + " is " + score)

要么:

`print("Total score for %s is %d" % (name, score))`

Use: .format():

print("Total score for {0} is {1}".format(name, score))

Or:

// Recommended, more readable code

print("Total score for {n} is {s}".format(n=name, s=score))

Or:

print("Total score for" + name + " is " + score)

Or:

`print("Total score for %s is %d" % (name, score))`

回答 3

在Python 3.6中,f-string它更加干净。

在早期版本中:

print("Total score for %s is %s. " % (name, score))

在Python 3.6中:

print(f'Total score for {name} is {score}.')

会做。

它更高效,更优雅。

In Python 3.6, f-string is much cleaner.

In earlier version:

print("Total score for %s is %s. " % (name, score))

In Python 3.6:

print(f'Total score for {name} is {score}.')

will do.

It is more efficient and elegant.


回答 4

保持简单,我个人喜欢字符串连接:

print("Total score for " + name + " is " + score)

它同时适用于Python 2.7和3.X。

注意:如果score是一个int,则应将其转换为str

print("Total score for " + name + " is " + str(score))

Keeping it simple, I personally like string concatenation:

print("Total score for " + name + " is " + score)

It works with both Python 2.7 an 3.X.

NOTE: If score is an int, then, you should convert it to str:

print("Total score for " + name + " is " + str(score))

回答 5

你试一试:

print("Total score for", name, "is", score)

Just try:

print("Total score for", name, "is", score)

回答 6

只要遵循这个

idiot_type = "the biggest idiot"
year = 22
print("I have been {} for {} years ".format(idiot_type, years))

要么

idiot_type = "the biggest idiot"
year = 22
print("I have been %s for %s years."% (idiot_type, year))

忘记所有其他格式,否则大脑将无法映射所有格式。

Just follow this

idiot_type = "the biggest idiot"
year = 22
print("I have been {} for {} years ".format(idiot_type, years))

OR

idiot_type = "the biggest idiot"
year = 22
print("I have been %s for %s years."% (idiot_type, year))

And forget all others, else the brain won’t be able to map all the formats.


回答 7

print("Total score for %s is %s  " % (name, score))

%s可以替换为%d%f

print("Total score for %s is %s  " % (name, score))

%s can be replace by %d or %f


回答 8

用途f-string

print(f'Total score for {name} is {score}')

要么

用途.format

print("Total score for {} is {}".format(name, score))

Use f-string:

print(f'Total score for {name} is {score}')

Or

Use .format:

print("Total score for {} is {}".format(name, score))

回答 9

如果score是数字,则

print("Total score for %s is %d" % (name, score))

如果score是一个字符串,则

print("Total score for %s is %s" % (name, score))

如果score是数字,%d则为,如果是字符串%s,则为,如果score是浮点型,则为%f

If score is a number, then

print("Total score for %s is %d" % (name, score))

If score is a string, then

print("Total score for %s is %s" % (name, score))

If score is a number, then it’s %d, if it’s a string, then it’s %s, if score is a float, then it’s %f


回答 10

这是我的工作:

print("Total score for " + name + " is " + score)

请记住在for前后放置一个空格is

This is what I do:

print("Total score for " + name + " is " + score)

Remember to put a space after for and before and after is.


动态打印一行

问题:动态打印一行

我想做几条给出标准输出的语句,但不要在语句之间看到换行符。

具体来说,假设我有:

for item in range(1,100):
    print item

结果是:

1
2
3
4
.
.
.

如何使它看起来像:

1 2 3 4 5 ...

更妙的是,是否可以打印单号最后一个号码,所以只有一个号码在屏幕上在同一时间?

I would like to make several statements that give standard output without seeing newlines in between statements.

Specifically, suppose I have:

for item in range(1,100):
    print item

The result is:

1
2
3
4
.
.
.

How get this to instead look like:

1 2 3 4 5 ...

Even better, is it possible to print the single number over the last number, so only one number is on the screen at a time?


回答 0

更改print item为:

  • print item, 在Python 2.7中
  • print(item, end=" ") 在Python 3中

如果要动态打印数据,请使用以下语法:

  • print(item, sep=' ', end='', flush=True) 在Python 3中

Change print item to:

  • print item, in Python 2.7
  • print(item, end=" ") in Python 3

If you want to print the data dynamically use following syntax:

  • print(item, sep=' ', end='', flush=True) in Python 3

回答 1

顺便说一句……如何每次都刷新它以便它在一个地方打印mi只需更改数字。

通常,这样做的方法是使用终端控制代码。这是一个非常简单的情况,对于该情况,您只需要一个特殊字符:用'\r'Python(和许多其他语言)编写的U + 000D CARRIAGE RETURN 。这是一个基于您的代码的完整示例:

from sys import stdout
from time import sleep
for i in range(1,20):
    stdout.write("\r%d" % i)
    stdout.flush()
    sleep(1)
stdout.write("\n") # move the cursor to the next line

关于此的一些事情可能令人惊讶:

  • \r去的字符串,这样的开始,程序运行时,光标会一直在数字后。这不只是装饰性的:如果您反过来做的话,某些终端仿真器会非常混乱。
  • 如果您不包括最后一行,则在程序终止后,您的外壳程序将在数字的顶部显示其提示。
  • stdout.flush在某些系统上,这是必需的,否则您将不会获得任何输出。其他系统可能不需要它,但是它没有任何危害。

如果您发现这不起作用,那么您首先应该怀疑的是您的终端仿真器有问题。该vttest程序可以帮助你测试。

你可以更换stdout.write一个print声明,但我宁愿不要混淆print与直接使用的文件对象。

By the way…… How to refresh it every time so it print mi in one place just change the number.

In general, the way to do that is with terminal control codes. This is a particularly simple case, for which you only need one special character: U+000D CARRIAGE RETURN, which is written '\r' in Python (and many other languages). Here’s a complete example based on your code:

from sys import stdout
from time import sleep
for i in range(1,20):
    stdout.write("\r%d" % i)
    stdout.flush()
    sleep(1)
stdout.write("\n") # move the cursor to the next line

Some things about this that may be surprising:

  • The \r goes at the beginning of the string so that, while the program is running, the cursor will always be after the number. This isn’t just cosmetic: some terminal emulators get very confused if you do it the other way around.
  • If you don’t include the last line, then after the program terminates, your shell will print its prompt on top of the number.
  • The stdout.flush is necessary on some systems, or you won’t get any output. Other systems may not require it, but it doesn’t do any harm.

If you find that this doesn’t work, the first thing you should suspect is that your terminal emulator is buggy. The vttest program can help you test it.

You could replace the stdout.write with a print statement but I prefer not to mix print with direct use of file objects.


回答 2

使用print item,使打印语句忽略换行符。

在Python 3中为print(item, end=" ")

如果希望每个数字都显示在同一位置,请使用示例(Python 2.7):

to = 20
digits = len(str(to - 1))
delete = "\b" * (digits + 1)
for i in range(to):
    print "{0}{1:{2}}".format(delete, i, digits),

在Python 3中,它有点复杂。在这里,您需要刷新,sys.stdout否则在循环完成之前它不会打印任何内容:

import sys
to = 20
digits = len(str(to - 1))
delete = "\b" * (digits)
for i in range(to):
   print("{0}{1:{2}}".format(delete, i, digits), end="")
   sys.stdout.flush()

Use print item, to make the print statement omit the newline.

In Python 3, it’s print(item, end=" ").

If you want every number to display in the same place, use for example (Python 2.7):

to = 20
digits = len(str(to - 1))
delete = "\b" * (digits + 1)
for i in range(to):
    print "{0}{1:{2}}".format(delete, i, digits),

In Python 3, it’s a bit more complicated; here you need to flush sys.stdout or it won’t print anything until after the loop has finished:

import sys
to = 20
digits = len(str(to - 1))
delete = "\b" * (digits)
for i in range(to):
   print("{0}{1:{2}}".format(delete, i, digits), end="")
   sys.stdout.flush()

回答 3

与其他示例一样,
我使用类似的方法,而不是花时间计算出最后的输出长度,等等,

我只是使用ANSI代码转义符移回到行的开头,然后在打印我的当前状态输出之前清除整行。

import sys

class Printer():
    """Print things to stdout on one line dynamically"""
    def __init__(self,data):
        sys.stdout.write("\r\x1b[K"+data.__str__())
        sys.stdout.flush()

要在迭代循环中使用,您只需调用以下内容:

x = 1
for f in fileList:
    ProcessFile(f)
    output = "File number %d completed." % x
    Printer(output)
    x += 1   

在这里查看更多

Like the other examples,
I use a similar approach but instead of spending time calculating out the last output length, etc,

I simply use ANSI code escapes to move back to the beginning of the line and then clear that entire line before printing my current status output.

import sys

class Printer():
    """Print things to stdout on one line dynamically"""
    def __init__(self,data):
        sys.stdout.write("\r\x1b[K"+data.__str__())
        sys.stdout.flush()

To use in your iteration loop you would just call something like:

x = 1
for f in fileList:
    ProcessFile(f)
    output = "File number %d completed." % x
    Printer(output)
    x += 1   

See more here


回答 4

您可以在打印语句中添加尾随逗号,以在每次迭代中打印空格而不是换行符:

print item,

另外,如果您使用的是Python 2.6或更高版本,则可以使用新的打印功能,该功能可以让您指定在要打印的每个项目的末尾甚至都不应该有空格(或者允许您指定要结束的任何位置)想):

from __future__ import print_function
...
print(item, end="")

最后,您可以通过从sys模块导入标准输出直接写入标准输出,该模块返回一个类似文件的对象:

from sys import stdout
...
stdout.write( str(item) )

You can add a trailing comma to your print statement to print a space instead of a newline in each iteration:

print item,

Alternatively, if you’re using Python 2.6 or later, you can use the new print function, which would allow you to specify that not even a space should come at the end of each item being printed (or allow you to specify whatever end you want):

from __future__ import print_function
...
print(item, end="")

Finally, you can write directly to standard output by importing it from the sys module, which returns a file-like object:

from sys import stdout
...
stdout.write( str(item) )

回答 5

更改

print item

print "\033[K", item, "\r",
sys.stdout.flush()
  • “ \ 033 [K”清除到行尾
  • \ r,返回到行的开头
  • flush语句确保它立即显示,以便您获得实时输出。

change

print item

to

print "\033[K", item, "\r",
sys.stdout.flush()
  • “\033[K” clears to the end of the line
  • the \r, returns to the beginning of the line
  • the flush statement makes sure it shows up immediately so you get real-time output.

回答 6

我认为一个简单的连接应该起作用:

nl = []
for x in range(1,10):nl.append(str(x))
print ' '.join(nl)

I think a simple join should work:

nl = []
for x in range(1,10):nl.append(str(x))
print ' '.join(nl)

回答 7

我在2.7上使用的另一个答案是仅打印“。”。每次循环运行(向用户表明事情还在运行)是这样的:

print "\b.",

打印“。” 每个字符之间没有空格。看起来更好一点,并且效果很好。\ b是那些想知道的退格字符。

Another answer that I’m using on 2.7 where I’m just printing out a “.” every time a loop runs (to indicate to the user that things are still running) is this:

print "\b.",

It prints the “.” characters without spaces between each. It looks a little better and works pretty well. The \b is a backspace character for those wondering.


回答 8

这么多复杂的答案。如果您拥有python 3,只需将其放在\r打印开始处,然后添加end='', flush=True到其中:

import time

for i in range(10):
    print(f'\r{i} foo bar', end='', flush=True)
    time.sleep(0.5)

这将原位写入0 foo bar,然后1 foo bar依此类推。

So many complicated answers. If you have python 3, simply put \r at the start of the print, and add end='', flush=True to it:

import time

for i in range(10):
    print(f'\r{i} foo bar', end='', flush=True)
    time.sleep(0.5)

This will write 0 foo bar, then 1 foo bar etc, in-place.


回答 9

要使数字彼此覆盖,可以执行以下操作:

for i in range(1,100):
    print "\r",i,

只要在第一列中打印该数字,它就应该起作用。

编辑:这是一个即使没有在第一栏中打印也可以使用的版本。

prev_digits = -1
for i in range(0,1000):
    print("%s%d" % ("\b"*(prev_digits + 1), i)),
    prev_digits = len(str(i))

我应该注意,此代码已经过测试,并且可以在Windows的Windows 2.5的WIndows控制台中正常运行。根据另一些说法,可能需要刷新stdout才能看到结果。YMMV。

To make the numbers overwrite each other, you can do something like this:

for i in range(1,100):
    print "\r",i,

That should work as long as the number is printed in the first column.

EDIT: Here’s a version that will work even if it isn’t printed in the first column.

prev_digits = -1
for i in range(0,1000):
    print("%s%d" % ("\b"*(prev_digits + 1), i)),
    prev_digits = len(str(i))

I should note that this code was tested and works just fine in Python 2.5 on Windows, in the WIndows console. According to some others, flushing of stdout may be required to see the results. YMMV.


回答 10

“顺便说一下……如何每次都刷新它,以便它在一个地方打印mi只需更改数字即可。”

这确实是一个棘手的话题。什么扎克建议(输出控制台控制代码)是实现这一目标的方法之一。

您可以使用(n)个curses,但这主要适用于* nixes。

在Windows上(这是有趣的部分),它很少被提及(我不明白为什么),您可以将Python绑定到WinAPI(默认情况下还与ActivePython一起使用http://sourceforge.net/projects/pywin32/)-它不是努力工作,效果很好。这是一个小例子:

import win32console, time

output_handle = win32console.GetStdHandle(  win32console.STD_OUTPUT_HANDLE )
info = output_handle.GetConsoleScreenBufferInfo()
pos = info["CursorPosition"]

for i in "\\|/-\\|/-":
    output_handle.WriteConsoleOutputCharacter( i, pos )
    time.sleep( 1 )

或者,如果要使用print(语句或函数,没有区别):

import win32console, time

output_handle = win32console.GetStdHandle(  win32console.STD_OUTPUT_HANDLE )
info = output_handle.GetConsoleScreenBufferInfo()
pos = info["CursorPosition"]

for i in "\\|/-\\|/-":
    print i
    output_handle.SetConsoleCursorPosition( pos )
    time.sleep( 1 )

win32console 模块使您可以使用Windows控制台执行更多有趣的事情…我不是WinAPI的忠实拥护者,但是最近我意识到,至少有一半的反对意见是由用C编写WinAPI代码引起的-pythonic绑定是更容易使用。

当然,所有其他答案都是不错的,而且是Python语言的,但是…如果我想在一行中打印怎么办?还是写多行文本,而不是清除并重新写相同的行?我的解决方案使这成为可能。

“By the way…… How to refresh it every time so it print mi in one place just change the number.”

It’s really tricky topic. What zack suggested ( outputting console control codes ) is one way to achieve that.

You can use (n)curses, but that works mainly on *nixes.

On Windows (and here goes interesting part) which is rarely mentioned (I can’t understand why) you can use Python bindings to WinAPI (http://sourceforge.net/projects/pywin32/ also with ActivePython by default) – it’s not that hard and works well. Here’s a small example:

import win32console, time

output_handle = win32console.GetStdHandle(  win32console.STD_OUTPUT_HANDLE )
info = output_handle.GetConsoleScreenBufferInfo()
pos = info["CursorPosition"]

for i in "\\|/-\\|/-":
    output_handle.WriteConsoleOutputCharacter( i, pos )
    time.sleep( 1 )

Or, if you want to use print (statement or function, no difference):

import win32console, time

output_handle = win32console.GetStdHandle(  win32console.STD_OUTPUT_HANDLE )
info = output_handle.GetConsoleScreenBufferInfo()
pos = info["CursorPosition"]

for i in "\\|/-\\|/-":
    print i
    output_handle.SetConsoleCursorPosition( pos )
    time.sleep( 1 )

win32console module enables you to do many more interesting things with windows console… I’m not a big fan of WinAPI, but recently I realized that at least half of my antipathy towards it was caused by writing WinAPI code in C – pythonic bindings are much easier to use.

All other answers are great and pythonic, of course, but… What if I wanted to print on previous line? Or write multiline text, than clear it and write the same lines again? My solution makes that possible.


回答 11

对于Python 2.7

for x in range(0, 3):
    print x,

对于Python 3

for x in range(0, 3):
    print(x, end=" ")

for Python 2.7

for x in range(0, 3):
    print x,

for Python 3

for x in range(0, 3):
    print(x, end=" ")

回答 12

In [9]: print?
Type:           builtin_function_or_method
Base Class:     <type 'builtin_function_or_method'>
String Form:    <built-in function print>
Namespace:      Python builtin
Docstring:
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep:  string inserted between values, default a space.
end:  string appended after the last value, default a newline.
In [9]: print?
Type:           builtin_function_or_method
Base Class:     <type 'builtin_function_or_method'>
String Form:    <built-in function print>
Namespace:      Python builtin
Docstring:
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep:  string inserted between values, default a space.
end:  string appended after the last value, default a newline.

回答 13

如果只想打印数字,则可以避免循环。

# python 3
import time

startnumber = 1
endnumber = 100

# solution A without a for loop
start_time = time.clock()
m = map(str, range(startnumber, endnumber + 1))
print(' '.join(m))
end_time = time.clock()
timetaken = (end_time - start_time) * 1000
print('took {0}ms\n'.format(timetaken))

# solution B: with a for loop
start_time = time.clock()
for i in range(startnumber, endnumber + 1):
    print(i, end=' ')
end_time = time.clock()
timetaken = (end_time - start_time) * 1000
print('\ntook {0}ms\n'.format(timetaken))

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100花费21.1986929975ms

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100花费491.466823551ms

If you just want to print the numbers, you can avoid the loop.

# python 3
import time

startnumber = 1
endnumber = 100

# solution A without a for loop
start_time = time.clock()
m = map(str, range(startnumber, endnumber + 1))
print(' '.join(m))
end_time = time.clock()
timetaken = (end_time - start_time) * 1000
print('took {0}ms\n'.format(timetaken))

# solution B: with a for loop
start_time = time.clock()
for i in range(startnumber, endnumber + 1):
    print(i, end=' ')
end_time = time.clock()
timetaken = (end_time - start_time) * 1000
print('\ntook {0}ms\n'.format(timetaken))

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 took 21.1986929975ms

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 took 491.466823551ms


回答 14

最好的方法是使用 \r角色

只需尝试以下代码:

import time
for n in range(500):
  print(n, end='\r')
  time.sleep(0.01)
print()  # start new line so most recently printed number stays

The best way to accomplish this is to use the \r character

Just try the below code:

import time
for n in range(500):
  print(n, end='\r')
  time.sleep(0.01)
print()  # start new line so most recently printed number stays

回答 15

在Python 3中,您可以这样操作:

for item in range(1,10):
    print(item, end =" ")

输出:

1 2 3 4 5 6 7 8 9 

元组:您可以对元组执行相同的操作:

tup = (1,2,3,4,5)

for n in tup:
    print(n, end = " - ")

输出:

1 - 2 - 3 - 4 - 5 - 

另一个例子:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
for item in list_of_tuples:
    print(item)

输出:

(1, 2)
('A', 'B')
(3, 4)
('Cat', 'Dog')

您甚至可以像这样打开元组的包装:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]

# Tuple unpacking so that you can deal with elements inside of the tuple individually
for (item1, item2) in list_of_tuples:
    print(item1, item2)   

输出:

1 2
A B
3 4
Cat Dog

另一个变化:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
for (item1, item2) in list_of_tuples:
    print(item1)
    print(item2)
    print('\n')

输出:

1
2


A
B


3
4


Cat
Dog

In Python 3 you can do it this way:

for item in range(1,10):
    print(item, end =" ")

Outputs:

1 2 3 4 5 6 7 8 9 

Tuple: You can do the same thing with a tuple:

tup = (1,2,3,4,5)

for n in tup:
    print(n, end = " - ")

Outputs:

1 - 2 - 3 - 4 - 5 - 

Another example:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
for item in list_of_tuples:
    print(item)

Outputs:

(1, 2)
('A', 'B')
(3, 4)
('Cat', 'Dog')

You can even unpack your tuple like this:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]

# Tuple unpacking so that you can deal with elements inside of the tuple individually
for (item1, item2) in list_of_tuples:
    print(item1, item2)   

Outputs:

1 2
A B
3 4
Cat Dog

another variation:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
for (item1, item2) in list_of_tuples:
    print(item1)
    print(item2)
    print('\n')

Outputs:

1
2


A
B


3
4


Cat
Dog

回答 16

打印语句末尾的逗号会省略新行。

for i in xrange(1,100):
  print i,

但这不会覆盖。

A comma at the end of the print statement omits the new line.

for i in xrange(1,100):
  print i,

but this does not overwrite.


回答 17

对于那些像我一样挣扎的人,我想出了以下似乎在python 3.7.4和3.5.2中都适用的代码。

我将范围从100扩展到1,000,000,因为它运行非常快,您可能看不到输出。这是因为设置的一个副作用end='\r'是最终循环迭代会清除所有输出。需要更长的数量才能证明其有效。此结果可能并非在所有情况下都令人满意,但在我的情况下还不错,并且OP没有指定一种方法或另一种方法。您可以使用if语句来评估要迭代的数组的长度,从而避免这种情况。在我的案例中,使其工作的关键是将方括号"{}".format()。否则,它不会起作用。

以下应按原样工作:

#!/usr/bin/env python3

for item in range(1,1000000):
    print("{}".format(item), end='\r', flush=True)

For those struggling as I did, I came up with the following that appears to work in both python 3.7.4 and 3.5.2.

I expanded the range from 100 to 1,000,000 because it runs very fast and you may not see the output. This is because one side effect of setting end='\r' is that the final loop iteration clears all of the output. A longer number was needed to demonstrate that it works. This result may not be desirable in all cases, but was fine in mine, and OP didn’t specify one way or another. You could potentially circumvent this with an if statement that evaluates the length of the array being iterated over, etc. The key to get it working in my case was to couple the brackets "{}" with .format(). Otherwise, it didn’t work.

Below should work as-is:

#!/usr/bin/env python3

for item in range(1,1000000):
    print("{}".format(item), end='\r', flush=True)

回答 18

for item in range(1,100):
    if item==99:
        print(item,end='')
    else:
        print (item,end=',')

输出:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24, 25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49, 50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74, 75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99

for item in range(1,100):
    if item==99:
        print(item,end='')
    else:
        print (item,end=',')

Output: 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99


回答 19

或更简单:

import time
a = 0
while True:
    print (a, end="\r")
    a += 1
    time.sleep(0.1)

end="\r" 从第一张打印的开始[0:]开始覆盖。

Or even simpler:

import time
a = 0
while True:
    print (a, end="\r")
    a += 1
    time.sleep(0.1)

end="\r" will overwrite from the beginning [0:] of the first print.


sys.stdout.write和print之间的区别?

问题:sys.stdout.write和print之间的区别?

在某些情况下 sys.stdout.write()更好的print

示例:更好的性能;更有意义的代码)

Are there situations in which sys.stdout.write() is preferable to print?

(Examples: better performance; code that makes more sense)


回答 0

print只是一个薄包装器,用于格式化输入(可修改,但默认情况下在args和换行符之间使用空格),并调用给定对象的write函数。默认情况下,此对象为sys.stdout,但是您可以使用“雪佛龙”格式传递文件。例如:

print >> open('file.txt', 'w'), 'Hello', 'World', 2+3

参见:https : //docs.python.org/2/reference/simple_stmts.html?highlight=print#the-print-statement


在Python 3.x中,print成为一个功能,但它仍然有可能通过比其他一些sys.stdout感谢file的说法。

print('Hello', 'World', 2+3, file=open('file.txt', 'w'))

参见https://docs.python.org/3/library/functions.html#print


在Python 2.6+中,print它仍然是一条语句,但可以将其用作

from __future__ import print_function

更新:Bakuriu指出要指出,print函数和print语句之间(并且更一般地,函数和语句之间)存在很小的差异。

评估参数时出现错误:

print "something", 1/0, "other" #prints only something because 1/0 raise an Exception

print("something", 1/0, "other") #doesn't print anything. The function is not called

print is just a thin wrapper that formats the inputs (modifiable, but by default with a space between args and newline at the end) and calls the write function of a given object. By default this object is sys.stdout, but you can pass a file using the “chevron” form. For example:

print >> open('file.txt', 'w'), 'Hello', 'World', 2+3

See: https://docs.python.org/2/reference/simple_stmts.html?highlight=print#the-print-statement


In Python 3.x, print becomes a function, but it is still possible to pass something other than sys.stdout thanks to the fileargument.

print('Hello', 'World', 2+3, file=open('file.txt', 'w'))

See https://docs.python.org/3/library/functions.html#print


In Python 2.6+, print is still a statement, but it can be used as a function with

from __future__ import print_function

Update: Bakuriu commented to point out that there is a small difference between the print function and the print statement (and more generally between a function and a statement).

In case of an error when evaluating arguments:

print "something", 1/0, "other" #prints only something because 1/0 raise an Exception

print("something", 1/0, "other") #doesn't print anything. The function is not called

回答 1

print首先将对象转换为字符串(如果还不是字符串)。如果它不是行的开头,而不是换行符,它将在对象之前放置一个空格。

使用时 stdout,您需要自己将对象转换为字符串(例如,通过调用“ str”),并且没有换行符。

所以

print 99

等效于:

import sys
sys.stdout.write(str(99) + '\n')

print first converts the object to a string (if it is not already a string). It will also put a space before the object if it is not the start of a line and a newline character at the end.

When using stdout, you need to convert the object to a string yourself (by calling “str”, for example) and there is no newline character.

So

print 99

is equivalent to:

import sys
sys.stdout.write(str(99) + '\n')

回答 2

我的问题是,是否存在 sys.stdout.write()print

前几天完成脚本开发后,我将其上传到了UNIX服务器。我所有的调试消息都使用了print语句,但这些语句出现在服务器日志中。

在这种情况下,您可能需要sys.stdout.write代替。

My question is whether or not there are situations in which sys.stdout.write() is preferable to print

After finishing developing a script the other day, I uploaded it to a unix server. All my debug messages used print statements, and these do not appear on a server log.

This is a case where you may need sys.stdout.write instead.


回答 3

这是基于Mark Lutz 的《Learning Python》一书的一些示例代码,它解决了您的问题:

import sys
temp = sys.stdout                 # store original stdout object for later
sys.stdout = open('log.txt', 'w') # redirect all prints to this log file
print("testing123")               # nothing appears at interactive prompt
print("another line")             # again nothing appears. it's written to log file instead
sys.stdout.close()                # ordinary file object
sys.stdout = temp                 # restore print commands to interactive prompt
print("back to normal")           # this shows up in the interactive prompt

在文本编辑器中打开log.txt将显示以下内容:

testing123
another line

Here’s some sample code based on the book Learning Python by Mark Lutz that addresses your question:

import sys
temp = sys.stdout                 # store original stdout object for later
sys.stdout = open('log.txt', 'w') # redirect all prints to this log file
print("testing123")               # nothing appears at interactive prompt
print("another line")             # again nothing appears. it's written to log file instead
sys.stdout.close()                # ordinary file object
sys.stdout = temp                 # restore print commands to interactive prompt
print("back to normal")           # this shows up in the interactive prompt

Opening log.txt in a text editor will reveal the following:

testing123
another line

回答 4

至少有一种情况需要sys.stdout打印而不是打印。

如果您想覆盖一行而不转到下一行,例如在绘制进度条或状态消息时,则需要遍历以下内容

Note carriage return-> "\rMy Status Message: %s" % progress

而且由于print添加了换行符,因此最好使用sys.stdout

There’s at least one situation in which you want sys.stdout instead of print.

When you want to overwrite a line without going to the next line, for instance while drawing a progress bar or a status message, you need to loop over something like

Note carriage return-> "\rMy Status Message: %s" % progress

And since print adds a newline, you are better off using sys.stdout.


回答 5

我的问题是,是否存在sys.stdout.write()print

如果您正在编写一个可以同时写入文件和stdout的命令行应用程序,那么它将非常方便。您可以执行以下操作:

def myfunc(outfile=None):
    if outfile is None:
        out = sys.stdout
    else:
        out = open(outfile, 'w')
    try:
        # do some stuff
        out.write(mytext + '\n')
        # ...
    finally:
        if outfile is not None:
            out.close()

这确实意味着您无法使用该with open(outfile, 'w') as out:模式,但有时值得。

My question is whether or not there are situations in which sys.stdout.write() is preferable to print

If you’re writing a command line application that can write to both files and stdout then it is handy. You can do things like:

def myfunc(outfile=None):
    if outfile is None:
        out = sys.stdout
    else:
        out = open(outfile, 'w')
    try:
        # do some stuff
        out.write(mytext + '\n')
        # ...
    finally:
        if outfile is not None:
            out.close()

It does mean you can’t use the with open(outfile, 'w') as out: pattern, but sometimes it is worth it.


回答 6

在2.x中,该print语句将对您提供的内容进行预处理,将其转换为字符串,处理分隔符和换行符,并允许重定向至文件。3.x将其转换为功能,但仍具有相同的职责。

sys.stdout 是一个文件或类似文件的文件,具有用于写入文件的方法,该方法沿该行使用字符串或其他内容。

In 2.x, the print statement preprocesses what you give it, turning it into strings along the way, handling separators and newlines, and allowing redirection to a file. 3.x turns it into a function, but it still has the same responsibilities.

sys.stdout is a file or file-like that has methods for writing to it which take strings or something along that line.


回答 7

当动态打印很有用时,例如在较长的过程中提供信息,则最好:

import time, sys
Iterations = 555
for k in range(Iterations+1):
    # some code to execute here ...
    percentage = k / Iterations
    time_msg = "\rRunning Progress at {0:.2%} ".format(percentage)
    sys.stdout.write(time_msg)
    sys.stdout.flush()
    time.sleep(0.01)

it is preferable when dynamic printing is useful, for instance, to give information in a long process:

import time, sys
Iterations = 555
for k in range(Iterations+1):
    # some code to execute here ...
    percentage = k / Iterations
    time_msg = "\rRunning Progress at {0:.2%} ".format(percentage)
    sys.stdout.write(time_msg)
    sys.stdout.flush()
    time.sleep(0.01)

回答 8

>>> sys.stdout.write(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected a string or other character buffer object
>>> sys.stdout.write("a")
a>>> sys.stdout.write("a") ; print(1)
a1

观察上面的示例:

  1. sys.stdout.write不会写非字符串对象,但是print

  2. sys.stdout.write不会在结尾处添加一个新行标志,但print

如果我们深入潜水,

sys.stdout 是一个文件对象,可用于输出print()

如果print()未指定的文件参数,sys.stdout则将使用

>>> sys.stdout.write(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected a string or other character buffer object
>>> sys.stdout.write("a")
a>>> sys.stdout.write("a") ; print(1)
a1

Observing the example above:

  1. sys.stdout.write won’t write non-string object, but print will

  2. sys.stdout.write won’t add a new line symbol in the end, but print will

If we dive deeply,

sys.stdout is a file object which can be used for the output of print()

if file argument of print() is not specified, sys.stdout will be used


回答 9

在某些情况下,sys.stdout.write()更适合打印吗?

例如,我正在研究一个小的函数,该函数在将数字作为参数传递时以金字塔格式打印星星,尽管您可以使用end =“”在单独的行中打印来完成此操作,但我使用sys.stdout.write来进行协调与印刷使这项工作。要详细说明此stdout.write,请在同一行中打印,因为print总是在单独的行中打印其内容。

import sys

def printstars(count):

    if count >= 1:
        i = 1
        while (i <= count):
            x=0
            while(x<i):
                sys.stdout.write('*')
                x = x+1
            print('')
            i=i+1

printstars(5)

Are there situations in which sys.stdout.write() is preferable to print?

For example I’m working on small function which prints stars in pyramid format upon passing the number as argument, although you can accomplish this using end=”” to print in a separate line, I used sys.stdout.write in co-ordination with print to make this work. To elaborate on this stdout.write prints in the same line where as print always prints its contents in a separate line.

import sys

def printstars(count):

    if count >= 1:
        i = 1
        while (i <= count):
            x=0
            while(x<i):
                sys.stdout.write('*')
                x = x+1
            print('')
            i=i+1

printstars(5)

回答 10

在某些情况下,sys.stdout.write()更适合打印吗?

我发现在多线程情况下stdout比打印效果更好。我使用队列(FIFO)存储要打印的行,并且在打印行之前保留所有线程,直到我的打印Q为空。即使这样,使用print有时也会在调试I / O上丢失最后的\ n(使用wing pro IDE)。

当我在字符串中使用\ n的std.out时,调试I / O格式正确,并且\ n正确显示。

Are there situations in which sys.stdout.write() is preferable to print?

I have found that stdout works better than print in a multithreading situation. I use Queue (FIFO) to store the lines to print and I hold all threads before the print line until my print Q is empty. Even so, using print I sometimes lose the final \n on the debug I/O (using wing pro IDE).

When I use std.out with \n in the string the debug I/O formats correctly and the \n’s are accurately displayed.


回答 11

在Python 3中,有使用print over的正当理由sys.stdout.write,但是这个原因也可以转化为使用原因sys.stdout.write

这是因为,现在print是Python 3中的一个函数,您可以重写它。因此,您可以在简单的脚本中的任何地方使用print,并确定需要写入的那些print语句stderr。现在,您可以重新定义打印功能,甚至可以通过使用内置模块来更改打印功能来全局更改它。当然,file.write您可以指定什么文件,但是通过覆盖打印,您还可以重新定义行分隔符或参数分隔符。

另一种方法是。也许您绝对确定要写信给stdout,但也知道要将print更改为其他内容,可以决定使用sys.stdout.write,并将print用于错误日志或其他内容。

因此,您使用什么取决于您打算如何使用它。print更加灵活,但这可能是使用和不使用它的原因。我仍然会选择灵活性,然后选择打印。print代替使用的另一个原因是熟悉度。现在,更多的人会通过印刷品了解您的意思,而很少了解sys.stdout.write

In Python 3 there is valid reason to use print over sys.stdout.write, but this reason can also be turned into a reason to use sys.stdout.write instead.

This reason is that, now print is a function in Python 3, you can override this. So you can use print everywhere in a simple script and decide those print statements need to write to stderr instead. You can now just redefine the print function, you could even change the print function global by changing it using the builtins module. Off course with file.write you can specify what file is, but with overwriting print you can also redefine the line separator, or argument separator.

The other way around is. Maybe you are absolutely certain you write to stdout, but also know you are going to change print to something else, you can decide to use sys.stdout.write, and use print for error log or something else.

So, what you use depends on how you intend to use it. print is more flexible, but that can be a reason to use and to not use it. I would still opt for flexibility instead, and choose print. Another reason to use print instead is familiarity. More people will now what you mean by print and less know sys.stdout.write.


回答 12

尝试将字节打印成十六进制外观时,以下区别之一是。例如,我们知道,十进制值的2550xFF十六进制的外观:

val = '{:02x}'.format(255) 

sys.stdout.write(val) # prints ff2
print(val)            # prints ff

One of the difference is the following, when trying to print a byte into its hexadecimal appearance. For example, we know that decimal value of 255 is 0xFF in hexadecimal appearance:

val = '{:02x}'.format(255) 

sys.stdout.write(val) # prints ff2
print(val)            # prints ff

回答 13

在python 2中,如果您需要传递函数,则可以将os.sys.stdout.write分配给变量,则不能(在repl中)使用print进行此操作。

>import os
>>> cmd=os.sys.stdout.write
>>> cmd('hello')
hello>>> 

那按预期工作。

>>> cmd=print
  File "<stdin>", line 1
    cmd=print
            ^
SyntaxError: invalid syntax

那行不通。打印是一种神奇的功能。

In python 2 if you need to pass around a function then you can assign os.sys.stdout.write to a variable, you cannot do this (in the repl) with print.

>import os
>>> cmd=os.sys.stdout.write
>>> cmd('hello')
hello>>> 

That works as expected.

>>> cmd=print
  File "<stdin>", line 1
    cmd=print
            ^
SyntaxError: invalid syntax

That does not work. print is a magical function.


回答 14

在Python 3中要指出的print和之间的区别sys.stdout.write也是在终端中执行时返回的值。在Python 3中,sys.stdout.write返回字符串的长度,而print仅返回None

因此,例如,在终端中以交互方式运行以下代码将打印出字符串,然后打印其长度,因为在交互运行时将返回并输出长度:

>>> sys.stdout.write(" hi ")
 hi 4

A difference between print and sys.stdout.write to point out in Python 3, is also the value which is returned when executed in terminal. In Python 3 sys.stdout.write returns the lenght of the string whereas print returns just None.

So for example running following code interactively in the terminal would print out the string followed by its lenght, since the lenght is returned and outputed when run interactively:

>>> sys.stdout.write(" hi ")
 hi 4

如何扩展输出显示以查看pandas DataFrame的更多列?

问题:如何扩展输出显示以查看pandas DataFrame的更多列?

有没有办法在交互式或脚本执行模式下扩大输出的显示?

具体来说,我describe()在pandas上使用该功能DataFrame。当DataFrame5列(标签)宽时,我得到了所需的描述性统计信息。但是,如果DataFrame具有更多列,则统计信息将被抑制,并返回如下所示的内容:

>> Index: 8 entries, count to max  
>> Data columns:  
>> x1          8  non-null values  
>> x2          8  non-null values  
>> x3          8  non-null values  
>> x4          8  non-null values  
>> x5          8  non-null values  
>> x6          8  non-null values  
>> x7          8  non-null values  

无论是6列还是7列,都会给出“ 8”值。“ 8”是什么意思?

我已经尝试过将IDLE窗口拖动更大,并增加“ Configure IDLE”宽度选项,但无济于事。

我使用熊猫的目的describe()是避免使用诸如Stata之类的第二个程序来进行基本的数据操作和调查。

Is there a way to widen the display of output in either interactive or script-execution mode?

Specifically, I am using the describe() function on a pandas DataFrame. When the DataFrame is 5 columns (labels) wide, I get the descriptive statistics that I want. However, if the DataFrame has any more columns, the statistics are suppressed and something like this is returned:

>> Index: 8 entries, count to max  
>> Data columns:  
>> x1          8  non-null values  
>> x2          8  non-null values  
>> x3          8  non-null values  
>> x4          8  non-null values  
>> x5          8  non-null values  
>> x6          8  non-null values  
>> x7          8  non-null values  

The “8” value is given whether there are 6 or 7 columns. What does the “8” refer to?

I have already tried dragging the IDLE window larger, as well as increasing the “Configure IDLE” width options, to no avail.

My purpose in using pandas and describe() is to avoid using a second program like Stata to do basic data manipulation and investigation.


回答 0

更新:熊猫0.23.4起

这不是必须的,如果设置,pandas会自动检测终端窗口的大小pd.options.display.width = 0。(有关较旧的版本,请参阅底部。)

pandas.set_printoptions(...)不推荐使用。而是使用pandas.set_option(optname, val)或等效地pd.options.<opt.hierarchical.name> = val。喜欢:

import pandas as pd
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

这是帮助set_option

set_option(pat,value)-设置指定选项的值

可用选项:
显示。[chop_threshold,colheader_justify,column_space,date_dayfirst,
         date_yearfirst,编码,expand_frame_repr,float_format,高度,
         line_width,max_columns,max_colwidth,max_info_columns,max_info_rows,
         max_rows,max_seq_items,mpl_style,multi_sparse,notebook_repr_html,
         pprint_nest_depth,精度,宽度]
模式。[sim_interactive,use_inf_as_null]

参量
----------
pat-str / regexp,应与单个选项匹配。

注意:为方便起见,支持部分匹配,但除非您使用
完整的选项名称(egxyzoption_name),将来您的代码可能会中断
版本,如果引入了具有相似名称的新选项。

value-期权的新价值。

退货
-------
没有

加薪
------
如果没有这样的选项,则为KeyError

display.chop_threshold:[默认:无] [当前:无]
:浮动或无
        如果设置为浮点值,则所有浮点值均小于给定阈值
        将由repr和朋友显示为正好为0。
display.colheader_justify:[默认:正确] [当前:正确]
: '左右'
        控制列标题的对正。由DataFrameFormatter使用。
display.column_space:[默认值:12] [当前:12]无可用描述。

display.date_dayfirst:[默认:False] [当前:False]
:布尔值
        如果为True,则打印和解析日期的日期为第一天,例如20/01/2005
display.date_yearfirst:[默认:False] [当前:False]
:布尔值
        如果为True,则打印和解析日期以年份为第一,例如2005/01/20
display.encoding:[默认:UTF-8] [当前:UTF-8]
:str / unicode
        默认为检测到的控制台编码。
        指定用于to_string返回的字符串的编码,
        这些通常是要在控制台上显示的字符串。
display.expand_frame_repr:[默认:True] [当前:True]
:布尔值
        是否为宽数据框打印完整的数据框代表
        跨多行,`max_columns`仍然受到尊重,但是输出将
        如果宽度超过“ display.width”,则跨多个“页面”进行环绕。
display.float_format:[默认:无] [当前:无]
:可调用
        可调用对象应接受浮点数并返回
        具有所需数字格式的字符串。这用
        在某些地方,例如SeriesFormatter。
        有关示例,请参见core.format.EngFormatter。
display.height:[默认值:60] [当前:1000]
:int
        不推荐使用。
        (已弃用,请改用display.height。)

display.line_width:[默认值:80] [当前:1000]
:int
        不推荐使用。
        (已弃用,请改用display.width。)

display.max_columns:[默认:20] [当前:500]
:int
        在__repr __()方法中使用max_rows和max_columns来确定是否
        to_string()或info()用于将对象呈现为字符串。如果
        python / IPython在终端中运行,可以将其设置为0和pandas
        将正确地自动检测终端的宽度并交换为较小的宽度
        格式,以防所有列都不能垂直放置。IPython笔记本,
        IPython qtconsole或IDLE不在终端中运行,因此它不是
        可以进行正确的自动检测。
        “无”值意味着无限。
display.max_colwidth:[默认:50] [当前:50]
:int
        列的最大宽度(以字符为单位)
        大熊猫数据结构。当列溢出时,会出现一个“ ...”
        占位符嵌入在输出中。
display.max_info_columns:[默认:100] [当前:100]
:int
        在DataFrame.info方法中使用max_info_columns来确定是否
        每列信息将被打印。
display.max_info_rows:[默认:1690785] [当前:1690785]
:int或无
        max_info_rows是一帧将要进行的最大行数
        重新进入控制台时,对其列执行null检查。
        默认值为1,000,000行。因此,如果DataFrame具有更多
        1,000,000行将不会对
        列,因此表示将花费更少的时间
        在互动会话中显示。值None表示总是
        重复时执行空检查。
display.max_rows:[默认:60] [当前:500]
:int
        设置打印时熊猫应输出的最大行数
        各种输出。例如,此值确定是否repr()
        数据框完全打印出来或只是摘要表示。
        “无”值意味着无限。
display.max_seq_items:[默认:无] [当前:无]
:int或无

        漂亮地打印长序列时,不超过`max_seq_items`
        将被打印。如果省略项目,将用加法表示
        “ ...”到结果字符串。

        如果设置为“无”,则要打印的项目数不受限制。
display.mpl_style:[默认:无] [当前:无]
:布尔

        将此设置为“默认”将修改matplotlib使用的rcParams
        默认情况下,为绘图提供更令人愉悦的视觉样式。
        将此设置为None / False会将值恢复为其初始值。
display.multi_sparse:[默认:True] [当前:True]
:布尔值
        “ sparsify” MultiIndex显示(不重复显示
        组内外层的元素)
display.notebook_repr_html:[默认:True] [当前:True]
:布尔值
        如果为True,则IPython Notebook将使用html表示形式
        熊猫对象(如果有)。
display.pprint_nest_depth:[默认值:3] [当前:3]
:int
        控制漂亮打印时要处理的嵌套层数
display.precision:[默认:7] [当前:7]
:int
        浮点输出精度(有效位数)。这是
        只是一个建议
display.width:[默认值:80] [当前:1000]
:int
        显示的宽度(以字符为单位)。如果python / IPython运行在
        可以将其设置为“无”的终端,熊猫会正确自动检测
        宽度。
        请注意,IPython笔记本,IPython qtconsole或IDLE不会在
        终端,因此无法正确检测宽度。
mode.sim_interactive:[默认:False] [当前:False]
:布尔值
        是否为了测试目的而模拟交互模式
mode.use_inf_as_null:[默认:False] [当前:False]
:布尔值
        True表示将None,NaN,INF,-INF视为null(旧方法),
        False表示None和NaN为空,但INF,-INF不为空
        (新方法)。
呼叫def:pd.set_option(self,* args,** kwds)

编辑:较旧的版本信息,其中许多已被弃用。

如@bmu 所述,pandas自动检测(默认情况下)显示区域的大小,当对象代表不适合显示时,将使用摘要视图。您提到了调整“ IDLE”窗口的大小,但没有任何效果。如果可以print df.describe().to_string(),它是否适合于“ IDLE”窗口?

终端大小由pandas.util.terminal.get_terminal_size()(已弃用和移除)确定,这将返回一个包含(width, height)显示内容的元组。输出是否与您的IDLE窗口的大小匹配?可能存在问题(在emacs中运行终端之前有一个问题)。

请注意,可以绕过自动检测,pandas.set_printoptions(max_rows=200, max_columns=10)如果行数,列数不超过给定的限制,则永远不会切换到摘要视图。


“ max_colwidth”选项有助于查看每列的截断形式。

Update: Pandas 0.23.4 onwards

This is not necessary, pandas autodetects the size of your terminal window if you set pd.options.display.width = 0. (For older versions see at bottom.)

pandas.set_printoptions(...) is deprecated. Instead, use pandas.set_option(optname, val), or equivalently pd.options.<opt.hierarchical.name> = val. Like:

import pandas as pd
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

Here is the help for set_option:

set_option(pat,value) - Sets the value of the specified option

Available options:
display.[chop_threshold, colheader_justify, column_space, date_dayfirst,
         date_yearfirst, encoding, expand_frame_repr, float_format, height,
         line_width, max_columns, max_colwidth, max_info_columns, max_info_rows,
         max_rows, max_seq_items, mpl_style, multi_sparse, notebook_repr_html,
         pprint_nest_depth, precision, width]
mode.[sim_interactive, use_inf_as_null]

Parameters
----------
pat - str/regexp which should match a single option.

Note: partial matches are supported for convenience, but unless you use the
full option name (e.g. x.y.z.option_name), your code may break in future
versions if new options with similar names are introduced.

value - new value of option.

Returns
-------
None

Raises
------
KeyError if no such option exists

display.chop_threshold: [default: None] [currently: None]
: float or None
        if set to a float value, all float values smaller then the given threshold
        will be displayed as exactly 0 by repr and friends.
display.colheader_justify: [default: right] [currently: right]
: 'left'/'right'
        Controls the justification of column headers. used by DataFrameFormatter.
display.column_space: [default: 12] [currently: 12]No description available.

display.date_dayfirst: [default: False] [currently: False]
: boolean
        When True, prints and parses dates with the day first, eg 20/01/2005
display.date_yearfirst: [default: False] [currently: False]
: boolean
        When True, prints and parses dates with the year first, eg 2005/01/20
display.encoding: [default: UTF-8] [currently: UTF-8]
: str/unicode
        Defaults to the detected encoding of the console.
        Specifies the encoding to be used for strings returned by to_string,
        these are generally strings meant to be displayed on the console.
display.expand_frame_repr: [default: True] [currently: True]
: boolean
        Whether to print out the full DataFrame repr for wide DataFrames
        across multiple lines, `max_columns` is still respected, but the output will
        wrap-around across multiple "pages" if it's width exceeds `display.width`.
display.float_format: [default: None] [currently: None]
: callable
        The callable should accept a floating point number and return
        a string with the desired format of the number. This is used
        in some places like SeriesFormatter.
        See core.format.EngFormatter for an example.
display.height: [default: 60] [currently: 1000]
: int
        Deprecated.
        (Deprecated, use `display.height` instead.)

display.line_width: [default: 80] [currently: 1000]
: int
        Deprecated.
        (Deprecated, use `display.width` instead.)

display.max_columns: [default: 20] [currently: 500]
: int
        max_rows and max_columns are used in __repr__() methods to decide if
        to_string() or info() is used to render an object to a string.  In case
        python/IPython is running in a terminal this can be set to 0 and pandas
        will correctly auto-detect the width the terminal and swap to a smaller
        format in case all columns would not fit vertically. The IPython notebook,
        IPython qtconsole, or IDLE do not run in a terminal and hence it is not
        possible to do correct auto-detection.
        'None' value means unlimited.
display.max_colwidth: [default: 50] [currently: 50]
: int
        The maximum width in characters of a column in the repr of
        a pandas data structure. When the column overflows, a "..."
        placeholder is embedded in the output.
display.max_info_columns: [default: 100] [currently: 100]
: int
        max_info_columns is used in DataFrame.info method to decide if
        per column information will be printed.
display.max_info_rows: [default: 1690785] [currently: 1690785]
: int or None
        max_info_rows is the maximum number of rows for which a frame will
        perform a null check on its columns when repr'ing To a console.
        The default is 1,000,000 rows. So, if a DataFrame has more
        1,000,000 rows there will be no null check performed on the
        columns and thus the representation will take much less time to
        display in an interactive session. A value of None means always
        perform a null check when repr'ing.
display.max_rows: [default: 60] [currently: 500]
: int
        This sets the maximum number of rows pandas should output when printing
        out various output. For example, this value determines whether the repr()
        for a dataframe prints out fully or just a summary repr.
        'None' value means unlimited.
display.max_seq_items: [default: None] [currently: None]
: int or None

        when pretty-printing a long sequence, no more then `max_seq_items`
        will be printed. If items are ommitted, they will be denoted by the addition
        of "..." to the resulting string.

        If set to None, the number of items to be printed is unlimited.
display.mpl_style: [default: None] [currently: None]
: bool

        Setting this to 'default' will modify the rcParams used by matplotlib
        to give plots a more pleasing visual style by default.
        Setting this to None/False restores the values to their initial value.
display.multi_sparse: [default: True] [currently: True]
: boolean
        "sparsify" MultiIndex display (don't display repeated
        elements in outer levels within groups)
display.notebook_repr_html: [default: True] [currently: True]
: boolean
        When True, IPython notebook will use html representation for
        pandas objects (if it is available).
display.pprint_nest_depth: [default: 3] [currently: 3]
: int
        Controls the number of nested levels to process when pretty-printing
display.precision: [default: 7] [currently: 7]
: int
        Floating point output precision (number of significant digits). This is
        only a suggestion
display.width: [default: 80] [currently: 1000]
: int
        Width of the display in characters. In case python/IPython is running in
        a terminal this can be set to None and pandas will correctly auto-detect the
        width.
        Note that the IPython notebook, IPython qtconsole, or IDLE do not run in a
        terminal and hence it is not possible to correctly detect the width.
mode.sim_interactive: [default: False] [currently: False]
: boolean
        Whether to simulate interactive mode for purposes of testing
mode.use_inf_as_null: [default: False] [currently: False]
: boolean
        True means treat None, NaN, INF, -INF as null (old way),
        False means None and NaN are null, but INF, -INF are not null
        (new way).
Call def:   pd.set_option(self, *args, **kwds)

EDIT: older version information, much of this has been deprecated.

As @bmu mentioned, pandas auto detects (by default) the size of the display area, a summary view will be used when an object repr does not fit on the display. You mentioned resizing the IDLE window, to no effect. If you do print df.describe().to_string() does it fit on the IDLE window?

The terminal size is determined by pandas.util.terminal.get_terminal_size() (deprecated and removed), this returns a tuple containing the (width, height) of the display. Does the output match the size of your IDLE window? There might be an issue (there was one before when running a terminal in emacs).

Note that it is possible to bypass the autodetect, pandas.set_printoptions(max_rows=200, max_columns=10) will never switch to summary view if number of rows, columns does not exceed the given limits.


The ‘max_colwidth’ option helps in seeing untruncated form of each column.


回答 1

尝试这个:

pd.set_option('display.expand_frame_repr', False)

从文档中:

display.expand_frame_repr:布尔值

是否跨多行打印宽数据帧的完整DataFrame repr,仍会考虑max_columns,但是如果宽度超过display.width,则输出将在多个“页面”中回绕。[默认:真] [当前:真]

请参阅:http : //pandas.pydata.org/pandas-docs/stable/generated/pandas.set_option.html

Try this:

pd.set_option('display.expand_frame_repr', False)

From the documentation:

display.expand_frame_repr : boolean

Whether to print out the full DataFrame repr for wide DataFrames across multiple lines, max_columns is still respected, but the output will wrap-around across multiple “pages” if it’s width exceeds display.width. [default: True] [currently: True]

See: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.set_option.html


回答 2

如果要临时设置选项以显示一个大的DataFrame,则可以使用option_context

with pd.option_context('display.max_rows', None, 'display.max_columns', None):
    print (df)

退出with块时,选项值将自动恢复。

If you want to set options temporarily to display one large DataFrame, you can use option_context:

with pd.option_context('display.max_rows', None, 'display.max_columns', None):
    print (df)

Option values are restored automatically when you exit the with block.


回答 3

仅使用以下3行对我有用:

pd.set_option('display.max_columns', None)  
pd.set_option('display.expand_frame_repr', False)
pd.set_option('max_colwidth', -1)

Anaconda / Python 3.6.5 /熊猫:0.23.0 / Visual Studio Code 1.26

Only using these 3 lines worked for me:

pd.set_option('display.max_columns', None)  
pd.set_option('display.expand_frame_repr', False)
pd.set_option('max_colwidth', -1)

Anaconda / Python 3.6.5 / pandas: 0.23.0 / Visual Studio Code 1.26


回答 4

使用以下方法设置列的最大宽度:

pd.set_option('max_colwidth', 800)

该特定语句将每列的最大宽度设置为800px。

Set column max width using:

pd.set_option('max_colwidth', 800)

This particular statement sets max width to 800px, per column.


回答 5

您可以使用print df.describe().to_string()它来强制显示整个表格。(您可以to_string()对任何DataFrame像这样使用。结果describe只是一个DataFrame本身。)

8是保存“描述”的DataFrame中的行数(因为describe计算8个统计信息,最小值,最大值,平均值等)。

You can use print df.describe().to_string() to force it to show the whole table. (You can use to_string() like this for any DataFrame. The result of describe is just a DataFrame itself.)

The 8 is the number of rows in the DataFrame holding the “description” (because describe computes 8 statistics, min, max, mean, etc.).


回答 6

您可以使用调整熊猫打印选项set_printoptions

In [3]: df.describe()
Out[3]: 
<class 'pandas.core.frame.DataFrame'>
Index: 8 entries, count to max
Data columns:
x1    8  non-null values
x2    8  non-null values
x3    8  non-null values
x4    8  non-null values
x5    8  non-null values
x6    8  non-null values
x7    8  non-null values
dtypes: float64(7)

In [4]: pd.set_printoptions(precision=2)

In [5]: df.describe()
Out[5]: 
            x1       x2       x3       x4       x5       x6       x7
count      8.0      8.0      8.0      8.0      8.0      8.0      8.0
mean   69024.5  69025.5  69026.5  69027.5  69028.5  69029.5  69030.5
std       17.1     17.1     17.1     17.1     17.1     17.1     17.1
min    69000.0  69001.0  69002.0  69003.0  69004.0  69005.0  69006.0
25%    69012.2  69013.2  69014.2  69015.2  69016.2  69017.2  69018.2
50%    69024.5  69025.5  69026.5  69027.5  69028.5  69029.5  69030.5
75%    69036.8  69037.8  69038.8  69039.8  69040.8  69041.8  69042.8
max    69049.0  69050.0  69051.0  69052.0  69053.0  69054.0  69055.0

但是,这并不是在所有情况下都可行,因为熊猫会检测到您的控制台宽度,并且仅to_string在输出适合控制台时才使用(请参阅的文档字符串set_printoptions)。在这种情况下,你可以显式调用to_string由作为回答BrenBarn

更新资料

对于0.10版,更改了宽数据帧的打印方式:

In [3]: df.describe()
Out[3]: 
                 x1            x2            x3            x4            x5  \
count      8.000000      8.000000      8.000000      8.000000      8.000000   
mean   59832.361578  27356.711336  49317.281222  51214.837838  51254.839690   
std    22600.723536  26867.192716  28071.737509  21012.422793  33831.515761   
min    31906.695474   1648.359160     56.378115  16278.322271     43.745574   
25%    45264.625201  12799.540572  41429.628749  40374.273582  29789.643875   
50%    56340.214856  18666.456293  51995.661512  54894.562656  47667.684422   
75%    75587.003417  31375.610322  61069.190523  67811.893435  76014.884048   
max    98136.474782  84544.484627  91743.983895  75154.587156  99012.695717   

                 x6            x7  
count      8.000000      8.000000  
mean   41863.000717  33950.235126  
std    38709.468281  29075.745673  
min     3590.990740   1833.464154  
25%    15145.759625   6879.523949  
50%    22139.243042  33706.029946  
75%    72038.983496  51449.893980  
max    98601.190488  83309.051963  

进一步更改了用于设置熊猫选项的API:

In [4]: pd.set_option('display.precision', 2)

In [5]: df.describe()
Out[5]: 
            x1       x2       x3       x4       x5       x6       x7
count      8.0      8.0      8.0      8.0      8.0      8.0      8.0
mean   59832.4  27356.7  49317.3  51214.8  51254.8  41863.0  33950.2
std    22600.7  26867.2  28071.7  21012.4  33831.5  38709.5  29075.7
min    31906.7   1648.4     56.4  16278.3     43.7   3591.0   1833.5
25%    45264.6  12799.5  41429.6  40374.3  29789.6  15145.8   6879.5
50%    56340.2  18666.5  51995.7  54894.6  47667.7  22139.2  33706.0
75%    75587.0  31375.6  61069.2  67811.9  76014.9  72039.0  51449.9
max    98136.5  84544.5  91744.0  75154.6  99012.7  98601.2  83309.1

You can adjust pandas print options with set_printoptions.

In [3]: df.describe()
Out[3]: 
<class 'pandas.core.frame.DataFrame'>
Index: 8 entries, count to max
Data columns:
x1    8  non-null values
x2    8  non-null values
x3    8  non-null values
x4    8  non-null values
x5    8  non-null values
x6    8  non-null values
x7    8  non-null values
dtypes: float64(7)

In [4]: pd.set_printoptions(precision=2)

In [5]: df.describe()
Out[5]: 
            x1       x2       x3       x4       x5       x6       x7
count      8.0      8.0      8.0      8.0      8.0      8.0      8.0
mean   69024.5  69025.5  69026.5  69027.5  69028.5  69029.5  69030.5
std       17.1     17.1     17.1     17.1     17.1     17.1     17.1
min    69000.0  69001.0  69002.0  69003.0  69004.0  69005.0  69006.0
25%    69012.2  69013.2  69014.2  69015.2  69016.2  69017.2  69018.2
50%    69024.5  69025.5  69026.5  69027.5  69028.5  69029.5  69030.5
75%    69036.8  69037.8  69038.8  69039.8  69040.8  69041.8  69042.8
max    69049.0  69050.0  69051.0  69052.0  69053.0  69054.0  69055.0

However this will not work in all cases as pandas detects your console width and it will only use to_string if the output fits in the console (see the docstring of set_printoptions). In this case you can explicitly call to_string as answered by BrenBarn.

Update

With version 0.10 the way wide dataframes are printed changed:

In [3]: df.describe()
Out[3]: 
                 x1            x2            x3            x4            x5  \
count      8.000000      8.000000      8.000000      8.000000      8.000000   
mean   59832.361578  27356.711336  49317.281222  51214.837838  51254.839690   
std    22600.723536  26867.192716  28071.737509  21012.422793  33831.515761   
min    31906.695474   1648.359160     56.378115  16278.322271     43.745574   
25%    45264.625201  12799.540572  41429.628749  40374.273582  29789.643875   
50%    56340.214856  18666.456293  51995.661512  54894.562656  47667.684422   
75%    75587.003417  31375.610322  61069.190523  67811.893435  76014.884048   
max    98136.474782  84544.484627  91743.983895  75154.587156  99012.695717   

                 x6            x7  
count      8.000000      8.000000  
mean   41863.000717  33950.235126  
std    38709.468281  29075.745673  
min     3590.990740   1833.464154  
25%    15145.759625   6879.523949  
50%    22139.243042  33706.029946  
75%    72038.983496  51449.893980  
max    98601.190488  83309.051963  

Further more the API for setting pandas options changed:

In [4]: pd.set_option('display.precision', 2)

In [5]: df.describe()
Out[5]: 
            x1       x2       x3       x4       x5       x6       x7
count      8.0      8.0      8.0      8.0      8.0      8.0      8.0
mean   59832.4  27356.7  49317.3  51214.8  51254.8  41863.0  33950.2
std    22600.7  26867.2  28071.7  21012.4  33831.5  38709.5  29075.7
min    31906.7   1648.4     56.4  16278.3     43.7   3591.0   1833.5
25%    45264.6  12799.5  41429.6  40374.3  29789.6  15145.8   6879.5
50%    56340.2  18666.5  51995.7  54894.6  47667.7  22139.2  33706.0
75%    75587.0  31375.6  61069.2  67811.9  76014.9  72039.0  51449.9
max    98136.5  84544.5  91744.0  75154.6  99012.7  98601.2  83309.1

回答 7

您可以设置输出显示以匹配您当前的端子宽度:

pd.set_option('display.width', pd.util.terminal.get_terminal_size()[0])

You can set the output display to match your current terminal width:

pd.set_option('display.width', pd.util.terminal.get_terminal_size()[0])

回答 8

根据v0.18.0文档,如果您在终端机(即非iPython笔记本电脑,qtconsole或IDLE)上运行,则熊猫自动检测屏幕宽度并即时调整屏幕宽度是2线它显示的列:

pd.set_option('display.large_repr', 'truncate')
pd.set_option('display.max_columns', 0)

According to the docs for v0.18.0, if you’re running on a terminal (ie not iPython notebook, qtconsole or IDLE), it’s a 2-liner to have Pandas auto-detect your screen width and adapt on the fly with how many columns it shows:

pd.set_option('display.large_repr', 'truncate')
pd.set_option('display.max_columns', 0)

回答 9

似乎以上所有答案都可以解决问题。还有一点:pd.set_option('option_name')您可以使用(自动完成功能)代替

pd.options.display.width = None

请参阅熊猫文档:选项和设置:

选项具有完整的“点分样式”,不区分大小写的名称(例如 display.max_rows)。您可以直接将选项作为顶级属性的属性来获取/设置options

In [1]: import pandas as pd

In [2]: pd.options.display.max_rows
Out[2]: 15

In [3]: pd.options.display.max_rows = 999

In [4]: pd.options.display.max_rows
Out[4]: 999

[…]

对于max_...参数:

max_rowsmax_columns在使用__repr__()的方法,以决定是否to_string()info()用于呈现的对象为字符串。如果python / IPython在终端中运行,则可以将其设置为0,并且pandas将正确地自动检测终端的宽度,并交换为较小的格式,以防所有列都不能垂直放置。IPython笔记本,IPython qtconsole或IDLE不在终端中运行,因此无法进行正确的自动检测。None”的值意味着无限。[重点不是原文]

对于width参数:

显示的宽度(以字符为单位)。如果python / IPython在终端中运行,则可以将其设置为,None而pandas将正确地自动检测宽度。请注意,IPython笔记本,IPython qtconsole或IDLE不在终端中运行,因此无法正确检测宽度。

It seems like all above answers solve the problem. One more point: instead of pd.set_option('option_name'), you can use the (auto-complete-able)

pd.options.display.width = None

See Pandas doc: Options and Settings:

Options have a full “dotted-style”, case-insensitive name (e.g. display.max_rows). You can get/set options directly as attributes of the top-level options attribute:

In [1]: import pandas as pd

In [2]: pd.options.display.max_rows
Out[2]: 15

In [3]: pd.options.display.max_rows = 999

In [4]: pd.options.display.max_rows
Out[4]: 999

[…]

for the max_... params:

max_rows and max_columns are used in __repr__() methods to decide if to_string() or info() is used to render an object to a string. In case python/IPython is running in a terminal this can be set to 0 and pandas will correctly auto-detect the width the terminal and swap to a smaller format in case all columns would not fit vertically. The IPython notebook, IPython qtconsole, or IDLE do not run in a terminal and hence it is not possible to do correct auto-detection. None’ value means unlimited. [emphasis not in original]

for the width param:

Width of the display in characters. In case python/IPython is running in a terminal this can be set to None and pandas will correctly auto-detect the width. Note that the IPython notebook, IPython qtconsole, or IDLE do not run in a terminal and hence it is not possible to correctly detect the width.


回答 10

import pandas as pd
pd.set_option('display.max_columns', 100)
pd.set_option('display.width', 1000)

SentenceA = "William likes Piano and Piano likes William"
SentenceB = "Sara likes Guitar"
SentenceC = "Mamoosh likes Piano"
SentenceD = "William is a CS Student"
SentenceE = "Sara is kind"
SentenceF = "Mamoosh is kind"


bowA = SentenceA.split(" ")
bowB = SentenceB.split(" ")
bowC = SentenceC.split(" ")
bowD = SentenceD.split(" ")
bowE = SentenceE.split(" ")
bowF = SentenceF.split(" ")

# Creating a set consisted of all words

wordSet = set(bowA).union(set(bowB)).union(set(bowC)).union(set(bowD)).union(set(bowE)).union(set(bowF))
print("Set of all words is: ", wordSet)

# Initiating dictionary with 0 value for all BOWs

wordDictA = dict.fromkeys(wordSet, 0)
wordDictB = dict.fromkeys(wordSet, 0)
wordDictC = dict.fromkeys(wordSet, 0)
wordDictD = dict.fromkeys(wordSet, 0)
wordDictE = dict.fromkeys(wordSet, 0)
wordDictF = dict.fromkeys(wordSet, 0)

for word in bowA:
    wordDictA[word] += 1
for word in bowB:
    wordDictB[word] += 1
for word in bowC:
    wordDictC[word] += 1
for word in bowD:
    wordDictD[word] += 1
for word in bowE:
    wordDictE[word] += 1
for word in bowF:
    wordDictF[word] += 1

# Printing Term frequency

print("SentenceA TF: ", wordDictA)
print("SentenceB TF: ", wordDictB)
print("SentenceC TF: ", wordDictC)
print("SentenceD TF: ", wordDictD)
print("SentenceE TF: ", wordDictE)
print("SentenceF TF: ", wordDictF)

print(pd.DataFrame([wordDictA, wordDictB, wordDictB, wordDictC, wordDictD, wordDictE, wordDictF]))

输出:

   CS  Guitar  Mamoosh  Piano  Sara  Student  William  a  and  is  kind  likes
0   0       0        0      2     0        0        2  0    1   0     0      2
1   0       1        0      0     1        0        0  0    0   0     0      1
2   0       1        0      0     1        0        0  0    0   0     0      1
3   0       0        1      1     0        0        0  0    0   0     0      1
4   1       0        0      0     0        1        1  1    0   1     0      0
5   0       0        0      0     1        0        0  0    0   1     1      0
6   0       0        1      0     0        0        0  0    0   1     1      0
import pandas as pd
pd.set_option('display.max_columns', 100)
pd.set_option('display.width', 1000)

SentenceA = "William likes Piano and Piano likes William"
SentenceB = "Sara likes Guitar"
SentenceC = "Mamoosh likes Piano"
SentenceD = "William is a CS Student"
SentenceE = "Sara is kind"
SentenceF = "Mamoosh is kind"


bowA = SentenceA.split(" ")
bowB = SentenceB.split(" ")
bowC = SentenceC.split(" ")
bowD = SentenceD.split(" ")
bowE = SentenceE.split(" ")
bowF = SentenceF.split(" ")

# Creating a set consisted of all words

wordSet = set(bowA).union(set(bowB)).union(set(bowC)).union(set(bowD)).union(set(bowE)).union(set(bowF))
print("Set of all words is: ", wordSet)

# Initiating dictionary with 0 value for all BOWs

wordDictA = dict.fromkeys(wordSet, 0)
wordDictB = dict.fromkeys(wordSet, 0)
wordDictC = dict.fromkeys(wordSet, 0)
wordDictD = dict.fromkeys(wordSet, 0)
wordDictE = dict.fromkeys(wordSet, 0)
wordDictF = dict.fromkeys(wordSet, 0)

for word in bowA:
    wordDictA[word] += 1
for word in bowB:
    wordDictB[word] += 1
for word in bowC:
    wordDictC[word] += 1
for word in bowD:
    wordDictD[word] += 1
for word in bowE:
    wordDictE[word] += 1
for word in bowF:
    wordDictF[word] += 1

# Printing Term frequency

print("SentenceA TF: ", wordDictA)
print("SentenceB TF: ", wordDictB)
print("SentenceC TF: ", wordDictC)
print("SentenceD TF: ", wordDictD)
print("SentenceE TF: ", wordDictE)
print("SentenceF TF: ", wordDictF)

print(pd.DataFrame([wordDictA, wordDictB, wordDictB, wordDictC, wordDictD, wordDictE, wordDictF]))

OutPut:

   CS  Guitar  Mamoosh  Piano  Sara  Student  William  a  and  is  kind  likes
0   0       0        0      2     0        0        2  0    1   0     0      2
1   0       1        0      0     1        0        0  0    0   0     0      1
2   0       1        0      0     1        0        0  0    0   0     0      1
3   0       0        1      1     0        0        0  0    0   0     0      1
4   1       0        0      0     0        1        1  1    0   1     0      0
5   0       0        0      0     1        0        0  0    0   1     1      0
6   0       0        1      0     0        0        0  0    0   1     1      0

回答 11

当数据规模很大时,我使用了这些设置。

# environment settings: 
pd.set_option('display.max_column',None)
pd.set_option('display.max_rows',None)
pd.set_option('display.max_seq_items',None)
pd.set_option('display.max_colwidth', 500)
pd.set_option('expand_frame_repr', True)

您可以在这里参考文档

I used these settings when scale of data is high.

# environment settings: 
pd.set_option('display.max_column',None)
pd.set_option('display.max_rows',None)
pd.set_option('display.max_seq_items',None)
pd.set_option('display.max_colwidth', 500)
pd.set_option('expand_frame_repr', True)

You can refer the documentationhere


回答 12

下一行足以显示数据框中的所有列。 pd.set_option('display.max_columns', None)

The below line is enough to display all columns from dataframe. pd.set_option('display.max_columns', None)


回答 13

如果您不想弄乱显示选项,而只想查看此特定的列列表,而无需扩展您查看的每个数据框,则可以尝试:

df.columns.values

If you don’t want to mess with your display options and you just want to see this one particular list of columns without expanding out every dataframe you view, you could try:

df.columns.values

回答 14

您还可以尝试循环:

for col in df.columns: 
    print(col) 

You can also try in a loop:

for col in df.columns: 
    print(col) 

回答 15

您只需执行以下步骤,

  • 您可以如下更改熊猫max_columns功能的选项

    import pandas as pd
    pd.options.display.max_columns = 10

    (这将显示10列,您可以根据需要进行更改)

  • 这样,您可以更改行数,如下所示(如果您还需要更改最大行数)

    pd.options.display.max_rows = 999

    (这允许一次打印999行)

请参考文档以更改熊猫的不同选项/设置

You can simply do the following steps,

  • You can change the options for pandas max_columns feature as follows

    import pandas as pd
    pd.options.display.max_columns = 10
    

    (this allows 10 columns to display, you can change this as you need)

  • Like that you can change the number of rows as you need to display as follows (if you need to change maximum rows as well)

    pd.options.display.max_rows = 999
    

    (this allows to print 999 rows at a time)

Please kindly refer the doc to change different options/settings for pandas


如何使用print()打印类的实例?

问题:如何使用print()打印类的实例?

我正在学习Python中的绳索。当我尝试Foobar使用该print()函数打印类的对象时,得到如下输出:

<__main__.Foobar instance at 0x7ff2a18c>

有没有办法设置及其对象打印行为(或字符串表示形式)?例如,当我调用类对象时,我想以某种格式打印其数据成员。如何在Python中实现?print()

如果您熟悉C ++类,则可以通过为类ostream添加friend ostream& operator << (ostream&, const Foobar&)方法来实现上述目的。

I am learning the ropes in Python. When I try to print an object of class Foobar using the print() function, I get an output like this:

<__main__.Foobar instance at 0x7ff2a18c>

Is there a way I can set the printing behaviour (or the string representation) of a class and its objects? For instance, when I call print() on a class object, I would like to print its data members in a certain format. How to achieve this in Python?

If you are familiar with C++ classes, the above can be achieved for the standard ostream by adding a friend ostream& operator << (ostream&, const Foobar&) method for the class.


回答 0

>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test

__str__方法是在打印时发生的事情,该__repr__方法是在使用repr()功能时(或在交互式提示下查看它时)发生的事情。如果这不是最Python的方法,我深表歉意,因为我也在学习-但这确实可行。

如果未提供任何__str__方法,Python将__repr__改为打印结果。如果定义__str__但没有__repr__,Python将使用你所看到的上面的__repr__,但仍使用__str__打印。

>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test

The __str__ method is what happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt). If this isn’t the most Pythonic method, I apologize, because I’m still learning too – but it works.

If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still use __str__ for printing.


回答 1

正如Chris Lutz所提到的,这是由__repr__您的类中的方法定义的。

从以下文档中repr()

对于许多类型,此函数会尝试返回一个字符串,该字符串将在传递给时产生一个具有相同值的对象eval(),否则表示形式是一个用尖括号括起来的字符串,其中包含对象类型的名称以及其他信息通常包括对象的名称和地址。类可以通过定义__repr__()方法来控制此函数为其实例返回的内容。

给定以下类Test:

class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return "<Test a:%s b:%s>" % (self.a, self.b)

    def __str__(self):
        return "From str method of Test: a is %s, b is %s" % (self.a, self.b)

..it在Python Shell中的行为如下:

>>> t = Test(123, 456)
>>> t
<Test a:123 b:456>
>>> print repr(t)
<Test a:123 b:456>
>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456

如果__str__未定义任何方法,则print(t)(或print(str(t)))将使用结果__repr__代替

如果__repr__未定义任何方法,则使用默认值,该默认值与..

def __repr__(self):
    return "<%s instance at %s>" % (self.__class__.__name__, id(self))

As Chris Lutz mentioned, this is defined by the __repr__ method in your class.

From the documentation of repr():

For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.

Given the following class Test:

class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return "<Test a:%s b:%s>" % (self.a, self.b)

    def __str__(self):
        return "From str method of Test: a is %s, b is %s" % (self.a, self.b)

..it will act the following way in the Python shell:

>>> t = Test(123, 456)
>>> t
<Test a:123 b:456>
>>> print repr(t)
<Test a:123 b:456>
>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456

If no __str__ method is defined, print(t) (or print(str(t))) will use the result of __repr__ instead

If no __repr__ method is defined then the default is used, which is pretty much equivalent to..

def __repr__(self):
    return "<%s instance at %s>" % (self.__class__.__name__, id(self))

回答 2

可以按以下方式完成可应用于任何类而无需特定格式的通用方法:

class Element:
    def __init__(self, name, symbol, number):
        self.name = name
        self.symbol = symbol
        self.number = number

    def __str__(self):
        return str(self.__class__) + ": " + str(self.__dict__)

然后,

elem = Element('my_name', 'some_symbol', 3)
print(elem)

产生

__main__.Element: {'symbol': 'some_symbol', 'name': 'my_name', 'number': 3}

A generic way that can be applied to any class without specific formatting could be done as follows:

class Element:
    def __init__(self, name, symbol, number):
        self.name = name
        self.symbol = symbol
        self.number = number

    def __str__(self):
        return str(self.__class__) + ": " + str(self.__dict__)

And then,

elem = Element('my_name', 'some_symbol', 3)
print(elem)

produces

__main__.Element: {'symbol': 'some_symbol', 'name': 'my_name', 'number': 3}

回答 3

如果遇到类似@Keith的情况,可以尝试:

print a.__dict__

它违背了我认为好的样式,但是如果您只是尝试调试,那么它应该可以做您想要的。

If you’re in a situation like @Keith you could try:

print a.__dict__

It goes against what I would consider good style but if you’re just trying to debug then it should do what you want.


回答 4

只是为了在@dbr的答案中加上我的两分钱,下面是他引用的官方文档中如何实现这句话的一个示例:

“ […返回一个字符串,当传递给eval()时,该字符串将产生具有相同值的对象,[…]”

给定此类定义:

class Test(object):
    def __init__(self, a, b):
        self._a = a
        self._b = b

    def __str__(self):
        return "An instance of class Test with state: a=%s b=%s" % (self._a, self._b)

    def __repr__(self):
        return 'Test("%s","%s")' % (self._a, self._b)

现在,很容易序列化Test类的实例:

x = Test('hello', 'world')
print 'Human readable: ', str(x)
print 'Object representation: ', repr(x)
print

y = eval(repr(x))
print 'Human readable: ', str(y)
print 'Object representation: ', repr(y)
print

因此,运行最后一段代码,我们将获得:

Human readable:  An instance of class Test with state: a=hello b=world
Object representation:  Test("hello","world")

Human readable:  An instance of class Test with state: a=hello b=world
Object representation:  Test("hello","world")

但是,正如我在最近的评论中所说:更多信息就在这里

Just to add my two cents to @dbr’s answer, following is an example of how to implement this sentence from the official documentation he’s cited:

“[…] to return a string that would yield an object with the same value when passed to eval(), […]”

Given this class definition:

class Test(object):
    def __init__(self, a, b):
        self._a = a
        self._b = b

    def __str__(self):
        return "An instance of class Test with state: a=%s b=%s" % (self._a, self._b)

    def __repr__(self):
        return 'Test("%s","%s")' % (self._a, self._b)

Now, is easy to serialize instance of Test class:

x = Test('hello', 'world')
print 'Human readable: ', str(x)
print 'Object representation: ', repr(x)
print

y = eval(repr(x))
print 'Human readable: ', str(y)
print 'Object representation: ', repr(y)
print

So, running last piece of code, we’ll get:

Human readable:  An instance of class Test with state: a=hello b=world
Object representation:  Test("hello","world")

Human readable:  An instance of class Test with state: a=hello b=world
Object representation:  Test("hello","world")

But, as I said in my last comment: more info is just here!


回答 5

您需要使用__repr__。这是一个类似的标准功能__init__。例如:

class Foobar():
    """This will create Foobar type object."""

    def __init__(self):
        print "Foobar object is created."

    def __repr__(self):
        return "Type what do you want to see here."

a = Foobar()

print a

You need to use __repr__. This is a standard function like __init__. For example:

class Foobar():
    """This will create Foobar type object."""

    def __init__(self):
        print "Foobar object is created."

    def __repr__(self):
        return "Type what do you want to see here."

a = Foobar()

print a

回答 6

@ user394430的响应的更漂亮的版本

class Element:
    def __init__(self, name, symbol, number):
        self.name = name
        self.symbol = symbol
        self.number = number

    def __str__(self):
        return  str(self.__class__) + '\n'+ '\n'.join(('{} = {}'.format(item, self.__dict__[item]) for item in self.__dict__))

elem = Element('my_name', 'some_symbol', 3)
print(elem)

产生视觉上漂亮的名称和值列表。

<class '__main__.Element'>
name = my_name
symbol = some_symbol
number = 3

更好的版本(感谢Ruud)对项目进行排序:

def __str__(self):
    return  str(self.__class__) + '\n' + '\n'.join((str(item) + ' = ' + str(self.__dict__[item]) for item in sorted(self.__dict__)))

A prettier version of response by @user394430

class Element:
    def __init__(self, name, symbol, number):
        self.name = name
        self.symbol = symbol
        self.number = number

    def __str__(self):
        return  str(self.__class__) + '\n'+ '\n'.join(('{} = {}'.format(item, self.__dict__[item]) for item in self.__dict__))

elem = Element('my_name', 'some_symbol', 3)
print(elem)

Produces visually nice list of the names and values.

<class '__main__.Element'>
name = my_name
symbol = some_symbol
number = 3

An even fancier version (thanks Ruud) sorts the items:

def __str__(self):
    return  str(self.__class__) + '\n' + '\n'.join((str(item) + ' = ' + str(self.__dict__[item]) for item in sorted(self.__dict__)))

回答 7

对于Python 3:

如果特定格式不重要(例如,用于调试),则仅继承下面的Printable类。无需为每个对象编写代码。

灵感来自这个答案

class Printable:
    def __repr__(self):
        from pprint import pformat
        return "<" + type(self).__name__ + "> " + pformat(vars(self), indent=4, width=1)

# Example Usage
class MyClass(Printable):
    pass

my_obj = MyClass()
my_obj.msg = "Hello"
my_obj.number = "46"
print(my_obj)

For Python 3:

If the specific format isn’t important (e.g. for debugging) just inherit from the Printable class below. No need to write code for every object.

Inspired by this answer

class Printable:
    def __repr__(self):
        from pprint import pformat
        return "<" + type(self).__name__ + "> " + pformat(vars(self), indent=4, width=1)

# Example Usage
class MyClass(Printable):
    pass

my_obj = MyClass()
my_obj.msg = "Hello"
my_obj.number = "46"
print(my_obj)

回答 8

这个线程中已经有很多答案,但是没有一个对我有特别的帮助,我必须自己解决这个问题,因此我希望这个答案能提供更多信息。

您只需要确保在类结束时有括号即可,例如:

print(class())

这是我正在从事的项目中的代码示例:

class Element:
    def __init__(self, name, symbol, number):
        self.name = name
        self.symbol = symbol
        self.number = number
    def __str__(self):
        return "{}: {}\nAtomic Number: {}\n".format(self.name, self.symbol, self.number

class Hydrogen(Element):
    def __init__(self):
        super().__init__(name = "Hydrogen", symbol = "H", number = "1")

要打印我的Hydrogen类,我使用了以下内容:

print(Hydrogen())

请注意,如果没有氢末的括号,这将无法正常工作。它们是必需的。

希望这会有所帮助,如果您还有其他问题,请告诉我。

There are already a lot of answers in this thread but none of them particularly helped me, I had to work it out myself, so I hope this one is a little more informative.

You just have to make sure you have parentheses at the end of your class, e.g:

print(class())

Here’s an example of code from a project I was working on:

class Element:
    def __init__(self, name, symbol, number):
        self.name = name
        self.symbol = symbol
        self.number = number
    def __str__(self):
        return "{}: {}\nAtomic Number: {}\n".format(self.name, self.symbol, self.number

class Hydrogen(Element):
    def __init__(self):
        super().__init__(name = "Hydrogen", symbol = "H", number = "1")

To print my Hydrogen class, I used the following:

print(Hydrogen())

Please note, this will not work without the parentheses at the end of Hydrogen. They are necessary.

Hope this helps, let me know if you have anymore questions.


如何在Python中打印到stderr?

问题:如何在Python中打印到stderr?

有几种写stderr的方法:

# Note: this first one does not work in Python 3
print >> sys.stderr, "spam"

sys.stderr.write("spam\n")

os.write(2, b"spam\n")

from __future__ import print_function
print("spam", file=sys.stderr)

这似乎与zen的Python#13 相矛盾,所以这里有什么区别,一种方法或另一种方法有什么优点或缺点?应该使用哪种方式?

应该有一种(最好只有一种)明显的方式来做到这一点。

There are several ways to write to stderr:

# Note: this first one does not work in Python 3
print >> sys.stderr, "spam"

sys.stderr.write("spam\n")

os.write(2, b"spam\n")

from __future__ import print_function
print("spam", file=sys.stderr)

That seems to contradict zen of Python #13 , so what’s the difference here and are there any advantages or disadvantages to one way or the other? Which way should be used?

There should be one — and preferably only one — obvious way to do it.


回答 0

我发现这是唯一的简短+灵活+便携式+可读的格式:

from __future__ import print_function
import sys

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

该功能eprint可以与标准print功能相同的方式使用:

>>> print("Test")
Test
>>> eprint("Test")
Test
>>> eprint("foo", "bar", "baz", sep="---")
foo---bar---baz

I found this to be the only one short + flexible + portable + readable:

from __future__ import print_function
import sys

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

The function eprint can be used in the same way as the standard print function:

>>> print("Test")
Test
>>> eprint("Test")
Test
>>> eprint("foo", "bar", "baz", sep="---")
foo---bar---baz

回答 1

import sys
sys.stderr.write()

是我的选择,更具可读性,并说出您打算做什么,并且可以跨版本移植。

编辑:“ pythonic”是我对可读性和性能的第三种思考……考虑到这两点,使用python 80%的代码将是pythonic。列表理解是不经常使用的“大事”(可读性)。

import sys
sys.stderr.write()

Is my choice, just more readable and saying exactly what you intend to do and portable across versions.

Edit: being ‘pythonic’ is a third thought to me over readability and performance… with these two things in mind, with python 80% of your code will be pythonic. list comprehension being the ‘big thing’ that isn’t used as often (readability).


回答 2

print >> sys.stderr在Python3中消失了。 http://docs.python.org/3.0/whatsnew/3.0.html说:

Old: print >> sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

对于我们许多人来说,将目标委派到命令末尾有些不自然。另类

sys.stderr.write("fatal error\n")

看起来更面向对象,并且优雅地从泛型到特定。但请注意,这write不是1:1的替代品print

print >> sys.stderr is gone in Python3. http://docs.python.org/3.0/whatsnew/3.0.html says:

Old: print >> sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

For many of us, it feels somewhat unnatural to relegate the destination to the end of the command. The alternative

sys.stderr.write("fatal error\n")

looks more object oriented, and elegantly goes from the generic to the specific. But note that write is not a 1:1 replacement for print.


回答 3

还没logging有人提及,但是日志记录是专门为传达错误消息而创建的。基本配置将设置写入stderr的流处理程序。

该脚本:

# foo.py
import logging

logging.basicConfig(format='%(message)s')
log = logging.getLogger(__name__)
log.warning('I print to stderr by default')
print('hello world')

在命令行上运行时具有以下结果:

$ python3 foo.py > bar.txt
I print to stderr by default

跳回到bar.txt将包含“世界你好”在标准输出。

Nobody’s mentioned logging yet, but logging was created specifically to communicate error messages. Basic configuration will set up a stream handler writing to stderr.

This script:

# foo.py
import logging

logging.basicConfig(format='%(message)s')
log = logging.getLogger(__name__)
log.warning('I print to stderr by default')
print('hello world')

has the following result when run on the command line:

$ python3 foo.py > bar.txt
I print to stderr by default

and bar.txt will contain the ‘hello world’ printed on stdout.


回答 4

对于Python 2,我的选择是: print >> sys.stderr, 'spam' 因为您可以简单地打印列表/字典等,而无需将其转换为字符串。 print >> sys.stderr, {'spam': 'spam'} 代替: sys.stderr.write(str({'spam': 'spam'}))

For Python 2 my choice is: print >> sys.stderr, 'spam' Because you can simply print lists/dicts etc. without convert it to string. print >> sys.stderr, {'spam': 'spam'} instead of: sys.stderr.write(str({'spam': 'spam'}))


回答 5

我使用Python 3进行了以下操作:

from sys import stderr

def print_err(*args, **kwargs):
    print(*args, file=stderr, **kwargs)

因此,现在我可以添加关键字参数,例如,避免回车:

print_err("Error: end of the file reached. The word ", end='')
print_err(word, "was not found")

I did the following using Python 3:

from sys import stderr

def print_err(*args, **kwargs):
    print(*args, file=stderr, **kwargs)

So now I’m able to add keyword arguments, for example, to avoid carriage return:

print_err("Error: end of the file reached. The word ", end='')
print_err(word, "was not found")

回答 6

我要说的是您的第一种方法:

print >> sys.stderr, 'spam' 

是“ …… 一种显而易见的方式”,而另一种则不满足规则1(“美丽胜于丑陋”。)

I would say that your first approach:

print >> sys.stderr, 'spam' 

is the “One . . . obvious way to do it” The others don’t satisfy rule #1 (“Beautiful is better than ugly.”)


回答 7

这将模仿标准打印功能,但在stderr上输出

def print_err(*args):
    sys.stderr.write(' '.join(map(str,args)) + '\n')

This will mimic the standard print function but output on stderr

def print_err(*args):
    sys.stderr.write(' '.join(map(str,args)) + '\n')

回答 8

在Python 3中,可以只使用print():

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

几乎开箱即用:

import sys
print("Hello, world!", file=sys.stderr)

要么:

from sys import stderr
print("Hello, world!", file=stderr)

这很简单,不需要除以外的任何内容sys.stderr

In Python 3, one can just use print():

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

almost out of the box:

import sys
print("Hello, world!", file=sys.stderr)

or:

from sys import stderr
print("Hello, world!", file=stderr)

This is straightforward and does not need to include anything besides sys.stderr.


回答 9

编辑在事后看来,我认为与更改sys.stderr的潜在混淆以及未看到更新的行为使此答案不如仅使用其他人指出的简单函数那样好。

仅使用partial可以节省1行代码。潜在的混乱不值得保存1行代码。

原版的

为了使它更加容易,这是使用“ partial”的版本,这对包装函数有很大帮助。

from __future__ import print_function
import sys
from functools import partial

error = partial(print, file=sys.stderr)

然后像这样使用它

error('An error occured!')

您可以执行以下操作(从http://coreygoldberg.blogspot.com.au/2009/05/python-redirect-or-turn-off-stdout-和.html):

# over-ride stderr to prove that this function works.
class NullDevice():
    def write(self, s):
        pass
sys.stderr = NullDevice()

# we must import print error AFTER we've removed the null device because
# it has been assigned and will not be re-evaluated.
# assume error function is in print_error.py
from print_error import error

# no message should be printed
error("You won't see this error!")

不利的一面是在创建时将sys.stderr的值部分分配给包装的函数。这意味着,如果稍后重定向stderr,它将不会影响此功能。 如果您打算重定向stderr,请使用aaguirre在此页面上提到的** kwargs方法。

EDIT In hind-sight, I think the potential confusion with changing sys.stderr and not seeing the behaviour updated makes this answer not as good as just using a simple function as others have pointed out.

Using partial only saves you 1 line of code. The potential confusion is not worth saving 1 line of code.

original

To make it even easier, here’s a version that uses ‘partial’, which is a big help in wrapping functions.

from __future__ import print_function
import sys
from functools import partial

error = partial(print, file=sys.stderr)

You then use it like so

error('An error occured!')

You can check that it’s printing to stderr and not stdout by doing the following (over-riding code from http://coreygoldberg.blogspot.com.au/2009/05/python-redirect-or-turn-off-stdout-and.html):

# over-ride stderr to prove that this function works.
class NullDevice():
    def write(self, s):
        pass
sys.stderr = NullDevice()

# we must import print error AFTER we've removed the null device because
# it has been assigned and will not be re-evaluated.
# assume error function is in print_error.py
from print_error import error

# no message should be printed
error("You won't see this error!")

The downside to this is partial assigns the value of sys.stderr to the wrapped function at the time of creation. Which means, if you redirect stderr later it won’t affect this function. If you plan to redirect stderr, then use the **kwargs method mentioned by aaguirre on this page.


回答 10

同样适用于标准输出:

print 'spam'
sys.stdout.write('spam\n')

如在其他答案中所述,打印提供了一个漂亮的界面,该界面通常更方便(例如,用于打印调试信息),而写入速度更快,并且当您必须以某种特定方式精确格式化输出时也可以更加方便。我也会考虑可维护性:

  1. 您稍后可以决定在stdout / stderr和常规文件之间切换。

  2. 在Python 3中,print()语法已更改,因此,如果您需要同时支持两个版本,则write()可能会更好。

The same applies to stdout:

print 'spam'
sys.stdout.write('spam\n')

As stated in the other answers, print offers a pretty interface that is often more convenient (e.g. for printing debug information), while write is faster and can also be more convenient when you have to format the output exactly in certain way. I would consider maintainability as well:

  1. You may later decide to switch between stdout/stderr and a regular file.

  2. print() syntax has changed in Python 3, so if you need to support both versions, write() might be better.


回答 11

我正在python 3.4.3中工作。我正在删除一些输入,以显示我如何到达这里:

[18:19 jsilverman@JSILVERMAN-LT7 pexpect]$ python3
>>> import sys
>>> print("testing", file=sys.stderr)
testing
>>>
[18:19 jsilverman@JSILVERMAN-LT7 pexpect]$ 

奏效了吗?尝试将stderr重定向到文件,看看会发生什么:

[18:22 jsilverman@JSILVERMAN-LT7 pexpect]$ python3 2> /tmp/test.txt
>>> import sys
>>> print("testing", file=sys.stderr)
>>> [18:22 jsilverman@JSILVERMAN-LT7 pexpect]$
[18:22 jsilverman@JSILVERMAN-LT7 pexpect]$ cat /tmp/test.txt
Python 3.4.3 (default, May  5 2015, 17:58:45)
[GCC 4.9.2] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
testing

[18:22 jsilverman@JSILVERMAN-LT7 pexpect]$

好吧,除了python给您的一些小介绍被吸引到stderr(它还能去哪里?)之外,它还是可以工作的。

I am working in python 3.4.3. I am cutting out a little typing that shows how I got here:

[18:19 jsilverman@JSILVERMAN-LT7 pexpect]$ python3
>>> import sys
>>> print("testing", file=sys.stderr)
testing
>>>
[18:19 jsilverman@JSILVERMAN-LT7 pexpect]$ 

Did it work? Try redirecting stderr to a file and see what happens:

[18:22 jsilverman@JSILVERMAN-LT7 pexpect]$ python3 2> /tmp/test.txt
>>> import sys
>>> print("testing", file=sys.stderr)
>>> [18:22 jsilverman@JSILVERMAN-LT7 pexpect]$
[18:22 jsilverman@JSILVERMAN-LT7 pexpect]$ cat /tmp/test.txt
Python 3.4.3 (default, May  5 2015, 17:58:45)
[GCC 4.9.2] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
testing

[18:22 jsilverman@JSILVERMAN-LT7 pexpect]$

Well, aside from the fact that the little introduction that python gives you has been slurped into stderr (where else would it go?), it works.


回答 12

如果您做一个简单的测试:

import time
import sys

def run1(runs):
    x = 0
    cur = time.time()
    while x < runs:
        x += 1
        print >> sys.stderr, 'X'
    elapsed = (time.time()-cur)
    return elapsed

def run2(runs):
    x = 0
    cur = time.time()
    while x < runs:
        x += 1
        sys.stderr.write('X\n')
        sys.stderr.flush()
    elapsed = (time.time()-cur)
    return elapsed

def compare(runs):
    sum1, sum2 = 0, 0
    x = 0
    while x < runs:
        x += 1
        sum1 += run1(runs)
        sum2 += run2(runs)
    return sum1, sum2

if __name__ == '__main__':
    s1, s2 = compare(1000)
    print "Using (print >> sys.stderr, 'X'): %s" %(s1)
    print "Using (sys.stderr.write('X'),sys.stderr.flush()):%s" %(s2)
    print "Ratio: %f" %(float(s1) / float(s2))

您会发现sys.stderr.write()始终快1.81倍!

If you do a simple test:

import time
import sys

def run1(runs):
    x = 0
    cur = time.time()
    while x < runs:
        x += 1
        print >> sys.stderr, 'X'
    elapsed = (time.time()-cur)
    return elapsed

def run2(runs):
    x = 0
    cur = time.time()
    while x < runs:
        x += 1
        sys.stderr.write('X\n')
        sys.stderr.flush()
    elapsed = (time.time()-cur)
    return elapsed

def compare(runs):
    sum1, sum2 = 0, 0
    x = 0
    while x < runs:
        x += 1
        sum1 += run1(runs)
        sum2 += run2(runs)
    return sum1, sum2

if __name__ == '__main__':
    s1, s2 = compare(1000)
    print "Using (print >> sys.stderr, 'X'): %s" %(s1)
    print "Using (sys.stderr.write('X'),sys.stderr.flush()):%s" %(s2)
    print "Ratio: %f" %(float(s1) / float(s2))

You will find that sys.stderr.write() is consistently 1.81 times faster!


回答 13

如果由于致命错误而要退出程序,请使用:

sys.exit("Your program caused a fatal error. ... description ...")

import sys在标题中

If you want to exit a program because of a fatal error, use:

sys.exit("Your program caused a fatal error. ... description ...")

and import sys in the header.


回答 14

问题的答案是:有两种不同的方法可以在python中打印stderr,但这取决于1.)我们正在使用哪个python版本2.)我们想要什么确切的输出。

print和stderr的write函数之间的区别: stderr:stderr(标准错误)是内置在每个UNIX / Linux系统中的管道,当程序崩溃并打印出调试信息(如Python中的回溯)时,它将进入stderr管。

print:print是一个包装器,用于格式化输入(输入是参数和换行符之间的空格),然后调用给定对象的write函数,给定对象默认为sys.stdout,但是我们可以传递文件,即我们也可以将输入内容打印到文件中。

Python2:如果我们使用的是python2

>>> import sys
>>> print "hi"
hi
>>> print("hi")
hi
>>> print >> sys.stderr.write("hi")
hi

Python2中的Python2尾部逗号已成为参数,因此,如果我们使用尾部逗号来避免打印后出现换行符,则在Python3中,这将类似于print(’Text to print’,end =”),这是Python2下的语法错误。

http://python3porting.com/noconv.html

如果我们在python3的sceario上进行相同的检查:

>>> import sys
>>> print("hi")
hi

在Python 2.6下,有一个将来的导入可以使打印成为函数。因此,为避免任何语法错误和其他差异,我们应该从以后的 import print_function 开始使用print()的任何文件。在未来的进口只适用的Python 2.6下和以后,因此为Python 2.5和更早的版本,你有两个选择。您可以将更复杂的打印转换为更简单的打印,也可以使用在Python2和Python3上均可使用的单独的打印功能。

>>> from __future__ import print_function
>>> 
>>> def printex(*args, **kwargs):
...     print(*args, file=sys.stderr, **kwargs)
... 
>>> printex("hii")
hii
>>>

案例:需要指出的是sys.stderr.write()或sys.stdout.write()(stdout(标准输出)是每个UNIX / Linux系统中都内置的管道)不能代替print,但是可以。在某些情况下,我们可以将其用作替代方案。Print是包装器,它在输入的末尾用空格和换行符包装,并使用write函数进行写入。这就是sys.stderr.write()更快的原因。

注意:我们也可以使用Logging进行跟踪和调试

#test.py
import logging
logging.info('This is the existing protocol.')
FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
logging.basicConfig(format=FORMAT)
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logging.warning("Protocol problem: %s", "connection reset", extra=d)

https://docs.python.org/2/library/logging.html#logger-objects

Answer to the question is : There are different way to print stderr in python but that depends on 1.) which python version we are using 2.) what exact output we want.

The differnce between print and stderr’s write function: stderr : stderr (standard error) is pipe that is built into every UNIX/Linux system, when your program crashes and prints out debugging information (like a traceback in Python), it goes to the stderr pipe.

print: print is a wrapper that formats the inputs (the input is the space between argument and the newline at the end) and it then calls the write function of a given object, the given object by default is sys.stdout, but we can pass a file i.e we can print the input in a file also.

Python2: If we are using python2 then

>>> import sys
>>> print "hi"
hi
>>> print("hi")
hi
>>> print >> sys.stderr.write("hi")
hi

Python2 trailing comma has in Python3 become a parameter, so if we use trailing commas to avoid the newline after a print, this will in Python3 look like print(‘Text to print’, end=’ ‘) which is a syntax error under Python2.

http://python3porting.com/noconv.html

If we check same above sceario in python3:

>>> import sys
>>> print("hi")
hi

Under Python 2.6 there is a future import to make print into a function. So to avoid any syntax errors and other differences we should start any file where we use print() with from future import print_function. The future import only works under Python 2.6 and later, so for Python 2.5 and earlier you have two options. You can either convert the more complex print to something simpler, or you can use a separate print function that works under both Python2 and Python3.

>>> from __future__ import print_function
>>> 
>>> def printex(*args, **kwargs):
...     print(*args, file=sys.stderr, **kwargs)
... 
>>> printex("hii")
hii
>>>

Case: Point to be noted that sys.stderr.write() or sys.stdout.write() ( stdout (standard output) is a pipe that is built into every UNIX/Linux system) is not a replacement for print, but yes we can use it as a alternative in some case. Print is a wrapper which wraps the input with space and newline at the end and uses the write function to write. This is the reason sys.stderr.write() is faster.

Note: we can also trace and debugg using Logging

#test.py
import logging
logging.info('This is the existing protocol.')
FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
logging.basicConfig(format=FORMAT)
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logging.warning("Protocol problem: %s", "connection reset", extra=d)

https://docs.python.org/2/library/logging.html#logger-objects


如何刷新打印功能的输出?

问题:如何刷新打印功能的输出?

如何强制将Python的打印功能输出到屏幕?

这与“ 禁用输出缓冲”不是重复的-链接的问题正在尝试无缓冲输出,尽管这更普遍。对于这个问题,最重要的答案太过强大或牵扯太多(对于这个问题,它们不是很好的答案),这个问题可以由相对新手在Google上找到。

How do I force Python’s print function to output to the screen?

This is not a duplicate of Disable output buffering – the linked question is attempting unbuffered output, while this is more general. The top answers in that question are too powerful or involved for this one (they’re not good answers for this), and this question can be found on Google by a relative newbie.


回答 0

在Python 3上,print可以采用可选flush参数

print("Hello world!", flush=True)

在Python 2上,您必须做

import sys
sys.stdout.flush()

打电话后print。默认情况下,print打印到sys.stdout(有关文件对象的更多信息,请参阅文档)。

On Python 3, print can take an optional flush argument

print("Hello world!", flush=True)

On Python 2 you’ll have to do

import sys
sys.stdout.flush()

after calling print. By default, print prints to sys.stdout (see the documentation for more about file objects).


回答 1

运行时python -h,我看到一个命令行选项

-u:无缓冲的二进制stdout和stderr; 也PYTHONUNBUFFERED = x有关与’-u’有关的内部缓冲的详细信息,请参见手册页

这是相关的文档

Running python -h, I see a command line option:

-u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x see man page for details on internal buffering relating to ‘-u’

Here is the relevant doc.


回答 2

从Python 3.3开始,您可以强制使用普通print()函数进行刷新,而无需使用sys.stdout.flush(); 只需将“ flush”关键字参数设置为true。从文档中

print(* objects,sep =”,end =’\ n’,file = sys.stdout,flush = False)

将对象打印到流文件中,以sep分隔,然后以end分隔。sep,end和file(如果存在)必须作为关键字参数给出。

所有非关键字参数都将像str()一样转换为字符串,并写入流中,以sep分隔,然后以end分隔。sep和end都必须是字符串;它们也可以是None,这意味着要使用默认值。如果没有给出对象,print()只会写完。

file参数必须是带有write(string)方法的对象;如果不存在或没有,将使用sys.stdout。通常是否由文件决定是否对输出进行缓冲,但是如果flush关键字参数为true,则将强制刷新流。

Since Python 3.3, you can force the normal print() function to flush without the need to use sys.stdout.flush(); just set the “flush” keyword argument to true. From the documentation:

print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

Print objects to the stream file, separated by sep and followed by end. sep, end and file, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.


回答 3

如何刷新Python打印输出?

我建议这样做的五种方法:

  • 在Python 3中,调用print(..., flush=True)(flush参数在Python 2的print函数中不可用,并且print语句没有类似物)。
  • 调用file.flush()输出文件(我们可以包装python 2的print函数来执行此操作),例如,sys.stdout
  • 将此函数
    print = partial(print, flush=True)应用于局部函数的模块中的每个打印函数调用,并应用于全局模块。
  • -u通过传递给解释器命令的标志()将其应用于进程
  • 将其应用于您环境中的每个python进程PYTHONUNBUFFERED=TRUE(并取消设置变量以撤消此操作)。

Python 3.3以上

使用Python 3.3或更高版本,您可以仅flush=True将关键字参数提供给该print函数:

print('foo', flush=True) 

Python 2(或<3.3)

他们没有将flush参数反向移植到Python 2.7,因此,如果您使用的是Python 2(或低于3.3),并且想要与2和3都兼容的代码,我建议以下兼容代码。(请注意,__future__导入必须位于/非常靠近“ 模块顶部 ”):

from __future__ import print_function
import sys

if sys.version_info[:2] < (3, 3):
    old_print = print
    def print(*args, **kwargs):
        flush = kwargs.pop('flush', False)
        old_print(*args, **kwargs)
        if flush:
            file = kwargs.get('file', sys.stdout)
            # Why might file=None? IDK, but it works for print(i, file=None)
            file.flush() if file is not None else sys.stdout.flush()

上面的兼容性代码将涵盖大多数用途,但要进行更彻底的处理,请参阅six模块

另外,您也可以file.flush()在打印后调用,例如使用Python 2中的print语句:

import sys
print 'delayed output'
sys.stdout.flush()

将一个模块中的默认值更改为 flush=True

您可以通过在模块的全局范围内使用functools.partial来更改打印功能的默认值:

import functools
print = functools.partial(print, flush=True)

如果您看看我们新的部分函数,​​至少在Python 3中:

>>> print = functools.partial(print, flush=True)
>>> print
functools.partial(<built-in function print>, flush=True)

我们可以看到它的工作原理与正常情况一样:

>>> print('foo')
foo

实际上,我们可以覆盖新的默认值:

>>> print('foo', flush=False)
foo

再次注意,这只会更改当前的全局范围,因为当前全局范围内的打印名称将使内置print函数(如果在该当前全局范围中使用Python 2使用,则取消引用兼容性函数)。

如果要在函数内部而不是在模块的全局范围内执行此操作,则应给它取一个不同的名称,例如:

def foo():
    printf = functools.partial(print, flush=True)
    printf('print stuff like this')

如果在函数中将其声明为全局变量,则需要在模块的全局命名空间中对其进行更改,因此,应将其放在全局命名空间中,除非特定行为正是您想要的。

更改流程的默认值

我认为这里最好的选择是使用-u标志来获取无缓冲的输出。

$ python -u script.py

要么

$ python -um package.module

文档

强制stdin,stdout和stderr完全没有缓冲。在重要的系统上,还将stdin,stdout和stderr置于二进制模式。

请注意,file.readlines()和文件对象(sys.stdin中的行)具有内部缓冲,不受该选项的影响。要解决此问题,您将需要在while 1:循环内使用file.readline()。

更改Shell操作环境的默认值

如果将环境变量设置为非空字符串,则可以在环境或从该环境继承的环境中的所有python进程中获得以下行为:

例如,在Linux或OSX中:

$ export PYTHONUNBUFFERED=TRUE

或Windows:

C:\SET PYTHONUNBUFFERED=TRUE

文档

PYTHONUNBUFFERD

如果将其设置为非空字符串,则等效于指定-u选项。


附录

这是Python 2.7.12中的print函数的帮助-请注意没有 flush参数:

>>> from __future__ import print_function
>>> help(print)
print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file: a file-like object (stream); defaults to the current sys.stdout.
    sep:  string inserted between values, default a space.
    end:  string appended after the last value, default a newline.

How to flush output of Python print?

I suggest five ways of doing this:

  • In Python 3, call print(..., flush=True) (the flush argument is not available in Python 2’s print function, and there is no analogue for the print statement).
  • Call file.flush() on the output file (we can wrap python 2’s print function to do this), for example, sys.stdout
  • apply this to every print function call in the module with a partial function,
    print = partial(print, flush=True) applied to the module global.
  • apply this to the process with a flag (-u) passed to the interpreter command
  • apply this to every python process in your environment with PYTHONUNBUFFERED=TRUE (and unset the variable to undo this).

Python 3.3+

Using Python 3.3 or higher, you can just provide flush=True as a keyword argument to the print function:

print('foo', flush=True) 

Python 2 (or < 3.3)

They did not backport the flush argument to Python 2.7 So if you’re using Python 2 (or less than 3.3), and want code that’s compatible with both 2 and 3, may I suggest the following compatibility code. (Note the __future__ import must be at/very “near the top of your module“):

from __future__ import print_function
import sys

if sys.version_info[:2] < (3, 3):
    old_print = print
    def print(*args, **kwargs):
        flush = kwargs.pop('flush', False)
        old_print(*args, **kwargs)
        if flush:
            file = kwargs.get('file', sys.stdout)
            # Why might file=None? IDK, but it works for print(i, file=None)
            file.flush() if file is not None else sys.stdout.flush()

The above compatibility code will cover most uses, but for a much more thorough treatment, see the six module.

Alternatively, you can just call file.flush() after printing, for example, with the print statement in Python 2:

import sys
print 'delayed output'
sys.stdout.flush()

Changing the default in one module to flush=True

You can change the default for the print function by using functools.partial on the global scope of a module:

import functools
print = functools.partial(print, flush=True)

if you look at our new partial function, at least in Python 3:

>>> print = functools.partial(print, flush=True)
>>> print
functools.partial(<built-in function print>, flush=True)

We can see it works just like normal:

>>> print('foo')
foo

And we can actually override the new default:

>>> print('foo', flush=False)
foo

Note again, this only changes the current global scope, because the print name on the current global scope will overshadow the builtin print function (or unreference the compatibility function, if using one in Python 2, in that current global scope).

If you want to do this inside a function instead of on a module’s global scope, you should give it a different name, e.g.:

def foo():
    printf = functools.partial(print, flush=True)
    printf('print stuff like this')

If you declare it a global in a function, you’re changing it on the module’s global namespace, so you should just put it in the global namespace, unless that specific behavior is exactly what you want.

Changing the default for the process

I think the best option here is to use the -u flag to get unbuffered output.

$ python -u script.py

or

$ python -um package.module

From the docs:

Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode.

Note that there is internal buffering in file.readlines() and File Objects (for line in sys.stdin) which is not influenced by this option. To work around this, you will want to use file.readline() inside a while 1: loop.

Changing the default for the shell operating environment

You can get this behavior for all python processes in the environment or environments that inherit from the environment if you set the environment variable to a nonempty string:

e.g., in Linux or OSX:

$ export PYTHONUNBUFFERED=TRUE

or Windows:

C:\SET PYTHONUNBUFFERED=TRUE

from the docs:

PYTHONUNBUFFERED

If this is set to a non-empty string it is equivalent to specifying the -u option.


Addendum

Here’s the help on the print function from Python 2.7.12 – note that there is no flush argument:

>>> from __future__ import print_function
>>> help(print)
print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file: a file-like object (stream); defaults to the current sys.stdout.
    sep:  string inserted between values, default a space.
    end:  string appended after the last value, default a newline.

回答 4

另外,如本博客中所建议,可以sys.stdout在无缓冲模式下重新打开:

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

每个stdout.writeprint操作后自动刷新。

Also as suggested in this blog one can reopen sys.stdout in unbuffered mode:

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

Each stdout.write and print operation will be automatically flushed afterwards.


回答 5

使用Python 3.x,该print()功能已扩展:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

因此,您可以执行以下操作:

print("Visiting toilet", flush=True)

Python文档条目

With Python 3.x the print() function has been extended:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

So, you can just do:

print("Visiting toilet", flush=True)

Python Docs Entry


回答 6

使用-u命令行开关可以,但是有点笨拙。这意味着如果用户在没有-u选项的情况下调用脚本,程序可能会出现错误的行为。我通常使用custom stdout,例如:

class flushfile:
  def __init__(self, f):
    self.f = f

  def write(self, x):
    self.f.write(x)
    self.f.flush()

import sys
sys.stdout = flushfile(sys.stdout)

…现在,您的所有print呼叫(sys.stdout隐式使用)将被自动flush编辑。

Using the -u command-line switch works, but it is a little bit clumsy. It would mean that the program would potentially behave incorrectly if the user invoked the script without the -u option. I usually use a custom stdout, like this:

class flushfile:
  def __init__(self, f):
    self.f = f

  def write(self, x):
    self.f.write(x)
    self.f.flush()

import sys
sys.stdout = flushfile(sys.stdout)

… Now all your print calls (which use sys.stdout implicitly), will be automatically flushed.


回答 7

为什么不尝试使用未缓冲的文件?

f = open('xyz.log', 'a', 0)

要么

sys.stdout = open('out.log', 'a', 0)

Why not try using an unbuffered file?

f = open('xyz.log', 'a', 0)

OR

sys.stdout = open('out.log', 'a', 0)

回答 8

丹的想法不太有效:

#!/usr/bin/env python
class flushfile(file):
    def __init__(self, f):
        self.f = f
    def write(self, x):
        self.f.write(x)
        self.f.flush()

import sys
sys.stdout = flushfile(sys.stdout)

print "foo"

结果:

Traceback (most recent call last):
  File "./passpersist.py", line 12, in <module>
    print "foo"
ValueError: I/O operation on closed file

我认为问题在于它是从文件类继承的,实际上是不必要的。根据sys.stdout的文档:

stdout和stderr不必是内置文件对象:任何对象都是可以接受的,只要它具有带有字符串参数的write()方法即可。

所以改变

class flushfile(file):

class flushfile(object):

使它工作正常。

Dan’s idea doesn’t quite work:

#!/usr/bin/env python
class flushfile(file):
    def __init__(self, f):
        self.f = f
    def write(self, x):
        self.f.write(x)
        self.f.flush()

import sys
sys.stdout = flushfile(sys.stdout)

print "foo"

The result:

Traceback (most recent call last):
  File "./passpersist.py", line 12, in <module>
    print "foo"
ValueError: I/O operation on closed file

I believe the problem is that it inherits from the file class, which actually isn’t necessary. According to the docs for sys.stdout:

stdout and stderr needn’t be built-in file objects: any object is acceptable as long as it has a write() method that takes a string argument.

so changing

class flushfile(file):

to

class flushfile(object):

makes it work just fine.


回答 9

这是我的版本,它也提供writelines()和fileno():

class FlushFile(object):
    def __init__(self, fd):
        self.fd = fd

    def write(self, x):
        ret = self.fd.write(x)
        self.fd.flush()
        return ret

    def writelines(self, lines):
        ret = self.writelines(lines)
        self.fd.flush()
        return ret

    def flush(self):
        return self.fd.flush

    def close(self):
        return self.fd.close()

    def fileno(self):
        return self.fd.fileno()

Here is my version, which provides writelines() and fileno(), too:

class FlushFile(object):
    def __init__(self, fd):
        self.fd = fd

    def write(self, x):
        ret = self.fd.write(x)
        self.fd.flush()
        return ret

    def writelines(self, lines):
        ret = self.writelines(lines)
        self.fd.flush()
        return ret

    def flush(self):
        return self.fd.flush

    def close(self):
        return self.fd.close()

    def fileno(self):
        return self.fd.fileno()

回答 10

在Python 3中,您可以覆盖打印功能,默认设置为 flush = True

def print(*objects, sep=' ', end='\n', file=sys.stdout, flush=True):
    __builtins__.print(*objects, sep=sep, end=end, file=file, flush=flush)

In Python 3 you can overwrite print function with default set to flush = True

def print(*objects, sep=' ', end='\n', file=sys.stdout, flush=True):
    __builtins__.print(*objects, sep=sep, end=end, file=file, flush=flush)

回答 11

我在Python 3.4中这样做:

'''To write to screen in real-time'''
message = lambda x: print(x, flush=True, end="")
message('I am flushing out now...')

I did it like this in Python 3.4:

'''To write to screen in real-time'''
message = lambda x: print(x, flush=True, end="")
message('I am flushing out now...')

回答 12

我首先努力了解冲洗选项的工作方式。我想做一个“加载显示”,这是我找到的解决方案:

for i in range(100000):
    print('{:s}\r'.format(''), end='', flush=True)
    print('Loading index: {:d}/100000'.format(i+1), end='')

第一行刷新先前的打印内容,第二行打印新的更新消息。我不知道这里是否存在单行语法。

I first struggled to understand how the flush option was working. I wanted to do a ‘loading display’ and here is the solution I found:

for i in range(100000):
    print('{:s}\r'.format(''), end='', flush=True)
    print('Loading index: {:d}/100000'.format(i+1), end='')

The first line flushes the previous print and the second line prints a new updated message. I don’t know if an one-line syntax exists here.