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)