473,735 Members | 1,903 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

what is the best practice to separate Pygtk and long running thread code

seb
Hi,

I am using pygtk for the first times.

I am wondering what would be the best "pattern" to interface pygtk with
a thread.

The thread is collecting informations (over the network for example) or
is doing some long calculations.

I would like also to separate the gui part to the action part so that I
should be easier to maintain.

*************** *************** *************** ***************
What should be the best practice in order to achieve this ?
*************** *************** *************** **************

What I use now is :

1)
the gui is launching the "action" evrey 1 sec and is checking for
message using a queue every second also.

gui.py

.....etc ...
class window1(SimpleG ladeApp):
#@-- class window1 }
#@-- init window1.__init_ _ {
def __init__(self, path='gui.glade ',
root='window1',
domain=app_name , kwargs={}):
path = os.path.join(gl ade_dir, path)
SimpleGladeApp. __init__(self, path, root, domain, **kwargs)
self.q=Queue.Qu eue()
self.action=act .action(self.q)
gobject.timeout _add (1000,self.acti on.go) # this is the action
asked
gobject.timeout _add (1000,self.proc ess) # check if a new message is
available in the queue

def process (self):
dir (self.q)
if self.q.empty() == False :
print "from main ",self.q.ge t()
return True

...etc ....

2)
The action part is making somehow the interface between the running
thread and the gui :
It puts the new information in the queue for the gui to process it
later.
action.py

import os
import gui
import time
import Queue
import Spethread # thread that always run in the background

class Singleton(objec t):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton , cls).__new__(cl s, *args,
**kwargs)
return cls._instance
class action(Singleto n):
def __init__(self, queue):
self.q=queue
self.thread_seb =Spethread.work er()
self.thread_seb .start()
self.go()

def go(self):
if self.thread_seb :
reponse=self.th read_seb.status ()
self.q.put(repo nse)
else :
self.q.put("le thread n'existe plus ")
return True

def stop(self):
self.thread_seb .die()
3)
The thread part is "just" a thread that should from time to time
time.Sleep in order for action to query if it has some new messages.

Spethread.py

import threading
import time

class worker(threadin g.Thread):

def __init__(self):
threading.Threa d.__init__(self )
self.value=0
self.go_on=1

def run(self):
print "self.go_on=",s elf.go_on
while self.go_on == 1:
self.value=int( time.time())
res=2
for i in range(0, 100):
res=res^i
print res
time.Sleep(0.01 )
def status(self):
return self.value
def die(self):
print "die request"
self.go_on=0
Thanks in advance for sharing this informations.
Sebastien.

PS :
the entire gui.py

gH#@-- python gui.py {
#@-- header gui.py {
#!/usr/bin/env python
# -*- coding: UTF8 -*-

# Python module gui.py
# Autogenerated from gui.glade
# Generated on Wed Sep 20 22:03:00 2006

# Warning: Do not modify any context comment beginning with # @--
# They are required to keep user's code
# Doing so will make it unable for kefir to help you further manage
your project

#@-- header gui.py }
#@-- app gui {
import os
import gobject
import gtk
import action as act
import Queue

from SimpleGladeApp import SimpleGladeApp, bindtextdomain

app_name = 'gui'
app_version = '0.0.1'

glade_dir = ''
locale_dir = ''

bindtextdomain( app_name, locale_dir)

#@-- app gui }
#@-- window window1 {
#@-- class window1 {
class window1(SimpleG ladeApp):
#@-- class window1 }
#@-- init window1.__init_ _ {
def __init__(self, path='gui.glade ',
root='window1',
domain=app_name , kwargs={}):
path = os.path.join(gl ade_dir, path)
SimpleGladeApp. __init__(self, path, root, domain, **kwargs)
self.q=Queue.Qu eue()
self.action=act .action(self.q)
gobject.timeout _add (1000,self.acti on.go)
gobject.timeout _add (1000,self.proc ess)
#@-- init window1.__init_ _ }
#@-- new window1.new {
def new(self):
print 'A new %s has been created' % self.__class__. __name__
#@-- new window1.new }
#@-- custom window1 {
# Write your own methods here
#@-- custom window1 }
#@-- callback window1.on_butt on1_clicked {
def on_button1_clic ked(self, widget, args=[]):
print 'on_button1_cli cked called with self.%s' %
widget.get_name ()
self.action.sto p()
print "arrete de thread"
#@-- callback window1.on_butt on1_clicked }
def process (self):
dir (self.q)
if self.q.empty() == False :
print "from main ",self.q.ge t()
return True

#@-- window window1 }
#@-- main gui.py {
#@-- init main {
def main():
#@-- init main }
#@-- body main {
Window1 = window1()
Window1.run()
#@-- body main }
#@-- main gui.py }
#@-- run gui.py {
if __name__ == '__main__':
main()
#@-- run gui.py }
#@-- python gui.py }

the glade file:
<?xml version="1.0" standalone="no" ?<!--*- mode: xml -*-->
<!DOCTYPE glade-interface SYSTEM
"http://glade.gnome.org/glade-2.0.dtd">

<glade-interface>

<widget class="GtkWindo w" id="window1">
<property name="visible"> True</property>
<property name="title" translatable="y es">window1</property>
<property name="type">GTK _WINDOW_TOPLEVE L</property>
<property name="window_po sition">GTK_WIN _POS_NONE</property>
<property name="modal">Fa lse</property>
<property name="resizable ">True</property>
<property name="destroy_w ith_parent">Fal se</property>
<property name="decorated ">True</property>
<property name="skip_task bar_hint">False </property>
<property name="skip_page r_hint">False</property>
<property name="type_hint ">GDK_WINDOW_TY PE_HINT_NORMAL</property>
<property name="gravity"> GDK_GRAVITY_NOR TH_WEST</property>
<property name="focus_on_ map">True</property>
<property name="urgency_h int">False</property>

<child>
<widget class="GtkVBox" id="vbox1">
<property name="visible"> True</property>
<property name="homogeneo us">False</property>
<property name="spacing"> 0</property>

<child>
<widget class="GtkEntry " id="entry1">
<property name="visible"> True</property>
<property name="can_focus ">True</property>
<property name="editable" >True</property>
<property name="visibilit y">True</property>
<property name="max_lengt h">0</property>
<property name="text" translatable="y es">this is it</property>
<property name="has_frame ">True</property>
<property name="invisible _char">*</property>
<property name="activates _default">False </property>
</widget>
<packing>
<property name="padding"> 0</property>
<property name="expand">T rue</property>
<property name="fill">Tru e</property>
</packing>
</child>

<child>
<widget class="GtkButto n" id="button1">
<property name="visible"> True</property>
<property name="can_focus ">True</property>
<property name="label" translatable="y es">button1</property>
<property name="use_under line">True</property>
<property name="relief">G TK_RELIEF_NORMA L</property>
<property name="focus_on_ click">True</property>
<signal name="clicked" handler="on_but ton1_clicked"
last_modificati on_time="Wed, 20 Sep 2006 19:59:06 GMT"/>
</widget>
<packing>
<property name="padding"> 0</property>
<property name="expand">F alse</property>
<property name="fill">Fal se</property>
<property name="pack_type ">GTK_PACK_ END</property>
</packing>
</child>
</widget>
</child>
</widget>

</glade-interface>

Sep 22 '06 #1
6 2865
seb wrote:
Hi,

I am using pygtk for the first times.

I am wondering what would be the best "pattern" to interface pygtk with
a thread.

The thread is collecting informations (over the network for example) or
is doing some long calculations.
Hi,

I would use several *processes*. If your scripts runs on Unix/Linux
you can use select() on the filedescriptors of the processes you created
with popen. On Windows you need to poll them, but maybe this is
better than threads, too. With idle_add you can get data from
the subproceses. It gets called if there are no actions in the
event-loop.

HTH,
Thomas

--
Thomas Güttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/
E-Mail: guettli (*) thomas-guettler + de
Spam Catcher: ni************* *@thomas-guettler.de

Sep 22 '06 #2
seb
Hi Thomas,

I am running WinXP so that casting processes and getting their results
is not so convenient.

I have tested idle add and it does the job : the thread is running
whenever there is no activity on the gui.
I still do not understand how it can be so responsive 'cause the thread
I am using at the moment do not have any time.sleep(ing) .

I am afraid I have still to use an intermediate class between the
computing thread and the gui to send data between the two of them but
now about all the computing time is devoided to the thread.

Thanks a lot !!!

Seb.

ps : the only mod that I have done to the gui.py in the init is

def __init__(self, path='gui.glade ',
root='window1',
domain=app_name , kwargs={}):
path = os.path.join(gl ade_dir, path)
SimpleGladeApp. __init__(self, path, root, domain, **kwargs)
self.q=Queue.Qu eue()
self.action=act .action(self.q)
gobject.idle_ad d(self.action.g o)
#gobject.timeou t_add (1000,self.acti on.go)
gobject.timeout _add (1000,self.proc ess)

Thomas Guettler wrote:
seb wrote:
Hi,

I am using pygtk for the first times.

I am wondering what would be the best "pattern" to interface pygtk with
a thread.

The thread is collecting informations (over the network for example) or
is doing some long calculations.

Hi,

I would use several *processes*. If your scripts runs on Unix/Linux
you can use select() on the filedescriptors of the processes you created
with popen. On Windows you need to poll them, but maybe this is
better than threads, too. With idle_add you can get data from
the subproceses. It gets called if there are no actions in the
event-loop.

HTH,
Thomas

--
Thomas Güttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/
E-Mail: guettli (*) thomas-guettler + de
Spam Catcher: ni************* *@thomas-guettler.de
Sep 22 '06 #3
seb wrote:
Hi,

I am using pygtk for the first times.

I am wondering what would be the best "pattern" to interface pygtk with
a thread.

The thread is collecting informations (over the network for example) or
is doing some long calculations.
It sounds like you don't need to share all your memory--any time you're
trying to "seperate" threads, you probably want to be using processes
instead.

Sep 22 '06 #4
seb
Hi,

I am running on WinXP so that is not so convenient to communicate
between separate processes.

In the past I have used blocking files but it may be a slow
communication way for some applications. It may also be too much
depending on the disk on which the program is run (network drives with
different rights).

It seems that RPC call would do the job but I would have liked
something simplier (although I did not tried it).

The best thing would be to have a queue feature that would be be shared
between processes but as far as I know It does not exists in python.
Thanks.
Seb
Do you know of some features like a queue that
sj*******@yahoo .com wrote:
seb wrote:
Hi,

I am using pygtk for the first times.

I am wondering what would be the best "pattern" to interface pygtk with
a thread.

The thread is collecting informations (over the network for example) or
is doing some long calculations.

It sounds like you don't need to share all your memory--any time you're
trying to "seperate" threads, you probably want to be using processes
instead.
Sep 23 '06 #5
seb wrote:
The best thing would be to have a queue feature that would be be shared
between processes but as far as I know It does not exists in python.
There is a queue class to share data between threads:

http://docs.python.org/lib/module-Queue.html

--
Thomas Güttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/
E-Mail: guettli (*) thomas-guettler + de
Spam Catcher: ni************* *@thomas-guettler.de

Sep 25 '06 #6
seb wrote:
Hi,

I am running on WinXP so that is not so convenient to communicate
between separate processes.
Can you elaborate?

Windows offers plenty of IPC possibilities, including interprocess
mutexes and semaphores. See for instance:
http://www.codeproject.com/threads/Win32IPC.asp

In the past I've used multiple processes under Python with
activepython's win32pipe for IPC without problems.

Sep 25 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

92
6506
by: Reed L. O'Brien | last post by:
I see rotor was removed for 2.4 and the docs say use an AES module provided separately... Is there a standard module that works alike or an AES module that works alike but with better encryption? cheers, reed
125
14804
by: Sarah Tanembaum | last post by:
Beside its an opensource and supported by community, what's the fundamental differences between PostgreSQL and those high-price commercial database (and some are bloated such as Oracle) from software giant such as Microsoft SQL Server, Oracle, and Sybase? Is PostgreSQL reliable enough to be used for high-end commercial application? Thanks
63
5905
by: Tristan Miller | last post by:
Greetings. Do any popular browsers correctly support <q>, at least for Western languages? I've noticed that Mozilla uses the standard English double-quote character, ", regardless of the lang attribute of the HTML document. Will any browsers render German-style quotes or French-style guillemots for lang="de" and lang="fr", respectively? Regards, Tristan
2
1832
by: Mike Hennessy | last post by:
I'm looking for people's opinions and feedback regarding the design of the application tier, and how to best logically separate out the Data Access from the Business Object's. Per the Microsoft prescriptive architecture documents, they recommend creating a completely separate logical Data Access Tier of components. Then creating a separate tier of Business Objects that consume them. My first question is...what does this actually buy you...
121
10127
by: typingcat | last post by:
First of all, I'm an Asian and I need to input Japanese, Korean and so on. I've tried many PHP IDEs today, but almost non of them supported Unicode (UTF-8) file. I've found that the only Unicode support IDEs are DreamWeaver 8 and Zend PHP Studio. DreamWeaver provides full support for Unicode. However, DreamWeaver is a web editor rather than a PHP IDE. It only supports basic IntelliSense (or code completion) and doesn't have anything...
4
2953
by: Mountain Bikn' Guy | last post by:
I need some advice on this. I am working on a fairly complex calculator app (C#) with lots of functions (and these functions in turn use math functions from an unmanaged C DLL). A calculation takes a lot of time (up to hours), and should run on a separate thread from the one that the GUI uses. The GUI also needs to display various properties for each function (such as parameters that can be set). It does this with property grid and other...
5
2410
by: Franco, Gustavo | last post by:
Hi, I have a question, and please I need a answer. How can I finalize a thread running with Application.Run (I need the message loop!!!) without call Thread.Abort?. I want to call Application.ExitThread in the same thread that it is running.
3
4936
by: RWF | last post by:
I have read that when using asynchronous IO it is best to keep all your operations asynchronous. But why if there is nothing left do in the AsyncCallback method other than to call an IO operation? Example: //DeliveryHelper is just a class containg an TcpClient and other state traced variables. //HelpState.CommStream is a property that returns TcpClient.GetStream() public void some method() {
669
26085
by: Xah Lee | last post by:
in March, i posted a essay “What is Expressiveness in a Computer Language”, archived at: http://xahlee.org/perl-python/what_is_expresiveness.html I was informed then that there is a academic paper written on this subject. On the Expressive Power of Programming Languages, by Matthias Felleisen, 1990. http://www.ccs.neu.edu/home/cobbe/pl-seminar-jr/notes/2003-sep-26/expressive-slides.pdf
0
8965
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9466
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9202
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8202
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6050
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4567
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4823
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3278
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2191
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.