Skip to content

Instantly share code, notes, and snippets.

@nobucshirai
Created February 11, 2025 02:56
Show Gist options
  • Save nobucshirai/5b9480f0922e37c92b75fc7d510915b3 to your computer and use it in GitHub Desktop.
Save nobucshirai/5b9480f0922e37c92b75fc7d510915b3 to your computer and use it in GitHub Desktop.
Clipboard Utility for Text Files – A Python script that reads one or more text files, formats them with headers and footers, and optionally copies the output to the clipboard (macOS only).
#!/usr/bin/env python3
"""
This script reads one or more specified text files and outputs their content with a header and footer.
If the header/footer symbol "~~~" is found in a file, alternative symbols are used.
It also provides an option to save the combined output to the clipboard (macOS only).
"""
import argparse
import subprocess
from typing import List
import re
ALTERNATIVE_SYMBOLS = ["###", "'''", '"""', "---", "@@@"]
def detect_alternative_symbols(content: str) -> str:
"""Detects and suggests alternative symbols if ~~~ is found in the file content."""
for symbol in ALTERNATIVE_SYMBOLS:
if symbol not in content:
return symbol
return "~~~" # Default back to ~~~ if no alternatives are available
def process_file(file_path: str) -> str:
"""Reads the file and processes it to add headers and footers."""
try:
with open(file_path, 'r') as file:
content = file.read()
header_footer_symbol = "~~~"
if "~~~" in content:
header_footer_symbol = detect_alternative_symbols(content)
output = f"{header_footer_symbol} {file_path}\n{content}\n{header_footer_symbol}"
return output
except FileNotFoundError:
raise FileNotFoundError(f"The file '{file_path}' does not exist.")
def copy_to_clipboard(text: str):
"""Copies the given text to the clipboard using pbcopy on macOS."""
subprocess.run("pbcopy", input=text, text=True, check=True)
def main():
"""Main function to handle argument parsing and script execution."""
parser = argparse.ArgumentParser(
description="Process and display one or more text files with headers and footers."
)
parser.add_argument(
"files",
type=str,
nargs="+",
help="Paths to the text files to process."
)
parser.add_argument(
"-c", "--clipboard",
action="store_true",
help="Copy the processed text to the clipboard (macOS only)."
)
args = parser.parse_args()
outputs: List[str] = []
for file_path in args.files:
try:
outputs.append(process_file(file_path))
except Exception as e:
outputs.append(f"Error processing file '{file_path}': {e}")
# Join outputs with an empty line between them
final_output = "\n\n".join(outputs)
if args.clipboard:
try:
copy_to_clipboard(final_output)
print("The output has been copied to the clipboard.")
except Exception as e:
print(f"Error copying to clipboard: {e}")
else:
print(final_output)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment