Created
March 27, 2019 13:10
-
-
Save stoyanovgeorge/e63874bcc59d45d49ea66e0044ae0a10 to your computer and use it in GitHub Desktop.
Checks and records in a CSV file how many processes with a <process_name> are running every 10 seconds.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import subprocess | |
import csv | |
import os | |
import time | |
from datetime import datetime | |
from pathlib import Path | |
#### Variables definition | |
home = str(Path.home()) | |
log_file = os.path.join(home, 'logs', 'pid_count.csv') | |
process = "<process_name>" | |
header = ['Date', 'Time', 'Count'] | |
### Functions definition | |
def get_pid(name): | |
pid_count = int(subprocess.check_output(["pgrep", "-c", process]).decode('utf8')) | |
check_date = datetime.now().strftime('%d-%m-%Y') | |
check_time = datetime.now().strftime('%T') | |
row = [check_date, check_time, pid_count] | |
return row | |
def header_write(log_file, header): | |
with open(log_file, "w") as csvf: | |
writer = csv.writer(csvf, delimiter=';') | |
writer.writerow(header) | |
def log_write(log_file, row): | |
with open(log_file, "a") as csvf: | |
writer = csv.writer(csvf, delimiter=';') | |
writer.writerow(row) | |
### Program execution | |
header_write(log_file, header) | |
while True: | |
log_write(log_file, get_pid(process)) | |
time.sleep(10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment