解析python 命令的 u引數

2021-08-23 12:21:58 字數 1056 閱讀 8141

今天在看arcface的訓練**,在shell指令碼中執行python 命令時後面加了-u 引數(python -u xx.py),於是對這個引數進行了下小研究。

用網上的乙個程式示例來說明,python中標準錯誤(std.err)和標準輸出(std.out)的輸出規則(標準輸出預設需要快取後再輸出到螢幕,而標準錯誤則直接列印到螢幕):

import sys

sys.stdout.write("stdout1")

sys.stderr.write("stderr1")

sys.stdout.write("stdout2")

sys.stderr.write("stderr2")

其中sys.stdout.write()和sys.stderr.write()均是向螢幕列印的語句。其實python中的print語句就是呼叫了sys.stdout.write(),例如在列印物件呼叫print obj 時,事實上是呼叫了 sys.stdout.write(obj+'\n')。

預想的結果是

stdout1stderr1stdout2stderr2
實際的結果為

stderr1stderr2stdout1stdout2
原因是python快取機制,雖然stderr和stdout預設都是指向螢幕的,但是stderr是無快取的,程式往stderr輸出乙個字元,就會在螢幕上顯示乙個;而stdout是有快取的,只有遇到換行或者積累到一定的大小,才會顯示出來。這就是為什麼上面的會最先顯示兩個stderr的原因。

有了上面的鋪墊,就可以引出python 的-u引數了。python命令加上-u(unbuffered)引數後會強制其標準輸出也同標準錯誤一樣不通過快取直接列印到螢幕。

執行結果

stdout1stderr1stdout2stderr2
這樣變成了預期的輸出了。

通過以上分析,不難看出尤其是在將python執行指令碼輸出到螢幕結果直接重定向到日誌檔案的情況下,使用-u引數,這樣將標準輸出的結果不經快取直接輸出到日誌檔案。

python命令 u引數用法解析

在shell指令碼中執行python 命令時後面加了 u 引數 python u xx.py 這個 u表示什麼?import sys sys.stdout.write stdout1 sys.stderr.write stderr1 sys.stdout.write stdout2 sys.stde...

python u 解析python 命令的 u引數

在shell指令碼中執行python 命令時後面加了 u 引數 python u xx.py 這個 u表示什麼?importsys sys.stdout.write stdout1 sys.stderr.write stderr1 sys.stdout.write stdout2 sys.stder...

Python的命令列引數解析

命令列引數解析在程式語言中基本都會碰到,python中內建了乙個用於命令項選項與引數解析的模組argparse。下面主要介紹兩種解析python命令列引數的方式。解析python中命令列引數的最傳統的方法是通過sys.argv。demo如下 usr env python python coding ...