是否存在sys.stdout.write()比print更可取的情况?

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


当前回答

在某些情况下是否更适合使用sys.stdout.write() 打印吗?

例如,我正在处理一个小函数,它在传递数字作为参数时以金字塔格式打印星星,尽管您可以使用end=""在单独的行中打印来完成这一点,但我使用sys.stdout.write与print配合使用来完成此工作。详细说明此标准输出。在同一行中写入打印,而as 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)

其他回答

在Python 2中。在X中,print语句对你给它的内容进行预处理,将其转换为字符串,处理分隔符和换行符,并允许重定向到文件。Python 3。X将其转换为一个函数,但它仍然具有相同的职责。

sys。Stdout是一个文件或类似文件的类,它有一些方法用于写入它,这些方法接受字符串或沿着这一行的东西。

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

如果您正在编写一个既可以写入文件又可以写入标准输出的命令行应用程序,那么它就很方便。你可以这样做:

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')作为out:模式,但有时这样做是值得的。

下面是一些基于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

其中一个区别如下,当试图将一个字节打印为其十六进制外观时。例如,我们知道十进制值255是十六进制的0xFF:

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

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

Print首先将对象转换为字符串(如果它还不是字符串)。如果对象不是行首,它也会在对象前加一个空格,在对象末尾加一个换行符。

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

So

print 99

等价于:

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