Michael Larsson
Michael Larsson

Reputation: 197

Python pyautogui hotkey with variable - works without like ('ctrl','a')

When i run:

pyautogui.hotkey('ctrl','a')

it works fine.

But when i put the string in a variable it doesn't work:

my_var = "'ctrl','a'"    
pyautogui.hotkey(my_var)

my_var is a string object, python do not trow an error, but nothing happens.

If I try with a list objekt like, dosen't work:

pyautogui.hotkey(list(my_var))

I can do:

print(my_var)

And I get back: 'ctrl','a'

I can make pyatogui.press(tab) work from a variable.

I have tryed some kind of raw string:

my_var = r"'ctrl','a'"

without any succes.

In PyCarm the comma is orange (probably a list of arguments), and green when string is put in a variable.

I upload an image of my example code:

enter image description here

And the complete code for anyone to try (maybe I should warn that it when it works press ctrl+a, witch in most programs are select all):

import time
import pyautogui

time.sleep(3)

# This part works
pyautogui.hotkey('ctrl','a')

# This part do not work, no error
my_var = "'ctrl','a'"
pyautogui.hotkey(my_var)

I run Windows10 and python 3.7 and PyCharm.

Upvotes: 1

Views: 4322

Answers (2)

Michael Larsson
Michael Larsson

Reputation: 197

Thanks rafalou38 for giving me some feedback, I been trying this for 2 h. Your ide actually works for this special case if we first do a split, and then add the str() funktion to the seperate list elements, I did it with the pluss sign insted as below:

my_var = "ctrl+a"
my_var = my_var.split('+')
pyautogui.hotkey(str(my_var[0]),str(my_var[1]))

This will be good enough for all cases with 2 arguments, and I could easy hardcode a case for 3 as well with:

len(my_var)

will give me how many elements it has, there could be some cases with 3 or even 4 but then very unlikly above that. Thanks a lot for the input. Great now I can go to bed, thinking this can be fixed for all likly cases.

I tried this for making a new folder witch is of order 3, and it worked out on first try:

my_var = "ctrl+shift+n"
my_var = my_var.split('+')
pyautogui.hotkey(str(my_var[0]),str(my_var[1]),str(my_var[2]))

:)

Upvotes: 1

rafalou38
rafalou38

Reputation: 602

pyautogui.hotkey('ctrl','a')
enter code here

Pases 2 arguments to the function

But when you use this:

my_var = "'ctrl','a'"    
pyautogui.hotkey(my_var)

You pases just 1 argument to the function which doses not work in this case

You can use:

my_var = ['ctrl','a']
pyautogui.hotkey(my_var[0],myvar[1])

or

my_var = {”first”:'ctrl',”second”:'a'}
pyautogui.hotkey(my_var[”first”],myvar[”second”])

Upvotes: 4

Related Questions