问题: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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。