Re: Loop Question

2013-06-25 Thread Lutz Horn

Hi,

Am 24.06.2013 14:12 schrieb christheco...@gmail.com:

username=raw_input(Please enter your username: )
password=raw_input(Please enter your password: )
if username == john doe and password == fopwpo:
 print Login Successful
else:
 print Please try again


while not username or not password or username != john doe or 
password != fopwpo:

print Please try again
username=raw_input(Please enter your username: )
password=raw_input(Please enter your password: )

print Login Successful


--
Opt out of PRISM, the NSA’s global data surveillance program.
Stop reporting your online activities to the American government
with these free alternatives to proprietary software.
http://prism-break.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Loop Question

2013-06-25 Thread Dave Angel

On 06/24/2013 08:20 AM, Lutz Horn wrote:

Hi,

Am 24.06.2013 14:12 schrieb christheco...@gmail.com:

username=raw_input(Please enter your username: )
password=raw_input(Please enter your password: )
if username == john doe and password == fopwpo:
 print Login Successful
else:
 print Please try again


while not username or not password or username != john doe or password
!= fopwpo:
 print Please try again
 username=raw_input(Please enter your username: )
 password=raw_input(Please enter your password: )

print Login Successful




That requires you to have four raw_input() calls instead of two.  And 
what purpose does adding the two new clauses to the while test serve? 
How is:


while not username or not password or username != john doe or password 
!= fopwpo:


different from:

while username != john doe or password != fopwpo:

(other than taking more time and space, and being harder to read) ?

--
DaveA
--
http://mail.python.org/mailman/listinfo/python-list


Re: Loop Question

2013-06-24 Thread christhecomic
Here is my code...I'm using 2.7.5

username=raw_input(Please enter your username: )
password=raw_input(Please enter your password: )
if username == john doe and password == fopwpo:
 print Login Successful
else:
 print Please try again
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loop Question

2013-06-24 Thread rusi
On Monday, June 24, 2013 5:42:51 PM UTC+5:30, christ...@gmail.com wrote:
 Here is my code...I'm using 2.7.5
 
 
 username=raw_input(Please enter your username: )
 password=raw_input(Please enter your password: )
 if username == john doe and password == fopwpo:
  print Login Successful
 else:
  print Please try again


Good!

Now take Steven's suggestion loop with a break
and bung your code into Steven's loop.
[Hint: You have to add a break somewhere!]

Or at least try!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loop Question

2013-06-24 Thread christhecomic
On Sunday, June 23, 2013 6:18:35 PM UTC-5, christ...@gmail.com wrote:
 How do I bring users back to beginning of user/password question once they
 
 fail it? thx

Can't seem to get this to cooperate...where does the while statement belong?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loop Question

2013-06-24 Thread John Gordon
In e41ce3a3-c8cb-4cfc-ba86-462f40f32...@googlegroups.com 
christheco...@gmail.com writes:

 On Sunday, June 23, 2013 6:18:35 PM UTC-5, christ...@gmail.com wrote:
  How do I bring users back to beginning of user/password question once they
  
  fail it? thx

 Can't seem to get this to cooperate...where does the while statement belong?

while True:
username = raw_input(Please enter your username: )
password = raw_input(Please enter your password: )

if username == john doe and password == fopwpo:
print Login Successful
break

else:
print Please try again

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, The Gashlycrumb Tinies

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loop Question

2013-06-24 Thread Chris “Kwpolska” Warrick
On Mon, Jun 24, 2013 at 8:42 PM, John Gordon gor...@panix.com wrote:
 In e41ce3a3-c8cb-4cfc-ba86-462f40f32...@googlegroups.com 
 christheco...@gmail.com writes:

 On Sunday, June 23, 2013 6:18:35 PM UTC-5, christ...@gmail.com wrote:
  How do I bring users back to beginning of user/password question once they
 
  fail it? thx

 Can't seem to get this to cooperate...where does the while statement belong?

 while True:
 username = raw_input(Please enter your username: )
 password = raw_input(Please enter your password: )

 if username == john doe and password == fopwpo:
 print Login Successful
 break

 else:
 print Please try again

You didn’t test the code, did you?  Because the code you posted is
right.  Remember to always test code before submitting.  And note that
the getpass module is what you should use for that second thing in
real life, for the security of your users.

--
Kwpolska http://kwpolska.tk | GPG KEY: 5EAAEA16
stop html mail| always bottom-post
http://asciiribbon.org| http://caliburn.nl/topposting.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loop Question

2013-06-24 Thread John Gordon
In mailman.3754.1372100014.3114.python-l...@python.org 
=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?= kwpol...@gmail.com 
writes:

  while True:
  username = raw_input(Please enter your username: )
  password = raw_input(Please enter your password: )
 
  if username == john doe and password == fopwpo:
  print Login Successful
  break
 
  else:
  print Please try again

 You didn't test the code, did you?  Because the code you posted is
 right.

It's right, therefore I did not test it?  I don't understand.

If the code has a bug, please point it out.

 And note that the getpass module is what you should use for that second
 thing in real life, for the security of your users.

I'm sure this is just an exercise for the OP to understand loops.  Security
would be counter-productive.

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, The Gashlycrumb Tinies

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loop Question

2013-06-24 Thread Dave Angel

On 06/24/2013 03:00 PM, John Gordon wrote:

In mailman.3754.1372100014.3114.python-l...@python.org 
=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?= kwpol...@gmail.com writes:


while True:
 username = raw_input(Please enter your username: )
 password = raw_input(Please enter your password: )

 if username == john doe and password == fopwpo:
 print Login Successful
 break

 else:
 print Please try again



You didn't test the code, did you?  Because the code you posted is
right.


It's right, therefore I did not test it?  I don't understand.


I expect that Chris simply misinterpreted the quoting in your message, 
thinking that the OP had both typed the

  Can't seem to get this to cooperate...where does t...
and the correct code.  In fact, the OP typed the former, and you typed 
the latter.



--
DaveA
--
http://mail.python.org/mailman/listinfo/python-list


Loop Question

2013-06-23 Thread christhecomic
How do I bring users back to beginning of user/password question once they
fail it? thx
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loop Question

2013-06-23 Thread rurpy
On 06/23/2013 05:18 PM, christheco...@gmail.com wrote:
 How do I bring users back to beginning of user/password question once they
 fail it? thx

This is not a very good question.  There is no context 
so we cannot tell if you are talking about a command line 
program that prompts for a username and password or a 
GUI program with a text box asking for the user/password
or something else.  Nor how exactly you go about doing
the asking.

Some code showing what you are trying to do would help
a lot.

I'll guess you're asking about a simple command line 
program.  Maybe something like the following is what 
you want?

while True:
user = input (User? ).strip()
pw = input (Password? ).strip()
if check_user (user, pw): break
print (Hello %s % user)

check_user() is a function you'll define somewhere that
checks the user and password and returns True if they are
correct and False if not.  

