I've written a small program that will move the cursor every 5 seconds if it has not been moved.
I've provided the code below.
But it seems that no matter how much I move it, Windows 10 does not recognise it's movement.
To speed up the testing, I've set Turn Off display to 1 min in the Power plan settings. When this code it run through the CMD, I can see the mouse moving back and forward, but the screen still goes to sleep after 1 min.
Is there something I'm missing here?
Thank you
#! python3
import pyautogui as p
import time as t
# CTRL+C to stop it
p.FAILSAFE = False
try:
while True:
# get current mouse position
x1,y1 = p.position()
positionStr1 = 'X: ' + str(x1).rjust(4) + ' Y: ' + str(y1).rjust(4)
print("check1")
print(positionStr1, end='')
print("\n")
# wait 5 sec
t.sleep(5)
#check the position again
x2,y2 = p.position()
positionStr2 = 'X: ' + str(x2).rjust(4) + ' Y: ' + str(y2).rjust(4)
print("check2")
print(positionStr2, end='')
print("\n")
if positionStr1 == positionStr2:
p.moveRel(200,0, duration=.1)
p.moveRel(-200,0,duration=.1)
p.moveRel(200,0, duration=.1)
p.moveRel(-200,0,duration=.1)
else:
print('mouse moved')
except KeyboardInterrupt:
print('\nDone')
Related
I have written the following two scripts to show the current mouse position in the console:
Using tkinter:
import tkinter
import time
print('Press Ctrl-C to quit.')
p=tkinter.Tk()
try:
while True:
x, y = p.winfo_pointerxy()
positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
print(positionStr, end='')
print('\b' * len(positionStr), end='', flush=True)
time.sleep(1)
except KeyboardInterrupt:
print('\n')
1535, 863
Using pyautogui
import pyautogui, sys
import time
print('Press Ctrl-C to quit.')
try:
while True:
x, y = pyautogui.position()
positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
print(positionStr, end='')
print('\b' * len(positionStr), end='', flush=True)
time.sleep(1)
except KeyboardInterrupt:
print('\n')
1919, 1079
Why these two are different? What is the difference between pyautogui.position() and tkinter.winfo_pointerxy()?
The referred question in comment doesn't answer my question because I want to know the difference between the two functions and how to get similar output.
As Stated In The Original Documentation Of Both Libraries
w.winfo_pointerxy(): Returns a tuple (x, y) containing the coordinates of the mouse pointer relative to w's root window.
Tkinter Documentation
While pyautogui.position() gives with respect to the left top corner of your screen.
PyAutoGUI Documentation
Use This x = p.winfo_pointerx() - p.winfo_rootx()
y = p.winfo_pointery() - p.winfo_rooty()
To Know More Getting the absolute position of cursor in tkinter
import pyautogui
import keyboard
while keyboard.is_pressed('q') == False:
get1 = input('\nGet Cords Press Enter! \n')
pos1 = pyautogui.position()
print(str(pos1[0]) + ',' + str(pos1[1]))
This will print your x, y cords every time you press enter to the console. When you're done, you can quit by pressing Q.
Not a lot of code needed and works pretty much flawlessly.
this is my code:
from threading import Timer
timeout = 5
t = Timer(timeout, print, ['Sorry, times up'])
t.start()
count_push1 = + 1
print("Please push the button to count up.You have 5 seconds.")
while True:
if bool(push_button1.read()):
press_count = + 1
print(press_count)
sleep(0.2)
break
else:
print('You pressed', press_count, 'times.')
break
break
I want the user to have 5 seconds.In that 5 seconds, the user will click a button, and timer will reset to 5 seconds.If button is not clicked in 5 seconds,it shows the total number of times user pressed the button.I tried but when I run the code,the code automatically ends.Someone help please
You have the order of the operators wrong. In your while loop, you need to change the counter to count_push1 += 1
At the top where you define the variable as being 1, I would remove the the + for readability.
Edit: count_push1 += 1 is short for count_push1 = count_push1 + 1
I am attempting to program a defusable bomb for a csgo prop and was trying to make it as close as i can to the original thing. I have got everything working smoothly. An entry code and a Timer. The only thing I need to do is add a defusable section to it. Whilst the Bombs timer is running I would need to be able to cancel that action with an Input Code. Where, and what would I put?
I have tried doing a
defuse = input("Defusal Code")
if defuse == "7355608":
break
import time
while True:
uin = input("")
try:
when_to_stop = abs(int(uin))
except KeyboardInterrupt:
break
except:
print("NAN!")
while when_to_stop > 0:
s, ms = divmod(when_to_stop, 100)
m, s = divmod(s, 60)
time_left = str(m).zfill(2) + ":" + str(s).zfill(2) + ":" + str(ms).zfill(2)
print(time_left, end="\r")
time.sleep(0.01)
when_to_stop -=1
print()
print("BOMB DETONATED")
Im using Pyautogui to print mouse's current position.
After i print the first coordinates, i want to delete it instantly and print the next coordinates.
import pyautogui as p
print('Press Ctrl-C to quit.')
try:
while True:
x, y = p.position()
positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
print(positionStr, end='') #printing current position
print('\b' * len(positionStr), end='', flush=True) #deleting previous print
except KeyboardInterrupt:
print('\nDone')
Instead of deleting the previous print, it prints the next coordinates with some weird squares.
I'm developing a screen capture tool, this tools aims to help software developers understand how users ended up crashing the application. The idea is to start screen capture once the mouse starts moving and stop it after 5 minutes the mouse didn't move. screen capture works fine through subprocess with ffmpeg, the only remaining problem (except for the application crashes) is to start and stop the screen capture. How can I do this? ideally it would work with condition variable but even a loop which tests if the mouse moved in the last second would do. Is there any chance python supports something like OnMouseMove()?
A loop + pywin32, like this:
import win32api
from time import sleep
count = 0
savedpos = win32api.GetCursorPos()
while(True):
if count>20*5: # break after 5sec
break
curpos = win32api.GetCursorPos()
if savedpos != curpos:
savedpos = curpos
print "moved to " + str(savedpos)
sleep(0.05)
count +=1
wxPython gives you access to a whole set of OnMouse events that you can bind to.
After considering my alternatives I think this the right way to handle my problem, please note I've updated the code to support remote desktop disconnect by checking if the GetCursorPos() throws an exception, also please note that when closing the remote desktop ffmpeg outputs
[dshow # ] real-time buffer full! frame dropped!
But the output file looks fine to me. This script was tested on Windows server 2012
# http://ffmpeg.zeranoe.com/builds/
# http://www.videohelp.com/tools/UScreenCapture
# http://sourceforge.net/projects/pywin32/files/pywin32/
import time, win32api, threading, subprocess, datetime, string, winerror
StopRecordingTimeout = 10
def captureFunction():
pos = None
proc = None
counter = 0
while True:
time.sleep(1)
exceptFlag = False
try:
newPos = win32api.GetCursorPos()
if pos == None:
pos = newPos
except Exception as e:
if e[0] == winerror.ERROR_ACCESS_DENIED:
exceptFlag = True
if newPos != pos and proc != None:
# mouse moved and we are recording already so just make sure the time out counter is zero
counter = 0
elif newPos != pos and proc == None:
# mouse moved and recording didn't start already
fileName = filter(lambda x : x in string.digits, str(datetime.datetime.now()))
fileName = 'output' + fileName + '.flv'
print 'start recording to ' + fileName
proc = subprocess.Popen('ffmpeg -f dshow -i video=UScreenCapture ' + fileName)
elif proc != None and (newPos == pos or exceptFlag):
# mouse didn't moved and recording already started
if counter < StopRecordingTimeout and not exceptFlag:
counter = counter + 1
print 'stop recording in ' + str(StopRecordingTimeout - counter) + ' seconds'
elif exceptFlag or counter >= StopRecordingTimeout:
print 'stop recording'
proc.terminate()
proc = None
counter = 0
pos = newPos
print 'start'
captureThread = threading.Thread(target = captureFunction)
captureThread.start()
captureThread.join()
print 'end'