Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

Simple Python Intergration Example


  • Please log in to reply
27 replies to this topic
mwdsmith
  • Members
  • 4 posts
  • Last active: Aug 18 2010 11:58 AM
  • Joined: 16 Aug 2010
Hi guys,

I have been trolling the forums for the last few days to search for a simple example where a python script:
1. Invokes a ahk function/script, passing it several variables
2. Recieves several variables back, placing them into python variables

I have looked at topics/references such as:
<!-- m -->http://www.autohotke...topic51591.html<!-- m --> and
<!-- m -->http://www.autohotke...tinku99/ahkdll/<!-- m -->

I can now run an ahk script from python, but I can't work out how to:
1. Wait for the ahk function to complete
2. Receive result variables back into python from the ahk script

Can anyone help me out or point me in the right direction?

Thank you,
Michael



ps. The main function I would like to call is ImageSearch, but I am sure I can modify an example of another function to suit me.

HotKeyIt
  • Moderators
  • 7439 posts
  • Last active: Jun 22 2016 09:14 PM
  • Joined: 18 Jun 2008
Here is an example tested in PortablePython_1.1_py3.0.1 and latest AutoHotkey.dll
:!: Note you will need to copy AutoHotkey.dll to system32 folder
[color=red]from ctypes import *
import time
ahk = cdll.AutoHotkey[/color]

ahk.ahktextdll("")
time.sleep(0.1)
ahk.addScript("Func(a=[color=red]\"\"[/color],b=[color=red]\"\"[/color]){\nMsgBox % a [color=red]\"`n\"[/color] b[color=red]\n[/color]}")
ahk.ahkFunction("func","test1", "test2")
Same Example in AHK
AutoHotkey.dll needs to be in scripts directory.
ahk:=AhkDllObject()

ahk.ahktextdll("")
Sleep 100
ahk.addScript("Func(a="""",b=""""){`nMsgBox % a ""``n"" b`n}")
ahk.ahkFunction("func","test1", "test2")
MsgBox Ende


mwdsmith
  • Members
  • 4 posts
  • Last active: Aug 18 2010 11:58 AM
  • Joined: 16 Aug 2010
Hi HotKeyIt,

I have got your example working well, thank you!

The only thing I cannot get working is passing variables back from AHK into python. Can you show me an example?

Gratefully,
Michael

HotKeyIt
  • Moderators
  • 7439 posts
  • Last active: Jun 22 2016 09:14 PM
  • Joined: 18 Jun 2008
Learning Python. Part 2 :D
from ctypes import *

import time



string1 = 'Hello' [color=green]#create a string variable[/color]

string2 = 'World' [color=green]#create a string variable[/color]

ahk = cdll.AutoHotkey [color=green]#load AutoHotkey[/color]

ahk.ahktextdll("") [color=green]#start script in persistent mode (wait for action)[/color]

while not ahk.ahkReady(): [color=green]#wait for AutoHotkey to start[/color]

    time.sleep(0.01) [color=green]#Sleep 100[/color]

ahk.addScript("Func(a=\"\",b=\"\"){\nreturn a \" \" b \"!\"\n}") [color=green]#add script to AutoHotkey[/color]



string = cast( ahk.ahkFunction("func",string1, string2), c_wchar_p).value [color=green]#call function and convert return pointer to unicode string[/color]

ahk.ahkExec("MsgBox " + string) [color=green]#execute some code in AutoHotkey[/color]


mwdsmith
  • Members
  • 4 posts
  • Last active: Aug 18 2010 11:58 AM
  • Joined: 16 Aug 2010
Hi HotKeyIt,

Thank you for your example, it helped me significantly.

When I tried your example* the returned string is in non-english characters and the ahkExec fails. However, if I replaced "c_wchar_p" with "c_char_p" it works well.

My last challenge is to pass more than one variable back into python. Is this easy? If not I will get around it by returning a delimited string and use python to split it up.

Gratefully,
Michael


* using Python 2.7

HotKeyIt
  • Moderators
  • 7439 posts
  • Last active: Jun 22 2016 09:14 PM
  • Joined: 18 Jun 2008
I've got Python 3.01 and AutoHotkey.dll unicode

from ctypes import *

import time



ahk = cdll.AutoHotkey #load AutoHotkey

ahk.ahktextdll("") #start script in persistent mode (wait for action)

while not ahk.ahkReady(): #Wait for AutoHotkey.dll to start

    time.sleep(0.01)

ahk.addScript("a=1\nb=2")



string1 = cast(ahk.ahkgetvar("a",0),c_wchar_p).value

string2 = cast(ahk.ahkgetvar("b",0),c_wchar_p).value

ahk.ahkExec("MsgBox " + string1 + "\nMsgBox " + string2)


mwdsmith
  • Members
  • 4 posts
  • Last active: Aug 18 2010 11:58 AM
  • Joined: 16 Aug 2010
Thank you so much for your generous help HotKeyIt; I very much appreciate it!

Warm regards,
Michael

adimpleo
  • Members
  • 22 posts
  • Last active: Feb 03 2012 08:16 PM
  • Joined: 14 Sep 2010
Error on Windows 7 64-bit.

I am running the following code (exact copy of the first code posted above):
from ctypes import *
import time
ahk = cdll.AutoHotkey

ahk.ahktextdll("")
time.sleep(0.1)
ahk.addScript("Func(a=\"\",b=\"\"){\nMsgBox % a \"`n\" b\n}")
ahk.ahkFunction("func","test1", "test2")

I am running Python 3.1.1.

The error message I am getting is:
Traceback (most recent call last):
File "C:/Program Files (x86)/AutoHotkeyold/AutohotkeyDLL/test.py", line 5, in <module>
ahk.ahktextdll("")
WindowsError: exception: access violation reading 0x0000000000000003

I am running the dll conained in the following package:
<!-- m -->http://www.autohotke.../AutoHotkey.zip<!-- m -->
Under the subdirectory: x64w

The autohotkey.dll conained in this package was placed in System32.

HotKeyIt
  • Moderators
  • 7439 posts
  • Last active: Jun 22 2016 09:14 PM
  • Joined: 18 Jun 2008
Can you try to change line 5:
ahk.ahktextdll("[color=red]#Persistent[/color]")


adimpleo
  • Members
  • 22 posts
  • Last active: Feb 03 2012 08:16 PM
  • Joined: 14 Sep 2010
Hi,

Thanks for your fast response. I get the same error message:
Traceback (most recent call last):
File "C:\Users\David Andersen\workspace\AutohotkeyDLLTest\src\test\Test.py", line 5, in <module>
ahk.ahktextdll("#Persistent")
WindowsError: exception: access violation reading 0x0000000000000003

HotKeyIt
  • Moderators
  • 7439 posts
  • Last active: Jun 22 2016 09:14 PM
  • Joined: 18 Jun 2008
Thanks for testing, can you also test if it fails from within AutoHotkey (same AutoHotkey example)?

adimpleo
  • Members
  • 22 posts
  • Last active: Feb 03 2012 08:16 PM
  • Joined: 14 Sep 2010
Thanks again HotKeyIT. Running #Persistant in autohotkey works fine:
C:\Program Files (x86)\AutoHotkeyegg\AutohotkeyDLL\x64w>autohotkey test.ahk

C:\Program Files (x86)\AutoHotkeyegg\AutohotkeyDLL\x64w>

The trayicon shows up like it should.

HotKeyIt
  • Moderators
  • 7439 posts
  • Last active: Jun 22 2016 09:14 PM
  • Joined: 18 Jun 2008
I do not have a 64 machine, so thanks for testing ;)
Did you run this code?
ahk:=AhkDllObject()

ahk.ahktextdll("")
Sleep 100
ahk.addScript("Func(a="""",b=""""){`nMsgBox % a ""``n"" b`n}")
ahk.ahkFunction("func","test1", "test2")
MsgBox Ende


adimpleo
  • Members
  • 22 posts
  • Last active: Feb 03 2012 08:16 PM
  • Joined: 14 Sep 2010
Hi,

That code executed successfully. "Test1" "Test2" "Ende"...

I do have a 64-bit machine. Opening Control Panel and looking at System it says: "64-bit Operating System"

I just copied autohotkey to the folder C:\Program Files (x86)\AutoHotkey by chance.

Edit: If typing msinfo32.exe from command line. I get up a gui saying "x64-based PC"

dysmas
  • Members
  • 63 posts
  • Last active: Apr 06 2011 11:01 AM
  • Joined: 28 Dec 2010
I have Python 2.6
Thanks for all these examples. In the beginning I got always error messages (from Autohotkey.dll) with : Error at line 1, the line (text in Chinese followed) does not contain a recognized action.

The problem was : strings were not unicode. The examples given above work if you write the strings with the u" syntax.

#!/usr/bin/python
# coding: utf-8 -*-

from ctypes import *
import time

ahk = cdll.AutoHotkey #load AutoHotkey
ahk.ahktextdll("") #start script in persistent mode (wait for action)
while not ahk.ahkReady(): #Wait for AutoHotkey.dll to start
    time.sleep(0.01)
ahk.addScript([color=red]u"a=1\nb=2"[/color])

string1 = cast(ahk.ahkgetvar([color=red]u"a[/color]",0),c_wchar_p).value
string2 = cast(ahk.ahkgetvar([color=red]u"b"[/color],0),c_wchar_p).value
ahk.ahkExec("MsgBox " + string1 + "\nMsgBox " + string2)

Strangely enough it was not necessary for the last line (but would do no harm)
In this configuration c_wchar_p is necessary, c_char_p would cause a similar error.

Another example :

ahk.ahktextdll("")
time.sleep(0.1)
ahk.addScript(u"Func(a=\"\",b=\"\"){\nMsgBox % a \"`n\" b\n}")
ahk.ahkFunction(u"func",u"test1", u"test2")

And here a full Python script which shows how to use a AHK window for a Python script. You only need autohotkey.dll in the same directory as the script.

#!/usr/bin/python
# coding: utf-8 -*-

from ctypes import *
import time

ahk = cdll.AutoHotkey #load AutoHotkey
ahk.ahktextdll("") #start script in persistent mode (wait for action)
while not ahk.ahkReady(): #wait for AutoHotkey to start
    time.sleep(0.01) #Sleep 100

var1 = """
gui, font, s18, Times New Roman
Gui, Add, Text, w650  Center c800000 vMyText1, Text1
gui, font, s11, Arial
Gui, Add, Text,w400 x200 r4 vMyText2, Text2

Gui, Add, Text, x10 w180 Right Section vMyText3, Text3

Gui, Add, Progress, ys x200 w400 vMyProgress1
Gui, Add, Text, xs w180 Right Section vMyText4, Text4
Gui, Add, Progress, ys x200 w400 -Smooth vMyProgress2
Gui, Add, Text, ys vMyText5, Text5

Gui, Show
FuncP1(a){
GuiControl,, MyProgress1, %a%
}

FuncP2(a){
GuiControl,, MyProgress2, %a%
}

FuncT1(a){
GuiControl,, MyText1, %a%
}

FuncT2(a){
GuiControl,, MyText2, %a%
}

FuncT3(a){
GuiControl,, MyText3, %a%
}

FuncT4(a){
GuiControl,, MyText4, %a%
}

FuncT5(a){
GuiControl,, MyText5, %a%
}
"""

ahk.addScript(unicode(var1)) #add script to AutoHotkey
text2 = u"x:/Ουκ ελάβον Πολιν  -  1فكّٯخضڜڪڿې۞۩ - ЮЯЖ ЙЏЎЊ ЉФД  - אבגסש תשרב  - 人 人 生 而 自 由, 在 尊 严 和 权 利 上 一.odt  avec un nom de fichier plutôt long pour montrer que ça va à la ligne quand il le faut "
ahk.ahkFunction(u"funcT2", text2)
ahk.ahkFunction(u"funcT1", u"Copie 51 fichiers modifiés (75Mo)")
ahk.ahkFunction(u"funcT3", u"texte justifé à droite")

for i in range (100) :
    val = unicode(str(i))
    val2= unicode(str(int(i / 2)))
    ahk.ahkFunction(u"funcP1", val) #call function and convert return pointer to unicode string
    ahk.ahkFunction(u"funcP2", val2)
    ahk.ahkFunction(u"funcT5", val2)
    time.sleep(0.1)


ahk.ahkExec(u"Gui, Destroy")