GithubHelp home page GithubHelp logo

spyoungtech / ahk Goto Github PK

View Code? Open in Web Editor NEW
837.0 837.0 65.0 1.35 MB

Python wrapper for AutoHotkey with full type support. Harness the automation power of AutoHotkey with the beauty of Python.

License: MIT License

Python 83.42% AutoHotkey 16.58%
ahk-script asyncio autohotkey automation python windows

ahk's People

Contributors

dizzythermal avatar filantus avatar forestsource avatar glutenberg avatar nickiel12 avatar pestitschek avatar pre-commit-ci[bot] avatar spatiag avatar spyoungtech avatar yemreak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ahk's Issues

Simplify wingets; use ahk_id to track windows

Need to come up with the most conscience way to identify and track windows.

Current implementation is crude and incomplete. Would like the Window class to track its own ahk_id as a better mechanism for making sure we keep accessing the same window.

Getting script output before closing it. [Not issue, just asking for help]

How i can run script that returns information to python before exiting?
For example, i run python script that shows nothing in console and starts AHK script with GUI button. Then i press this button and python console shows me "pressed!". Then i press it again and "pressed!" appears second time in python console. Then i close GUI and python script finishes itself.

I did something, but my example does not works.

from ahk import AHK
from ahk.window import Window

gui = """
#SingleInstance, force
#NoTrayIcon
#Persistent

Gui, bfb:Add, Button, x5 y5 w140 h90 gBigButton, DON'T PRESS
Gui, bfb:Show, w150 h100, lmao
Gui, bfb:-MinimizeBox
return

BigButton:
FileAppend, "Button pressed!", *
return

bfbGuiClose:
ExitApp
"""

def main():
	try:
		ahk = AHK(executable_path="AutoHotkey.exe")
	except:
		return

	print("Starting getting information from script!")
	result = ahk.run_script(gui, blocking=False)
	while True:
		print(result.stdout)

if __name__ == '__main__':
	main()

Image_search - ValueError: malformed node or string: None

File "c:/Users/rrajpuro/Documents/Macros/test.py", line 6, in run
ac.image_search("C:\Users\rrajpuro\Pictures\War.JPG")
File "C:\Users\rrajpuro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\ahk\screen.py", line 74, in image_search
return ast.literal_eval(resp)
File "C:\Users\rrajpuro\AppData\Local\Programs\Python\Python37-32\lib\ast.py", line 91, in literal_eval
return _convert(node_or_string)
File "C:\Users\rrajpuro\AppData\Local\Programs\Python\Python37-32\lib\ast.py", line 90, in _convert
return _convert_signed_num(node)
File "C:\Users\rrajpuro\AppData\Local\Programs\Python\Python37-32\lib\ast.py", line 63, in _convert_signed_num
return _convert_num(node)
File "C:\Users\rrajpuro\AppData\Local\Programs\Python\Python37-32\lib\ast.py", line 55, in _convert_num
raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: None

Would this awesome lib using AutoHotkey.dll?

dll file can be upload to pypi, and I found an issue while call 64bit AutoHotkey.dll,
will this ahk lib support dll file path arg?

Download URL:
https://github.com/HotKeyIt/ahkdll-v1-release/

python 64-bit: x64w/AutoHotkey.dll or AutoHotkeyMini.dll
python 64-bit: Win32w/AutoHotkey.dll or AutoHotkeyMini.dll

btw, 64-bit dll seems occur an crash while using ahkgetvar

main.py

#! python3
import ctypes
import time
import sys
import pathlib
import typing

dll_file_path = str(
    pathlib.Path(__file__).parent / f'AutoHotkey{sys.hash_info.width}.dll')

ahk_instance = ctypes.cdll.LoadLibrary(dll_file_path)
ahk_instance = ctypes.CDLL(dll_file_path)

ahk_instance.ahktextdll("")

while not ahk_instance.ahkReady():
    time.sleep(0.1)


def goahk(code: str):
    """run source code with autohotkey."""
    return ahk_instance.ahkExec(code)


def getahk(var_name: str):
    """get var value from ahk script by var name"""
    result = ahk_instance.ahkgetvar(var_name, 0)
    result = ctypes.cast(result, ctypes.c_wchar_p)
    return result.value


__all__ = ['goahk', 'getahk']


def test():
    goahk(u'''msgbox Hello World;
var_name=sss
    ''')
    print(getahk('var_name'), flush=1)


if __name__ == "__main__":
    test()

