我需要将打印函数输出发送到文件,但出现错误请帮忙。
我的脚本:
#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
最佳答案
您不能在 Python 中写入这样的文件。你应该这样做:
f = open(logfile,'w')
f.write("########################## {} logs\n".format(ip))
f.close()
关于python - 无法将打印功能输出发送到文件并在执行期间出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41299029/