Copy-Paste In Python - python-3.x

I am new to python. So I wanted to improve my skills. Before posting this question I tried to find some code or an idea that would guide me with what I intend to do. I did see some examples and posts on SO and other sites. But they all(the ones I came across) showed how to do it for single object. Below is what I want to do.
I want to write a utility in python that would allow me to choose from content I want to paste based on what my last 10,say, copy commands were for.
suppose I clicked copy when selecting a folder and then later I selected some text and pressed ctrl+c. Now I want to get option that would let me paste both the folder as well as the text.
Is that possible?
Thanks.

You could save the last 10 text items from a clipboard using tkinter:
#!/usr/bin/env python3
from tkinter import Tk
from collections import deque
def call_repeatedly(root, delay, func, *args):
func(*args)
root.after(delay, call_repeatedly, root, delay, func, *args)
def poll_clipboard(root, items):
text = root.clipboard_get()
if not items or items[-1] != text:
items.append(text)
def main():
root = Tk()
root.withdraw() # hide GUI
clipboard_items = deque(maxlen=10) # save last 10 clipboard items
call_repeatedly(root, 50, poll_clipboard, root, clipboard_items) # ms
call_repeatedly(root, 1000, print, clipboard_items) # print every second
root.after(10000, root.destroy) # exit in 10 seconds
root.mainloop()
main()
It polls clipboard every 50 ms. Polling is bad in general if there is an alternative interface that could allow you to subscribe to the clipboard events to be notified when new item is copied into the clipboard.
will it work for any kind of content, text, images etc. ?
This code works with text only. In general, you could get/set other types e.g., images (gtk, qt might provide a cross-platform way to do it).
Will it allow me to copy-paste text across all the applications ?
You are working with a clipboard so yes, it should work across all applications that can
work with a clipboard.
Can we make it work as normal ctrl+c (copy command)
Copy command can be implemented using a set command e.g., from pyperclip.py:
def gtkSetClipboard(text):
cb = gtk.Clipboard()
cb.set_text(text)
cb.store()
gtkSetClipboard(text) copies text to the clipboard.

Related

How to Create a Cursor or Loading Indicator for an Infinite Loop