Since you didn't say, I'm also assuming you're using 
Python 3; for Python 2 the code will be a little 
different.  

This is a useful guide to asking questions in a way that
makes it easier for people to answer (and thus help
*you* get better, faster answers):
  http://www.catb.org/esr/faqs/smart-questions.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loop Question

2013-06-23 Thread Steven D'Aprano
On Sun, 23 Jun 2013 16:18:35 -0700, christhecomic wrote:

 How do I bring users back to beginning of user/password question once
 they fail it? thx

Write a loop. If they don't fail (i.e. they get the password correct), 
then break out of the loop.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loop Question

2013-06-23 Thread christhecomic
I'm using 2.7
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter event loop question

2008-08-30 Thread gordon
On Aug 29, 10:46 pm, Russell E. Owen [EMAIL PROTECTED] wrote:
you
 can safely compute stuff with a background thread and display it from the 
 main thread). But cross that bridge later.
 -- Russell

thanks Russel
gordon
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter event loop question

2008-08-29 Thread gordon
On Aug 29, 4:45 am, Russell E. Owen [EMAIL PROTECTED] wrote:
your Controller object should not create root nor should
 it call mainloop to start the event loop.

guys
thanks for the helpful replies..I rewrote the code as you advised. It
creates a controller object and a gui object from main script.However
i had to chain some method calls in my code.i am
wondering if that can be avoided in some way.

this is the sequence
1.user enters some value in the textfield,and clicks OKbutton
2.on OKbuttonclick ,the gui takes userinput value and quits
eventloop.It then calls controller and pass the userinputvalue.
3.controller does some calculation(i shd have an external program to
do calculation,but for simplicity i just wrote a method inside
controller) with the given value,obtains the result and calls gui's
updateDisplay(), passing the result value.
4.the gui creates the result as text on a canvas.then the mainloop()
is called to resume event loop

again user enters some value in the textfield,and clicks OKbutton ...

I exit the application by clicking quitButton that calls destroy() on
top level window.
 I tried my application by entering some value on text field and then
clicking OKbutton ,the calculated result is displayed on canvas .I do
this process say 3 times ..Then i click the Quit button and the window
closes.
I have put a print statement inside the gui's updateDisplay()method
right after the resuming of event loop by parent.mainloop().This print
statement gets printed as many times as i had clicked
the OK button(here in this case 3 times).Is this due to clearing of
the stack ?
I feel that it was not a good design ..I would be grateful if someone
would tell me how i could improve it..can those chaining of method
calls be avoided?

this is how i restructured the code

moduleA.py
---
import moduleB
from Tkinter import Tk
class MyController(object):
def __init__(self):
print controller()
def validateSelection(self,userinputVal):
if(userinputVal  50 or userinputVal==0):
userinputVal=50
self.doSomeCalculation(userinputVal)

def doSomeCalculation(self,userinputVal):
resultvalue=2*userinputVal +10
self.updateResults(resultvalue)
def updateResults(self,resultvalue):
self.myapp.updateDisplay(resultvalue);

if __name__ == __main__:
controller=MyController()
root = Tk()
root.wm_title(MyUIApp)
controller.myapp =moduleB.MyUI(root,controller)
root.mainloop()

moduleB.py
---
from Tkinter import *
class MyUI(object):
def __init__(self, parent,controller):
self.myParent = parent
self.mainframe = Frame(parent,background=grey)
self.mainframe.pack(fill=BOTH,expand=YES)
self.controller=controller
added a canvas and OK,QUIT buttons

def okBtnClick(self):
print okBtnClicked
self.okButton.configure(state=DISABLED)
userinputvalue = self.getUserInputValue()
self.myParent.quit()  #quits event loop
self.controller.validateSelection(userinputvalue)

def quitBtnClick(self):
print Quit Btn clicked
self.myParent.destroy()
def updateDisplay(self,resultValue):
message='result is='+str(resultValue)
self.canvresult.delete(ALL)
self.canvresult.create_text(1, 40, anchor=W, text=message,
width=280)
self.okButton.configure(state=NORMAL)
self.myParent.mainloop() # resumes event loop
print 'in updateDisplay():called mainloop'

thanks
gordon
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter event loop question

2008-08-29 Thread Russell E. Owen
In article 
[EMAIL PROTECTED],
 gordon [EMAIL PROTECTED] wrote:

 On Aug 29, 4:45 am, Russell E. Owen [EMAIL PROTECTED] wrote:
 your Controller object should not create root nor should
  it call mainloop to start the event loop.
 
 guys
 thanks for the helpful replies..I rewrote the code as you advised. It
 creates a controller object and a gui object from main script.However
 i had to chain some method calls in my code.i am
 wondering if that can be avoided in some way.
 
 this is the sequence
 1.user enters some value in the textfield,and clicks OKbutton
 2.on OKbuttonclick ,the gui takes userinput value and quits
 eventloop.It then calls controller and pass the userinputvalue.
 3.controller does some calculation(i shd have an external program to
 do calculation,but for simplicity i just wrote a method inside
 controller) with the given value,obtains the result and calls gui's
 updateDisplay(), passing the result value.
 4.the gui creates the result as text on a canvas.then the mainloop()
 is called to resume event loop
 
 again user enters some value in the textfield,and clicks OKbutton ...
 
 I exit the application by clicking quitButton that calls destroy() on
 top level window.
  I tried my application by entering some value on text field and then
 clicking OKbutton ,the calculated result is displayed on canvas .I do
 this process say 3 times ..Then i click the Quit button and the window
 closes.
 I have put a print statement inside the gui's updateDisplay()method
 right after the resuming of event loop by parent.mainloop().This print
 statement gets printed as many times as i had clicked
 the OK button(here in this case 3 times).Is this due to clearing of
 the stack ?
 I feel that it was not a good design ..I would be grateful if someone
 would tell me how i could improve it..can those chaining of method
 calls be avoided?
 
 this is how i restructured the code

Why do you quite the event loop? Just leave it running.

On pressing the button you validate the input, perform the computation 
and display the result, all without leaving the event loop.

If your computation is very slow then you have other issues to deal with 
(in particular background threads cannot safely talk to Tkinter, but you 
can safely compute stuff with a background thread and display it from 
the main thread). But cross that bridge later.

-- Russell
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter event loop question

2008-08-28 Thread gordon
On Aug 27, 10:42 pm, Fredrik Lundh [EMAIL PROTECTED] wrote:
 so I guess the question here is from where you expect to call that
 method, and what you expect Tkinter to do when you call it...

thanks for the reply

i was planning to write a controller (as in MVC) that will instantiate
a gui class and show the ui.the gui will send user input back to the
controller which in turn will process it and send a result to the gui
to be displayed

something like

controllermodule.py

class Controller:
   def createGUI(self):
  root=Tk()
  self.mygui=uimodule.MyGUI(root)
  root.mainloop()
   def sendMessageToUI(self):
  self.mygui.displayResult(someresultValue)



i don't know if this is the right way to do this..when i call
sendMessage() it tries to call displayResult() on the gui instance
which is already in an event loop.displayResult() gets called only
after the event loop is finished(when i close gui window).

is there a way to  keep the gui window open and have the controller
send a message to the gui instance so that i can pass the processed
result value to the gui instance?

thanks
gordon


--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter event loop question

2008-08-28 Thread Russell E. Owen
In article 
[EMAIL PROTECTED],
 gordon [EMAIL PROTECTED] wrote:

 On Aug 27, 10:42 pm, Fredrik Lundh [EMAIL PROTECTED] wrote:
  so I guess the question here is from where you expect to call that
  method, and what you expect Tkinter to do when you call it...
 
 thanks for the reply
 
 i was planning to write a controller (as in MVC) that will instantiate
 a gui class and show the ui.the gui will send user input back to the
 controller which in turn will process it and send a result to the gui
 to be displayed
 
 something like
 
 controllermodule.py
 
 class Controller:
def createGUI(self):
   root=Tk()
   self.mygui=uimodule.MyGUI(root)
   root.mainloop()
def sendMessageToUI(self):
   self.mygui.displayResult(someresultValue)
 
 
 
 i don't know if this is the right way to do this..when i call
 sendMessage() it tries to call displayResult() on the gui instance
 which is already in an event loop.displayResult() gets called only
 after the event loop is finished(when i close gui window).
 
 is there a way to  keep the gui window open and have the controller
 send a message to the gui instance so that i can pass the processed
 result value to the gui instance?

Normally MVC applies within one application with one event loop. So you 
set up your GUI and then start the event loop. The GUI will process user 
events (e.g. typing text, pressing buttons, selecting menus) as 
callbacks that do things like create Controller objects and execute 
methods on them.

So for starters your Controller object should not create root nor should 
it call mainloop to start the event loop. Those two actions should be 
done once by the main script that launches your application.

As to where to go from here...it would help to know more about what you 
are trying to do.

-- Russell
--
http://mail.python.org/mailman/listinfo/python-list


Tkinter event loop question

2008-08-27 Thread gordon
is it possible to send a message to the gui instance while the Tk
event loop is running?I mean after i create a gui object like

root=Tk()
mygui=SomeUI(root)

and call
root.mainloop()

can i send message to mygui without quitting the ui or closing the
window?i tried some code like
mygui.someMethod()
but it only gets executed after i close the the ui window.Is there a
way to get this message passing while gui is running ?

(forgive me ,it is a repeat question..but i am a bit desperate)
thanks
gordon
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter event loop question

2008-08-27 Thread Fredrik Lundh

gordon wrote:


is it possible to send a message to the gui instance while the Tk
event loop is running?I mean after i create a gui object like

root=Tk()
mygui=SomeUI(root)

and call
root.mainloop()

can i send message to mygui without quitting the ui or closing the
window?i tried some code like
mygui.someMethod()
but it only gets executed after i close the the ui window.Is there a
way to get this message passing while gui is running ?


it's the event loop that keeps Tkinter running, and Tkinter then calls 
your program (typically via command callbacks or event handlers) when 
it's time to do something.


so I guess the question here is from where you expect to call that 
method, and what you expect Tkinter to do when you call it...


/F

--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter event loop question

2008-08-27 Thread Cameron Laird
In article [EMAIL PROTECTED],
Fredrik Lundh  [EMAIL PROTECTED] wrote:
gordon wrote:

 is it possible to send a message to the gui instance while the Tk
 event loop is running?I mean after i create a gui object like
.
.
.
 but it only gets executed after i close the the ui window.Is there a
 way to get this message passing while gui is running ?

it's the event loop that keeps Tkinter running, and Tkinter then calls 
your program (typically via command callbacks or event handlers) when 
it's time to do something.

so I guess the question here is from where you expect to call that 
method, and what you expect Tkinter to do when you call it...
.
.
.
... but there certainly are Tkinter applications that 
respond to the user or other outside messages.  Just
as Fredrik advises, the next step would be for you to
provide a bit of detail on what you have in mind for
passing a message in.
--
http://mail.python.org/mailman/listinfo/python-list


newbie: for loop within for loop question

2008-06-15 Thread takayuki
Hi everyone,

I'm studying python via the excellent how to think like a python
programmer book by Allen Downey.  Noob question follows...

I have a txt file (animals.txt) which contains the following text each
on a separate line: aardvark, bat, cat, dog, elephant, fish, giraffe,
horse, inchworm, jackelope

I want to create a function that loops through the animals.txt file
and does *not* print the word if any of the user specified letters are
in that word.

def hasnolet(x):

--
http://mail.python.org/mailman/listinfo/python-list


Re: newbie: for loop within for loop question

2008-06-15 Thread takayuki
Dennis,

thanks for your reply.  unfortunately i accidentally posted only half
of my question!  the real post should be up now.

my apologies.

takayuki


On Jun 16, 10:15 am, Dennis Lee Bieber [EMAIL PROTECTED] wrote:
 On Sun, 15 Jun 2008 17:18:54 -0700 (PDT), takayuki
 [EMAIL PROTECTED] declaimed the following in comp.lang.python:

  Hi everyone,

  I'm studying python via the excellent how to think like a python
  programmer book by Allen Downey.  Noob question follows...

  I have a txt file (animals.txt) which contains the following text each
  on a separate line: aardvark, bat, cat, dog, elephant, fish, giraffe,
  horse, inchworm, jackelope

  I want to create a function that loops through the animals.txt file
  and does *not* print the word if any of the user specified letters are
  in that word.

  def hasnolet(x):

 Hope this wasn't a homework assignment... It gave me my first excuse
 to try the set module...

  import sets
  words = [  aardvark, bat, cat, dog, elephant, fish ]
  exclude = want
  excludeset = sets.Set(exclude)
  excludeset

 Set(['a', 't', 'w', 'n']) for w in words:

 ... if not excludeset.intersection(w):
 ... print w
 ...
 dog
 fish

 --
 WulfraedDennis Lee Bieber   KD6MOG
 [EMAIL PROTECTED]  [EMAIL PROTECTED]
 HTTP://wlfraed.home.netcom.com/
 (Bestiaria Support Staff:   [EMAIL PROTECTED])
 HTTP://www.bestiaria.com/

--
http://mail.python.org/mailman/listinfo/python-list


Re: newbie: for loop within for loop question

2008-06-15 Thread Calvin Spealman
The sets module is no longer needed, as we have the built-in sets  
type. Its even getting a literal syntax soon.


As for the original problem, I agree on the homework smell.

On Jun 15, 2008, at 9:31 PM, takayuki wrote:


Dennis,

thanks for your reply.  unfortunately i accidentally posted only half
of my question!  the real post should be up now.

my apologies.

takayuki


On Jun 16, 10:15 am, Dennis Lee Bieber [EMAIL PROTECTED] wrote:

On Sun, 15 Jun 2008 17:18:54 -0700 (PDT), takayuki
[EMAIL PROTECTED] declaimed the following in comp.lang.python:


Hi everyone,



I'm studying python via the excellent how to think like a python
programmer book by Allen Downey.  Noob question follows...


I have a txt file (animals.txt) which contains the following text  
each
on a separate line: aardvark, bat, cat, dog, elephant, fish,  
giraffe,

horse, inchworm, jackelope



I want to create a function that loops through the animals.txt file
and does *not* print the word if any of the user specified  
letters are

in that word.



def hasnolet(x):


Hope this wasn't a homework assignment... It gave me my  
first excuse

to try the set module...


import sets
words = [  aardvark, bat, cat, dog, elephant, fish ]
exclude = want
excludeset = sets.Set(exclude)
excludeset


Set(['a', 't', 'w', 'n']) for w in words:

... if not excludeset.intersection(w):
... print w
...
dog
fish

--
WulfraedDennis Lee Bieber   KD6MOG
[EMAIL PROTECTED]  [EMAIL PROTECTED]
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff:   web- 
[EMAIL PROTECTED])

HTTP://www.bestiaria.com/


--
http://mail.python.org/mailman/listinfo/python-list


--
http://mail.python.org/mailman/listinfo/python-list


Regex loop question

2008-03-03 Thread Mike P
Hi Experts,

I've written a peice of code that works fine and fits, and passes
values into a peice of SPSS code, the problem is that it is not
dynamic, and so i though about how i can make it dynamic, (other code
may not have upto 10 some may have more) and came up with regex for an
idea, but i can't seem to make it work, can anyone offer any advice?
Below is current working code

time_variables = {ActivityTime: Activity_Time,
ExposureTime_Last:Exposure_Time_1,
ExposureTime_Last2:Exposure_Time_2,
ExposureTime_Last3:Exposure_Time_3,
ExposureTime_Last4:Exposure_Time_4,
ExposureTime_Last5:Exposure_Time_5,
ExposureTime_Last6:Exposure_Time_6,
ExposureTime_Last7:Exposure_Time_7,
ExposureTime_Last8:Exposure_Time_8,
ExposureTime_Last9:Exposure_Time_9,
ExposureTime_Last10:Exposure_Time_10}

for Var in time_variables.keys():
time_manips = (COMPUTE %s = SUBSTR(%s,(INDEX(%s,'T'))+1) .
COMPUTE %s = number(%s, TIME8).
VARIABLE LABEL %s.
VARIABLE LEVEL %s (SCALE).
FORMATS %s (TIME8).
VARIABLE WIDTH %s (8).
EXECUTE.) %(Var, Var,
Var,time_variables[Var],Var,time_variables[Var],time_variables[Var],time_variables[Var],time_variables[Var])
spss.Submit(time_manips)


Now to make it dynamic i've gone for the following...

reg_time = re.compile(^ExposureTime_Last([0-9]*)$)
reg_Activity = re.compile(^ActivityTime)
for Var in time_variables.keys():
if reg_time.match(Var):
match = reg_time.match(Var)
E_time = Exposure_Time_%s % match.groups()[0]
else:
match = reg_time.match(Var)
match.groups()[0] = Activity_Time


time_manips = (COMPUTE %s = SUBSTR(%s,(INDEX(%s,'T'))+1) .
COMPUTE %s = number(%s, TIME8).
VARIABLE LABEL %s.
VARIABLE LEVEL %s (SCALE).
FORMATS %s (TIME8).
VARIABLE WIDTH %s (8).
EXECUTE.) %(Var, Var,
Var,time_variables[Var],Var,time_variables[Var],time_variables[Var],time_variables[Var],time_variables[Var])
print(time_manips)

All help welcome, or if a different approach is better please let me
know

Mike


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regex loop question

2008-03-03 Thread Peter Otten
Mike P wrote:

 Hi Experts,
 
 I've written a peice of code that works fine and fits, and passes
 values into a peice of SPSS code, the problem is that it is not
 dynamic, and so i though about how i can make it dynamic, (other code
 may not have upto 10 some may have more) and came up with regex for an
 idea, but i can't seem to make it work, can anyone offer any advice?
 Below is current working code
 
 time_variables = {ActivityTime: Activity_Time,
 ExposureTime_Last:Exposure_Time_1,
 ExposureTime_Last2:Exposure_Time_2,
 ExposureTime_Last3:Exposure_Time_3,
 ExposureTime_Last4:Exposure_Time_4,
 ExposureTime_Last5:Exposure_Time_5,
 ExposureTime_Last6:Exposure_Time_6,
 ExposureTime_Last7:Exposure_Time_7,
 ExposureTime_Last8:Exposure_Time_8,
 ExposureTime_Last9:Exposure_Time_9,
 ExposureTime_Last10:Exposure_Time_10}
 
 for Var in time_variables.keys():
 time_manips = (COMPUTE %s = SUBSTR(%s,(INDEX(%s,'T'))+1) .
 COMPUTE %s = number(%s, TIME8).
 VARIABLE LABEL %s.
 VARIABLE LEVEL %s (SCALE).
 FORMATS %s (TIME8).
 VARIABLE WIDTH %s (8).
 EXECUTE.) %(Var, Var,
 Var,time_variables[Var],Var,time_variables[Var],
 time_variables[Var],time_variables[Var],time_variables[Var]) 
 spss.Submit(time_manips)
 
 
 Now to make it dynamic i've gone for the following...
 
 reg_time = re.compile(^ExposureTime_Last([0-9]*)$)
 reg_Activity = re.compile(^ActivityTime)
 for Var in time_variables.keys():
 if reg_time.match(Var):
 match = reg_time.match(Var)
 E_time = Exposure_Time_%s % match.groups()[0]
 else:
 match = reg_time.match(Var)
 match.groups()[0] = Activity_Time
 
 
 time_manips = (COMPUTE %s = SUBSTR(%s,(INDEX(%s,'T'))+1) .
 COMPUTE %s = number(%s, TIME8).
 VARIABLE LABEL %s.
 VARIABLE LEVEL %s (SCALE).
 FORMATS %s (TIME8).
 VARIABLE WIDTH %s (8).
 EXECUTE.) %(Var, Var,
 Var,time_variables[Var],Var,time_variables[Var],time_variables[Var],
 time_variables[Var],time_variables[Var]) 
 print(time_manips)
 
 All help welcome, or if a different approach is better please let me
 know

I'd clean up the original code a bit rather than introducing another source
of errors (the regexes):

# no warranties
time_variables = [
(ActivityTime, Activity_Time),
(ExposureTime_Last,Exposure_Time_1)]
time_variables.extend((ExposureTime_Last%d % i, Exposure_Time_%d % i)
for i in range(2, 11))

