Re: [Tutor] Ptyhon GUI doubt

2009-08-26 Thread Alan Gauld


"Reddy Etikela, Rajasekhar"  wrote

I am new to the Python. I have installed Python 2.6.2 version in windows 
XP.

When I try to open the IDLE(Python GUI), getting the below message.


Others have advised what to do for IDLE but since you are on XP I'd
strongly recommend using Pythonwin instead of IDLE.

If you downloaded Python from the python.org web site you need to
download and install the additional Windows package and inside that
you will find Pythonwin. This is a more powerful IDE than IDLE with
several useful Windows specific extras. Find it here:

http://sourceforge.net/projects/pywin32/files/

Select the version corresponding to your version of Python..

If you got your Python from activestate.com then pythonwin is already 
included.

In fact I'd go so far as to recommend dumping the python.org installation
and getting the activestate version. It has a whole bunch of extras 
including

all of the python documentation in Windows help format.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to remove first '/'

2009-08-26 Thread Brett Wilkins
I would say the best way would be to use lstrip...
path='/path/to/file'
stripped_path = path.lstrip('/')

Cheers
--Brett

> Hello,
> I want to strip the first '/' from the following:
>
> '/path/to/file'
>
> How can I do this?
>
> Dave
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] design advise

2009-08-26 Thread davidwilson
Hello,
I would like advise on what method would be better in terms of search and 
retrieval.

In my application I need to choose how to store data for each user, for example:

/news
/articles
/games

My difficulty now comes in how to store this data in that I will need to create 
views of the data depending on where in the directory the viewer is at for 
example file:///news/ should contain all the news submitted by all users and 
file:///games/ should contain all games ...

Also in the file:///users/user/ the user will need access only to their own 
items, so for example, file:///users/user_1/news/ will list all news added by 
user_1 etc...

Which is the more efficient option for storing this data, is it better to have 
all in one place and for each users'
 view to search by user id and return the filtered down list, or store it 
within each users' individual directory and then create a new list by 
traversing each users' directory?

Thanks
Dave
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Declaration order of classes... why it is important?

2009-08-26 Thread Mac Ryan
Hello everybody,

I am using "storm" (https://storm.canonical.com/) to manage my
database. In storm, relationships between tables (each table is
represented by a class) are expressed like this (line #4):

1 >>> class Employee(Person):
2 ... __storm_table__ = "employee"
3 ... company_id = Int()
4 ... company = Reference(company_id, Company.id)

where Company is another class. Now, what I noticed is that Company must
be declared as a class before Employee, or python will throw an
exception (Company is not defined).

I would be interested in understanding why this is so designed. I
expected that the exception would not be thrown at all, as I imagined
that the interpreter simply kept track of where classes were declared
and would try to evaluate the code only once an actual object would be
instantiated (at that point the interpreter would know where to look for
each class code).

BTW, the behaviour I am describing is exactly what happens with function
declaration: the following code evaluates as expected, indeed.

def fone():
  ftwo()
def ftwo():
  print "hello"
fone()

I would also be interested in knowing if there is a way around this or
if I simply have to live with it. 

It is not that this impede to achieve anything, but in reading code, I
normally prefer to have the big picture first [This is a house, as you
see is composed of walls, roof, basement. A wall can have...] while this
behaviour obliges me to write the code the other way around ["This is a
brick, if you put together bricks you get a wall, if you put together
walls you get..."]

Thanks in advance,
Mac.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] design advise

2009-08-26 Thread Alan Gauld

 wrote

In my application I need to choose how to store data for each user, for 
example:


/news
/articles
/games

My difficulty now comes in how to store this data in that I will need to 
create views


Which is the more efficient option for storing this data, is it better to 
have
all in one place and for each users' view to search by user id and return 
the
filtered down list, or store it within each users' individual directory 
and then

create a new list by traversing each users' directory?


How about storing it in one place and creating shortcuts from the users 
areas
to the master? That way items can be shared by users but still appear to be 
private.


It might also be worth a look at how Apple do that stuff on MacOS... 
including

iTunes etc

Alan G 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Declaration order of classes... why it is important?

2009-08-26 Thread Wayne
On Wed, Aug 26, 2009 at 11:25 AM, Mac Ryan  wrote:

> Hello everybody,
>
>I am using "storm" (https://storm.canonical.com/) to manage my
> database. In storm, relationships between tables (each table is
> represented by a class) are expressed like this (line #4):
>
> 1 >>> class Employee(Person):
> 2 ... __storm_table__ = "employee"
> 3 ... company_id = Int()
> 4 ... company = Reference(company_id, Company.id)
>
> where Company is another class. Now, what I noticed is that Company must
> be declared as a class before Employee, or python will throw an
> exception (Company is not defined).


>
> I would be interested in understanding why this is so designed. I
> expected that the exception would not be thrown at all, as I imagined
> that the interpreter simply kept track of where classes were declared
> and would try to evaluate the code only once an actual object would be
> instantiated (at that point the interpreter would know where to look for
> each class code).
>
> BTW, the behaviour I am describing is exactly what happens with function
> declaration: the following code evaluates as expected, indeed.
>
> def fone():
>  ftwo()
> def ftwo():
>  print "hello"
> fone()


Try it with a class definition instead:

In [1]: class One:
   ...: Two()
   ...:
   ...:
---
NameError Traceback (most recent call last)

C:\Documents and Settings\Wayne\ in ()

C:\Documents and Settings\Wayne\ in One()

NameError: name 'Two' is not defined

Yet with a function inside a class:

In [2]: class One:
   ...: def spam(self):
   ...: Two()
   ...:
   ...:

No problems.

My guess is that it has to do with the difference between class and function
definitions. AFAIK, classes are simply another namespace exactly like the
global namespace. Similar to an 'import' statement which executes all the
code found in that module. Further testing verifies this:

In [3]: class One:
   ...: print "Hello"
   ...:
   ...:
Hello

Of course usually with a class you declare an __init__ method (function)
that would eliminate your problem. The __init__ method is called on object
instantiation.

In [4]: class One:
   ...: def __init__(self):
   ...: Two()
   ...:
   ...:

In [5]: One()
---
NameError Traceback (most recent call last)

C:\Documents and Settings\Wayne\ in ()

C:\Documents and Settings\Wayne\ in __init__(self)

NameError: global name 'Two' is not defined

HTH,
Wayne

p.s. The In[#] instead of >>> are because I'm using Ipython.




>
>
> I would also be interested in knowing if there is a way around this or
> if I simply have to live with it.
>
> It is not that this impede to achieve anything, but in reading code, I
> normally prefer to have the big picture first [This is a house, as you
> see is composed of walls, roof, basement. A wall can have...] while this
> behaviour obliges me to write the code the other way around ["This is a
> brick, if you put together bricks you get a wall, if you put together
> walls you get..."]
>
> Thanks in advance,
> Mac.
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
To be considered stupid and to be told so is more painful than being called
gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
every vice, has found its defenders, its rhetoric, its ennoblement and
exaltation, but stupidity hasn’t. - Primo Levi
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Declaration order of classes... why it is important?

2009-08-26 Thread Kent Johnson
On Wed, Aug 26, 2009 at 12:25 PM, Mac Ryan wrote:
> Hello everybody,
>
>        I am using "storm" (https://storm.canonical.com/) to manage my
> database. In storm, relationships between tables (each table is
> represented by a class) are expressed like this (line #4):
>
> 1 >>> class Employee(Person):
> 2 ...     __storm_table__ = "employee"
> 3 ...     company_id = Int()
> 4 ...     company = Reference(company_id, Company.id)
>
> where Company is another class. Now, what I noticed is that Company must
> be declared as a class before Employee, or python will throw an
> exception (Company is not defined).
>
> I would be interested in understanding why this is so designed. I
> expected that the exception would not be thrown at all, as I imagined
> that the interpreter simply kept track of where classes were declared
> and would try to evaluate the code only once an actual object would be
> instantiated (at that point the interpreter would know where to look for
> each class code).

The body of a class definition is executed when it is encountered. The
result is a class object (an instance of 'type', usually). Any names
defined at class scope become attributes of the class. The class name
becomes a reference to the class object.

> BTW, the behaviour I am describing is exactly what happens with function
> declaration: the following code evaluates as expected, indeed.
>
> def fone():
>  ftwo()
> def ftwo():
>  print "hello"
> fone()

Yes, functions are different than classes. The body of a function is
not executed until it is called.

Note that class methods behave like functions (well, they are
functions) - they are not executed until called. But statements at
class scope are executed to create the class.
>
> I would also be interested in knowing if there is a way around this or
> if I simply have to live with it.

You have to live with it unless you can put the attributes inside a
method. In this case, I don't think that will work.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] design advise

2009-08-26 Thread Kent Johnson
On Wed, Aug 26, 2009 at 7:52 AM,  wrote:
> Hello,
> I would like advise on what method would be better in terms of search and 
> retrieval.
>
> In my application I need to choose how to store data for each user, for 
> example:
>
> /news
> /articles
> /games
>
> My difficulty now comes in how to store this data in that I will need to 
> create views of the data depending on where in the directory the viewer is at 
> for example file:///news/ should contain all the news submitted by all users 
> and file:///games/ should contain all games ...
>
> Also in the file:///users/user/ the user will need access only to their own 
> items, so for example, file:///users/user_1/news/ will list all news added by 
> user_1 etc...
>
> Which is the more efficient option for storing this data, is it better to 
> have all in one place and for each users'
>  view to search by user id and return the filtered down list, or store it 
> within each users' individual directory and then create a new list by 
> traversing each users' directory?

Maybe you should consider storing the data in a database instead of in
the file system? Then it would be easy to retrieve all news, or just
the news for a single user.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Declaration order of classes... why it is important?

2009-08-26 Thread Dave Angel

Kent Johnson wrote:

On Wed, Aug 26, 2009 at 12:25 PM, Mac Ryan wrote:
  

Hello everybody,

   I am using "storm" (https://storm.canonical.com/) to manage my
database. In storm, relationships between tables (each table is
represented by a class) are expressed like this (line #4):

1 >>> class Employee(Person):
2 ... __storm_table__ =employee"
3 ... company_id =nt()
4 ... company =eference(company_id, Company.id)

where Company is another class. Now, what I noticed is that Company must
be declared as a class before Employee, or python will throw an
exception (Company is not defined).

I would be interested in understanding why this is so designed. I
expected that the exception would not be thrown at all, as I imagined
that the interpreter simply kept track of where classes were declared
and would try to evaluate the code only once an actual object would be
instantiated (at that point the interpreter would know where to look for
each class code).



The body of a class definition is executed when it is encountered. The
result is a class object (an instance of 'type', usually). Any names
defined at class scope become attributes of the class. The class name
becomes a reference to the class object.

  

BTW, the behaviour I am describing is exactly what happens with function
declaration: the following code evaluates as expected, indeed.

def fone():
 ftwo()
def ftwo():
 print "hello"
fone()



Yes, functions are different than classes. The body of a function is
not executed until it is called.

Note that class methods behave like functions (well, they are
functions) - they are not executed until called. But statements at
class scope are executed to create the class.
  

I would also be interested in knowing if there is a way around this or
if I simply have to live with it.



You have to live with it unless you can put the attributes inside a
method. In this case, I don't think that will work.

Kent

  

In Python, you don't declare classes, you define them.

You can forward reference inside a definition (or method), but not 
elsewhere.  That's because it's a one-pass system, where the lines are 
executed in order.  In the case of a "def", execution consists of 
compiling the body and making a function object.  That function object 
may forward reference all it likes, as long as it's not called until 
those references are available.


So there are two workarounds to get what you'd like.  Your problem is 
that you want the classes in a certain order, but that the first class 
has class attributes that have a forward reference.  You can't do that 
directly.


1)  As Kent suggested, you can put the attribute initialization inside a 
"dummy class method," one that will only be executed once, and that you 
promise will be executed before any other method of the class.  Then 
when you have finished defining the dependency (the other class), you 
call this dummy method.



Since you don't define all the other stuff, I have to simplify your 
case.  Give a working fragment, if this is too simplified.


class Employee(object):
  __storm_table__ = "employee"
  company_id = []
  company = Company.id #where Company is a forward reference

class Company:
   id = 42


This gives an error  trying to define the Employee.company attribute.  
So define a classmethod to finish the job, and invoke it later


class Employee(object):
   @classmethod
   def finish(cls):
   cls.__storm_table__ = "employee"
   cls.company_id = []
   cls.company = Company.id #where Company is a forward 
reference
   del cls.finish  #remove this method so it won't be called a 
second time


class Company:
   id = 42

Employee.finish()   #This finishes initializing the class


help(Employee)
print Employee.company_id

2) Simpler:   Simply define the forward referencing class method later 
in the file, in the same place you would have invoked finish().


class Employee(object):
   __storm_table__ = "employee"
   company_id = []
   #company = Company.id #Do this later

class Company:
   id = 42

Employee.company_id = Company.id


DaveA
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Declaration order of classes... why it is important?

2009-08-26 Thread Mac Ryan
On Wed, 2009-08-26 at 15:46 -0400, Dave Angel wrote:
> So define a classmethod to finish the job, and invoke it later
> 
> class Employee(object):
> @classmethod
> def finish(cls):
> cls.__storm_table__ = "employee"
> cls.company_id = []
> cls.company = Company.id #where Company is a forward 
> reference
> del cls.finish  #remove this method so it won't be called a 
> second time
> 
> class Company:
> id = 42
> 
> Employee.finish()   #This finishes initializing the class
> 
> 
> help(Employee)
> print Employee.company_id

First things first, thank you Wayne, Kent and Dave for your extensive
and complementary explanations. As many things in python, what it seemed
obscure at first now - with your help - seems perfectly obvious.

Second thing: the example that Dave gave me and that I left quoted above
makes use of decorators, but this is something that I still do not
understand. I believe I got a grasp of the concept of metaclasses, to
which the concept of decorator seems to be related, but the official
documentation is a a bit obscure for me.

I don't want to steal your time asking for an explanation that probably
is already somewhere out there, but my google searches did not return
anything useful (I assume I am using the wrong keywords here), so if you
have a good pointer for me, I would be very grateful. :)

Mac.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Declaration order of classes... why it is important?

2009-08-26 Thread Alan Gauld


"Mac Ryan"  wrote


1 >>> class Employee(Person):
2 ... __storm_table__ = "employee"
3 ... company_id = Int()
4 ... company = Reference(company_id, Company.id)

where Company is another class. Now, what I noticed is that Company must
be declared as a class before Employee, or python will throw an
exception (Company is not defined).


Thats because you are using Comany as a class attribute rather
than an instance attribute. A class is an object in Python, in the
same sense that functions are objects. Python creates the class
object by evaluating the class definition. Instances are created
by calling the class object.


I would be interested in understanding why this is so designed. I
expected that the exception would not be thrown at all, as I imagined
that the interpreter simply kept track of where classes were declared
and would try to evaluate the code only once an actual object would be
instantiated (at that point the interpreter would know where to look for
each class code).


No it interprets the class definition when it first sees it and the result
is a class object. Because you refer to Company as part of the definition
of a class attribute - part of the class object - Python needs to evaluate
Company to create the class.



BTW, the behaviour I am describing is exactly what happens with function
declaration: the following code evaluates as expected, indeed.

def fone():
 ftwo()
def ftwo():
 print "hello"
fone()

I would also be interested in knowing if there is a way around this or
if I simply have to live with it.


functions are objects too. But there are no variables inside the
function that persist, even local variables are created then destroyed.
But if you consider a default parameter you do get an error:

def p(a=b):
a()

def b():
   print 'hello'

p()

Will give a name error and thats as close as I can get to what you
are doing with the class definition using clas variables.

If you use instamnce variables the problem does not exist:


class C:

 d = M
 def __init__(self):
pass


Traceback (most recent call last):
 File "", line 1, in 
   class C:
 File "", line 2, in C
   d = M
NameError: name 'M' is not defined


class D:

 def __init__(self):
   self.d = M








It is not that this impede to achieve anything, but in reading code, I
normally prefer to have the big picture first [This is a house, as you
see is composed of walls, roof, basement. A wall can have...] while this
behaviour obliges me to write the code the other way around ["This is a
brick, if you put together bricks you get a wall, if you put together
walls you get..."]


You can put the top level function in a separate module and import
the lower level ones, similarly you can put the class definitions in
separate modules. But IMHO its better to just get used to Pythons way
of working. Cut n Paste works wonders :-)

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Declaration order of classes... why it is important?

2009-08-26 Thread Kent Johnson
On Wed, Aug 26, 2009 at 5:52 PM, Mac Ryan wrote:
> Second thing: the example that Dave gave me and that I left quoted above
> makes use of decorators, but this is something that I still do not
> understand. I believe I got a grasp of the concept of metaclasses, to
> which the concept of decorator seems to be related, but the official
> documentation is a a bit obscure for me.
>
> I don't want to steal your time asking for an explanation that probably
> is already somewhere out there, but my google searches did not return
> anything useful (I assume I am using the wrong keywords here), so if you
> have a good pointer for me, I would be very grateful. :)

http://personalpages.tds.net/~kent37/kk/1.html

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] AUTO: James D Mcclatchey is out of the office. (returning 08/31/2009)

2009-08-26 Thread James D Mcclatchey

I am out of the office until 08/31/2009.

I will respond to your message when I return.


Note: This is an automated response to your message  "Tutor Digest, Vol 66,
Issue 72" sent on 8/26/09 17:01:48.

This is the only notification you will receive while this person is away.


*IMPORTANT NOTICE: This communication, including any attachment, contains 
information that may be confidential or privileged, and is intended solely for 
the entity or individual to whom it is addressed.  If you are not the intended 
recipient, you should delete this message and are hereby notified that any 
disclosure, copying, or distribution of this message is strictly prohibited.  
Nothing in this email, including any attachment, is intended to be a legally 
binding signature.
*
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Declaration order of classes... why it is important?

2009-08-26 Thread Dave Angel

Mac Ryan wrote:

On Wed, 2009-08-26 at 15:46 -0400, Dave Angel wrote:
  

So define a classmethod to finish the job, and invoke it later

class Employee(object):
@classmethod
def finish(cls):
cls.__storm_table__ = "employee"
cls.company_id = []
cls.company = Company.id #where Company is a forward 
reference
del cls.finish  #remove this method so it won't be called a 
second time


class Company:
id = 42

Employee.finish()   #This finishes initializing the class


help(Employee)
print Employee.company_id



First things first, thank you Wayne, Kent and Dave for your extensive
and complementary explanations. As many things in python, what it seemed
obscure at first now - with your help - seems perfectly obvious.

Second thing: the example that Dave gave me and that I left quoted above
makes use of decorators, but this is something that I still do not
understand. I believe I got a grasp of the concept of metaclasses, to
which the concept of decorator seems to be related, but the official
documentation is a a bit obscure for me.

I don't want to steal your time asking for an explanation that probably
is already somewhere out there, but my google searches did not return
anything useful (I assume I am using the wrong keywords here), so if you
have a good pointer for me, I would be very grateful. :)

Mac.


  
(I see Kent posted a good link.  But I had already composed this, so 
I'll send it along.  First time, I accidentally posted to c.l.p.  but 
I'll do better this time.)


Decorators are syntactic sugar to save typing;  what they accomplish can 
always be done another way, but generally not as readable.


#somebody (eg., Python library) defines a function that takes a function 
as parameter, and returns a function, generally a different one related 
to the first

def  mydecorator(funct):

return newfunct


class  myclass(object):
   @mydecorator
def  mymethod(self, arg1, arg2):
...

Instead of the @syntax, we could also have written:

class  myclass(object):
def mymethod(self, arg1, arg2)
  
mymethod = mydecorator(mymethod) #this call happens 
when the class is being created



Now there are a couple of decorators that are in the standard library 
that everyone should know about:classmethod() and staticmethod().  
They wrap a method in a new one (which ends up having the same name), 
such that the first argument is either eaten (staticmethod), or changed 
to a class (classmethod).


Hope that was sufficient detail.

DaveA


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Callbacks in Python

2009-08-26 Thread Jramak
Hello

I'm confused by callbacks. I would really appreciate any introduction or
help in understanding the concept of callbacks.

Thanks much
Jramak
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Callbacks in Python

2009-08-26 Thread Luke Paireepinart
Suppose you are writing a GUI application.  You don't want to write it from
scratch so you want to use TKInter or WXPython.  However, you also want to
process the user's mouse clicks.  These clicks won't occur in a consistent
manner;  sometimes they may occur frequently (double-clicking), sometimes
infrequently (they're busy reading your interface, whatever.)  So if you
just poll the TKInter side of the program for events, a lot of the polls
will be wasted.  What you really want is that your code is run only when
your event occurs.So you write a program that does what you want on each
mouse click.  Then you pass it to TKInter and say "hey, call this whenever
you get a mouseclick event!"  that function you wrote is called a
"callback".

Make sense?

On Wed, Aug 26, 2009 at 8:47 PM, Jramak  wrote:

> Hello
>
> I'm confused by callbacks. I would really appreciate any introduction or
> help in understanding the concept of callbacks.
>
> Thanks much
> Jramak
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Callbacks in Python

2009-08-26 Thread Luke Paireepinart
On Wed, Aug 26, 2009 at 8:51 PM, Luke Paireepinart
wrote:
>
> So you write a program that does what you want on each mouse click.
>

I meant "function" rather than "program".
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] how do I post event to thread?

2009-08-26 Thread Jeff Peery
hello,
I've read a bit about multi thread communication, and found that most people 
use a queue, which makes sense. however in my case I simply have two threads, a 
main thread and one other. the main thread is doing many different things and 
the second thread is receiving numerical data via a serial port.. when data 
comes in, I want to post the data to the main thread so it can use the it. I 
don't want to use a queue because I don't want to lock up my main thread in a 
loop that is always looking at the queue waiting to get something out of it. I 
would prefer to do something like post an event. The alternative would be to 
simply have a method in my main thread called OnResult(data), and when data 
comes in to the second thread I could call main_thread.OnResult(data). This 
would solve my problem, but I'm not sure if that is an ok thing to do... 
calling a main thread method from within a second thread?
 
is there a way to post an event to the main thread from a second thread?
 
Is it ok to pass the main thread (self) into the second thread and have the 
second thread
call a main_thread.OnResult(data) method to pass the data into the main thread? 
I'm not sure how the main thread handles this, my guess is that it can only do 
one thing at a time so it might be exactly that same as 'posting an event'.
 
any thoughts would be much appreciated. thanks!
 
Jeff


  ___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how do I post event to thread?

2009-08-26 Thread Dave Angel

Jeff Peery wrote:

hello,
I've read a bit about multi thread communication, and found that most people 
use a queue, which makes sense. however in my case I simply have two threads, a 
main thread and one other. the main thread is doing many different things and 
the second thread is receiving numerical data via a serial port.. when data 
comes in, I want to post the data to the main thread so it can use the it. I 
don't want to use a queue because I don't want to lock up my main thread in a 
loop that is always looking at the queue waiting to get something out of it. I 
would prefer to do something like post an event. The alternative would be to 
simply have a method in my main thread called OnResult(data), and when data 
comes in to the second thread I could call main_thread.OnResult(data). This 
would solve my problem, but I'm not sure if that is an ok thing to do... 
calling a main thread method from within a second thread?
 
is there a way to post an event to the main thread from a second thread?
 
Is it ok to pass the main thread (self) into the second thread and have the second thread

call a main_thread.OnResult(data) method to pass the data into the main thread? 
I'm not sure how the main thread handles this, my guess is that it can only do 
one thing at a time so it might be exactly that same as 'posting an event'.
 
any thoughts would be much appreciated. thanks!
 
Jeff



  
You have some confusion here.  A function doesn't belong to a thread, 
it's just code.  When that code is called from the main thread, it's a 
function in the main thread.  When the same function is called from a 
second thread, it's a function in that one.  The trick to communicating 
between threads is *not* calling, it's a queue.  You can use standard 
ones, or you can write your own.  And you can call it lots of things.  
But basically the main thread will need to poll the "queue" somehow, to 
decide whether there's anything there to do.


What is your main thread doing?  Is yours a GUI program?  If so, the 
main thread already has a polling loop, and you can just post an event 
on the event queue.  Something like "callafter" or whatever it's called 
in your particular GUI.


A queue of length 1 might be just a flag that's set by the secondary 
thread whenever there's data available.  And it gets cleared by the main 
thread whenever it's noticed and acted upon.


When the OS creates a thread, it basically creates a second stack frame, 
and creates another instance of the static space called "thread local 
storage (TLS)."  Python presumably puts the thread object into the 
thread local storage.  And the OS switches threads by restoring the 
stack pointer to point to a different stack frame, as well as the 
threadpointer to point to whichever TLS corresponds to it.  Most things 
are totally shared between the threads.  There are various OS things 
that affect the scheduling, so for example if you make a blocking call 
to an OS function, a thread switch will let other threads run in the 
meantime.  Presumably an example of that is the call to read the serial 
port.  Another way a thread can voluntarily give up control is with a 
sleep() call.  Hopefully a GUI mainloop does one of those whenever there 
are no events waiting.


There's more subtlety to threads.  But this should get you started, and 
help point the way to questions more specific to your program design.  
Tell us python version, OS, and what GUI library you may be using.


DaveA


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor