Will
Will

Reputation: 41

How to have pyautogui turn a hotkey into a variable

I am trying to get pyautogui to copy a number, then turn that number into a variable. Here is my code that is trying to achieve that but it just returns "none". How do I fix this? I want it to copy the number then turn test1 into that number amount.

pyautogui.mouseDown()
pyautogui.moveRel(100, 0) #####FIND DOLLAR AMOUNT MOVE
pyautogui.mouseUp()
pyautogui.hotkey('ctrl', 'c')
test1 = pyautogui.hotkey('ctrl', 'v')
print(test1)

Upvotes: 2

Views: 2882

Answers (2)

Velibor Pjevalica
Velibor Pjevalica

Reputation: 31

Hampus Larsson is right: in order to collect data you need to use the clipboard. An alternative way is to use pyperclip module and the paste method from there.

For example:

import pyperclip

pyautogui.hotkey('ctrl', 'c')
test1 = pyperclip.paste()

Upvotes: 3

Hampus Larsson
Hampus Larsson

Reputation: 3100

pyautogui doesn't doesn't return a value with the method hotkey(), so when you try to save the output, you just capture the "none" that the method returns by default.

If you want to gather what you just copied, then you will need to target the clipboard of your computer. If you're running Windows, then that is relatively simple. Just use Powershell!

import subprocess
clipboard = subprocess.check_output("powershell.exe Get-Clipboard", stderr=subprocess.STDOUT, shell=True)
clipboard = clipboard.decode() #Subprocess.check_output() returns bytes, so if you want to handle it like a string, this is needed to "decode" it.

As you can see above, I simply used the windows Powershell to execute the command Get-Clipboard which returns a string representation of whatever you have in your clipboard. The only downside to using this method of retrieval is that you have to wait while your computer opens up a Powershell-window in the background and executes the command.

Upvotes: 1

Related Questions