for key, value in time_variables:
time_manips = COMPUTE %(key)s = SUBSTR(%(key)s
(INDEX(%(key)s,'T'))+1) .
COMPUTE %(value)s = number(%(key)s, TIME8).
VARIABLE LABEL %(value)s.
VARIABLE LEVEL %(value)s (SCALE).
FORMATS %(value)s (TIME8).
VARIABLE WIDTH %(value)s (8).
EXECUTE. % dict(key=key, value=value)
spss.Submit(time_manips)

It might be even better to move the logic into SPSS and to replace the
numerical suffices with array indices (if supported), but I can't help you
with that.

Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop question

2007-10-11 Thread Paul Hankin
On Oct 11, 4:40 am, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 On Wed, 10 Oct 2007 20:25:00 +, Paul Hankin wrote:
  A works-for-me:

pairs = (test[i:i+2] for i in xrange(len(test)-1))
for a,b in pairs:
   ... print a,b

  for a, b in zip(test, test[1:]):
print a, b

 May be unfortunately slow if test is half a gigabyte of data, what with
 essentially making three copies of it. Lazy procedures like the generator
 expression above are often much better.

 Just for completion, here's another way:

 prev = test[0]
 for i in xrange(1, len(test)):
 print prev, test[i]
 prev = test[i]

Why not just:

for i in xrange(len(test) - 1):
print test[i], test[i + 1]

--
Paul Hankin

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop question

2007-10-11 Thread Paul Rubin
Steven D'Aprano [EMAIL PROTECTED] writes:
pairs = (test[i:i+2] for i in xrange(len(test)-1))
for a,b in pairs:
   ... print a,b
  
  for a, b in zip(test, test[1:]):
print a, b
 
 May be unfortunately slow if test is half a gigabyte of data, what with 
 essentially making three copies of it. Lazy procedures like the generator 
 expression above are often much better.

Untested:

from itertools import izip, islice
for a,b in izip(test, islice(test,1,None)):
   print a,b

seems more natural.
-- 
http://mail.python.org/mailman/listinfo/python-list


for loop question

2007-10-10 Thread Robert Dailey
Hi,

I'm currently writing my own CSV parser since the built in one doesn't
support Unicode. I'm wondering if there's a way to iterate over the
characters in a unicode string and have access to both the 'current' and the
'next' characters each iteration. For example:

test = uHello World

for cur,next in test:
print cur,next

Ideally, this would output:

'H', 'e'
'e', 'l'
'l', 'l'
'l', 'o'
etc...

Of course, the for loop above isn't valid at all. I am just giving an
example of what I'm trying to accomplish. Anyone know how I can achieve the
goal in the example above? Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: for loop question

2007-10-10 Thread Rafael Sachetto
Try this:

test = uHello World

n = range(len(test))

for i in n:
   cur  =  test[i]
   try:
  next = test[i+1]
   except:
  next = 
print cur, next

just

On 10/10/07, Robert Dailey [EMAIL PROTECTED] wrote:

 Hi,

 I'm currently writing my own CSV parser since the built in one doesn't
 support Unicode. I'm wondering if there's a way to iterate over the
 characters in a unicode string and have access to both the 'current' and the
 'next' characters each iteration. For example:

 test = uHello World

 for cur,next in test:
 print cur,next

 Ideally, this would output:

 'H', 'e'
 'e', 'l'
 'l', 'l'
 'l', 'o'
 etc...

 Of course, the for loop above isn't valid at all. I am just giving an
 example of what I'm trying to accomplish. Anyone know how I can achieve the
 goal in the example above? Thanks.

 --
 http://mail.python.org/mailman/listinfo/python-list




-- 
Rafael Sachetto Oliveira

Sir - Simple Image Resizer
http://rsachetto.googlepages.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: for loop question

2007-10-10 Thread Tim Chase
 test = uHello World
 
 for cur,next in test:
 print cur,next
 
 Ideally, this would output:
 
 'H', 'e'
 'e', 'l'
 'l', 'l'
 'l', 'o'
 etc...
 
 Of course, the for loop above isn't valid at all. I am just giving an
 example of what I'm trying to accomplish. Anyone know how I can achieve the
 goal in the example above? Thanks.

A works-for-me:

  pairs = (test[i:i+2] for i in xrange(len(test)-1))
  for a,b in pairs:
... print a,b
...
H e
e l
l l
l o
o
   w
w o
o r
r l
l d
 

-tkc



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop question

2007-10-10 Thread Carsten Haese
On Wed, 2007-10-10 at 14:56 -0500, Robert Dailey wrote:
 Hi,
 
 I'm currently writing my own CSV parser since the built in one doesn't
 support Unicode.

Why do you think you need a CSV parser that supports unicode?

-- 
Carsten Haese
http://informixdb.sourceforge.net


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop question

2007-10-10 Thread Paul Hankin
On Oct 10, 9:12 pm, Tim Chase [EMAIL PROTECTED] wrote:
  test = uHello World

  for cur,next in test:
  print cur,next

  Ideally, this would output:

  'H', 'e'
  'e', 'l'
  'l', 'l'
  'l', 'o'
  etc...

  Of course, the for loop above isn't valid at all. I am just giving an
  example of what I'm trying to accomplish. Anyone know how I can achieve the
  goal in the example above? Thanks.

 A works-for-me:

   pairs = (test[i:i+2] for i in xrange(len(test)-1))
   for a,b in pairs:
 ... print a,b

for a, b in zip(test, test[1:]):
  print a, b

--
Paul Hankin

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop question

2007-10-10 Thread Robert Dailey
All the ideas presented here are workable. I definitely have a lot of
solutions to choose from. Thanks everyone for your help. I wasn't sure if
there was some sort of language feature to naturally do this, so I had to
post on the mailing list to make sure.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: for loop question

2007-10-10 Thread Rafael Sachetto
Very nice solution :)

On 10/10/07, Paul Hankin [EMAIL PROTECTED] wrote:

 On Oct 10, 9:12 pm, Tim Chase [EMAIL PROTECTED] wrote:
   test = uHello World
 
   for cur,next in test:
   print cur,next
 
   Ideally, this would output:
 
   'H', 'e'
   'e', 'l'
   'l', 'l'
   'l', 'o'
   etc...
 
   Of course, the for loop above isn't valid at all. I am just giving an
   example of what I'm trying to accomplish. Anyone know how I can
 achieve the
   goal in the example above? Thanks.
 
  A works-for-me:
 
pairs = (test[i:i+2] for i in xrange(len(test)-1))
for a,b in pairs:
  ... print a,b

 for a, b in zip(test, test[1:]):
   print a, b

 --
 Paul Hankin

 --
 http://mail.python.org/mailman/listinfo/python-list




-- 
Rafael Sachetto Oliveira

Sir - Simple Image Resizer
http://rsachetto.googlepages.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: for loop question

