2016-07-12 7 views
4

pythonの出力をコンソールとエラーのあるテキストファイルの両方に出力したいと思います。Python:コンソールとテキストファイルの両方にstdoutを含むエラー

これまでのところ、私の試みが、これらは以下のとおりです。コンソールを使用し

:ファイルへ

# mystdout.py 
# note that it has missing) sign 
print("hello 


# in the terminal: 
chmod a+x mystdout.py; ./mystdout.py 2>&1 | tee output.txt 
# does not print to oputut.txt if mystout.py has syntax errors 

印刷(のpython3):「ティーと呼ばれるクラスを定義

with open('out.txt', 'a') as f: 
    print('hello world', file=f) 
    # this does not print to console, only to the file 

"

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
# Author : Bhishan Poudel 
# Date  : Jul 12, 2016 


# Imports 
import sys 
import subprocess 

##============================================================================= 
class Tee(object): 
    def __init__(self, *files): 
     self.files = files 
    def write(self, obj): 
     for f in self.files: 
      f.write(obj) 
      f.flush() 
    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('This works good, prints all the output to both console and to a file') 
print("This does not print output to file in case of syntax errors") 
print("This does not print output of subprocess.call") 

質問 と仮定私は(ハロー印刷するCプログラムから)

subprocess.call('./hello') 
# How to print output of this executable to both console and outputfile? 

注実行を持っている:
How to redirect 'print' output to a file using python?:コードが実行ハロー

// gcc -o hello hello.c 
#include<stdio.h> 

int main() { 
    printf("hello\n"); 
return 0; } 

関連リンクを生成します
http://linux.byexamples.com/archives/349/how-to-redirect-output-to-a-file-as-well-as-display-it-out/
Output on the console and file using python

+0

あなたのPythonスクリプトは、シェバングを持っていません。どのようにしてシステムはPythonでそれを実行させると考えていますか? – jpmc26

+0

@ jpmc26、私のpythonスクリプトは、スクリプトの最上位にある#!/ usr/bin/env pythonのshebangを持っていますか?#/ usr/bin/python? –

+0

この質問の 'mystdout.py'スクリプトには例がありません。使用する適切なものは、環境構成によって異なります。 – jpmc26

答えて

4

あなたはbashの(最小バージョン4)を使用している場合は、実行することができます:./mystdout |& tee output.txt。それ以外の場合は./mystdout 2>&1 | tee output.txtの提案も有効です。

+0

私は試しました:./mystdout.py |&tee output.txt –

+0

'|&'を使っても? – Pierre

+0

bashの: –

3

@Pierreのソリューションが動作するはずです。 それ以外の場合は、stdout/stderrを外部プロセスから遮断し、2つのハンドラ(コンソール用、特定のファイル用)でロギングを使用することをお勧めします。 ここにはログ設定のexampleがあります。

+0

速いスクリプトだけではなく、「プロダクション」コードを書いている場合は重要です。この回答は、私の場合よりはるかに長期的な答えです。 – Pierre

1

私はbash 3.2.53を使用しています。残念ながら、ピエールのソリューションは私のために働いていません。そしてgrundicによって参照される解決策は私にとっては複雑すぎた。

だから、私は簡単な解決策を考え出した:
エラーなしでPythonの実行は、この方法は、私のために働いていたとき:

python3 a.py | tee aout.txt 

# to test other example 
echo hello this is a test | tee hello.txt 

# Like this it works for every commands. 
関連する問題