Jump to content

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

embed python


  • Please log in to reply
16 replies to this topic
tinku99
  • Members
  • 560 posts
  • Last active: Feb 08 2015 12:54 AM
  • Joined: 03 Aug 2007
The python manual gives an example of how to embed python, but not how to embed it dynamically...
Its pretty straight forward, after installing python2.6 using the automated installer, you can just do this:
pythondll := DllCall("LoadLibrary", "str", "c:\windows\system32\python26.dll")
init := DllCall("c:\windows\system32\python26.dll\Py_Initialize"
, "Cdecl")
msgbox python initalized
call := DllCall("c:\windows\system32\python26.dll\PyRun_SimpleString"
, "str", "import sys", "Cdecl")
msgbox will exit using python code
call := DllCall("c:\windows\system32\python26.dll\PyRun_SimpleString"
, "str", "sys.exit(0)", "Cdecl")
init := DllCall("c:\windows\system32\python26.dll\Py_Finalize"
, "Cdecl")
msgbox % never called
git repo: embedpython

majkinetor
  • Moderators
  • 4512 posts
  • Last active: May 20 2019 07:41 AM
  • Joined: 24 May 2006
Thanks.
We should definitely have 1 page listing links to all kinds of integration available ATM (lisp, lua, vbscript, python...)
Posted Image

SoLong&Thx4AllTheFish
  • Members
  • 4999 posts
  • Last active:
  • Joined: 27 May 2007
Is available in the Wiki <!-- m -->http://www.autohotke... ... _languages<!-- m -->

I added <!-- m -->http://www.autohotke... ... ing#Python<!-- m -->

Laszlo
  • Moderators
  • 4713 posts
  • Last active: Mar 31 2012 03:17 AM
  • Joined: 14 Feb 2005
Very simple, indeed: only 4 dll calls are needed. It also works with Python 3.1.1. The following example (borrowed from the PyWin32 demos) shows how to use graphics from Python, assuming PyWin32 is also installed:
py =

( %

import win32gui, win32con, win32api

import time, math, random, sys



def OnPaint_1(hwnd, msg, wp, lp):

    dc, ps=win32gui.BeginPaint(hwnd)

    win32gui.SetGraphicsMode(dc, win32con.GM_ADVANCED)

    br=win32gui.CreateSolidBrush(win32api.RGB(255,0,0))

    win32gui.SelectObject(dc, br)

    angle=win32gui.GetWindowLong(hwnd, win32con.GWL_USERDATA)

    win32gui.SetWindowLong(hwnd, win32con.GWL_USERDATA, angle+2)

    r_angle=angle*(math.pi/180)

    win32gui.SetWorldTransform(dc,

        {'M11':math.cos(r_angle), 'M12':math.sin(r_angle), 'M21':math.sin(r_angle)*-1, 'M22':math.cos(r_angle),'Dx':250,'Dy':250})

    win32gui.MoveToEx(dc,250,250)

    win32gui.BeginPath(dc)

    win32gui.Pie(dc, 10, 70, 200, 200, 350, 350, 75, 10)

    win32gui.Chord(dc, 200, 200, 850, 0, 350, 350, 75, 10)

    win32gui.LineTo(dc, 300,300)

    win32gui.LineTo(dc, 100, 20)

    win32gui.LineTo(dc, 20, 100)

    win32gui.LineTo(dc, 400, 0)

    win32gui.LineTo(dc, 0, 400)

    win32gui.EndPath(dc)

    win32gui.StrokeAndFillPath(dc)

    win32gui.EndPaint(hwnd, ps)

    return 0

wndproc_1={win32con.WM_PAINT:OnPaint_1}



def OnPaint_2(hwnd, msg, wp, lp):

    dc, ps=win32gui.BeginPaint(hwnd)

    win32gui.SetGraphicsMode(dc, win32con.GM_ADVANCED)

    l,t,r,b=win32gui.GetClientRect(hwnd)



    for x in range(25):

        vertices=(

            {'x':int(random.random()*r), 'y':int(random.random()*b), 'Red':int(random.random()*0xff00), 'Green':0, 'Blue':0, 'Alpha':0},

            {'x':int(random.random()*r), 'y':int(random.random()*b), 'Red':0, 'Green':int(random.random()*0xff00), 'Blue':0, 'Alpha':0},

            {'x':int(random.random()*r), 'y':int(random.random()*b), 'Red':0, 'Green':0, 'Blue':int(random.random()*0xff00), 'Alpha':0},

           `)

        mesh=((0,1,2),)

        win32gui.GradientFill(dc,vertices, mesh, win32con.GRADIENT_FILL_TRIANGLE)

    win32gui.EndPaint(hwnd, ps)

    return 0

wndproc_2={win32con.WM_PAINT:OnPaint_2}



def TestSetWorldTransform():

    wc = win32gui.WNDCLASS()

    wc.lpszClassName = 'test_win32gui_1'

    wc.style =  win32con.CS_GLOBALCLASS|win32con.CS_VREDRAW | win32con.CS_HREDRAW

    wc.hbrBackground = win32con.COLOR_WINDOW+1

    wc.lpfnWndProc=wndproc_1

    class_atom=win32gui.RegisterClass(wc)

    hwnd = win32gui.CreateWindow(wc.lpszClassName,

        'Spin the Lobster!',

        win32con.WS_CAPTION|win32con.WS_VISIBLE,

        100,100,900,900, 0, 0, 0, None)

    for x in range(500):

        win32gui.InvalidateRect(hwnd,None,True)

        win32gui.PumpWaitingMessages()

        time.sleep(0.01)

    win32gui.DestroyWindow(hwnd)

    win32gui.UnregisterClass(wc.lpszClassName, None)



def TestGradientFill():

    wc = win32gui.WNDCLASS()

    wc.lpszClassName = 'test_win32gui_2'

    wc.style =  win32con.CS_GLOBALCLASS|win32con.CS_VREDRAW | win32con.CS_HREDRAW

    wc.hbrBackground = win32con.COLOR_WINDOW+1

    wc.lpfnWndProc=wndproc_2

    class_atom=win32gui.RegisterClass(wc)

    hwnd = win32gui.CreateWindowEx(0, class_atom,'Kaleidoscope',

        win32con.WS_CAPTION|win32con.WS_VISIBLE|win32con.WS_THICKFRAME|win32con.WS_SYSMENU,

        100,100,900,900, 0, 0, 0, None)

    s=win32gui.GetWindowLong(hwnd,win32con.GWL_EXSTYLE)

    win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, s|win32con.WS_EX_LAYERED)

    win32gui.SetLayeredWindowAttributes(hwnd, 0, 175, win32con.LWA_ALPHA)

    for x in range(30):

        win32gui.InvalidateRect(hwnd,None,True)

        win32gui.PumpWaitingMessages()

        time.sleep(0.3)

    win32gui.DestroyWindow(hwnd)

    win32gui.UnregisterClass(class_atom,None)



TestSetWorldTransform()

TestGradientFill()

sys.exit(0)

)



DllCall("LoadLibrary", "str", A_WinDir "\SYSTEM32\python31.dll")

DllCall(A_WinDir "\SYSTEM32\python31.dll\Py_Initialize", "Cdecl")

DllCall(A_WinDir "\SYSTEM32\python31.dll\PyRun_SimpleString", "str",py, "Cdecl") ; exit script from Python

DllCall(A_WinDir "\SYSTEM32\python31.dll\Py_Finalize", "Cdecl")


kakarukeys
  • Members
  • 86 posts
  • Last active: Jul 18 2010 03:10 PM
  • Joined: 28 Sep 2009
How about the other way round?

Can embed AutoHotKey in python? How to run AutoHotKey expressions inside Python program? I've checked AutoHotKey.dll, and it's for running an ahk file.
TypingAid autocompletion program made with AHK.

tinku99
  • Members
  • 560 posts
  • Last active: Feb 08 2015 12:54 AM
  • Joined: 03 Aug 2007
Sure, Here is an example.
tested with python2.6, requires AutoHotkey.dll in the working directory or path...
ahkpython.py:
from ctypes import *

ahk = cdll.AutoHotkey
pyclient = create_string_buffer("ahkpython.ahk")   # no unicode in ahk

CMPFUNC = CFUNCTYPE(c_int, c_int)
def py_cmp_func(a):
     print "ahk: " , a
     return a

cmp_func = CMPFUNC(py_cmp_func)
fx = create_string_buffer(str(cast(cmp_func, c_void_p).value))

script = create_string_buffer("""
fx2(msg){
WinActivate %msg%
msgbox in function fx2 with %msg% from python 
return "success" 
}
""")
ahk.ahkdll(pyclient, "", fx) 
ahk.ahkassign(create_string_buffer("fx"), fx)
ahk.addScript(script)
ahk.ahkFunction(create_string_buffer("fx2"), create_string_buffer("Untitled"))
ahkpython.ahk
#Persistent
dllcall(A_ScriptParams, "int", 42, "cdecl int")
return

f1::
inputbox, x, enter a numerical parameter for python callback
result := dllcall(A_ScriptParams, "int", x, "cdecl int")
return
remarks:
create_string_buffer is required because autohotkey.dll exported functions do not work with unicode.
See HotkeyIt's excellent chm help file for documentation on the functions.

kakarukeys
  • Members
  • 86 posts
  • Last active: Jul 18 2010 03:10 PM
  • Joined: 28 Sep 2009
:) No, I just want to run one or two AHK statements
TypingAid autocompletion program made with AHK.

tinku99
  • Members
  • 560 posts
  • Last active: Feb 08 2015 12:54 AM
  • Joined: 03 Aug 2007

:) No, I just want to run one or two AHK statements

You can use ahkFunction or ahkLabel. :arrow: autohotkey.dll documentation

kakarukeys
  • Members
  • 86 posts
  • Last active: Jul 18 2010 03:10 PM
  • Joined: 28 Sep 2009
:D this is nice.... I only have one doubt left...
The license is GPL, so I suppose my application that has embedded ahk expressions and ahk dlls has to be licensed under GPL too? or so I think.
TypingAid autocompletion program made with AHK.

tinku99
  • Members
  • 560 posts
  • Last active: Feb 08 2015 12:54 AM
  • Joined: 03 Aug 2007
Search the forum for licensing issues

tinku99
  • Members
  • 560 posts
  • Last active: Feb 08 2015 12:54 AM
  • Joined: 03 Aug 2007
VarSetCapacity(x, 200, 80)

y := &x



py = 

(

import ctypes

from ctypes import *

ahkpointer = %y%

cmsg = create_string_buffer("hello from python")

pcmsg = ctypes.cast(cmsg, c_void_p).value

ctypes.memmove(ahkpointer, pcmsg, sizeof(cmsg))

)



pythondll := DllCall("LoadLibrary", "str", "c:\windows\system32\python26.dll")

init := DllCall("c:\windows\system32\python26.dll\Py_Initialize"

, "Cdecl")

call := DllCall("c:\windows\system32\python26.dll\PyRun_SimpleString"

, "str", py, "Cdecl")

msgbox % "x = " . x

return



!q::

finish := DllCall("c:\windows\system32\python26.dll\Py_Finalize"

, "Cdecl")

ExitApp

!r::Reload


tinku99
  • Members
  • 560 posts
  • Last active: Feb 08 2015 12:54 AM
  • Joined: 03 Aug 2007

I am trying to embed auto hot key into python. I don't understand what to do at all. I tried running both codes but nothing happened, that I know of anyways...

For my first post, you need python2.6. For Laszlo's example, you need python 3.1.1 and pywin32.
Which version did you install ?

Also, you may want to rephrase your question, like this.

sam.reckoner
  • Members
  • 51 posts
  • Last active: Apr 06 2012 02:20 AM
  • Joined: 11 Oct 2007

Sure, Here is an example.....


Thanks for the excellent example! I have been carefully studying it. It seems like only purpose of the ahkpython.ahk script is to provide a staging area for the functions that are going to be injected from the Python process.

Is that right?

In that case, the ahkpython.ahk file can be put in a TEMP directory for other Python processes to call as needed, although I'm not sure the injected functions would be persistent across Python calls, or whether the ahkpython.ahk I would have to be emptied regularly to handle this.

tinku99
  • Members
  • 560 posts
  • Last active: Feb 08 2015 12:54 AM
  • Joined: 03 Aug 2007
win32com by mark hammond includes a python.interpreter object: 12
register it by running
c:\python27\lib\site-packages\win32com\servers\interp.py
then
i := python := ComObjCreate("Python.Interpreter")
i.Exec("import win32api")
r :=  i.Eval("win32api.GetComputerName()")
msgbox % r


lrh9
  • Members
  • 102 posts
  • Last active: Mar 14 2011 08:33 PM
  • Joined: 10 Jun 2009
I've written a python 3.1 wrapper for Lexiko's AutoHotkey here:

<!-- m -->http://www.autohotke... ... highlight=<!-- m -->

I'm wondering if it would be possible to communicate hotstring or hotkey events from the ahk script back to Python.

I'm thinking that embedding Python and using local sockets might work.

(More details in my thread.)

Ideas?