How to copy to clipboard from browser using python 3.10.4 and Ubuntu 22.04? - clipboard

I have the following code that is automating a process in the browser.
At the line pt.click(clicks=3) I can get the text selected in the input box (Chrome). At the line pc.copy() I should copy this text and send it to the variable self.message to be processed. This step is not working.
There are a lot of documents and tutorials on how to do that on Windows and Mac, not in Ubuntu, specially in Ubuntu 22.04.
I am using OS Ubuntu 22.04 and Python 3.10.4.
What am I missing?
from turtle import right
import cv2 as cv
from time import sleep
# Waiting time
print('Waiting 2s')
sleep(2)
import pyautogui as pt
import paperclip as pc
from tkinter import ttk
....
def nav_message(self):
try:
clipPicCenter = pt.locateCenterOnScreen('./clip_pic.png', confidence=0.7)
# print('LocateCenter clip_pic', clipPicCenter)
pt.moveTo(clipPicCenter[0]+48, clipPicCenter[1]-60, duration=self.speed)
pt.click(clicks=3)
sleep(.9)
self.message = pc.copy() //Out PUT - Pyperclip do not have the method copy()
print(self.message)
# pt.click(button='right', clicks=1)
# pos = pt.position()
# pt.moveTo(pos[0]+20, pos[1]-300, duration=self.speed)
# txt = pt.click()
# print(txt)
# self.nav_input_box()
# pt.write(txt)
# txt = pt.hotkey("ctrl", "c") # copy the text (simulating key strokes)
# pt.click(button=right)
except Exception as e:
print ('Exception (nav_green_dot): ', e)

you can use this to copy something to your clipboard
import pyperclip
s1 = "Hello world"
pyperclip.copy(s1)
s2 = pyperclip.paste()
print(s2)

Line 9 you import paperclip as pc. You need to import pyperclip as pc (Note that it starts with py and not pa). The 2 are spelled similar, but your code imports the paperclip library for Django instead of the pyperclip library for managing the clipboard. Heres a codeblock with your fixed imports:
from turtle import right
import cv2 as cv
from time import sleep
# Waiting time
print('Waiting 2s')
sleep(2)
import pyautogui as pt
# this used to be "paperclip"
# "pyperclip" is what you need to import
import pyperclip as pc
from tkinter import ttk

Related

reading multiple images in python

I want to read multiple images in python I'm using this code but when I run it,nothing happens.
Could you tell me what is the problem?
import glob , cv2
import numpy as np
def read_img(img_list , img):
n=cv2.imread(img)
img_list.append(n)
return img_list
path = glob.glob("02291G0AR/*.bmp")
list_ = []
cv_image = [read_img(list_,img) for img in path]
print(cv_image)
"02291G0AR" is the folder where my images are save in. and it's near my code file
Perhaps it's just a matter of the print function not being the adequate one to use. I'd try:
for img in cv_image:
cv2.imshow('image',img)

`ProcessPoolExecutor` works on Ubuntu, but fails with `BrokenProcessPool` when running Jupyter 5.0.0 notebook with Python 3.5.3 on Windows 10

