python - 无法将打印功能输出发送到文件并在执行期间出错

标签 python linux python-2.7

我需要将打印函数输出发送到文件,但出现错误请帮忙。

我的脚本:

  #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/

相关文章:

python - 使用 numpy.savetxt 保存 utf-8 编码的文本

linux - 使用 makefile.in 将 linux 源代码编译为 windows 7

python - subprocess.call 与 os.system python

python - 如何检测屏幕上是否存在图像?

python - 为什么 chr(0x24) + chr(0x84) 的结果在 python 2 和 3 中不同

python - HTML 网页抓取一个值

python - 将库合并到脚本中?

linux - 打开终端后执行命令,其中使用 ssh 登录远程机器

linux - 我如何从 nodejs 重启 linux

python - 写入 CSV 时出现 UnicodeEncodeError