Skip to content

Instantly share code, notes, and snippets.

@ProjectEli
Created December 29, 2024 00:30
Show Gist options
  • Save ProjectEli/a3de55e6f2c2df760eee41bc819c1f52 to your computer and use it in GitHub Desktop.
Save ProjectEli/a3de55e6f2c2df760eee41bc819c1f52 to your computer and use it in GitHub Desktop.
Save opened tabs for potential reboot in windows
import psutil
import csv
import datetime, time, locale
import os
def getCurrentTimeForFileName():
"""Gets the current time in YYYYMMDDhhmmss format."""
now = datetime.datetime.now()
return now.strftime("%Y%m%d_%H%M%S")
def getCurrentTimeLocaleFormat(locale_str=None):
"""
Gets the current time in an appropriate locale format.
Args:
locale_str (str, optional): The locale string to use (e.g., "en_US.UTF-8", "de_DE.UTF-8", "ko_KR.UTF-8").
If None, uses the system's default locale. Defaults to None.
Returns:
str: The current time formatted according to the specified or system locale,
or an error message if the locale is invalid.
"""
try:
if locale_str:
locale.setlocale(locale.LC_TIME, locale_str)
else:
locale.setlocale(locale.LC_TIME, "") #Use system default locale
now = datetime.datetime.now()
# Use strftime with locale-aware format codes
formatted_time = now.strftime("%c") # %c is locale's preferred date and time representation
return formatted_time
except locale.Error as e:
return f"Error setting locale: {e}"
except Exception as e:
return f"An unexpected error occurred: {e}"
def getOpenFilesForProcess(pid):
"""
Gets a list of open files for a given process ID.
Args:
pid: The process ID (PID) of the process.
Returns:
A list of open file names for the given process.
"""
try:
p = psutil.Process(pid)
open_files = []
for file_obj in p.open_files():
try: # Try decoding with UTF-8 first (most common)
path = file_obj.path.encode('utf-8').decode('utf-8')
except UnicodeDecodeError:
try: # Fallback to CP949 if UTF-8 fails
path = file_obj.path.encode('cp949').decode('cp949')
except UnicodeDecodeError:
try: # Fallback to system default encoding if cp949 fails
path = file_obj.path.encode(os.device_encoding(0)).decode(os.device_encoding(0))
except:
path = file_obj.path #If all fails just keep the raw bytes
print(f"Encoding error for PID {pid}: {file_obj.path}. Keeping raw bytes.")
open_files.append(path)
return open_files
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as e:
return []
def saveOpenFiles(process_name, pid, open_files, output_file, output_format="csv"):
"""
Saves the list of open files for a process to a file.
Args:
process_name: The name of the process.
pid: The process ID (PID) of the process.
open_files: A list of open file names.
output_file: The path to the output file.
output_format: The format of the output file ("csv" or "txt"). Default is "csv".
"""
if not open_files:
return
# Open the output file in appropriate mode
with open(output_file, "a", newline="", encoding='utf-8') as f:
if output_format == "csv":
writer = csv.writer(f) # Create a CSV writer
writer.writerow(["Process Name", "PID", "Open File"]) # Write header row
for file in open_files: # Write data rows (filter by extension if needed)
if any(ext in file for ext in (".pdf", ".dwg", ".pptx", ".ai", ".doc", ".opju")):
writer.writerow([process_name, pid, file])
elif output_format == "txt":
f.write(f"Process: {process_name} (PID: {pid})\n") # Write process information
for file in open_files: # Write open files with extension filtering (if needed)
if any(ext in file for ext in (".pdf", ".dwg", ".pptx", ".ai", ".doc", ".opju")):
f.write(f" - {file}\n")
else:
raise ValueError(f"Invalid output format: {output_format}")
def saveOpenFileList(processFilterList = ("inventor.exe", "Illustrator.exe", "acad.exe", "MATLAB.exe"),
extensionFilterList = (".pdf", ".pptx", ".ai", ".doc", ".opju")):
"""Saves a list of open files for all processes to a file."""
# Get the current time and system locale time
start_time = time.time()
system_time = getCurrentTimeLocaleFormat()
print(f"Current working directory: {os.getcwd()}")
print(f"System Locale Time: {system_time}")
# Get a list of all running processes
processes = psutil.process_iter(['pid', 'name'])
print(f"Elapsed time to load proc list: {(time.time()-start_time):.4f} seconds") # Format to 4 decimal places
# Specify the output file and format (change as needed)
output_file = f"{getCurrentTimeForFileName()}.txt"
output_format = "txt"
# Iterate through processes and save their open files
for proc in processes:
try:
pid = proc.info['pid']
name = proc.info['name']
print(f"Process: {name} (PID: {pid})")
open_files = getOpenFilesForProcess(pid)
if open_files:
# Filter by process name (optional)
if any(name in n for n in processFilterList): # for notepad.exe, handle are closed after open
saveOpenFiles(name, pid, open_files, output_file, output_format)
# Or filter by open file extensions (combined approach)
elif any(ext in file for file in open_files for ext in extensionFilterList):
saveOpenFiles(name, pid, open_files, output_file, output_format)
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as e:
continue
print(f"Opened file information saved to {output_file} in {output_format} format.")
print(f"Elapsed time: {(time.time()-start_time):.4f} seconds") # Format to 4 decimal places
if __name__ == "__main__":
saveOpenFileList()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment