I'm trying to write a python script which would allow me to paste large pieces of code. Now I can get the system to paste text from a variable. However the code I want to paste is long and has a lot of special characters in it. Is there any way I can get around this easily?
Here is the code I have at present.
import pyautogui
from tkinter import Tk
root = Tk()
root.withdraw()
result = 'Text to Paste'
x, y = pyautogui.position()
pyautogui.click(x, y)
pyautogui.typewrite(result)
import pyautogui, time, pyperclip # pyperclip used for copy and paste
var1 = ("words block here") # you replace this with large words
pyautogui.click(x=399, y=600) # click where you want to paste "var1" value
time.sleep(1) # delay
pyperclip.copy(var1) # variable that stores your pasting block
time.sleep(1) # delay
pyautogui.hotkey("ctrl", "v") # and paste it with pyautogui.
Related
I wrote some code to help to copy and paste multiple lines in a program that doesn't allow you to copy and paste multiple rows nicely like excel does. I've tried writing this tool in AHK but something about AHK doesn't seem to play nice with the program in question (RSLogix studio 5000, AHK always misses lines when copy and pasting). This python code works nicely and doesn't miss lines when copying or pasting, but I've encountered a new issue. Despite what I've set the hotkeys to (ctrl 1 brings up a window asking how many lines you'd like to copy or paste, ctrl 2 copies that many lines, ctrl 3 pastes that many lines) pressing ctrl always brings up the input window. If I remove the input window and hardcode the value for "lines" then everything works as expected. Something about this window is making the program act strangely. Does anyone have any ideas?
thanks in advance for your time:)
import pyautogui
import easygui
import keyboard
import pyperclip
import time
from pynput.keyboard import HotKey, Key, KeyCode, Listener
from pynput import keyboard
copy_list=[]
lines = 0
def function_1():
global lines
lines = easygui.integerbox("Enter number of lines to copy")
print(lines)
def function_2():
global lines
copy_list.clear()
for x in range(int(lines)):
pyautogui.hotkey('ctrl', 'c')
clp=pyperclip.paste()
pyperclip.copy("")
copy_list.append(clp)
pyautogui.press('down')
print(copy_list)
def function_3():
global lines
for x in range(int(lines)):
pyperclip.copy(copy_list[x])
pyautogui.hotkey('ctrl', 'v')
pyautogui.press('enter',presses=3,interval=0.05)
with keyboard.GlobalHotKeys({
'<ctrl>+1': function_1,
'<ctrl>+2': function_2,
'<ctrl>+3': function_3}) as h:
h.join()
I’m doing some testing activity which requires me to capture screenshot of applications/DB etc and save it to a document. The whole activity has more than 50 screenshots. Is there a way in Python through which I can take a screenshot with windows shortcut key( eg; CTRL ALT shift C) and it appends the image to a document file. I believe the python program should be running in background like nohup in Unix.
For storing screen captures in Word using a hotkey, you can use a combination of libraries.
Use win32gui to open Word
Use python-docx to update the document and save
Use PyAutoGUI to do the screen capture
Use keyboard to listen for the hotkey
For this script to work, you will need to create the Word document before running the script.
# Need these libraries
# pip install keyboard
# pip install PyAutoGUI
# pip install python-docx
# pip install win32gui
import keyboard
import pyautogui
from docx import Document
from docx.shared import Inches
import win32gui
from PIL import ImageGrab
shotfile = "C:/tmp/shot.png" # temporary image storage
docxfile = "C:/tmp/shots.docx" # main document
hotkey = 'ctrl+shift+q' # use this combination anytime while script is running
def do_cap():
try:
print ('Storing capture...')
hwnd = win32gui.GetForegroundWindow() # active window
bbox = win32gui.GetWindowRect(hwnd) # bounding rectangle
# capture screen
shot = pyautogui.screenshot(region=bbox) # take screenshot, active app
# shot = pyautogui.screenshot() # take screenshot full screen
shot.save(shotfile) # save screenshot
# append to document. Doc must exist.
doc = Document(docxfile) # open document
doc.add_picture(shotfile, width=Inches(7)) # add image, 7 inches wide
doc.save(docxfile) # update document
print ('Done capture.')
except Exception as e: # allow program to keep running
print("Capture Error:", e)
keyboard.add_hotkey(hotkey, do_cap) # set hot keys
print("Started. Waiting for", hotkey)
keyboard.wait() # Block forever
I'm trying to build a lightweight Text-to-Speech GUI where I can select text in, say, Word or Chrome, and then press a button in my GUI and have it read it.
I've already figured out all the pieces to create the GUI and get the TTS to work, but I can't get the form factor right. I'm trying to mimic the form factor of Dragon Naturally Speaking's text-to-speech because, well it's simple and what I'm used to.
Here are the missing steps in the user story I can't get to work, in order:
1) user highlights text in an application (word, chrome, notepad, whatever) with the mouse and presses the gui button
2) data from the external application is pulled in as UTF-8 and stored in a variable called "text"
I know there's a problem in that several windows can have selected text. My solution is to pull the selected text from the most recently previously selected window.
Right now the kludgy work around is to Ctrl-C whatever text I want read and then press the button, because I can pull the data from the clipboard, but this is a really terrible user experience and confusing, as well. I tried using pyperclip to get the button to put the text in the clipboard, but it doesn't seem to work, so I'm not sure if the clipboard idea is a dead end.
def select_text(self):
#copy
pyperclip.copy() # doesn't work
#get text
win32clipboard.OpenClipboard()
text = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
#say it!
self.say_text(text)
I can't seem to find anything like this anywhere, and I have no idea where to start. Any help would be appreciated.
I think I figured it out. It's pretty ugly, but it works; I'm a beginner at coding, and this is just a hobby for me. Honestly, I'm just happy to have it working.
I've bound the command to Alt_L+Q; I'll probably add the Alt_R+Q later, but I'll never use them. For some reason using Alt alone without the L or R doesn't work.
Also, Without the first sleep statement, it doesn't work at all. The second sleep statement is precautionary.
# set clipboard data
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText('No text is currently selected.')
win32clipboard.CloseClipboard()
text = None #this is what will be read
chg_rate = 0 #reading speed +/- 0.0 to 1.0
chg_vol = 0 #volume +/- 0.0 to 1.0
def get_text():
#current_window = win32gui.GetForegroundWindow()
import pythoncom
pythoncom.CoInitialize()
cw = win32com.client.Dispatch('WScript.Shell')
time.sleep(.7)
cw.SendKeys('^c') #copies text
time.sleep(.2)
#get text
win32clipboard.OpenClipboard()
text = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
return text
#define the hot key
def create_hotkey():
# The key combination to check
COMBINATIONS = [
{keyboard.Key.alt_l, keyboard.KeyCode(char='Q')},
{keyboard.Key.alt_l, keyboard.KeyCode(char='q')}
]
# The currently active modifiers
current = set()
def execute():
text = get_text()
if not isinstance(text, str):
text = "Selected input is not UTF-8 text."
say_text(text)
def on_press(key):
if any([key in COMBO for COMBO in COMBINATIONS]):
current.add(key)
if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):
execute()
def on_release(key):
if any([key in COMBO for COMBO in COMBINATIONS]):
current.remove(key)
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
#run hotkey
create_hotkey()
I just moved from Matlab to Python. So I am looking hopefully to re-build my GUI in Matlab Guide with Page Python (only hopeful for better performance for big data)
I designed several Push Buttons and inside the code I try to write the below code just beneath Button1.configure.
I can not take out seop value from this clicked () function although I even define it as global variable. I need seop for whole the program.
self.Button1.configure(text='''Data''')
def clicked():
global seop
from tkinter import filedialog, messagebox
fname = filedialog.askopenfilename (initialdir="C:\Sgty")
import numpy as np
seop = np.loadtxt (fname)
messagebox.showinfo ('Data Import', 'Int')
s1 = self.Button1.configure (command=clicked, text="Import Data")
I'm running a script in a console to help me in a repetitive task.
I want open image in gallery and write down numbers from an image.
feh = subprocess.Popen(['feh', 'tmp.jpg'])
print ("Input number from image:")
number = input()
feh.kill()
This code works, but window managers keep focusing feh, which adds an additional step of refocusing console window. Is there an additional argument I can pass to prevent this behavior or another way around?
One dirty workaround is to simply refocus window by mouse.
I used xdotool
feh = subprocess.Popen(['feh', 'tmp.jpg'])
time.sleep(0.1)
subprocess.call(['xdotool', 'click', '1'])
something = input()
feh.kill()
Python has native GUI modules, named tkinter.
GUI program can be terrifyingly easy to write, if it is python.
#!/usr/bin/python2 -i
from Tkinter import *
from PIL import *
import os
files = [f for f in os.listdir('.') if f.endswith(".png")]
root = Tk()
label = Label(root)
label.pack()
for name in files:
im = PhotoImage(file=name)
label.config(image=im)
print("your number plz")
input_str = raw_input()