【问题标题】:how to write the output of cpu command into a excel file如何将cpu命令的输出写入excel文件
【发布时间】:2020-06-17 16:23:02
【问题描述】:

我想为 cpu% 创建一个 python 脚本,使其每 5 秒运行一次并输出到 excel 文件中。我设法运行了一次脚本,它在 excel 中的输出如下。我如何每 5 秒重复一次并仅将值而不是标题名称插入到 excel 中。请帮助我刚开始学习python。 输出-

enter image description here

import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
import numpy as np
import psutil
CPU = psutil.cpu_percent(interval=1)
df = pd.DataFrame({'CPU': [CPU]})

writer = ExcelWriter(r'C:\Users\kumardha\Desktop\DK_TEST\Pandas3.xlsx')
df.to_excel(writer,'Sheet1',index=False)
writer.save()

【问题讨论】:

  • 下面是我希望我的输出在单列 CPU 10.7 14.01 中的 excel 文件中的方式
  • 听起来您只是希望能够在后续运行中追加。如果是这样,请查看this 答案。
  • 这能回答你的问题吗? -stackoverflow.com/questions/20219254/…
  • @totalhack 答案是如何附加到 excel 中,这有帮助,但我想使用诸如重复功能之类的东西,它每 5 秒重复一次我的代码并将输出附加到 excel 中。我使用了重复.text 文件,但在这里它不起作用
  • @totalhack 下面是我用来在文本文件中做同样事情的代码。我想要与 excel 文件完全相同。 import time,os,psutil def repeat(seconds,filename): while True: a = print(time.ctime()) f = open(r'C:\Users\kumardha\Desktop\DK_TEST\1.txt', ' a+') CPU = psutil.cpu_percent(interval=1) s = str(CPU) b = print(s +' 是时间 '+time.ctime()) 时的当前 cpu) time.sleep(5) f.write(s +' 是时间 '+time.ctime()+"\n") 的当前 cpu print(f.read()) repeat(5,'ss.txt')

标签: python python-3.x pandas python-2.7


【解决方案1】:

我假设这是你所期望的......

import pandas as pd
import numpy as np
import psutil
import time
from openpyxl import load_workbook

def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
                              truncate_sheet=False, 
                              **to_excel_kwargs):




    # ignore [engine] parameter if it was passed
    if 'engine' in to_excel_kwargs:
        to_excel_kwargs.pop('engine')

    writer = pd.ExcelWriter(filename, engine='openpyxl')

    # Python 2.x: define [FileNotFoundError] exception if it doesn't exist 
    try:
        FileNotFoundError
    except NameError:
        FileNotFoundError = IOError


    try:
        # try to open an existing workbook
        writer.book = load_workbook(filename)

        # get the last row in the existing Excel sheet
        # if it was not specified explicitly
        if startrow is None and sheet_name in writer.book.sheetnames:
            startrow = writer.book[sheet_name].max_row

        # truncate sheet
        if truncate_sheet and sheet_name in writer.book.sheetnames:
            # index of [sheet_name] sheet
            idx = writer.book.sheetnames.index(sheet_name)
            # remove [sheet_name]
            writer.book.remove(writer.book.worksheets[idx])
            # create an empty sheet [sheet_name] using old index
            writer.book.create_sheet(sheet_name, idx)

        # copy existing sheets
        writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
    except FileNotFoundError:
        pass

    if startrow is None:
        startrow = 0
    df.to_excel(writer, sheet_name, startrow=startrow,**to_excel_kwargs)

    # save the workbook
    writer.save()


def repeat(seconds,filename): 
    first_time=True
    while True: 
        CPU = psutil.cpu_percent(interval=1)
        df = pd.DataFrame({'CPU': [CPU]})
        s = str(CPU)
        b = print(s +' is current cpu at time '+time.ctime())
        if first_time:
            append_df_to_excel(filename,df,sheet_name='Sheet1',index=False)
            first_time=False
        else:
            append_df_to_excel(filename,df,sheet_name='Sheet1',header=False,index=False)
        time.sleep(seconds)

filename='path to filename'
repeat('delay you want in seconds',filename)

【讨论】:

    【解决方案2】:

    您可以使用 subprocess.check 查看运行脚本后的输出。我以前用过这个不和谐的机器人。我建议你阅读这篇文章:Running shell command and capturing the output

    subprocess.check_output()
    

    祝你好运

    【讨论】:

      猜你喜欢
      • 2015-01-30
      • 1970-01-01
      • 2012-02-18
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-17
      相关资源
      最近更新 更多