Mouse control with python - python

I'm running Ubuntu 12.04 and working with python 2. I would like to be able to control my mouse, and I have found several different python modules intended to do this, but cannot get them to work.
I installed dogtail, but when I try:
dogtail.rawinput.click(x,y)
I get:
AttributeError: 'module' object has no attribute 'rawinput'
I then tried pymouse and although I used pip to install it when I import pymouse:
from pymouse import PyMouse
I get:
TypeError: Object value must be tuple, dictionary or DictWrapper: 0
I tried the uinput module as well but the mouse commands only seemed to work when placed in a loop, which is frustrating/ridiculous.
If anyone knows how to fix either of those problems/what I'm doing wrong/better or easier to use modules I would much appreciate the help.

I'll assume that my problem is the same as yours, given the limited error information. The full exception and traceback I got was:
>>> import pymouse
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/pymouse/__init__.py", line 95, in <module>
from unix import PyMouse, PyMouseEvent
File "/usr/local/lib/python2.7/dist-packages/pymouse/unix.py", line 53, in <module>
class PyMouseEvent(PyMouseEventMeta):
File "/usr/local/lib/python2.7/dist-packages/pymouse/unix.py", line 66, in PyMouseEvent
'client_died': False,
File "/usr/local/lib/python2.7/dist-packages/Xlib/ext/record.py", line 121, in create_context
ranges = ranges)
File "/usr/local/lib/python2.7/dist-packages/Xlib/protocol/rq.py", line 1403, in __init__
self._binary = apply(self._request.to_binary, args, keys)
File "/usr/local/lib/python2.7/dist-packages/Xlib/protocol/rq.py", line 1088, in to_binary
return apply(self.to_binary, varargs, keys)
File "<string>", line 3, in to_binary
File "/usr/local/lib/python2.7/dist-packages/Xlib/protocol/rq.py", line 523, in pack_value
data.append(self.type.pack_value(v))
File "/usr/local/lib/python2.7/dist-packages/Xlib/protocol/rq.py", line 1102, in pack_value
return apply(self.to_binary, (), value)
File "/usr/local/lib/python2.7/dist-packages/Xlib/protocol/rq.py", line 1088, in to_binary
return apply(self.to_binary, varargs, keys)
File "<string>", line 4, in to_binary
File "/usr/local/lib/python2.7/dist-packages/Xlib/protocol/rq.py", line 573, in check_value
vals.append(f.check_value(val[i]))
File "/usr/local/lib/python2.7/dist-packages/Xlib/protocol/rq.py", line 582, in check_value
raise TypeError('Object value must be tuple, dictionary or DictWrapper: %s' % val)
TypeError: Object value must be tuple, dictionary or DictWrapper: 0
Note the exception occurs in Xlib. I had version 0.15rc1 installed. Downgrading to 0.14 fixed the problem.

use pynput .
It can control mouse, keyboard, etc.
examples:
mouse = Controller()
# Set pointer position
mouse.position = (10, 20)
# Press and release
mouse.press(Button.left)
mouse.release(Button.left)

this is my piece of code
from pymouse import PyMouse
m = PyMouse()
m.click(654, 169,1)
the first two arguments ar for X,Y
the last argument to define wich click 1=left click 2=right
i wish it helps
m.click(x,y,click)

I recomend you install pyautogui. You can control mouse and write.
Example:
import pyautogui as py
py.move(x,y) #it moves the mouse
py.click(x,y) #click the mouse on a position
py.write('write this') #Write
py.press('enter') #press a key (enter in this case)

Related

No module named keyboard after converting py to exe

