2016-12-23 18 views
1

我需要将打印功能输出发送到文件,但我收到错误请帮助。在执行过程中无法将打印功能输出发送到文件和出现错误

我的脚本:

#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

你为什么使用'>>'?这不像C,在Python中是整数上使用的移位运算符。 – TidB

回答

1

你不能写这样的文件在Python中。你应该这样做,而不是:

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

实际上,您可以将订单混淆。 –

+1

如果您正在写入文件,则需要明确添加换行符。 –

0

你试图使用Unix >>符号附加到内Python中的文件。

在Python >>是位运算符一个期望两个整数作为操作数(x >> y返回x与比特由y地方移动到右侧)。

0

您是误解如何>>重定向操作符。在Python 2中,print statement不支持重定向,但你必须把它之前生产的印刷价值的表达,你需要打开文件第一:

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

注意,print声明不是函数,不包含括号。

您可以使用Python 3兼容print()function在Python 2,但你需要使用下面的import语句在顶部:

from __future__ import print_function 

之后,你应该使用file参数:

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

您可能想看看使用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在字符串模板有结束。

相关问题