I am scraping current follow requests from Instagram. I have a main infinite loop that it making the requests and prints OK when it is done. I want to display an animated cursor or loading progress while it is downloading names.
while 1:
response = requests.get(IG_CFR_PAGE, headers=headers(""), params=params, cookies=cookies)
if response.status_code == 200:
cfr = response.json()
for entry in cfr["data"]["data"]:
#print(entry["text"])
usernames.append(entry["text"])
if cfr["data"]["cursor"]!= None:
params['cursor'] = cfr["data"]["cursor"]
time.sleep(1)
else:
break
else:
print(response.status_code)
print("Error in request .... aborting")
break
print("ok")
I looked for tqdm but it takes an iterable. In my case, I am just looping over JSON keys in line for entry in cfr["data"]["data"]: and so I guess can't use it. I just need suggestions as to know what should I use to indicate that this script is actually doing something. I just need suggestions or pseudocode is fine to send me in a right direction... the actual programming code is not needed as I will do that myself.
Thank you
As far as I'm aware, most functions that allow you to change the mouse cursor in Python are available only from various GUI modules - most of the popular ones, such as tkinter, PyQt5, pygame or others.
The problem is that most of these may only work when you've created a window of the GUI, which is probably unnecessary or not a nice idea if you're not using the same GUI, or any GUI for that matter. Even then, some may only take effect when the mouse pointer hovers over a certain widget in that GUI.
Note:
I've only (unsuccessfully) tried doing this with pygame.cursors before. It may be convenient because it even lets you create a custom shape with strings, or use a system cursor. But it displays a pygame.error: video system not initialized if you try doing this without having called pygame.display.init() first. I tried creating a window and setting a cursor, but it didn't seem to take effect.
After a quick google search for other ways to set an animated cursor, I came across this SO answer which might offer some insight if you're on windows.
Overall, using a terminal animation may probably be better and easier, so
this is an attempt at a basic answer for a loading animation in a terminal window :
(Of course, for an indefinite length of loop, it doesn't make sense to store a percentage completion etc, so this just animates at an arbitrary pace and repeats when it reaches the end)
i, w, d = 0, 20, 10000
while True:
# Do whatever
# No print statements except this last one
i = (i+1)%(w*d)
l = i//d
print("\r Processing... |" + " "*l+ "█" + " "*(w-l-1) +"|", end='')
i is used for iteration, w is the length of the bar, and d used to create some sort of 'delay', so that the bar doesn't change at every single iteration, but some slower (visible) speed
Edit: Important Note: The '\r' that resets the cursor position doesn't work in every terminal - it may still move to a new line for the next print() instead of the start of the same line - but this should most likely be fine in your system Terminal/cmd etc... May not be a good idea to run this in IDLE :P
Edit 2: Based on your comment, for a blinking indicator (using the same approach) -
i, d = 0, 300000
while True:
i = (i+1)%d
print("\r Working... " + ("█" if i < d/2 else " "), end='')

How to manipulate tkinter GUI from an imported file

I try to create a small GUI with tkinter. To make my code more readable I want to split the code in 2 files. One for the GUI information and one for the process informations. Or is it a bad idea?
So I create a gui.py where I import my process informations from program.py.
gui.py:
import tkinter as tk
from program import *
root = tk.Tk()
btn_Start = tk.Button(text="Start", command=start_loop)
btn_Stop = tk.Button(text="Stop", command=stop_loop, state=tk.DISABLED)
btn_Start.grid(row=1, column=0)
btn_Stop.grid(row=1, column=1)
root.mainloop()
program.py:
def start_loop():
print('disable Start button and enable Stop button')
# what is the code to disable the start button and enable the stop button?
def stop_loop():
print('disable Stop button and enable Start button')
# what is the code to disable the stop button and enable the start button?
How do I tell the button the disable/enable information in my program.py file? I do not understand how I get the information from the gui to the program and back to the gui?
Thanks for your help
For such a small program, it is overkill.
Looking at the tkinter programs I've written, all of them are between 200−300 lines. This is including headers, comments and blank lines. The number of actual code lines is 100−200.
In my opinion that is small enough to comfortably handle in an editor in one file.
Looking over most of my source code repositories, the longest Python files tend to top out at around 230 lines of actual code.
Keeping all the code in one file has significant advantages for a program when you need to install it. Just copy the file and you're done. No need for modules and a setup.py.

Tkinter CPU activity after inserting text from file

If I take a 25MB/190,000 line text file and dump it into a text widget the process finishes quickly but I still see python.exe using 50%CPU for another minute or so afterwards. The bigger the file, the longer it takes for the CPU to drop off to 0% usage. When I start loading multiple files into different text widgets they load into the widget instantly but the CPU stays at 50% and the GUI runs horribly slow until it finishes whatever its doing in the backend. Can someone explain to me why the CPU is still being used and why its impacting performance if the text is already in the widget? What is it needing to do? Any way around this?
from tkinter import *
file = r"C:\path\to\large\file.txt"
def doit():
with open(file, 'r') as f:
txt.insert('end', ''.join(f))
f.close()
main = Tk()
txt = Text(main)
txt.grid(row=0)
btn = Button(main, text="click here", command=doit)
btn.grid(row=1, columnspan=2)
main.mainloop()
I thought maybe it was because im handling the file line by line instead of loading the entire file into RAM. I tried readlines() but I get the same results.
Most likely it is calculating where the line breaks go, for lines past the area currently visible on the screen. With the numbers you gave, the lines average over 130 characters long; if some of them are considerably over that, this is a situation that Tkinter is known to be slow in.
You could perhaps turn off word-wrap (by configuring the Text with wrap=NONE), which would probably require that you add a horizontal scroll bar. If that is unacceptable, it's possible that adding newlines of your own could help, if there's some natural point at which to insert them in your data.
Note that ''.join(f) is a rather inefficient way to read the entire file into a single string - just use f.read() for that.

Remember search query in Sublime Text 3

Is there any way to make Sublime Text 3 remember the previously entered search query in the "go to anything"?
I frequently use the "go to anything" to jump to line numbers. If Sublime Text could remember the last entered query I would not have to remember the line number and type it again.
I am already familiar with the bookmarks function and it is not really an alternative solution.
You can use a plugin that saves the content of the gotoAnything-panel when its modified, and then puts the content on the panel when it gets opened.
Basic plugin example:
import sublime, sublime_plugin
class GotoAnythingSaver(sublime_plugin.EventListener): # Use EventListener
# In my case gotoAnything view id is 2.
def on_modified(self, view): # This is called when a view is modified (text changed)
if (view.id() == 2): # Save content
self.content = self.get_view_content(view)
def on_activated_async(self, view): # This is called when a view is activated
if view.id() == 2 and hasattr(self, 'content'): # Restore content if empty
if not self.get_view_content(view):
view.run_command('insert', {"characters":self.content})
def get_view_content(self, view):
return view.substr(sublime.Region(0, view.size()))
To save the plugin use menu Tools>new Plugin and then save it in the given folder (folder name should be User), use fileName GotoAnythingSaver.py.
Example result used to go to the same line again:
Edit: tested on Sublime Text 3 build 3103 on Linux Mint and Windows 10. OP says this plugin leave the gotoanything dysfunctional, this doesn't happened to me, but be careful.
I would appreciate if someone could test it or help me, because I am not sure if the identifier of the view associated with goto-anything panel is always 2.

QClipboard works funny under GNU/Linux

#!/usr/bin/python
from PyQt4.QtGui import QApplication, QClipboard
import sys
app = QApplication(sys.argv)
QApplication.clipboard().setText('yo', mode=QClipboard.Clipboard)
input() #wait for input
When I set mode=QClipboard.Clipboard (the default one), it doesn't work. It leaves old data in the clipboard and in the selection clipboard.
When I change it to mode=QClipboard.Selection (the one specific to X), it replaces both selection and primary clipboard with yo.
Question: why the "main thing" (mode defaults to QClipboard.Clipboard after all) doesn't work, while something that should work only conditionally (QClipboard.supportsSelection()) does the job? How can I make this work properly?
I can't actually reproduce the problem on my Linux system: it all works fine for me.
However, the docs say that the clipboard needs an event-loop on X11:
the X11 clipboard is event driven, i.e. the clipboard will not
function properly if the event loop is not running. Similarly, it is
recommended that the contents of the clipboard are stored or retrieved
in direct response to user-input events, e.g. mouse button or key
presses and releases. You should not store or retrieve the clipboard
contents in response to timer or non-user-input events.
So you might be able get your example working on your system by forcing the processing of queued events like this:
app.clipboard().setText('yo')
app.processEvents()
input()
Obviously that is a contrived "solution", though, and the correct way to do things is to start the event-loop and follow the advice in the docs.

Resources