61

stdoutPythonでスクリプト実行ログをファイルにリダイレクトする方法と、pythonicな方法を見つけようとしています。これを達成する簡単な方法はありますか?

4

8 に答える 8

63

ロギング モジュール ( http://docs.python.org/library/logging.html )を使用します。

import logging

logger = logging.getLogger('scope.name')

file_log_handler = logging.FileHandler('logfile.log')
logger.addHandler(file_log_handler)

stderr_log_handler = logging.StreamHandler()
logger.addHandler(stderr_log_handler)

# nice output format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_log_handler.setFormatter(formatter)
stderr_log_handler.setFormatter(formatter)

logger.info('Info message')
logger.error('Error message')
于 2012-07-04T10:34:12.440 に答える
55

私はこれを思いついた[未テスト]

import sys

class Tee(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
            f.write(obj)
            f.flush() # If you want the output to be visible immediately
    def flush(self) :
        for f in self.files:
            f.flush()

f = open('out.txt', 'w')
original = sys.stdout
sys.stdout = Tee(sys.stdout, f)
print "test"  # This will go to stdout and the file out.txt

#use the original
sys.stdout = original
print "This won't appear on file"  # Only on stdout
f.close()

print>>xyzin python は のwrite()関数を期待しますxyz。これを持つ独自のカスタムオブジェクトを使用できます。または、sys.stdout にオブジェクトを参照させることもできます>>xyz

于 2012-07-04T08:27:26.233 に答える
11

Serpensの回答に基づいて構築し、次の行を追加したいだけです:

logger.setLevel('DEBUG')

これにより、ログに記録するメッセージのレベルを選択できます。

たとえば、Serpens の例では、

logger.info('Info message')

デフォルトでは警告以上を記録するため、記録されません。

使用されるレベルの詳細については、こちらを参照してください

于 2014-04-13T12:46:19.153 に答える
8

おそらく最短の解決策:

def printLog(*args, **kwargs):
    print(*args, **kwargs)
    with open('output.out','a') as file:
        print(*args, **kwargs, file=file)

printLog('hello world')

'hello world' を書き込み、print()sys.stdoutoutput.outまったく同じように動作します。

注: printLog 関数には file 引数を指定しないでください。のような呼び出しprintLog('test',file='output2.out')はサポートされていません。

于 2017-08-28T11:32:16.830 に答える
3

loggingこの機能が組み込まれているライブラリを使用する必要があります。ロガーにハンドラーを追加するだけで、出力の送信先を決定できます。

于 2012-07-04T08:43:13.797 に答える
2

最も簡単な解決策は、標準出力をリダイレクトすることです。Python プログラム ファイルでは、次を使用します。

if __name__ == "__main__":
   sys.stdout = open('file.log', 'w')
   #sys.stdout = open('/dev/null', 'w')
   main()

std 出力 (例: の出力print 'hi there') はリダイレクトされるfile.logか、2 行目のコメントを外すと、出力が抑制されます。

于 2012-07-04T09:04:46.693 に答える