2016-12-23 48 views
1

印刷機能の出力をファイルに送信する必要がありますが、エラーが表示されます。実行中にprint funtionの出力をファイルに出力できません。

マイスクリプト:

#get time for to create log file 
    timestamp = time.strftime("%Y%m%d-%H%M%S") 

    ## Open the file with read only permit 
    f = open ('file1', 'r') 

    ## Read the first line 
    line = f.readline() 

    ## If the file is not empty keep reading line one at a time 
    ## till the file is empty 
    while line: 
    print timestamp 
    ip,owner = line.split() 
    print ip 
    logfile = ("log-" + timestamp) 
    print('################################### ' + ip + ' logs') >>logfile 
    print logfile 
    FNULL = open(logfile, 'a') 
    sshconnection = subprocess.call(["ssh", ip, "uptime"], stdout=FNULL,  stderr=FNULL, shell=False) 
    if sshconnection == 0: 
    print('Connection Established to Remote Host ' + ip) 
    else: 
    print('Please check the Remote Host Reachable or Password less configured' + ip) 
    print owner 
    newpassword() 

コード実行の後、私はエラーの下に取得しています:

print('################################### ' + ip + ' logs  ####################################') >> logfile 
TypeError: unsupported operand type(s) for >>: 'str' and 'str' 

私はあなたがこのようなファイルに書き込むことはできませんpython2.7

+0

なぜ '>>'を使用していますか?これはPythonでは整数に使用されるビットシフト演算子であるCに似ていません。 – TidB

答えて

1

を使用していますPythonで。あなたは代わりにこれを行う必要があります:あなたは、Python内のファイルに追加するためのUnix >>記号を使用しようとしている

f = open(logfile,'w') 
f.write("##########################  {} logs\n".format(ip)) 
f.close() 
+0

実際には、OPが注文を混ぜ合わせてしまうことがあります。 –

+1

ファイルに書き込む場合は、改行を明示的に追加する必要があります。 –

0

。パイソン>>

は、オペランドとして2つの整数を(x >> y戻るビットのxy場所右シフト)期待ビット演算子です。

0

>>リダイレクト演算子の誤解があります。 Pythonの2では、print statementは、サポートのリダイレクトを扱っていますが、あなたは、プリント値を生成する前の式にそれを配置する必要があり、そしてあなたがに必要なファイル最初のオープン:print声明こと

with open(logfile, 'a') as log: 
    print >> log, '################################### ' + ip + ' logs' 

注意を関数ではないため、かっこは使用されません。

あなたは、Python 2にはPython 3互換print()functionを使用することができますが、先頭に次のインポート文を使用する必要があります。

with open(logfile, 'a') as log: 
    print('################################### ' + ip + ' logs', file=logfile) 

from __future__ import print_function 

た後、あなたがfile引数を使用したいです

あなたは、文字列にデータを補間するstring formatting with str.format()を使用して見てみたいことがあります。

with open(logfile, 'a') as log: 
    print('################################### {} logs'.format(ip), file=logfile) 

また、ファイルに直接書き込むことができますが、明示的に改行を追加することを忘れないでください:

with open(logfile, 'a') as log: 
    log.write('################################### {} logs\n'.format(ip)) 

があり、文字列テンプレートの末尾に\nに注意してください。

関連する問題