Skip to content

Instantly share code, notes, and snippets.

@brandonlou
Created August 4, 2020 23:26
Show Gist options
  • Save brandonlou/af0e03c3dbcd2501dd974a4de3047861 to your computer and use it in GitHub Desktop.
Save brandonlou/af0e03c3dbcd2501dd974a4de3047861 to your computer and use it in GitHub Desktop.
Reads and copies a file line by line whenever a user pastes.
#!/usr/bin/env python3
import sys
import pyperclip
import platform
from pynput import keyboard
# Paste key combination
if platform.system() == 'Darwin': # Mac
COMBINATION = {keyboard.Key.cmd, keyboard.KeyCode(char='v')}
else: # Linux and Windows
COMBINATION = {keyboard.Key.ctrl, keyboard.KeyCode(char='v')}
current = set()
paste_detected = False
# Detect if user pasted something.
def on_press(key):
global paste_detected
if key in COMBINATION:
current.add(key)
if all(k in current for k in COMBINATION):
paste_detected = True
print('Paste detected!\n')
def on_release(key):
try:
current.remove(key)
except KeyError:
pass
# Monitor the keyboard in a non-blocking fashion.
listener = keyboard.Listener(
on_press=on_press,
on_release=on_release)
listener.start()
# Get filepath as first argument.
try:
filepath = sys.argv[1]
except IndexError:
print("Error: No file specified.")
sys.exit()
with open(filepath) as file:
line = file.readline().strip()
while line:
# Copy one line
pyperclip.copy(line)
print("Copied: " + line)
while True:
if paste_detected:
# Read next line
line = file.readline().strip()
paste_detected = False
break
# Stop monitoring the keyboard and prompt user.
listener.stop()
print("End of file. No more lines to copy!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment