Python チュートリアル: sys.stdout メソッド

Python の sys モジュールのメソッドの 1 つは stdout で、引数を使用してコンソール ウィンドウに直接表示します。

これらの種類の出力は、単純な print ステートメント、式、入力プロンプトなどさまざまです。print() メソッドは同じ動作をしますが、最初に sys.stdout() メソッドに変換され、結果がコンソールに表示されます。

sys.stdout メソッドの構文

sys.stdout

パラメータ

パラメータは関係しません。出力ファイル オブジェクトとして sys.stdout を使用します。
戻り値

このメソッドは値を返さず、出力をコンソールに直接表示するだけです。

例: Python での sys.stdout メソッドの使用

# import the sys module to use methods
import sys
sys.stdout.write('This is my first line')
sys.stdout.write('This is my second line')

出力:

This is my first line This is my second line

sys.stdout.write() メソッドで渡されたパラメータを返し、それを画面に表示します。

例: sys.stdout.write() メソッドと print() メソッド

import sys
# print shows new line at the end
print("First line ")
print("Second line ")
# displays output directly on console without space or newline
sys.stdout.write('This is my first line ')
sys.stdout.write('This is my second line ')
# for inserting new line
sys.stdout.write("n")
sys.stdout.write('In new line ')
# writing string values to file.txt
print('Hello', 'World', 2+3, file=open('file.txt', 'w'))

出力:

First line
Second line
This is my first line This is my second line
In new line
# file.txt will be created with text "Hello World 5" as a string

sys.stdout.write() メソッドを使用して、コンテンツをコンソールに直接表示します。print() ステートメントには、入力の書式設定も行う stdout() メソッドの周囲の薄いラッパーがあります。したがって、デフォルトでは、引数の間にスペースが挿入され、新しい行が入力されます。

Python 3.0 以降、print() メソッドは stdout() メソッドだけでなく、file パラメータも受け入れます。行にスペースを与えるには、「n」を stdout.write() メソッドに渡します。
サンプルコード: sys.stdout.write() メソッドを使用してリストを表示する

import sys
# sys.stdout assigned to "carry" variable
carry = sys.stdout
my_array = ['one', 'two', 'three']
# printing list items here
for index in my_array:
    carry.write(index)

出力:

# prints a list on a single line without spaces
onetwothree

出力は、 stdout.write() メソッドが指定された引数にスペースや改行を提供していないことを示しています。

例: Python での sys.stdout.flush() メソッドの使用

import sys
# import for the use of the sleep() method
import time
# wait for 5 seconds and suddenly shows all output
for index in range(5):
    print(index, end =' ')
    time.sleep(1)
print()
# print one number per second till 5 seconds
for index in range(5):
    # end variable holds /n by default
    print(index, end =' ')
    sys.stdout.flush()
    time.sleep(1)

出力結果:

0 1 2 3 4 # no buffer
0 1 2 3 4 # use buffer

sys.stdout.flush() メソッドはバッファをフラッシュします。これは、書き込み前に待機する場合でも、バッファーの内容をコンソールに書き込むことを意味します。

例: Python での sys.stdout.encoding() メソッドの使用

# import sys module for stdout methods
import sys
# if the received value is not None, then the function prints repr(receivedValue) to sys.stdout
def display(receivedValue):
    if receivedValue is None:
        return
    mytext = repr(receivedValue)
    # exception handling
    try:
        sys.stdout.write(mytext)
    # handles two exceptions here
    except UnicodeEncodeError:
        bytes = mytext.encode(sys.stdout.encoding, 'backslashreplace')
        if hasattr(sys.stdout, 'buffer'):
            sys.stdout.buffer.write(bytes)
        else:
            mytext = bytes.decode(sys.stdout.encoding, 'strict')
            sys.stdout.write(mytext)
    sys.stdout.write("n")
display("my name")

出力:

'my name'

メソッド sys.stdout.encoding() は、sys.stdout のエンコーディングを変更するために使用されます。メソッド display() では、これを使用して、対話型 Python セッションに挿入された式を評価します。

例外ハンドラーには 2 つのオプションがあります。 パラメーター値がエンコード可能な場合は、backslashreplace エラー ハンドラーを使用してエンコードします。それ以外の場合、エンコード可能でない場合は、sys.std.errors エラー ハンドラーを使用してエンコードする必要があります。

例: sys.stdout をログ ファイルに複製する

import sys
# method for multiple log saving in txt file
class multipleSave(object):
    def __getattr__(self, attr, *arguments):
        return self._wrap(attr, *arguments)
    def __init__(self, myfiles):
        self._myfiles = myfiles
    def _wrap(self, attr, *arguments):
        def g(*a, **kw):
            for f in self._myfiles:
                res = getattr(f, attr, *arguments)(*a, **kw)
            return res
        return g
sys.stdout = multipleSave([ sys.stdout, open('file.txt', 'w') ])
# Python小白学习交流群:711312441
# all print statement works here
print ('123')
print (sys.stdout, 'this is second line')
sys.stdout.write('this is third linen')

出力:

# file.txt will be created on the same directory with multiple logs in it.
123
<__main__.multipleSave object at 0x00000226811A0048> this is second line
this is third line

出力コンソール結果をファイルに保存するには、open() メソッドを使用して保存します。すべてのコンソール出力を同じログ ファイルに保存します。

このようにして、コンソールに出力された出力をログ ファイルに保存できます。

おすすめ

転載: blog.csdn.net/qdPython/article/details/132008582