2007-10-10 Thread Tim Chase
Paul Hankin wrote:
 On Oct 10, 9:12 pm, Tim Chase [EMAIL PROTECTED] wrote:
   pairs = (test[i:i+2] for i in xrange(len(test)-1))
   for a,b in pairs:
 ... print a,b
 
 for a, b in zip(test, test[1:]):
   print a, b

Very nice!

I second this solution as better than my original.  The only 
improvement (in quotes, because it might be more work/opacity 
than the problem merits) might be to use izip/islice from 
itertools to do the evaluation lazily if test gets large:

   from itertools import izip, islice
   for a,b in izip(test, islice(test, 1, None)):
 print a,b

[side note/question]
What's with islice having the first optional paramenter expand as 
the stop/third argument by default:

   islice(test, 1) - stop at 1
   islice(test, 1, 2) - start at 1, stop at 2

islice (in python2.4) doesn't even take kword params, so you 
can't force it like

   islice(test, start=1)

but instead must specify a stop parameter, even if it's None:

   islice(test, 1, None)

Seems bogus, IMHO.

-tkc



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop question

2007-10-10 Thread George Sakkis
On Oct 10, 4:12 pm, Tim Chase [EMAIL PROTECTED] wrote:

  test = uHello World

  for cur,next in test:
  print cur,next

  Ideally, this would output:

  'H', 'e'
  'e', 'l'
  'l', 'l'
  'l', 'o'
  etc...

  Of course, the for loop above isn't valid at all. I am just giving an
  example of what I'm trying to accomplish. Anyone know how I can achieve the
  goal in the example above? Thanks.

 A works-for-me:

   pairs = (test[i:i+2] for i in xrange(len(test)-1))
   for a,b in pairs:
 ... print a,b
 ...
 H e
 e l
 l l
 l o
 o
w
 w o
 o r
 r l
 l d
  

 -tkc

Or generalized for arbitrary iterables, number of items at a time,
combination function and stopping criterion:

from itertools import islice, takewhile, repeat

def taking(iterable, n, combine=tuple, pred=bool):
iterable = iter(iterable)
return takewhile(pred, (combine(islice(iterable,n)) for _ in
repeat(0)))

 for p in taking(test,2): print p

(u'H', u'e')
(u'l', u'l')
(u'o', u' ')
(u'W', u'o')
(u'r', u'l')
(u'd',)

 for p in taking(test,2, combine=''.join): print p

He
ll
o
Wo
rl
d


George

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop question

2007-10-10 Thread Larry Bates
Tim Chase wrote:
 test = uHello World

 for cur,next in test:
 print cur,next

 Ideally, this would output:

 'H', 'e'
 'e', 'l'
 'l', 'l'
 'l', 'o'
 etc...

 Of course, the for loop above isn't valid at all. I am just giving an
 example of what I'm trying to accomplish. Anyone know how I can 
 achieve the
 goal in the example above? Thanks.
 
 A works-for-me:
 
   pairs = (test[i:i+2] for i in xrange(len(test)-1))
   for a,b in pairs:
 ... print a,b
 ...
 H e
 e l
 l l
 l o
 o
   w
 w o
 o r
 r l
 l d
  
 
 -tkc
 
 
 
import itertools

test = uHello World
ltest=['%s' % c for c in test]

for a, b in itertools.izip(ltest, ltest[1:]):
 print x, y

'H' 'e'
'e' 'l'
'l' 'l'
'l' 'o'
'o' ' '
' ' 'W'
'W' 'o'
'o' 'r'
'r' 'l'
'l' 'd'

-Larry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop question

2007-10-10 Thread Robert Dailey
I've tried everything to make the original CSV module work. It just doesn't.
I've tried UTF-16 encoding (which works fine with codecs.open()) but when I
pass in the file object returned from codecs.open() into csv.reader(), the
call to reader.next() fails because it says something isnt' in the range of
range(128) or something (Not really an expert on Unicode so I'm not sure of
the meaning). I would use CSV if I could!

On 10/10/07, Carsten Haese [EMAIL PROTECTED] wrote:

 On Wed, 2007-10-10 at 15:27 -0500, Robert Dailey wrote:
  I'm using CSV for localization in a game I'm involved with.

 That doesn't tell me why you think you need a CSV parser that supports
 Unicode. There is no such thing as a Unicode file. The file contains a
 stream of octets that represent some encoding of Unicode code points. If
 the encoding is chosen properly, such as UTF-8, the standard CSV parser
 should be able to parse the resulting stream.

 -Carsten



-- 
http://mail.python.org/mailman/listinfo/python-list

Re: for loop question

2007-10-10 Thread Carsten Haese
On Wed, 2007-10-10 at 16:03 -0500, Robert Dailey wrote:
 I've tried everything to make the original CSV module work. It just
 doesn't. I've tried UTF-16 encoding

What do you mean, tried? Don't you know what the file is encoded in?

  (which works fine with codecs.open()) but when I pass in the file
 object returned from codecs.open() into csv.reader(), the call to
 reader.next() fails because it says something isnt' in the range of
 range(128) or something (Not really an expert on Unicode so I'm not
 sure of the meaning). I would use CSV if I could!

That's because the codec-file object feeds it decoded Unicode strings,
but the CSV module wants to work with encoded octet strings, so it tries
to encode the unicode string with the default codec. The default codec
is ASCII, which can't represent characters with code points greater than
127.

Instead of passing the file object directly to the csv parser, pass in a
generator that reads from the file and explicitly encodes the strings
into UTF-8, along these lines:

def encode_to_utf8(f):
for line in f:
yield line.encode(utf-8)

There may be a fundamental problem with this approach that I can't
foresee at the moment, but it's worth a try when your alternative is to
build a Unicode-aware CSV parser from scratch.

Hope this helps,

-- 
Carsten Haese
http://informixdb.sourceforge.net


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop question

2007-10-10 Thread Robert Dailey
On 10/10/07, Carsten Haese [EMAIL PROTECTED] wrote:

 Instead of passing the file object directly to the csv parser, pass in a
 generator that reads from the file and explicitly encodes the strings
 into UTF-8, along these lines:

 def encode_to_utf8(f):
 for line in f:
 yield line.encode(utf-8)

 There may be a fundamental problem with this approach that I can't
 foresee at the moment, but it's worth a try when your alternative is to
 build a Unicode-aware CSV parser from scratch.

 Hope this helps,


I did the following:


#

def encode_utf8( f ):
for line in f:
yield line.encode( utf-8 )

#

def BeginLocalizationParsing( outputDir, inputRoot, inputFile ):
f = codecs.open( inputFile, rb, encoding=utf-16 )

r = csv.reader( encode_utf8( f ) )
print r.next()

#

It worked perfectly! Thank you! I guess I don't have to make a CSV parser
after all :P
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: for loop question