I am making an application which automatically enters your username and password. Everything works fine but when I try to convert it to .exe using auto-py-to-exe I get this error when I launch main.exe. I have added the modules in the hidden-import menu but it doesn't seem to work. I'm pretty new to this so please keep the answers more simple :D Here is the code of the actual program:
from pynput.mouse import Button
import keyboard
from pynput.keyboard import Key, Controller, Listener, KeyCode
mouse = Controller()
keyboards = Controller()
f = open("parolochetach.txt", "r")
list_of_lists = []
for line in f:
stripped_line = line.strip()
line_list = stripped_line.split()
list_of_lists.append(line_list)
f.close()
while True:
if keyboard.is_pressed('1') or keyboard.is_pressed('2') or keyboard.is_pressed('3') or keyboard.is_pressed('4') or\
keyboard.is_pressed('5') or keyboard.is_pressed('6') or keyboard.is_pressed('7') or keyboard.is_pressed('8')\
or keyboard.is_pressed('9'):
number = int(keyboard.read_key())
if number-1 <= len(list_of_lists):
mouse.position = (404, 415)
mouse.press(Button.left)
mouse.release(Button.left)
keyboards.type(list_of_lists[number-1][0])
mouse.position = (404, 465)
mouse.press(Button.left)
mouse.release(Button.left)
keyboards.type(list_of_lists[number-1][1])
keyboards.press(Key.enter)
keyboards.release(Key.enter)
I also tried to avoid using the keyboard module but I can't make it work. When I do something simple like:
def on_press(key):
if key==KeyCode.from_char('1'):
print("yes")
it works with no errors but when I add the click and type functions:
number = int(key)
if number - 1 <= len(list_of_lists):
mouse.position = (404, 415)
mouse.press(Button.left)
mouse.release(Button.left)
keyboards.type(list_of_lists[number - 1][0])
mouse.position = (404, 465)
mouse.press(Button.left)
mouse.release(Button.left)
keyboards.type(list_of_lists[number - 1][1])
keyboards.press(Key.enter)
keyboards.release(Key.enter)
it stops working and I get multiple errors:
Unhandled exception in listener callback
File"myfile", line 211, ni inner return f(self,*args, **kwargs)
File "", line 284, in _process
self.on_press(key)
File "", line 127, in inner
if f(*args) is False:
File "", line 17, in on_press
number = int(key)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'KeyCode'
Traceback (most recent call last):
File "", line 31, in <module>
listener.join()
File "", line 259, in join
six.reraise(exc_type, exc_value, exc_traceback)
File "", line 718, in reraise
raise value.with_traceback(tb)
File "", line 211, in inner
return f(self, *args, **kwargs)
File "", line 284, in _process
self.on_press(key)
File "", line 127, in inner
if f(*args) is False:
File "", line 17, in on_press
number = int(key)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'KeyCode'
This is my answer for another question here and it did work in that case.
Try using pyinstaller and if it can't find modules try this:
From Documentation
Helping PyInstaller Find Modules
Extending the Path If Analysis recognizes that a module is needed, but
cannot find that module, it is often because the script is
manipulating sys.path. The easiest thing to do in this case is to use
the --paths option to list all the other places that the script might
be searching for imports:
pyi-makespec --paths=/path/to/thisdir
--paths=/path/to/otherdir myscript.py
These paths will be noted in the spec file in the pathex argument.
They will be added to the current sys.path during analysis.

Pyperclip: "When using gi.repository you must not import static modules like "gobject"

I am making a program that will allow my phone to share its clipboard with my PC. I am using Pyperclip as it appears to be the easiest and most cross-platform solution. However, when I run the code below:
...
elif "incoming_clipboard:" in server_command:
print(server_command)
pyperclip.copy(server_command.replace("incoming_clipboard: ", ""))
...
I get the error:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner
self.run()
File "/usr/lib/python3.9/threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "/home/chris/Documents/Programming/Synchrony/Desktop/Phone.py", line 30, in do_sync
self.handle_commands(bluetooth_socket)
File "/home/chris/Documents/Programming/Synchrony/Desktop/Phone.py", line 65, in handle_commands
pyperclip.copy(server_command.replace("incoming_clipboard: ", ""))
File "/usr/lib/python3.9/site-packages/pyperclip/__init__.py", line 659, in lazy_load_stub_copy
return copy(text)
File "/usr/lib/python3.9/site-packages/pyperclip/__init__.py", line 158, in copy_gtk
cb = gtk.Clipboard()
File "/usr/lib/python3.9/site-packages/gi/__init__.py", line 69, in __getattr__
raise AttributeError(_static_binding_error)
AttributeError: When using gi.repository you must not import static modules like "gobject". Please change all occurrences of "import gobject" to "from gi.repository import GObject". See: https://bugzilla.gnome.org/show_bug.cgi?id=709183
I know its not due to the string being invalid or anything, because 1) I am explicitly converting it from bytes to a string, and 2) it prints perfectly fine. I don't know if this is relevant, but I am using Linux, so perhaps that is affecting Pyperclip?
Do you guys have any solutions?
https://github.com/dynobo/normcap/issues/100
After going to the Github page for PyperClip, I found a similar issue that someone else had that suggested switching to PyClip. After installing PyClip and implementing it in project, I can confirm that it works perfectly without any issues.

Running code returns with "color must int or tuple"

I was running a tower defence game in the arcade module but after I press start, the game freezes up and returns with
Traceback (most recent call last):
File "D:\lib\site-packages\arcade\text.py", line 278, in draw_text
label = draw_text_cache[key]
KeyError: "05064200240left('Calibri', 'Arial')FalseFalse"
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\ThisPC\Downloads\The Great Skeleton War\lab_12.py", line 2890, in <module>
arcade.run()
File "D:\lib\site-packages\arcade\window_commands.py", line 236, in run
pyglet.app.run()
File "D:\lib\site-packages\pyglet\app\__init__.py", line 107, in run
event_loop.run()
File "D:\lib\site-packages\pyglet\app\base.py", line 167, in run
timeout = self.idle()
File "D:\lib\site-packages\pyglet\app\base.py", line 243, in idle
window.dispatch_event('on_draw')
File "D:\lib\site-packages\pyglet\window\__init__.py", line 1333, in dispatch_event
if EventDispatcher.dispatch_event(self, *args) != False:
File "D:\lib\site-packages\pyglet\event.py", line 422, in dispatch_event
self._raise_dispatch_exception(event_type, args, getattr(self, event_type), exception)
File "D:\lib\site-packages\pyglet\event.py", line 476, in _raise_dispatch_exception
raise exception
File "D:\lib\site-packages\pyglet\event.py", line 415, in dispatch_event
if getattr(self, event_type)(*args):
File "C:\Users\ThisPC\Downloads\The Great Skeleton War\lab_12.py", line 1136, in on_draw
arcade.render_text(globalvars.level_text, SCREEN_WIDTH - 104, SCREEN_HEIGHT - 50)
File "D:\lib\site-packages\arcade\text.py", line 88, in render_text
draw_text(text.text,
File "D:\lib\site-packages\arcade\text.py", line 281, in draw_text
image = get_text_image(text=text,
File "D:\lib\site-packages\arcade\text.py", line 218, in get_text_image
draw.multiline_text((image_start_x, image_start_y), text, text_color, align=align, font=font)
File "D:\lib\site-packages\PIL\ImageDraw.py", line 446, in multiline_text
self.text(
File "D:\lib\site-packages\PIL\ImageDraw.py", line 365, in text
ink = getink(fill)
File "D:\lib\site-packages\PIL\ImageDraw.py", line 313, in getink
ink, fill = self._getink(fill)
File "D:\lib\site-packages\PIL\ImageDraw.py", line 112, in _getink
ink = self.draw.draw_ink(ink)
TypeError: color must be int or tuple
And I'm not really sure why. It says my python packages are wrong so I uninstalled and reinstalled python multiple times too.
Can anyone help me?
Thanks in advance btw.
Without any code, this is hard. But here's my guess.
Perhaps it was made for Python 2 instead of Python 3, or the modules have been updated. Normally Python programs are run inside a virtual environments and have a requirements.txt file for the module versions. You can activate a virtual environment, install the packages and run it.
The issue arises from the wrong data type, the variable color should be of the type int or tuple. On line 278 of the file "D:\lib\site-packages\arcade\text.py" in draw_text, what is the type(key)?
Without code, it's hard to answer.
I think that when you decided the color that you wanted to use, probably in a text that you want to write on the screen, you chose the wrong format. You probably passed an array instead of a tuple that has this form: (int, int, int). (for (r, g, b)) if you did use an array you can still use it but you'll have to add the tuple(your_array) command when you're passing it at the place you want to pass it to.

Can't understand the error

Given below is the error which I am getting while running the code (which is in my previous post wx Import Error) in Python 2.6. Can anyone tell about this error? I am unable to understand it.
Traceback (most recent call last):
File "C:\Python26\music_player_v1\player_skeleton.py", line 153, in <module>
frame = MediaFrame()
File "C:\Python26\music_player_v1\player_skeleton.py", line 148, in __init__
panel = MediaPanel(self)
File "C:\Python26\music_player_v1\player_skeleton.py", line 25, in __init__
self.layoutControls()
File "C:\Python26\music_player_v1\player_skeleton.py", line 46, in layoutControls
audioTBSizer = self.buildAudioToolBar()
File "C:\Python26\music_player_v1\player_skeleton.py", line 65, in buildAudioToolBar
self.rewind = SBitmapButton(self, -1, upbmp, (48, 48))
File "C:\Python26\Lib\wx-2.8-msw-unicode\wx\lib\agw\shapedbutton.py", line 995, in __init__
self.SetBitmapLabel(bitmap)
File "C:\Python26\Lib\wx-2.8-msw-unicode\wx\lib\agw\shapedbutton.py", line 1068, in SetBitmapLabel
image = wx.ImageFromBitmap(bitmap)
File "C:\Python26\Lib\wx-2.8-msw-unicode\wx\_core.py", line 3473, in ImageFromBitmap
val = _core_.new_ImageFromBitmap(*args, **kwargs)
PyAssertionError: C++ assertion "bmp.Ok()" failed at ..\..\src\msw\dib.cpp(148) in wxDIB::Create(): wxDIB::Create(): invalid bitmap
Not sure if this is entirely related to your problem, but the SWIG-generated wrappers won't hold onto any Python objects passed to any set*() methods or the like in wx. You will need to hold onto such objects yourself or you will experience strange errors.
It looks like you have an invalid bitmap. In reading the tracebacks, it's usually the bottom traceback that's the most useful, and this one is saying that you have an "invalid bitmap".
Your application cant find an image file, put all images in one file and in your code give the exact path where to find the images.That wil solve that error.

lightblue Python module not working on mac

I'm trying to connect to wiimote via Python on mac osx 10.7.2.
For that I'm trying to use lightblue. When running: import lightblue Python gives me this error.
>>> import lightblue
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lightblue/__init__.py", line 160, in <module>
from _lightblue import *
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lightblue/_lightblue.py", line 27, in <module>
import _IOBluetooth
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lightblue/_IOBluetooth.py", line 47, in <module>
globals=globals())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/objc/_bridgesupport.py", line 142, in initFrameworkWrapper
_parseBridgeSupport(data, globals, frameworkName)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/objc/_bridgesupport.py", line 42, in _parseBridgeSupport
objc.parseBridgeSupport(data, globals, frameworkName, *args, **kwds)
ValueError: cftype for 'IOBluetoothDeviceInquiryRef' must include gettypeid_func, tollfree or both
I found one with a similar problem here: http://python.6.n6.nabble.com/Python-bridgesupport-issue-on-Lion-td2161049.html#a32196961 but the answer doesn't help me much, since it seems to me that it is already using lightblue's files. Any suggestions?
Seems like a bug with Apple's gen_bridge_metadata script. You can make the error go away by editing the generated file by hand.
Open up /System/Library/Frameworks/IOBluetooth.framework/Versions/Current/Resources/BridgeSupport/IOBluetooth.bridgesupport and delete the lines that start with <cftype.

Categories