I put the dll file in the dir of main.py
using 32-bit python.exe will run success => show msgbox and print sss
using 32-bit python.exe will run failed=> show msgbox and exited with code=3221225477

sorry for my stupid English grammar...

Feature/Keyboard

Relates to #9

Similarly to hotkeys, keyboard implements pure-python, cross-platform keyboard functionality.

I'm not sure how much value there is in implementing this right now, as anyone should be able to use keyboard and get more than enough functionality.

At any rate, I'm not sure what interface this will take if any, but it's a low priority for now for the reasons mentioned.

feature/winMove

Implement winmove functionality

Ref: https://www.autohotkey.com/docs/commands/WinMove.htm

Probably the interface for this would be something like how mouse moves, except you'd use a particular Window object

win = ahk.active_window
win.move(200, 200)  # moves upper-left-hand corner to (200, 200)

This also includes altering the width/height of a window. This could be additional arguments for a move method. Additionally property setters for width and height should also be implemented

win.move(200, 200, width=500, height=700)  #  move and additionally adjust width/height 
win.width = 500  # sets window width to 500px
win.height = 700  # sets window height to 700px

Misconfigured path causes PermissionError within subprocess.Popen call

python runned from cmd with admin privileges.
running any action, e.g. ahk.mouse_move(x=100, y=100, speed=30, blocking=False)
will throw PermissionError:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python\Python37\lib\site-packages\ahk\mouse.py", line 89, in mouse_move
    self.run_script(script, blocking=blocking)
  File "C:\Python\Python37\lib\site-packages\ahk\script.py", line 76, in run_script
    result = self._run_script(script_text, decode=decode, blocking=blocking, **runkwargs)
  File "C:\Python\Python37\lib\site-packages\ahk\script.py", line 66, in _run_script
    proc = subprocess.Popen(runargs, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
  File "C:\Python\Python37\lib\subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "C:\Python\Python37\lib\subprocess.py", line 1178, in _execute_child
    startupinfo)
PermissionError: [WinError 5] Access is denied

Checking permissions from PowerShell:

PS D:\Prog\AutoHotkey> Get-Acl | fl


Path   : Microsoft.PowerShell.Core\FileSystem::D:\Prog\AutoHotkey
Owner  : BUILTIN\Administrators
Group  : G:S-1-5-21-1413140394-118887914-2539411025-513
Access : Все Allow  FullControl
         NT AUTHORITY\SYSTEM Allow  FullControl
         S-1-5-21-1413140394-118887914-2539411025-1000 Allow  FullControl
         BUILTIN\Administrators Allow  FullControl
Audit  :
Sddl   : O:BAG:S-1-5-21-1413140394-118887914-2539411025-513D:AI(A;OICIID;FA;;;WD)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;S-1-5
         -21-1413140394-118887914-2539411025-1000)(A;OICIID;FA;;;BA)



PS D:\Prog\AutoHotkey> Dir | Get-Acl | fl
...
Path   : Microsoft.PowerShell.Core\FileSystem::D:\Prog\AutoHotkey\AutoHotkey.exe
Owner  : BUILTIN\Administrators
Group  : G:S-1-5-21-1413140394-118887914-2539411025-513
Access : Все Allow  FullControl
         NT AUTHORITY\SYSTEM Allow  FullControl
         S-1-5-21-1413140394-118887914-2539411025-1000 Allow  FullControl
         BUILTIN\Administrators Allow  FullControl
Audit  :
Sddl   : O:BAG:S-1-5-21-1413140394-118887914-2539411025-513D:AI(A;ID;FA;;;WD)(A;ID;FA;;;SY)(A;ID;FA;;;S-1-5-21-14131403
         94-118887914-2539411025-1000)(A;ID;FA;;;BA)

Path   : Microsoft.PowerShell.Core\FileSystem::D:\Prog\AutoHotkey\AutoHotkeyA32.exe
Owner  : BUILTIN\Administrators
Group  : G:S-1-5-21-1413140394-118887914-2539411025-513
Access : Все Allow  FullControl
         NT AUTHORITY\SYSTEM Allow  FullControl
         S-1-5-21-1413140394-118887914-2539411025-1000 Allow  FullControl
         BUILTIN\Administrators Allow  FullControl
Audit  :
Sddl   : O:BAG:S-1-5-21-1413140394-118887914-2539411025-513D:AI(A;ID;FA;;;WD)(A;ID;FA;;;SY)(A;ID;FA;;;S-1-5-21-14131403
         94-118887914-2539411025-1000)(A;ID;FA;;;BA)

Path   : Microsoft.PowerShell.Core\FileSystem::D:\Prog\AutoHotkey\AutoHotkeyU32.exe
Owner  : BUILTIN\Administrators
Group  : G:S-1-5-21-1413140394-118887914-2539411025-513
Access : Все Allow  FullControl
         NT AUTHORITY\SYSTEM Allow  FullControl
         S-1-5-21-1413140394-118887914-2539411025-1000 Allow  FullControl
         BUILTIN\Administrators Allow  FullControl
Audit  :
Sddl   : O:BAG:S-1-5-21-1413140394-118887914-2539411025-513D:AI(A;ID;FA;;;WD)(A;ID;FA;;;SY)(A;ID;FA;;;S-1-5-21-14131403
         94-118887914-2539411025-1000)(A;ID;FA;;;BA)

Path   : Microsoft.PowerShell.Core\FileSystem::D:\Prog\AutoHotkey\AutoHotkeyU64.exe
Owner  : BUILTIN\Administrators
Group  : G:S-1-5-21-1413140394-118887914-2539411025-513
Access : Все Allow  FullControl
         NT AUTHORITY\SYSTEM Allow  FullControl
         S-1-5-21-1413140394-118887914-2539411025-1000 Allow  FullControl
         BUILTIN\Administrators Allow  FullControl
Audit  :
Sddl   : O:BAG:S-1-5-21-1413140394-118887914-2539411025-513D:AI(A;ID;FA;;;WD)(A;ID;FA;;;SY)(A;ID;FA;;;S-1-5-21-14131403
         94-118887914-2539411025-1000)(A;ID;FA;;;BA)
...

It's looks like need to run subprocess from admin privileges as well.
For this need to add to subprosess.Popen these args before running AutoHotkey.exe executable:

'runas', '/noprofile', '/user:Administrator',

Templating engine; Jinja2?

Currently, ahk scripts fed to AutoHotkey are written inline and values are simply substituted using str.format.

The goal is to move towards something of a django-like templating system. Ideally that means users can easily override/extend default .ahk templates. The internal interface would maybe look something like script = render_template('templates/mouse/move_mouse.ahk')

Not sure if Jinja2 is the right tool for this or not, but it's probably my first choice at the moment.

Add nonblocking functionality for more functions

There are some functions right now that can reasonably be run in a nonblocking mode which currently don't accept a blocking keyword argument. The keyword should be added for these functions.

Trying to acquire pixel color raises WinError 5

Seems to be a permission related issue.
Unsure how to fix this.

Simple code ran from PyCharm:

from ahk import AHK

ahk = AHK(executable_path='C:\\Program Files\\AutoHotkey')
a = ahk.pixel_get_color(2, 2)
print(a)

German umlaute with python 3.7+ not working as expected

Hello,
i try to write a script that writes ingame item names in the chat, but all umlauts are displayed funny (e.g. http://i.gyazo.com/3df9910aff56e821f362e6a88f084acf.png). does anyone know how i can solve this problem?
I use Windows 10 and have the Unicode 64 bit version of AHK v1.1.32.00.

When I execute the following code I get the character ü in game, but I expect ü
(I Have a German keyboard and layout in Windows!)

ahk.send_input("ü")

Case while Set up mouse keys

Hello,
I got little issue when I started using mouse on keypad ala 'Set up Mouse Keys' on windows.
On key Number5 it listen to mouse click, in real world.
In Ahk it send me back numer 5, meaning - type in number instead of pressing Number5 and click down mouse.
Do you know any workaround for this issue?

Compile scripts?

Wondering if the ActionChain implementation (#25) could be changed to support creating a single script that could then be compiled into an exe. Maybe a compile method that produces an exe that should, more or less, be the same as using the .perform method when executed.

An interface for this might look like

ac = ActionChain()
ac.mouse_drag(size, 0, relative=True)
ac.mouse_drag(0, size, relative=True)
ac.mouse_drag(size * -1, 0, relative=True)
ac.mouse_drag(0, size*-1, relative=True)
ac.compile('draw_square.exe')

This project needs documentation

Methods need docstrings.

Want to also produce some documentation in the form of sphinx + autodoc to be published via readthedocs.

Execute Python functions in response to Hotkeys

Right now, HotKeys only support running autohotkey code. It would be nice if we could figure out how it may be possible to hook executing Python functions in response to a hotkey being pressed.

For anyone looking for this functionality in the meantime, I recommend using the keyboard library.

Run script by specifying path to an ahk file

Currently, the only way to run arbitrary autohotkey scripts is to use run_script, which only accepts a script as a string of the full script.

Functionality should be added to specify the path of an autohotkey script. Something like this should be possible

ahk.run_script('C:\\Path\\To\\MyScript.ahk')

I think this can safely/reasonably be added to the run_script method without issue.

Missing Directives

Currently the directives implementations are incomplete. Particularly, directives which take in parameters are not fully implemented.

I think defaults for arguments should be the same as in AutoHotkey, unless a good argument can be made for a more sensible default. We may also opt to provide defaults where AutoHotkey does not.

Anything that is deprecated, not recommended, or being removed in AutoHotkey v2.0 should not be implemented.

How to stop a thread at the end of a program

Any ideas? I have, basically, an infinite poll loop thread that has a while stop_thread == False: , and that works fine, but that means that to close the program, I would have to call a close/cleanup function that changes the stop_thread variable. But I don't know how else to do it. I need the loop, but I would like to keep it simple and not have to call any cleanup function at the end of the program.

I ran into this problem when I was testing the modified module in the cmd prompt and I couldn't stop the program because when I called quit(), the loop would continue.

Contribution, how to ask questions about syntax and naming schemes

How should I go about asking questions about things like syntax, code requirements, what should/shouldn't be added, etc, if I want to contribute. Questions like this one.

I think I might have found a great solution for ahk->python communication, but it requires win32 to work. Is requiring win32 as a module acceptable?

AHK string escaping

Need a way to help make strings 'safe' for keyboard typing functionality.
I'm thinking something similar to Jinja's HTML escaping.

I don't think we can guarantee safety against malicious/untrusted inputs, but it should behave well with all common characters.

Using AHK functions?

Is there a way to use something like this?
FileAppend, % Clipboard "n", C:\file.txt`

How to check specific radius of pixels?

In ahk you can search pixel in specific radius of pixels, but in python ahk you can search in only one pixel.

PixelSearch, Px, Py, 679, 380, 687, 388, 0x00008C, 1, Fast
ahk.pixel_search('0x00008C')
Is there any way to check radius, but not a pixel?

Sorry for bad english, it's not my native language..

find window methods

Something analogous to selenium's find_element_by methods or BeautifulSoup's find/find_all methods.

I think the API will also be similar with window Controls.

Send script as stdin

Currently, a tempfile is written to disk before calling the AutoHotkey executable, passing along the tempfile path.

Since AHK 1.1.17 -- scripts can be provided with stdin.

Specify an asterisk (*) for the filename to read the script text from standard input (stdin). For an example, see ExecScript().

So, we should do this instead as it removed the overhead of writing to (and AHK subsequently reading from) the physical disk.

NoModuleFoundError?

I'm not really sure where to ask such a dumb, beginner question... but this module looks awesome and I need help with the initial set up.

Directory
venv /
---------- Include /
---------- Lib /
-------------------- site-packages /
---------------------------------------- ahk /
---------------------------------------- (all of my various pip installs here) /
---------- Scripts /
MyPythonFile.py

When I try to import ahk within MyPythonFile.py, I get a ModuleNotFoundError: no module named 'ahk'
When I try to import any other module that I've installed via pip, it works fine.
Example: import requests, works just fine

Other information:

  • I'm using Spyder as my IDE,
  • I can import and use ahk when I do .\venv\Scripts\activate and then run python from within the Windows cmd line.

What am I doing wrong?

Thank you for any help.

How to stop ahk script in mid run?

I am trying to write a hotkey class version that binds functions to hotkeys. (https://github.com/Nickiel12/ahk/tree/Bindable-Hotkeys) My question is, is there a way to stop a running script? Or listen for a hotkey and exit after 3 seconds? I am using file write to see if the hotkey had been pressed. My problem is when I try to shut it down, the script doesn't stop till the hotkey is pressed and exitapp is called.

How to execute frozen script as exe with PyInstaller? TemplateNotFound

Error while trying to execute script freezed to exe with pyinstaller:
Traceback (most recent call last):
File "autoLogin.py", line 4, in
File "site-packages\ahk\mouse.py", line 88, in mouse_move
File "site-packages\ahk\mouse.py", line 84, in _mouse_move
File "site-packages\ahk\script.py", line 49, in render_template
File "site-packages\jinja2\environment.py", line 830, in get_template
File "site-packages\jinja2\environment.py", line 804, in _load_template
File "site-packages\jinja2\loaders.py", line 113, in load
File "site-packages\jinja2\loaders.py", line 187, in get_source
jinja2.exceptions.TemplateNotFound: mouse/mouse_move.ahk
[12584] Failed to execute script autoLogin

Feature/Hotkeys

Not sure what interface I want hotkeys to take.

keyboard is a project that offers cross-platform hotkeys and keyboard actions.

Not sure if to model after keyboard or do something else.

Here's a quick mockup I have in mind

myhotkey = Hotkey('CTRL+T', some_script)
myhotkey.start()  #  start the process with the hotkey trigger (e.g. listening in the background)
myhotkey.stop()  #  stop the script

Where some_script would be an ahk script to put under the hotkey declaration.

Another possible idea would be to have hotkeys have the ability to perform callbacks for Python functions, similar to keyboard, but I can't think of a great way to accomplish this at the moment.

Changes for AHK_PATH

Per action items out of #31 -- It would probably be nice to see some improvements for how this environment variable is documented/used. I think I want to:

  • update docs to be more clear on how AHK_PATH is used
  • raise an error (or warning?) on mis-configuration of of the variable

Alternatives might include

  • rename the variable
  • have this functionality removed/deprecated
  • add functionality to support either specify a directory or executable file.

Feature/GUI

Implement GUI interface. REF: https://www.autohotkey.com/docs/commands/Gui.htm

  • FileSelectFile
  • FileSelectFolder
  • Gui
  • Gui control types
  • [ ]GuiControl
  • GuiControlGet
  • Gui ListView control
  • Gui TreeView control
  • IfMsgBox
  • Image Handles
  • InputBox
  • LoadPicture
  • Menu
  • MenuGetHandle
  • MenuGetName
  • MsgBox
  • OnMessage
  • Progress
  • SplashImage
  • SplashTextOn/SplashTextOff
  • Standard Windows Fonts
  • Styles for a window/control
  • ToolTip

return None instead of empty string

Sometimes functions will return an empty string when they should probably be returning None instead. This is because they are doing return self.run_script(...) but the script doesn't return any value. It will be better if these were all consistent and returned None instead.

communication decoding

I am using the win32 to get a windows event when a file changes. I need some help with a design decision. What happens in the below code is as follows

  1. initiate class
  2. define a win32 event and start a loop to get events
  3. when it gets an event.... aaaand here is where I get stuck.

I need help choosing which of the following to use. Do I have one file that all ahk scripts write to with each hotkey writing an identifying code to the file, and check the most recent code to a dict etc. Or do I make a separate file for every hotkey with the hotkey code in the name and trigger the last_edited_event.

The First Choice
Ups - one file, simpler
downs - complex(er) decoding, long uses of the program with frequent use could lead to large files because if I delete the last hotkey-code, it might accidentally block a hotkey write. (Though, admittedly, this is less of a concern than it could be, depending how python handles opening and reading files)

The Second Choice
Ups - read/writes are simpler, decoding is simpler
downs - finding the changed file could be resource intensive as all files have to be checked

So it comes down to, Large files from extended runs VS large CPU usage when a lot of ahk communication files are present.

PS. Same thing but another system for live data transfer like your "filewrite *"

`
class Abstract_Communicator(metaclass=abc.ABCMeta):

def __init__(self, directory:str):

    if directory == None:
        self.path = pathlib.Path(os.path.abspath(".")) / "tmp"
    else:
        if type(directory) != str: 
            raise TypeError(f"Expected type str, but got type {type(directory)}")
        
        self.path = pathlib.Path(directory)
    if not self.path.exists():
        raise FileNotFoundError(f"The directory or file at {self.path} doesn't exist")
    
    self.stop_thread = False
    self.thread = threading.Thread(target=self.event_loop)
    self.thread.start()

def __del__(self):
    self.stop_thread = True  

@abc.abstractmethod
def on_event(self):
    print("An event!!!")

def event_loop(self):
    change_handle = win32file.FindFirstChangeNotification (
    str(self.path),
    0,
    win32con.FILE_NOTIFY_CHANGE_LAST_WRITE
    )

    try:
        while self.stop_thread == False:
            result = win32event.WaitForSingleObject (change_handle, 500)

            #
            # If the WaitFor... returned because of a notification (as
            #  opposed to timing out or some error) then look for the
            #  changes in the directory contents.
            #
            if result == win32con.WAIT_OBJECT_0:
                self.on_event()
            win32file.FindNextChangeNotification (change_handle)

    finally:
        win32file.FindCloseChangeNotification (change_handle)

class EventListener(Abstract_Communicator):

def on_event(self):
    #this isn't totally implemented
    return super().on_event()

`

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.