Grr
Grr

Reputation: 16079

Accessing text copied to clipboard by python

So I want to be able to use a python script to copy the contents of a folder and then be able to paste those contents to a location of my choosing i.e. text file, browser, etc... I came across this solution for copying text to the clipboard, but when i implement this solution I am not able to paste anything. I am using python 3.4. Below is code i am using:

import os 
import tkinter as tk
import tkinter.filedialog

r = tk.Tk()
r.withdraw()
photo_path= tkinter.filedialog.askdirectory(title='Which folder would you like to copy the contents from?', initialdir='/')

# Get list of filenames in current directory
file_list=[]

for filename in os.listdir(photo_path):
    if os.path.splitext(filename)[1]=='.JPG':
        file_list.append(os.path.splitext(filename)[0])
    else: pass

file_search='code:('+' OR '.join(file_list)+')'

r.clipboard_clear()
r.clipboard_append(file_search)
r.destroy()

Upvotes: 3

Views: 2916

Answers (2)

TigerhawkT3
TigerhawkT3

Reputation: 49320

If you don't use the clipboard content before your script ends, it is discarded. Keep it running until you no longer need the clipboard content. The following program will keep '1234' in the clipboard for 10 seconds. If you don't paste it within that time, it is lost. If you do paste it within that time, it will remain in the clipboard even after the program ends.

import tkinter as tk

r = tk.Tk()
r.withdraw()

r.clipboard_clear()
r.clipboard_append('1234')
r.after(10000, lambda: r.destroy())
r.mainloop()

Upvotes: 3

cmglorioso
cmglorioso

Reputation: 65

How do I read text from the (windows) clipboard from python?

"Worth noting, in py34, win7, SetClipboardText did not work without a preceding call to EmptyClipboard"

import win32clipboard

# set clipboard data
win32clipboard.OpenClipboard()
win32clipboard.SetClipboardText('testing 123')
win32clipboard.CloseClipboard()

# get clipboard data
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
print data

Upvotes: -2

Related Questions