简体   繁体   English

CPU 输出为 csv 格式 - python

[英]CPU output to csv format - python

I'm trying to get the entire CPU output in the csv format.我正在尝试以 csv 格式获取整个 CPU 输出。 But it prints only the last line in the csv output.但它只打印 csv 输出中的最后一行。 Can someone look into this and help me on correcting the below script.有人可以调查一下并帮助我更正以下脚本。

   import paramiko
   import subprocess
   import csv
   myfile = open(r"file input path")
   txt = myfile.read()
   client = paramiko.SSHClient()
   target_host = txt
   un = 'root'
   pwd = 'xxx'
   client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
   client.connect(hostname=target_host,username=un,password=pwd)
   stdin, stdout, stderr = client.exec_command('ps -aux')
   for line in stdout:
      with open("cpuoutput.csv", "w", newline="") as f:
           f.write(line)
   print (line) 

When you open file with mode "w" (write) then it removes previous countent当您以模式"w" (写入)打开文件时,它会删除以前的计数

so you should open file only once - before loop所以你应该只打开一次文件 - 在循环之前

with open("cpuoutput.csv", "w", newline="") as f:
    for line in stdout:
        f.write(line)
        print (line) 

or you have to use mode "a" (append) to keep previous content或者您必须使用模式"a" (附加)来保留以前的内容

  for line in stdout:
       with open("cpuoutput.csv", "a", newline="") as f:
            f.write(line)
       print (line) 

First method should be faster for bigger files because it doesn't have to close and reopen file for every line.对于较大的文件,第一种方法应该更快,因为它不必为每一行关闭并重新打开文件。

Second method can be safer when script can get crush because often system saves data on disk not when Python write() but when Python close() file - so closing after every line can keep previous lines on disk when there is cruch.第二种方法在脚本可能会崩溃时会更安全,因为系统通常不是在 Python write()而是在 Python close()文件时将数据保存在磁盘上 - 因此在每行之后关闭可以在出现崩溃时将前几行保留在磁盘上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM