[Python.NET] dotnet, threading and py2exe

Brian Lloyd brian.lloyd at revolutionhealth.com
Thu Jan 3 15:44:14 CET 2008

Hi Sebastian - when you talk about it 'running perfectly with
the normal python.exe', I assume you mean the one that comes
with python.net.

That exe is actually written in C# and explicitly sets the
apartment mode to STA.

I suspect the problem is that py2exe will create its own form
of exe which won't do that, so you'll get the default threading
model (MTA).

It might be possible for your script to set the main thread to
STA, if it is the very first thing your program does. You may
want to refer to the docs on that -- I remember it was kind of
complicated and hard to get it set from python code, but don't
recall all of the details.


On 1/3/08 5:46 AM, "Sebastian Stang" <sebastian at yuca-lab.de> wrote:

> Dear pythoneers,
> i want to deliver my program, which runs perfectly 'uncompiled', as an
> exe file to customers.
> The problem: i have to use an activeX component in a windows-form, and
> com-components can only be created in single-thread apartments.
> But when i use py2exe to compile it, the application is run in a multi-
> threaded-apartment
> (System.Threading.Thread.CurrentThread.GetApartmentState() is MTA).
> I tried some workarounds, e.g. create the form in an STA-thread or
> create the activex in an STA like this:
> thread_is_ready = False
> axBrowser = None
> def create_browser_thread(*args):
> global thread_is_ready
> global axBrowser
> print System.Threading.Thread.CurrentThread.GetApartmentState()
> axBrowser = AxSHDocVw.AxWebBrowser()
> thread_is_ready = True
> #and the initialization function in my main form class:
> def InitializeComponent(self):
> global thread_is_ready
> global axBrowser
> job = System.Threading.ThreadStart(create_browser_thread)
> thread = System.Threading.Thread(job)
> thread.SetApartmentState(System.Threading.ApartmentState.STA)
> thread.Start()
> while not thread_is_ready:
> pass
> self.Controls.Add(axBrowser)
> This all worked fine when run with python.exe from command-line.
> However, compiled with py2exe, the initialization function ends
> without exceptions, but the form is not shown and the program hangs.
> Telling the form to shop does not help either.
> Did anyone experience similar problems?
> best regards,
> Pablo
> _________________________________________________
> Python.NET mailing list - PythonDotNet at python.org
> http://mail.python.org/mailman/listinfo/pythondotnet

Brian Lloyd

brian.lloyd at revolutionhealth.com

More information about the PythonDotNet mailing list