2007-10-10 Thread Steven D'Aprano
On Wed, 10 Oct 2007 20:25:00 +, Paul Hankin wrote:

 A works-for-me:

   pairs = (test[i:i+2] for i in xrange(len(test)-1))
   for a,b in pairs:
  ... print a,b
 
 for a, b in zip(test, test[1:]):
   print a, b

May be unfortunately slow if test is half a gigabyte of data, what with 
essentially making three copies of it. Lazy procedures like the generator 
expression above are often much better.


Just for completion, here's another way:

prev = test[0]
for i in xrange(1, len(test)):
print prev, test[i]
prev = test[i]



-- 
Steven.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter, main loop question.

2006-11-23 Thread Bjoern Schliessmann
Exod wrote:

 Don't know if its possible in this light-weight GUI toolset, but
 can i somehow hook up into the mainloop in it, for example if i
 were to create an internet application, i would need to keep
 recieving data from within it?

That's something where you could try the Twisted framework
(http://twistedmatrix.com). Its event loop integrates with many GUI
toolkits', also Tk's.

Regards,


Björn

-- 
BOFH excuse #394:

Jupiter is aligned with Mars.

-- 
http://mail.python.org/mailman/listinfo/python-list


Tkinter, main loop question.

2006-11-22 Thread Exod
Don't know if its possible in this light-weight GUI toolset, but can i
somehow hook up into the mainloop in it, for example if i were to
create an internet application, i would need to keep recieving data
from within it?

-- 
http://mail.python.org/mailman/listinfo/python-list


for loop question

2006-07-06 Thread bruce
hi..

basic foor/loop question..

i can do:

 for a in foo
  print a

if i want to do something like
  for a, 2, foo
print foo

where go from 2, to foo..

i can't figure out how to accomplish this... 

can someone point me to how/where this is demonstrated...

found plenty of google for for/loop.. just not this issue..

thanks

-bruce

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop question

2006-07-06 Thread Preston Hagar
On 7/6/06, bruce [EMAIL PROTECTED] wrote:
hi..basic foor/loop question..i can do: for a in fooprint aif i want to do something likefor a, 2, fooprint foowhere go from 2, to foo..i can't figure out how to accomplish this...
can someone point me to how/where this is demonstrated...You might want to look here:http://www.freenetpages.co.uk/hp/alan.gauld/tutloops.htm
I am not exactly sure what you are asking, so perhaps a hopefully related example will help you on your way.Let's say you have a variable foo and want to count from 2 to the value of foo, you could do the following:
foo = 20for i in range(2,foo): print iThis would print the numbers 2 through 29 out.Hope this helps.Preston
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: for loop question

2006-07-06 Thread Daniel Haus
just do:

for a in range(2, foo+1):
print a

range(a, b) gives [a, a+1, a+2, ..., b-2, b-1]


bruce schrieb:

 hi..

 basic foor/loop question..

 i can do:

  for a in foo
   print a

 if i want to do something like
   for a, 2, foo
 print foo

 where go from 2, to foo..

 i can't figure out how to accomplish this...

 can someone point me to how/where this is demonstrated...

 found plenty of google for for/loop.. just not this issue..
 
 thanks
 
 -bruce

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: for loop question

2006-07-06 Thread bruce
'ppreaciate the answers

duh...

-bruce


-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] Behalf
Of Daniel Haus
Sent: Thursday, July 06, 2006 2:02 PM
To: python-list@python.org
Subject: Re: for loop question


just do:

for a in range(2, foo+1):
print a

range(a, b) gives [a, a+1, a+2, ..., b-2, b-1]


bruce schrieb:

 hi..

 basic foor/loop question..

 i can do:

  for a in foo
   print a

 if i want to do something like
   for a, 2, foo
 print foo

 where go from 2, to foo..

 i can't figure out how to accomplish this...

 can someone point me to how/where this is demonstrated...

 found plenty of google for for/loop.. just not this issue..
 
 thanks
 
 -bruce

-- 
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop question

2006-07-06 Thread Grant Edwards
On 2006-07-06, Daniel Haus [EMAIL PROTECTED] wrote:

 i can do:

  for a in foo
   print a

 if i want to do something like
   for a, 2, foo
 print foo

 where go from 2, to foo..

 just do:

 for a in range(2, foo+1):
 print a

Except that in the OP's example foo was a sequence, not an
integer.  I think.

-- 
Grant Edwards   grante Yow!  You can't hurt
  at   me!! I have an ASSUMABLE
   visi.comMORTGAGE!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop question

2006-07-06 Thread Daniel Haus
 Except that in the OP's example foo was a sequence, not an
 integer.  I think.

Yes, possibly. But then, what's from 2 to foo?

this way it might be

for a in [2] + foo:
print a

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop question

2006-07-06 Thread York
for a in range(2, len(foo)): print a

or maybe you need
for a in range(1, len(foo)): print a
?

York


bruce wrote:
 hi..
 
 basic foor/loop question..
 
 i can do:
 
  for a in foo
   print a
 
 if i want to do something like
   for a, 2, foo
 print foo
 
 where go from 2, to foo..
 
 i can't figure out how to accomplish this... 
 
 can someone point me to how/where this is demonstrated...
 
 found plenty of google for for/loop.. just not this issue..
 
 thanks
 
 -bruce
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Asyncore Loop Question

2005-10-31 Thread John W
Hello,

I have a gui application where I am trying to use the asyncore module
to gather data from other computers. I am able to connect, but I
am getting constant handle_write_event method calls into my
application. It is obviously slowing down the gui processing
significantly.

My understanding is that the handle_write_event and handle_read_event
are both edge notifications and I should just get the method call
essentially just once.

I think the problem is how I have my loop() call configured. All
I am trying to do with the code below is to open the socket (that
works) and then receive a single handle_write_event method call.
Instead, I am getting constantly barraged with them.

I have tried several different types of the loop() call (using poll,
timeout...) but with no luck. If anyone can explain what I should
be doing to get a single handle_write_event call until I actually write
something to the socket (which my code is not presently doing yet), I
would appreciate 

Below is some code showing what I am doing:

--
class Connection(asyncore.dispatcher):
 def __init__ (self, server_name, port_num ):
 self.message_queue = []

 asyncore.dispatcher.__init__(self)
 self.create_socket( socket.AF_INET, socket.SOCK_STREAM )
 self.connect(( server_name, port_num ))


 def handle_read_event( self ):
 print handle_read_event received


 def handle_write_event( self ):
 print Asking for a write

 if len( self.message_queue )  0:
 # Pop the first message off the queue
 self.send_next_message()


class TestApp:
 def __init__( self, server_name, port_number ):

 self.nomad = Connection( server_name, port_number )
 asyncore.loop()


Output ends up being a constant stream of:
Asking for a write
Asking for a write
Asking for a write
Asking for a write
Asking for a write

...
...
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Asyncore Loop Question

2005-10-31 Thread Steve Holden
John W wrote:
 Hello,
 
 I have a gui application where I am trying to use the asyncore module to
 gather data from other computers. I am able to connect, but I am getting
 constant handle_write_event method calls into my application. It is
 obviously slowing down the gui processing significantly.
 
 My understanding is that the handle_write_event and handle_read_event are
 both edge notifications and I should just get the method call essentially
 just once.
 
 I think the problem is how I have my loop() call configured. All I am trying
 to do with the code below is to open the socket (that works) and then
 receive a single handle_write_event method call. Instead, I am getting
 constantly barraged with them.
 
 I have tried several different types of the loop() call (using poll,
 timeout...) but with no luck. If anyone can explain what I should be doing
 to get a single handle_write_event call until I actually write something to
 the socket (which my code is not presently doing yet), I would appreciate
 
 Below is some code showing what I am doing:
 
 --
 class Connection(asyncore.dispatcher):
 def __init__ (self, server_name, port_num ):
 self.message_queue = []
 
 asyncore.dispatcher.__init__(self)
 self.create_socket( socket.AF_INET, socket.SOCK_STREAM )
 self.connect(( server_name, port_num ))
 
 
 def handle_read_event( self ):
 print handle_read_event received
 
 
 def handle_write_event( self ):
 print Asking for a write
 
 if len( self.message_queue )  0:
 # Pop the first message off the queue
 self.send_next_message()
 
 
 class TestApp:
 def __init__( self, server_name, port_number ):
 
 self.nomad = Connection( server_name, port_number )
 asyncore.loop()
 
 
 Output ends up being a constant stream of:
 Asking for a write
 Asking for a write
 Asking for a write
 Asking for a write
 Asking for a write
 
 ...
 ...
 
 
Normally if a socket channel asks for a write and you have no data you 
should respond by removing it from the list of write-enabled channels 
for the asyncore loop until you *do* have some data for it. Otherwise 
every time the loop scans the channels expecting notification it will 
tell you again that you can write to that channel.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Asyncore Loop Question

2005-10-31 Thread John W
Steve,

Ar you saying that I should close the connection until I have data to
write? Or should I be using the readable and writable methods to
turn it off?

Thanks for your help, unfortunatly, I have struggled with the
documentation and getting a clear understanding of everything.
This is my first socket program as well.

Thanks,

JohnOn 10/31/05, Steve Holden [EMAIL PROTECTED] wrote:
John W wrote: Hello, I have a gui application where I am trying to use the asyncore module to gather data from other computers. I am able to connect, but I am getting constant handle_write_event method calls into my application. It is
 obviously slowing down the gui processing significantly. My understanding is that the handle_write_event and handle_read_event are both edge notifications and I should just get the method call essentially
 just once. I think the problem is how I have my loop() call configured. All I am trying to do with the code below is to open the socket (that works) and then receive a single handle_write_event method call. Instead, I am getting
 constantly barraged with them. I have tried several different types of the loop() call (using poll, timeout...) but with no luck. If anyone can explain what I should be doing to get a single handle_write_event call until I actually write something to
 the socket (which my code is not presently doing yet), I would appreciate Below is some code showing what I am doing: --
 class Connection(asyncore.dispatcher): def __init__ (self, server_name, port_num ): self.message_queue = [] asyncore.dispatcher.__init__(self) self.create_socket( socket.AF_INET
, socket.SOCK_STREAM ) self.connect(( server_name, port_num )) def handle_read_event( self ): print handle_read_event received def handle_write_event( self ):
 print Asking for a write if len( self.message_queue )  0: # Pop the first message off the queue self.send_next_message() class TestApp: def __init__( self, server_name, port_number ):
 self.nomad = Connection( server_name, port_number ) asyncore.loop() Output ends up being a constant stream of: Asking for a write Asking for a write Asking for a write
 Asking for a write Asking for a write  ... ...Normally if a socket channel asks for a write and you have no data youshould respond by removing it from the list of write-enabled channels
for the asyncore loop until you *do* have some data for it. Otherwiseevery time the loop scans the channels expecting notification it willtell you again that you can write to that channel.regardsSteve
--Steve Holden +44 150 684 7255+1 800 494 3119Holden
Web
LLC
www.holdenweb.comPyCon TX
2006www.python.org/pycon/--http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Asyncore Loop Question

2005-10-31 Thread Steve Holden
John W wrote:
 On 10/31/05, Steve Holden [EMAIL PROTECTED] wrote:
 
John W wrote:

Hello,

I have a gui application where I am trying to use the asyncore module to
gather data from other computers. I am able to connect, but I am getting
constant handle_write_event method calls into my application. It is
obviously slowing down the gui processing significantly.

My understanding is that the handle_write_event and handle_read_event

are

both edge notifications and I should just get the method call

essentially

just once.

I think the problem is how I have my loop() call configured. All I am

trying

to do with the code below is to open the socket (that works) and then
receive a single handle_write_event method call. Instead, I am getting
constantly barraged with them.

I have tried several different types of the loop() call (using poll,
timeout...) but with no luck. If anyone can explain what I should be

doing

to get a single handle_write_event call until I actually write something

to

the socket (which my code is not presently doing yet), I would

appreciate

Below is some code showing what I am doing:

--
class Connection(asyncore.dispatcher):
def __init__ (self, server_name, port_num ):
self.message_queue = []

asyncore.dispatcher.__init__(self)
self.create_socket( socket.AF_INET, socket.SOCK_STREAM )
self.connect(( server_name, port_num ))


def handle_read_event( self ):
print handle_read_event received


def handle_write_event( self ):
print Asking for a write

if len( self.message_queue )  0:
# Pop the first message off the queue
self.send_next_message()


class TestApp:
def __init__( self, server_name, port_number ):

self.nomad = Connection( server_name, port_number )
asyncore.loop()


Output ends up being a constant stream of:
Asking for a write
Asking for a write
Asking for a write
Asking for a write
Asking for a write

...
...



Normally if a socket channel asks for a write and you have no data you
should respond by removing it from the list of write-enabled channels
for the asyncore loop until you *do* have some data for it. Otherwise
every time the loop scans the channels expecting notification it will
tell you again that you can write to that channel.


 
 Steve,
 
 Ar you saying that I should close the connection until I have data to write?
 Or should I be using the readable and writable methods to turn it off?
 
 Thanks for your help, unfortunatly, I have struggled with the documentation
 and getting a clear understanding of everything. This is my first socket
 program as well.
 
I was actually mis-remembering my asyncore documentation, which is a 
little sad given that I wrote it :-)

What you need is to implement a writable() method. Suppose your output 
generation creates a buffer is self.buffer, a suitable implementation 
would look like this:

 def writable(self):
 return (len(self.buffer)  0)

As I wrote in the documentation:


writable( )

Called each time around the asynchronous loop to determine whether a 
channel's socket should be added to the list on which write events can 
occur. The default method simply returns True, indicating that by 
default, all channels will be interested in write events.


regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

-- 
http://mail.python.org/mailman/listinfo/python-list