I'm running Jupyter 5.0.0 notebook with Python 3.5.3 on Windows 10. The following example code fails to run:
from concurrent.futures import as_completed, ProcessPoolExecutor
import time
import numpy as np
def do_work(idx1, idx2):
time.sleep(0.2)
return np.mean([idx1, idx2])
with ProcessPoolExecutor(max_workers=4) as executor:
futures = set()
for idx in range(32):
future = winprocess.submit(
executor, do_work, idx, idx * 2
)
futures.add(future)
for future in as_completed(futures):
print(future.result())
... and throws BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.
The code works perfectly fine on Ubuntu 14.04.
I've understand that Windows doesn't have os.fork, thus multiprocessing is handled differently, and doesn't always play nice with interactive mode and Jupyter.
What are some workarounds to make ProcessPoolExecutor work in this case?
There are some similar questions, but they relate to multiprocessing.Pool:
multiprocessing.Pool in jupyter notebook works on linux but not windows
Closer inspection shows that a Jupyter notebook can run external python modules which is parallelized using ProcessPoolExecutor. So, a solution is to do the parallelizable part of your code in a module and call it from the Jupyter notebook.
That said, this can be generalized as a utility. The following can be stored as a module, say, winprocess.py and imported by jupyter.
import inspect
import types
def execute_source(callback_imports, callback_name, callback_source, args):
for callback_import in callback_imports:
exec(callback_import, globals())
exec('import time' + "\n" + callback_source)
callback = locals()[callback_name]
return callback(*args)
def submit(executor, callback, *args):
callback_source = inspect.getsource(callback)
callback_imports = list(imports(callback.__globals__))
callback_name = callback.__name__
future = executor.submit(
execute_source,
callback_imports, callback_name, callback_source, args
)
return future
def imports(callback_globals):
for name, val in list(callback_globals.items()):
if isinstance(val, types.ModuleType) and val.__name__ != 'builtins' and val.__name__ != __name__:
import_line = 'import ' + val.__name__
if val.__name__ != name:
import_line += ' as ' + name
yield import_line
Here is how you would use this:
from concurrent.futures import as_completed, ProcessPoolExecutor
import time
import numpy as np
import winprocess
def do_work(idx1, idx2):
time.sleep(0.2)
return np.mean([idx1, idx2])
with ProcessPoolExecutor(max_workers=4) as executor:
futures = set()
for idx in range(32):
future = winprocess.submit(
executor, do_work, idx, idx * 2
)
futures.add(future)
for future in as_completed(futures):
print(future.result())
Notice that executor has been changed with winprocess and the original executor is passed to the submit function as a parameter.
What happens here is that the notebook function code and imports are serialized and passed to the module for execution. The code is not executed until it is safely in a new process, thus does not trip up with trying to make a new process based on the jupyter notebook itself.
Imports are handled in such a way as to maintain aliases. The import magic can be removed if you make sure to import everything needed for the function being executed inside the function itself.
Also, this solution only works if you pass all necessary variables as arguments to the function. The function should be static so to speak, but I think that's a requirement of ProcessPoolExecutor as well. Finally, make sure you don't execute other functions defined elsewhere in the notebook. Only external modules will be imported, thus other notebook functions won't be included.

Python 3.2 script not working and/or importing tkinter when running from Linux desktop

I'm really puzzled by this, but the answer is probably quite simple and just can't see it:
I have a series of python modules that work fine from within the python interpreter, but nothing happens when running from a GUI situation. I've tried creating a .desktop file, adding shebangs, changing permissions to 777 and renaming to .pyw for all the modules. A single test module works fine on its own, so I know that it's not a typo error.
If I click the main module .pyw file and click 'Run' from the system dialogue nothing happens at all. Similarly the .py file (and the .desktop via menu)... nothing. Here is the start of my code:#
#!/usr/bin/python3
import tkinter as tk, imp, sys
root = tk.Tk()
msg = tk.messagebox
sdg = tk.simpledialog
import capitaliser_cfg as cfg, fileio as io
imp.reload(cfg) ; imp.reload(io)
### GO AND GET COUNTY LIST ####
# Nb: attach to config for simplicity
cfg.counties = io.getfilelist("counties.txt", "London")
if not type(cfg.counties)==list:
k = msg.showerror(cfg.version, cfg.counties)
root.destroy()
root.mainloop()
### GO AND GET DICTIONARY ####
cfg.tempdict = [[],[],[]]
cfg.spelldict = io.getdictionary("addressdict.txt","roda","Road")
if not type(cfg.spelldict)==dict:
k = msg.showerror(cfg.version, cfg.spelldict)
root.destroy()
root.mainloop()
import thinbutton as tb, labelradio as lr, fieldblock as fb, bigbutton as bb
import textblock as tx, padding as pd, widget_tools as wt
import capitaliser_mth as mth
import capitaliser_bnd as bnd
imp.reload(tb) ; imp.reload(lr) ; imp.reload(fb) ; imp.reload(bb)
imp.reload(tx) ; imp.reload(pd) ; imp.reload(wt) ;
imp.reload(mth)
imp.reload(bnd)
If I put k = msg.showerror("xxxx","yyyy") after the line sdg = tk.simpledialog, still nothing happens which leads me to believe that tkinter is not loading for some reason.
Any ideas anyone ?
For Python 2 try:
import tkMessageBox
import tkSimpleDialog
msg = tkMessageBox
sdg = tkSimpleDialog
or simpler:
import tkMessageBox as msg
import tkSimpleDialog as sdk
For Python 3 try:
from tkinter import messagebox
from tkinter import simpledialog
msg = messagebox
sdg = simpledialog
or simpler:
from tkinter import messagebox as msg
from tkinter import simpledialog as sdg

