102

Pythonスクリプトを実行して、出力をテキストファイルにキャプチャし、コンソールに表示したいと思います。

Pythonスクリプト自体のプロパティとして指定したいと思います。echo "hello world" | tee test.txt毎回コマンドプロンプトでコマンドを使用しないでください。

スクリプト内で私は試しました:

sys.stdout = open('log.txt','w')

ただし、これは画面にstdout出力を表示しません。

ロギングモジュールについて聞いたことがありますが、そのモジュールを使用して作業を行うことができませんでした。

4

14 に答える 14

152

Python ファイルの実行中にシェル リダイレクトを使用できます。

python foo_bar.py > file

これにより、Python ソースからファイルへの stdout に出力されるすべての結果がログファイルに書き込まれます。

または、スクリプト内からログを記録する場合:

import sys

class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout
        self.log = open("logfile.log", "a")
   
    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)  

    def flush(self):
        # this flush method is needed for python 3 compatibility.
        # this handles the flush command by doing nothing.
        # you might want to specify some extra behavior here.
        pass    

sys.stdout = Logger()

これで、次を使用できます。

print "Hello"

これにより、stdout とログファイルの両方に「Hello」が書き込まれます。

于 2013-02-16T04:00:38.877 に答える
23

出力をコンソールとテキスト ファイルに同時にリダイレクトする方法を取得しました。

te = open('log.txt','w')  # File where you need to keep the logs

class Unbuffered:

   def __init__(self, stream):

       self.stream = stream

   def write(self, data):

       self.stream.write(data)
       self.stream.flush()
       te.write(data)    # Write the data of stdout here to a text file as well



sys.stdout=Unbuffered(sys.stdout)
于 2013-02-16T05:49:11.130 に答える
1

Python スクリプトが外部で使用される方法を変更せずに、出力をファイルとターミナルにリダイレクトするには、次を使用できますpty.spawn(itself)

#!/usr/bin/env python
"""Redirect stdout to a file and a terminal inside a script."""
import os
import pty
import sys

def main():
    print('put your code here')

if __name__=="__main__":
    sentinel_option = '--dont-spawn'
    if sentinel_option not in sys.argv:
        # run itself copying output to the log file
        with open('script.log', 'wb') as log_file:
            def read(fd):
                data = os.read(fd, 1024)
                log_file.write(data)
                return data

            argv = [sys.executable] + sys.argv + [sentinel_option]
            rc = pty.spawn(argv, read)
    else:
        sys.argv.remove(sentinel_option)
        rc = main()
    sys.exit(rc)

モジュールが (Windows で) 利用できない場合は、より移植性の高い関数ptyに置き換えることができますが、疑似端末の代わりに通常のパイプを提供します。一部のプログラムの動作が変わる可能性があります。teed_call()

ファイルのようなオブジェクトで置き換えるよりもpty.spawnおよびベースのソリューションの利点は、ファイル記述子レベルで出力をキャプチャできることです。たとえば、スクリプトが stdout/stderr で出力を生成できる他のプロセスを開始した場合などです。関連する質問に対する私の回答を参照してください: Redirect stdout to a file in Python?subprocess.Popensys.stdout

于 2014-09-10T03:31:24.677 に答える
-6

ドキュメントに示されているように、印刷リントの「シェブロン」構文で >> python を使用して、出力をファイルにリダイレクトできます

見てみましょう、

fp=open('test.log','a')   # take file  object reference 
print >> fp , "hello world"            #use file object with in print statement.
print >> fp , "every thing will redirect to file "
fp.close()    #close the file 

ファイル test.log をチェックアウトすると、データが得られ、コンソールに印刷するには、単純な printステートメントを使用します。

于 2013-02-16T05:51:37.613 に答える