0

I want to create a python script for cpu% to run every 5 seconds and output into excel file. I have managed to run the script once and its output in excel is below. How do i repeat it every 5 seconds and insert into excel just the value not the header-name. Please help i just started learning python. output-

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()
Anuvrat Parashar
  • 2,960
  • 5
  • 28
  • 55
Dharmendra
  • 15
  • 2
  • 8
  • below is the how i want my output in excel file in a single column CPU 10.7 14.01 – Dharmendra Mar 05 '20 at 05:10
  • It sounds like you just want to be able to append on subsequent runs. If so, have a look at [this](https://stackoverflow.com/a/47738103/10682164) answer. – totalhack Mar 05 '20 at 05:45
  • Does this answer your question ? -https://stackoverflow.com/questions/20219254/how-to-write-to-an-existing-excel-file-without-overwriting-data-using-pandas/47740262#47740262 – Ananth.P Mar 05 '20 at 06:15
  • @totalhack that answer is how to append to the excel which helps but i want to use something like repeat function which repeats my code in every 5 seconds and append the output into excel.i have used repeat with .text file but here it's not working – Dharmendra Mar 05 '20 at 07:57
  • @totalhack below is the code i used to do the same thing in text file. i want exactly same with excel file. 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 +' is current cpu at time '+time.ctime()) time.sleep(5) f.write(s +' is current cpu at time '+time.ctime()+"\n") print(f.read()) repeat(5,'ss.txt') – Dharmendra Mar 05 '20 at 08:06
  • @Ananth.P please read my comments above – Dharmendra Mar 05 '20 at 08:06
  • @dharmendra can you able to append the data in Excel file ? If it's please share the snippet – Ananth.P Mar 05 '20 at 08:51
  • @Ananth.P no i'm not able to do that. i am kind of stuck here. – Dharmendra Mar 05 '20 at 09:12
  • @Dharmendra i have added a answer . Please check – Ananth.P Mar 05 '20 at 09:57
  • @Ananth.P yes, exactly what i was looking for. thank you so much. now, i just need to do the same for memory and i will be done. – Dharmendra Mar 05 '20 at 10:35
  • Glad to help you ! – Ananth.P Mar 05 '20 at 10:36

2 Answers2

0

You can use subprocess.check to see what your output from running your script would be. Ive used this before with discord bots. I recommend you read this post: Running shell command and capturing the output

subprocess.check_output()

Good Luck

0

I m assuming this is what you expected ..

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)
Ananth.P
  • 445
  • 2
  • 8