I used lots of different source codes, and even copied and pasted but I keep getting random symbols that shift when i move my mouse over them
here is my code...
import pyautogui, time, sys
print('Press Ctrl-C to quit.')
try:
while True:
CurserPos = pyautogui.position()
print('\b' * len(CurserPos), end='\r')
sys.stdout.flush()
I will show the output as an image.
I am rather new to Python and would really appreciate some expert advice.
Thanks
Code :
import pyautogui
pyautogui.displayMousePosition()
Here is some output :
Press Ctrl-C to quit.
X: 0 Y: 1143 RGB: ( 38, 38, 38)
Here is the video where this is being demonstrated https://youtu.be/dZLyfbSQPXI?t=809
This code will print the live position of your mouse after every one second.
import pyautogui as py #Import pyautogui
import time #Import Time
while True: #Start loop
print (py.position())
time.sleep(1)
Pyautogui can programmatically control the mouse & keyboard.
More information about it can be found here https://pypi.org/project/PyAutoGUI/
Use pyautogui.displayMousePosition() instead of pyautogui.position()
If you want the coordinates of displayMousePosition stored in a variable, try this:
import pyautogui
def getMousePosition():
pyautogui.displayMousePosition()
coords = pyautogui.position()
return coords
Related
I have been learning python recently and decided to learn more about pyautogui, what you see down below is a macro of mine. My question is simple; is there a way to let this macro run in a specific window. For example: I want this macro to run in google chrome while I am in discord chatting with my friends (text channel so I'm not in the google chrome window). (Ignore my sloppy method of writing code)
import pyautogui
import random
import time
import mouse
#############################
tijd = 0
actief = 0
float (actief)
#############################
while not mouse.is_pressed('right'):
time.sleep(0.01)
bank_x1, bank_y1 = pyautogui.position()
time.sleep (0.5)
while not mouse.is_pressed('right'):
time.sleep(0.01)
bank_x2, bank_y2 = pyautogui.position()
print ("{} {} {} {}".format(bank_x1,bank_x2,bank_y1,bank_y2))
#############################
lijst = [[bank_x1,bank_x2,bank_y1,bank_y2,200,243],[1203,1236,721,749,23,49],[390,422,112,140,22,46]]
while not mouse.is_pressed('middle') or actief > tijd:
for i in range(0, 4):
x = random.randint(lijst[i][0], lijst[i][1])
y = random.randint(lijst[i][2], lijst[i][3])
pyautogui.moveTo(x, y)
wacht = random.randint(lijst[i][4], lijst[i][5]) / 100
time.sleep(wacht)
str (actief_str)
pyautogui.click()
pyautogui.press('esc')
No. Not with pyautogui.
Pyautogui simulates actual keyboard and mouse input to the system, not to a specific window. Thus, it will always act exactly the same as if you were pressing the keys and clicking the mouse yourself. So, no. You cannot use it to send keystrokes to background applications. The keystrokes will always effect the window that is focused, just as they do when you physically input them with a keyboard or mouse.
This question shows how you could achieve it with winapi, but it is much more complicated and less user-friendly than pyautogui.
I need to run a code for hours, and the computer I am working with has a (forced and unchangeable) screensaver policy. (It locks after 10 minutes). What can I do to prevent it? Is there any line of code to prevent that?
This worked for me. I'll just leave it here so people can use it.
import ctypes
ctypes.windll.kernel32.SetThreadExecutionState(0x80000002) #this will prevent the screen saver or sleep.
## your code and operations
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000) #set the setting back to normal
You can prevent screen saver by moving mouse cursor on a fixed period of time, below function can handle cursor moving.
import win32api
import random
def wakeup():
win32api.SetCursorPos((random.choice(range(100)),random.choice(range(100))))
This is a coded solution that you can place in your program (also works for Mac users):
pip3 install pyautogui
https://pypi.org/project/PyAutoGUI/ (Reference)
import pyautogui
import time
def mouse_move():
while True:
pyautogui.moveTo(100, 100, duration = 1) # move the mouse
time.sleep(60) # Every 1 min
pyautogui.moveTo(50, 100, duration = 1) # move the mouse
mouse_move()
Or, without the while loop, run it when required if your program is already within a while loop:
def mouse_move():
pyautogui.moveTo(50, 100, duration = 1) # move the mouse
mouse_move()
I want to simulate an event where I left click on the Windows desktop, I drag the mouse a little to create a Selection box to another point, and then keep holding the left button at that point for some time without the Selection box disappearing.
The problem is, I can't get him to keep the Selection box, whenever he gets to the other point the Selection box disappears indicating that the button has been released.
I tried to implement in Python using PyAutoGUI. I tried several ways to do this but still unsuccessfully. Is there any function I'm missing?
import time
import pyautogui
time.sleep(3)
while True:
pyautogui.moveTo(1080, 380)
pyautogui.mouseDown(button='left')
pyautogui.dragTo(917, 564, 1, button='left')
time.sleep(10)
pyautogui.mouseUp(button='left')
time.sleep(2)
Simply removing 2 lines of code and changing dragTo() to moveTo() seems to do what you are trying to do:
import time
import pyautogui
time.sleep(3)
while True:
pyautogui.moveTo(1080, 380)
pyautogui.mouseDown(button='left')
pyautogui.moveTo(917, 564, 1)
time.sleep(10)
This might help you a bit:
pyautogui.moveTo(1277, 127)
pyautogui.dragTo(1277, 225, button='left', duration=5)
(duration is in seconds)
I am trying to automate some cookie-clicker style game (on a website) by letting python click my mouse for me on an ubuntu system. The clicking part is functioning fine, but I cant seem to cancel my program with CTRL-C because the browser window is active since I am constantly clicking on it with a moving mouse. For now I have a timed solution, but thats not really optimal.
Here is my very simple code:
from pymouse import PyMouse
from pymouse import PyMouseEvent
import time
from datetime import datetime
m = PyMouse()
x,y = m.position() #gets mouse current position coordinates
print x
print y
finish = datetime(2016, 3, 21, 14, 1)
print finish
while datetime.now() < finish:
for y in range(160,520,3):
time.sleep(0.005)
m.click(470,y,1)
I looked at the PyMouse examples and found a part to end my program by right-clicking, but I cant seem to get it working if I try to combine this.
from pymouse import PyMouse
from pymouse import PyMouseEvent
import time
from datetime import datetime
class Clickonacci(PyMouseEvent):
def cookies(self):
m = PyMouse()
x,y = m.position() #gets mouse current position coordinates
print x
print y
finish = datetime(2016, 3, 21, 14, 41)
print finish
while datetime.now() < finish:
for y in range(160,520,3):
time.sleep(0.005)
m.click(470,y,1)
def __init__(self):
PyMouseEvent.__init__(self)
self.cookies()
def click(self, x, y, button, press):
if button == 2:
if press:
self.stop()
C = Clickonacci()
C.run()
This lets me exit my program by right-clicking and prints the initial mouse coordinates, but its not controlling the mouse to click automated on the given positions.
Maybe anyone with more experience can untangle this to make it work?
EDIT:
I installed via pip install pymouse, not sure if its the same version as https://github.com/pepijndevos/PyMouse
So I am searching for a way to end my program either by right-clicking my mouse or pressing a certain key even when the terminal window in which I started my program is not the active window.
I created a small Python script using win32api to use on the popular game Cookie Clicker (a game where you have to click on a Big Cookie to gain points) just for fun. It has a function called "auto_clicker" that do just that: keeps clicking on the screen on the point the user defined. This is the script:
# -*- coding: utf-8 -*-
import win32con
import win32api
def clicker(x,y):
"""Clicks on given position x,y
Input:
x -- Horizontal position in pixels, starts from top-left position
y -- Vertical position in pixels, start from top-left position
"""
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
def auto_clicker(x = -1,y = -1):
"""Keep clicking on position x,y. If no input is given, gets from actual
mouse position.
"""
if x == -1 | y == -1:
x,y = win32api.GetCursorPos()
while True:
clicker(x,y)
It works nicely, but I want to make some improvements:
How can I get the cursor position only when the user clicks instead when the function is called? I would prefer to not add another module
since win32api seems to contain everything I needed. Tried this
method without success.
How can I detect a keypress like "Escape", so I can exit from my program without the ugly hack I am using now (Ctrl+Alt+Del seems to give SetCursorPos denied access, so Python throws a error and exit the program).
Can I make this program portable? Seems like I can do using Tkinter and generating a invisible Tk window, but I tried to write something without success.
I don't think with win32api you can listen to clicks you can just generate them (not sure though). However, try using pyHook, it's a simple api easy to use and can be found here http://sourceforge.net/apps/mediawiki/pyhook/index.php?title=Main_Page. With pyhook you can create a listener to listen to a mouse event and upon a mouse click you can do whatever you want, the example in the link shows you how. As for key press, you can use the same api for that too, also an example is provided, good luck!
use pynput . It can control mouse, keyboard, etc.
examples:
from pynput.mouse import Button, Controller
mouse = Controller()
# Read pointer position
print('The current pointer position is {0}'.format(
mouse.position))
# Set pointer position
mouse.position = (10, 20)
print('Now we have moved it to {0}'.format(
mouse.position))
# Move pointer relative to current position
mouse.move(5, -5)
# Press and release
mouse.press(Button.left)
mouse.release(Button.left)
# Double click; this is different from pressing and releasing
# twice on Mac OSX
mouse.click(Button.left, 2)
# Scroll two steps down
mouse.scroll(0, 2)