Gnome desktop has 2 clipboards, the X.org (saves every selection) and the legacy one (CTRL+C). I am writing a simple python script to clear both clipboards, securely preferably, since it may be done after copy-pasting a password.
The code that I have seen over here is this:
# empty X.org clipboard
os.system("xclip -i /dev/null")
# empty GNOME clipboard
os.system("touch blank")
os.system("xclip -selection clipboard blank")
Unfortunately this code creates a file named blank
for some reason, so we have to remove it:
os.remove("blank")
However the main problem is that by calling both of these scripts, it leaves the xclip
process open, even after I close the terminal.
I also know about this method:
os.system("echo "" | xclip -selection clipboard") # empty clipboard
However this one leaves a \n
newline character in the clipboard, so I would not call this method effective either.
So how to do it properly then?
I know three ways to clear the clipboard from Python. First using tkinter:
try:
from Tkinter import Tk
except ImportError:
from tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.destroy()
Second with xclip, but I use xclip like this:
echo -n | xclip -selection clipboard
Does it create a new line?
Finally, it's possible to user xsel:
xsel -bc
PRIMARY
and CLIPBOARD
. Neither of them is "legacy".xclip
has to leave a background process running to serve the selection it sets to any processes requesting it. It's mostly useless when the selection is empty, but it does go away as soon as anything else is selected/copied, and it is surely not a security risk.os.system
(or system
in any language), except to run a shell command specified by the user (like !
in less
). It uses the shell (specifically, /bin/sh
), which (because it is meant for interactive use) requires various kinds of quoting to avoid misinterpretation of generated input, it affects signal handling, it can't set up the child's open files directly, and it makes it all too easy to ignore the exit status of the child.xclip
and xsel
, as mentioned, are widely available (both are in the Ubuntu repositories, for instance). You run external programs in Python using subprocess
; in Python 3.5 or better it looks like one of
subprocess.run("xclip",stdin=subprocess.DEVNULL)
subprocess.run(["xclip","-selection","clipboard"],input="")
subprocess.run(["xsel","-c"])
(The choice between stdin
and input
matters more if you don't immediately wait on the program to exit.) xsel
has an explicit --clear
option, which avoids the need for input and a background process.
With any of these, you'll need to treat each of the two common selection types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With