Is there a way to directly send a python output to clipboard?
You can use an external program, xsel
:
from subprocess import Popen, PIPE
p = Popen(['xsel','-pi'], stdin=PIPE)
p.communicate(input='Hello, World')
With xsel
, you can set the clipboard you want to work on.
-p
works with thePRIMARY
selection. That's the middle click one.-s
works with theSECONDARY
selection. I don't know if this is used anymore.-b
works with theCLIPBOARD
selection. That's yourCtrl + V
one.
Read more about X's clipboards here and here.
A quick and dirty function I created to handle this:
def paste(str, p=True, c=True):
from subprocess import Popen, PIPE
if p:
p = Popen(['xsel', '-pi'], stdin=PIPE)
p.communicate(input=str)
if c:
p = Popen(['xsel', '-bi'], stdin=PIPE)
p.communicate(input=str)
paste('Hello', False) # pastes to CLIPBOARD only
paste('Hello', c=False) # pastes to PRIMARY only
paste('Hello') # pastes to both
You can also try pyGTK's clipboard
:
import pygtk
pygtk.require('2.0')
import gtk
clipboard = gtk.clipboard_get()
clipboard.set_text('Hello, World')
clipboard.store()
This works with the Ctrl + V
selection for me.
How do I copy a string to the clipboard?
Actually, pywin32
and ctypes
seem to be an overkill for this simple task. Tkinter
is a cross-platform GUI framework, which ships with Python by default and has clipboard accessing methods along with other cool stuff.
If all you need is to put some text to system clipboard, this will do it:
from Tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.update() # now it stays on the clipboard after the window is closed
r.destroy()
And that's all, no need to mess around with platform-specific third-party libraries.
If you are using Python 3, replace TKinter
with tkinter
.
Copy the output of `print` to clipboard directly
Python doesn't have clipboard APIs built in, except as part of the tkinter
GUI, but there are a number of libraries on PyPI that do.
For example, with pyperclip
, you can copy any string you want to the clipboard like this:
In[56]: import pyperclip
In[57]: pyperclip.copy(view_code)
But you may be able to use tkinter
. Depending on your platform, whether you're using a console-mode or qtconsole session, etc., this may not work, or may require popping up an unwanted window, but you can try it and see:
In [119]: import tkinter
In [120]: tk = tkinter.Tk()
In [121]: tk.clipboard_clear()
In [122]: tk.clipboard_append(view_code)
If your setup does require you to display a window (e.g., I think this will happen in a console-mode session on Windows), you might still be able to do it without too much distraction. See this answer, suggested by J.Doe if you're interested.
But it might be simpler and more useful to just write to a file:
In[58}: with open('spam.txt', 'w') as f: f.write(view_code)
Or, since you're using IPython, you can use %save
or various other magic commands. (See this question so I don't have to go over them all here.)
Or, there are multiple third-party implementations of IPython addons to give you clipboard copy commands, like this one (which I just found in a random search, so I'm not endorsing it or anything… but it seems to work):
In[61]: %clip view_code
If you actually need to capture the output of print
for some reason, the two obvious ways to do it are to monkeypatch or shadow print
, or to patch sys.stdout
. For example:
import builtins
import io
import sys
def print(*args, **kw):
if kw.get('file', sys.stdout) is sys.stdout:
buf = io.StringIO()
builtins.print(*args, **kw, file=buf)
pyperclip.copy(buf.getvalue())
builtins.print(*args, **kw)
A button that copy the output into a clipboard using Tkinter
You can do it by using one of tkinter
's universal clipboard_append()
widget method which means you wouldn't need to download and install an additional third-party module such as clipboard
. (Note that there's also a clipboard_get()
method that the linked documentation doesn't mention.)
Here's how to modify your code to do it: I've added a Copy To Clipboard button and defined a copy_to_cliboard()
function that will be called when it's clicked. The function uses the clipboard_append()
method (after first clearing the clipboard via another universal widget method named clipboard_clear()
).
import tkinter as tk # PEP 8 suggests avoiding `import *`
import numpy as nmpi
import random
def generate():
srt = int(entrynbr1.get())
rng = int(entrynbr2.get())
sze = int(entrynbr3.get())
values = random.sample(range(srt, rng), sze)
hola = nmpi.array(values)
text_entry.delete('1.0', tk.END)
text_entry.insert(tk.END, str(hola))
def copy_to_clipboard():
"""Copy current contents of text_entry to clipboard."""
top.clipboard_clear() # Optional.
top.clipboard_append(text_entry.get('1.0', tk.END).rstrip())
top = tk.Tk()
top.title("Number Generator")
top.minsize(600, 700)
top.resizable(0, 0)
lblnbr1 = tk.Label(top, text="Start",bg='azure')
lblnbr1.place(x=120, y=50)
entrynbr1 = tk.Entry(top, border=2)
entrynbr1.place(x=200, y=50)
lblnbr2 = tk.Label(top, text="Range",bg='azure')
lblnbr2.place(x=120, y=100)
entrynbr2 = tk.Entry(top, border=2)
entrynbr2.place(x=200, y=100)
lblnbr3 = tk.Label(top, text="Size",bg='azure')
lblnbr3.place(x=120, y=150)
entrynbr3 = tk.Entry(top, border=2)
entrynbr3.place(x=200, y=150)
gen = tk.Button(top, border=4 ,text="Generate Numbers", bg='LightBlue1', command=generate)
gen.place(x=220, y=200)
clp = tk.Button(top, border=4 ,text="Copy To Clipboard", bg='LightBlue1',
command=copy_to_clipboard)
clp.place(x=220, y=240)
text_entry = tk.Text(top, width=80, height=27, border=4, relief=tk.RAISED)
text_entry.pack()
text_entry.place(x=10, y=280)
top['background'] = 'azure'
top.mainloop()
Copying the contents of a variable to the clipboard
Have you tried this?
import os
def addToClipBoard(text):
command = 'echo ' + text.strip() + '| clip'
os.system(command)
Read more solutions here.
Edit:
You may call it as:
addToClipBoard(your_variable)
How to copy file from a folder to clipboard using tkinter?
I don't think tkinter has method to copy files, but if you are on windows you can use the powershell command Set-Clipboard
. You can use subprocess
module to run this command. Here is a minimal example.
import subprocess
import tkinter as tk
def copy_file():
#cmd = r"ls '{}' | Set-Clipboard".format(absolute_path) # if you only want the contents of folder to be copied
cmd = r"gi '{}' | Set-Clipboard".format("background.png") # copies both folder and its contents
subprocess.run(["powershell", "-command", cmd], shell=True) # windows specific
root = tk.Tk()
copyfile = tk.Button(root, text="Copy file from c:\\", command=copy_file)
copyfile.pack()
root.mainloop()
Now you might want to run the copy_file
from another thread. Here is a reference to my old answer
Related Topics
How to Exit Linux Terminal Using Python Script
Detect New or Modified Files with Python
Numpy Selecting Specific Column Index Per Row by Using a List of Indexes
How to Make Ball Bounce Off Wall with Pygame
Converting Int to Bytes in Python 3
Compare Two Dataframes and Output Their Differences Side-By-Side
Format Output String, Right Alignment
Environment Variable Differences When Using Paramiko
How to Check Type of Files Without Extensions
What Is the Purpose of a Backslash at the End of a Line
Python Multiprocessing Linux Windows Difference
Trying to Import a Module: Undefined Symbol: Pyunicodeucs4_Decodeutf8
How to Write to a CSV Line by Line
In Matplotlib, What Does the Argument Mean in Fig.Add_Subplot(111)
Importing Variables from Another File
What's the Difference Between Select_Related and Prefetch_Related in Django Orm
Typeerror: Not All Arguments Converted During String Formatting Python