from Gui import * in python 3?

I'm trying this:
import os, sys
from Gui import *
import Image as PIL
import ImageTk
class ImageBrowser(Gui):
def __init__(self):
Gui.__init__(self)
self.button = self.bu(command=self.quit, relief=FLAT)
def image_loop(self, dirname='.'):
files = os.listdir(dirname)
for file in files:
try:
self.show_image(file)
print (file)
self.mainloop()
except IOError:
continue
except:
break
def show_image(self, filename):
image = PIL.open(filename)
self.tkpi = ImageTk.PhotoImage(image)
self.button.config(image=self.tkpi)
def main(script, dirname='.'):
g = ImageBrowser()
g.image_loop(dirname)
if __name__ == '__main__':
main(*sys.argv)
I'm getting an error that says:
from Gui import *
ImportError: No module named Gui
I'm assuming "from Gui import *" doesn't work in python 3, does anyone know how to do this in python 3? Thank you so much (:
If you are talking about the Gui module that comes with Swampy, then
in order to use Gui with Python3, you'll need to install the Python3 version of Swampy.

How use Django with Tornado web server?

How do I use Django with the Tornado web server?
it's very simple ( especially with django 1.4) .
1 - just build your django project( and apps ) and make sure it works fine.
2- create a new python file at the root folder ( same dir where you used django-admin.py startproject)
3- then copy the code below , edit the os.environ['DJANGO_SETTINGS_MODULE'] line, and paste it in that new .py file.
import os
import tornado.httpserver
import tornado.ioloop
import tornado.wsgi
import sys
import django.core.handlers.wsgi
#sys.path.append('/home/lawgon/') # path to your project ( if you have it in another dir).
def main():
os.environ['DJANGO_SETTINGS_MODULE'] = 'myProject.settings' # path to your settings module
application = django.core.handlers.wsgi.WSGIHandler()
container = tornado.wsgi.WSGIContainer(application)
http_server = tornado.httpserver.HTTPServer(container)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
Django 1.6+ it should be like this:
import os
import tornado.httpserver
import tornado.ioloop
import tornado.wsgi
from django.core.wsgi import get_wsgi_application
def main():
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' # path to your settings module
application = get_wsgi_application()
container = tornado.wsgi.WSGIContainer(application)
http_server = tornado.httpserver.HTTPServer(container)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
UPDATE:
I created a minimal working demo which shows how to use the Tornado web server to run nicely with django:
https://github.com/tamasgal/django-tornado
ORIGINAL POST:
Just a remark: The WSGI application workflow has been changed from 1.6 to 1.7. You have to replace the import
import django.core.handlers.wsgi
with
from django.core.wsgi import get_wsgi_application
and change the application initialisation from
application = django.core.handlers.wsgi.WSGIHandler()
to
application = get_wsgi_application()
This is the modified code from the Moayyad Yaghi's answer:
import os
import tornado.httpserver
import tornado.ioloop
import tornado.wsgi
import sys
import django.core.handlers.wsgi
from django.core.wsgi import get_wsgi_application
#sys.path.append('/home/lawgon/') # path to your project ( if you have it in another dir).
def main():
os.environ['DJANGO_SETTINGS_MODULE'] = 'myProject.settings' # path to your settings module
application = django.core.handlers.wsgi.WSGIHandler()
application = get_wsgi_application()
container = tornado.wsgi.WSGIContainer(application)
http_server = tornado.httpserver.HTTPServer(container)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
There's a project called tornado-proxy that would help you. But I would like to recommend that you use Nginx. In the Nginx config you could now use proxy_pass to direct your calls like this:
location /comet {
proxy_pass http://localhost:8081;
}
location / {
proxy_pass http://localhost:8080;
}
In real world you would connect Django and some production-ready webserver with WSGI. This demo shows how you can run Tornado (and it's webserver) and Django side by side from one python module serving different URL prefixes: https://github.com/bdarnell/django-tornado-demo.
Tornado would block on serving any request directed to Django, though.

Resources