I am trying to make an autoclicker that clicks the up key for 10 seconds, then the down key for 10 seconds. I am using the pyautogui module for this and I am getting this error for some reason whenever I run:
keyUp() missing 1 required positional argument: 'key'
This is the rest of the code:
import pyautogui, time
time.sleep(2)
x = 0
times = 20
while True:
if x == times:
print("Stopped Clicking")
break
else:
pyautogui.keyUp(), time.sleep(10), pyautogui.keyDown()
x += 1
Check the pyautogui docs: https://pyautogui.readthedocs.io/en/latest/keyboard.html#the-press-keydown-and-keyup-functions
The keyUp and keyDown don't correspond to the Up key and the Down key, they correspond to a given key (which you have to supply as the argument) going up and down. For example, keyDown('space') holds the spacebar down and leaves it down until keyUp('space') is called.
What I think you want is to call the press function on the up and down keys, something like:
import pyautogui, time
time.sleep(2)
for _ in range(20):
pyautogui.press("up")
time.sleep(10)
pyautogui.press("down")
print("Stopped Clicking")
Related
Iv'e been trying to create a countdown timer for a game in python however i'm not sure how to code it without including the input question for the time at the beginning of the code.
So far the code looks like this
import time
import datetime
# Create class that acts as a countdown
def countdown(s):
# Calculate the total number of seconds
total_seconds = s
# While loop that checks if total_seconds reaches zero
# If not zero, decrement total time by one second
while total_seconds > 0:
# Timer represents time left on countdown
timer = datetime.timedelta(seconds = total_seconds)
# Prints the time left on the timer
print(timer, end="\r")
# Delays the program one second
time.sleep(1)
# Reduces total time by one second
total_seconds -= 1
print("You have been caught.")
# Inputs for hours, minutes, seconds on timer
s = input("Enter the time in seconds: ")
countdown(int(s))
exit()
I want to make the code so it has an automatic countdown for 10 seconds as soon as the user presses enter. Any ideas?
If I understand your question correctly you just want the user to press the enter key instead of actually inputing a number? then you can just hard code the time value and call the function with that value, while using an empty input call to wait for a keypress.
input("Press enter to continue...")
countdown(10)
exit()
here you're not storing the value from input anywhere and just using the input function to block until the user presses enter.
You could do it this way:
import time
def countdown(time_sec):
while time_sec:
minutes, secs = divmod(time_sec, 60)
time_format = f'{minutes}:{secs}'
print(time_format, end='\r')
time.sleep(1)
time_sec -= 1
print("stop")
countdown(5)
i want create a script can hold down the space bar and press a key every 10 seconds, with one another key to close the loop but I made a mistake somewhere and I don't know how to fix it.
import keyboard
import time
time.sleep(8)
timer = 0
while True:
try:
while timer < 10:
time.sleep(0.1)
timer += 0.1
keyboard.press('space')
keyboard.press('z')
timer = 0
if keyboard.is_pressed('q'):
break
except:
break
I dont understand why if I press q, it won't stop the loop.
So I want to hold down the c key for lets say 0.2 seconds then without waiting even a little bit press space and release it without delay ( 0.0 seconds ) and to do that I thought using pyautogui.keyDown("")
and keyUp("") would help but it has a slight delay in it so like when I do
pyautogui.keyDown("c")
pyautogui.keyUp("C")
What it does is holds the key "c" for like some seconds but I didn't give it any delay I just want it to press c for 0.0 seconds my main thing is
import pyautogui
import time
time.sleep(0.5)
pyautogui.keyDown("c")
time.sleep(0.2) # so it would put 0.2 second delay in it i didnt know it had a delay in itself
pyautogui.keyUp("c")
time.sleep(0.5)
pyautogui.keyDown("space")
pyautogui.keyUp("space")
time.sleep(0.5)
pyautogui.keyDown("c")
time.sleep(0.2)
pyautogui.keyUp("c")
time.sleep(0.5)
pyautogui.keyDown("space")
pyautogui.keyUp("space")
The time.sleep is the delay I want it to be but it has a delay on its own without the time.sleep so thats too long for me to time my thing I tried doing pyautogui.typewrite but it glitches most of the times maybe if there is like a hold for x seconds thing please tell me how to do it
I looked at the documentation and apparently there is a .1 second delay between pyautogui commands, to allow you to break into the operation manually in case of runaway, documented here: #fail-safe. They warn against it, but you might be able to do this:
import pyautogui
import time
KEY_C = "c"
KEY_SPACE = "space"
time.sleep(0.5)
pyautogui.FAILSAFE = False # danger zone
pyautogui.keyDown(KEY_C)
time.sleep(0.2)
pyautogui.keyUp(KEY_C)
pyautogui.keyDown(KEY_SPACE)
pyautogui.keyUp(KEY_SPACE)
pyautogui.FAILSAFE = True # out of danger
# do it again
time.sleep(0.5)
pyautogui.FAILSAFE = False
pyautogui.keyDown(KEY_C)
time.sleep(0.2)
pyautogui.keyUp(KEY_C)
pyautogui.keyDown(KEY_SPACE)
pyautogui.keyUp(KEY_SPACE)
pyautogui.FAILSAFE = True
I'm trying to learn python and while learning I've come across a bit of a problem.
import time
import pyautogui
def SendScript():
time.sleep(2)
with open('script.txt') as f:
lines = f.readlines()
for line in lines:
time.sleep(2)
pyautogui.typewrite(line.strip())
pyautogui.press('enter')
SendScript()
I'm trying to print something to the screen every second time the 'enter' key has been pressed, but I'm an extreme beginner so I really don't know how to do that. Could someone help me accomplish this task?
You could create a new boolean variable to track if the enter key has been pressed before. That way, every time the for loop iterates, the value of pressed switches and only when the value of pressed is True will it print something.
import time
import pyautogui
def SendScript():
pressed = False
time.sleep(2)
with open('script.txt') as f:
lines = f.readlines()
for line in lines:
time.sleep(2)
if pressed:
print("Something")
pressed = not pressed
pyautogui.typewrite(line.strip())
pyautogui.press('enter')
SendScript()
From a more step-back approach, you could do:
events=['event1', 'event2', 'event3', 'event4', 'event5', 'event6', 'event7', 'event8']
counter = 0
for event in events:
counter += 1
if counter % 2 == 0: # ie do stuff when divisible by 2, ie when its even
print('print what you want to be printed every second time')
else:
pass
Of course you are not looping through events like I do in this example. The point is counting the events and only doing stuff when this count is even.
As indicated in another answer already, a simple toggle can be implemented with a bool and then code which toggles it every time something happens:
thing = False
:
if happens(something):
thing = not thing
This is fine for toggling between two states. A more general approach which allows for more states is to use a numeric variable and a modulo operator:
times = 0
maxtimes = 12
:
if happens(something):
times += 1
if times % maxtimes == 1:
print("ding dong")
The modulo could be compared to 0 instead if you want to print on the 12th, 24th etc iterations instead of the first, the 13th, etc, or of course any other offset within the period if that's what you want.
Another useful trick is to flip-flop between zero and some other value.
value = 0
othervalue = 1234
:
if happens(something):
value = othervalue - value
Of course, you can flip-flop between any two values actually; subtract the current value from their sum to get the other one.
Needless to say, just toggling or flip-flopping isn't very useful on its own; you'd probably add some (directly or indirectly) user-visible actions inside the if happens(something): block too.
You could use a generator for this:
def everySecondTime():
while True:
yield "hi"
yield "not hi"
mygen = everySecondTime()
print(next(mygen))
print(next(mygen))
print(next(mygen))
print(next(mygen))
This prints
hi
not hi
hi
not hi
I'm sure it's clear to you how you could adapt this to do some other actions instead.
Whether this approach is better than just using a boolean is highly debatable, but I thought I'd leave it here so you could learn about generators (the yield keyword) if you want to.
I am using Psychopy to create a psychological task. For a given routine, I would like the height of a polygon (rectangle) to increase with every key press (same key every time), until it reaches the maximum number of key presses (e.g. 10). I cannot figure out how to create a loop to count number of key presses within the same routine, nor how to use this to generate a variable that will constantly update the size of the polygon.
Here is what I have tried as code in the routine which gets stuck in while loop... and I am not sure if the loop should go in the code "Before Routine" or for "Each Frame"
total_key_count = 0
while True:
resp_key = event.waitKeys(keyList=['1'])
if resp_key == '1':
total_key_count = total_key_count + 1
# .. or break out of the loop if reach 10
elif total_key_count == 10:
break
Thanks!
Never use event.waitKeys() in a Builder code component. Builder is structured around a drawing loop that requires updating the screen and responding to events on every screen refresh. If you call waitKeys(), you pause execution completely until a key is pressed, which will completely break Builder's temporal structure.
In the Begin routine tab, put this:
key_count = 0
max_keys = 10
In the Each frame tab, put this:
key_press = event.getKeys('1')
if key_press: # i.e. if list not empty
key_count = key_count + 1
if key_count <= max_keys:
# increment the height of the stimulus by some value
# (use what is appropriate to its units):
your_stimulus.size[1] = your_stimulus.size[1] + 0.1
else:
# terminate the routine (if required)
continueRoutine = False
Note that getKeys(), unlike waitKeys() just checks instantaneously for keypresses. i.e. it doesn't pause, waiting for a key. This is fine though, as this code will run on every screen refresh, until the required number of keys have been pushed.
Presumably you also need to save some data about the response. This would best be done in the End routine tab, e.g.
thisExp.addData('completion_time', t) # or whatever needs recording