redirect stderr to syslog?

2014-08-15 Thread Russell E. Owen
We are using the syslog module for logging, and would like to redirect 
stderr to our log. Is there a practical way to do it?

I realize the logging module supports this and has a syslog writer, so 
that's a fallback. But we were hoping to use the syslog module for 
performance.

-- Russell

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


Re: Mac python py2app problem

2014-07-17 Thread Russell E. Owen
In article c2pqokfofe...@mid.individual.net,
 Gregory Ewing greg.ew...@canterbury.ac.nz wrote:

 Nicholas Cannon wrote:
  I do like the idea of making a .dmg file
  because i have used them downloading other apps and it works great but i 
  dont
  know how to make them!
 
 In Disk Utility, use FileNewDisk Image from Folder.

Or...open Disk Utility and drop the app onto its dock icon.

-- Russell

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


Suggested GUI framework for Mac and unix?

2014-01-06 Thread Russell E. Owen
I have a free cross-platform Python GUI application that has to run on 
Mac and linux. It is presently written in Tkinter, but for various 
reasons* it may be time to switch.

I've heard many good things about wxpython and qt, but not used either, 
and am wondering if somebody could tell me if either (or both) would 
meet the following needs:
-  Reliable on mac and linux. (I see that wxpython now runs under Cocoa 
but I've not seen any reports on how well that went.)
- Compatible with matplotlib.
- Able to display (grayscale) images with arbitrary zoom. I currently 
use PIL with Tkinter's Canvas widget for this.
- Compatible with a sound library for playing sound cues. I presently 
use pygame for this and have been considering switching to PySDL.
- Compatible with Twisted Framework.
- Prediction is hard, but indications of a long-term future would be a 
definite bonus.

-- Russell

*I have no wish to disparage Tkinter. I personally like it and am very 
grateful to the developers. However, several issues are driving me to 
look for alternatives:
* There is a known crashing bug in recent versions of Tcl/Tk that keeps 
me at 8.5.11. Unfortunately I've not found a workaround.
* Tcl/Tk 8.5.11 is not compatible with Mavericks unless one runs in 
32-bit mode.
* There are known issues with the Tcl/Tk event loop since the switch to 
Cocoa. These are unlikely to be fixed, though in many cases it is 
practical to work around them. This is more of a long-term worry than a 
concrete problem.

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


Re: Running python's own unit tests?

2013-11-15 Thread Russell E. Owen
In article 5285223d.50...@timgolden.me.uk,
 Tim Golden m...@timgolden.me.uk wrote:

 http://docs.python.org/devguide/

Thank you and the other responders. I was expecting to find the 
information here http://docs.python.org/2/using/unix.html under 
Building Python. The developer's guide is a nice resource.

-- Russell

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


Running python's own unit tests?

2013-11-14 Thread Russell E. Owen
I'm building python from source and trying to figure out how to test the 
result. I must be overlooking something obvious, but I looked through 
the documentation and source and tried some google searches (which turn 
up plenty about writing unit tests in python, but nothing about testing 
a python distribution).

Any hints?

-- Russell

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


Re: Why is Ruby on Rails more popular than Django?

2013-03-07 Thread Russell E. Owen
In article 
3d9fe0b2-7931-4ab6-8929-235460729...@q9g2000pbf.googlegroups.com,
 rusi rustompm...@gmail.com wrote:

 On Mar 6, 11:03 pm, Jason Hsu jhsu802...@gmail.com wrote:
  I'm currently in the process of learning Ruby on Rails.  I'm going through 
  the Rails for Zombies tutorial, and I'm seeing the power of Rails.
 
  I still need to get a Ruby on Rails site up and running for the world to 
  see.  (My first serious RoR site will profile mutual funds from a value 
  investor's point of view.)
 
  I have an existing web site and project called Doppler Value Investing 
  (dopplervalueinvesting.com) that uses Drupal to display the web pages and 
  Python web-scraping scripts to create *.csv and *.html files showing 
  information on individual stocks.  My site has a tacked-on feel to it, and 
  I definitely want to change the setup.
 
  At a future time, I will rebuild my Doppler Value Investing web site in 
  either Ruby on Rails or Django.  The Ruby on Rails route will require 
  rewriting my Python script in Ruby.  The Django route will require learning 
  Django.  (I'm not sure which one will be easier.)
 
  My questions:
  1.  Why is Ruby on Rails much more popular than Django?
 
 Where there is choice there is no freedom
 http://www.jiddu-krishnamurti.net/en/1954/1954-03-03-jiddu-krishnamurti-8th-pu
 blic-talk
 
 Python-for-web offered so much choice -- zope, django, turbogears,
 cherrypy, web.py etc etc -- that the newbie was completely drowned.
 With Ruby there is only one choice to make -- choose Ruby and rails
 follows.
 
 Anyone who's used emacs will know this as the bane of FLOSS software
 -- 100 ways of doing something and none perfect -- IOW too much
 spurious choice.
 
 GvR understood and rigorously implemented a dictum that Nicklaus Wirth
 formulated decades ago -- The most important thing about language
 design is what to leave out. Therefore Python is a beautiful
 language.  Unfortunately the same leadership did not carry over to web
 frameworks and so we have a mess.
 
 I guess the situation is being corrected with google putting its
 artillery behind django.

I strongly agree. The fact that there is no de-facto standard web system 
for Python is a major problem. Consider:
- With too many choice one has no idea which projects will be maintained 
and which will be abandoned.
- Expert knowledge among users is spread more thinly.
- The effort of contributors is diluted.

Years ago when I had some simple web programming to do I looked at the 
choices, gave up and used PHP (which I hated, but got the job done). If 
RoR had been available I would have been much happier using that.

In my opinion the plethora of Python web frameworks is a serious 
detriment to trust and wider acceptance of Python for this use. If  
Django is becoming this standard, that is excellent news.

Some choice is good, but in my opinion too much choice and lack of a 
de-facto standard are very detrimental.

-- Russell

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


Re: Keeping a Tkinter GUI alive during a long running process

2012-12-26 Thread Russell E. Owen
In article kb0jjh$7pm$1...@dont-email.me,
 Kevin Walzer k...@codebykevin.com wrote:

 I maintain a Tkinter application that's a front-end to to a package 
 manger, and I have never been able to find a way to keep the app from 
 locking up at some point during the piping in of the package manager's 
 build output into a text widget. At some point the buffer is overwhelmed 
 and the app simply can't respond anymore, or writes data to the text 
 widget after locking up for a period.
 
 I've long used the typical Tkinter design pattern of opening a pipe to 
 the external command, and letting it do its thing. However, after a 
 time, this locks up the app. If I try to throttle the buffer with some 
 combination of update or after or update_idletasks, that keeps the 
 data flowing, but it comes in too slowly and keeps flowing in long after 
 the external process has terminated.
 
 Below is a sample function that illustrates how I approach this issue. 
 Can someone suggest a better approach?
 
   #install a fink package
  def installPackage(self):
 
  self.package = self.infotable.getcurselection()
  if not self.package:
  showwarning(title='Error', message='Error', detail='Please 
 select a package name.', parent=self)
  return
  else:
  self.clearData()
  self.packagename = self.package[0][1]
  self.status.set('Installing %s' % self.packagename)
  self.setIcon(self.phynchronicity_install)
  self.playSound('connect')
  self.showProgress()
  self.file = Popen('echo %s | sudo -S %s -y install %s' % 
 (self.passtext, self.finkpath.get(), self.packagename), shell=True, 
 bufsize=0, stdout=PIPE).stdout
  for line in self.file:
  self.inserturltext(line)
  self.after(5000, self.update_idletasks)

I suggest you use the threading or multiprocessing module: call 
subprocess.Popen in the spawned thread or process, read stdout in a 
tight loop write the result into a queue. Then have your main process 
asynchronously read the queue using polling.

It sounds a bit complicated, but in lieu of a way to asynchronously read 
the stdout pipe, I don't know what else to do that's safe.

Another option to consider is to use Twisted framework, which has its 
own support for running tasks. However, if you are not using Twisted 
already, it's a big addition.

-- Russell

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


Re: Tkinter bug in Entry widgets on OS X

2012-09-13 Thread Russell E. Owen
In article k1qhgn$me0$1...@dont-email.me,
 Kevin Walzer k...@codebykevin.com wrote:

 On 8/31/12 6:18 AM, Arnaud Delobelle wrote:
  I'm very inexperienced with Tkinter (I've never used it before).  All
  I'm looking for is a workaround, i.e. a way to somehow suppress that
  output.
 
 What are you trying to do? Navigate the focus to another widget? You 
 should use the tab bar for that, not the arrow key. The entry widget is 
 a single-line widget, and doesn't have up/down as the text widget does.

Based on other replies it looks as if the OP found a way to intercept 
the event with suitable binding.

But I can answer the why: on Mac OS X in a one-line text box up-arrow 
should move the cursor to the beginning and down-arrow to the end. 
That's standard behavior.

In any case I can't imagine ever wanting to see special chars get added 
when arrow keys are pressed. The default behavior of the Entry widget is 
unfortunate.

-- Russell

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


Re: What's wrong with this code?

2012-07-23 Thread Russell E. Owen
In article 
CAPTjJmqrhztsUkRSYb56=TX=hdomvo8mepcsy0ytjauptcm...@mail.gmail.com,
 Chris Angelico ros...@gmail.com wrote:

 On Tue, Jul 24, 2012 at 12:50 AM, Stone Li viewfromoff...@gmail.com wrote:
 
  I'm totally confused by this code:
 
  Code:
 
 Boiling it down to just the bit that matters:
 
 c = None
 d = None
 x = [c,d]
 e,f = x
 c = 1
 d = 2
 print e,f
 
 When you assign e,f = x, you're taking the iterable x and unpacking
 its contents. There's no magical referenceness that makes e bind to
 the same thing as c; all that happens is that the objects in x gain
 additional references. When you rebind c and d later, that doesn't
 change x, nor e/f.
 
 What you've done is just this:
 
 x = [None, None]
 e,f = x
 c = 1
 d = 2
 print e,f
 
 It's clear from this version that changing c and d shouldn't have any
 effect on e and f. In Python, any time you use a named variable in an
 expression, you can substitute the object that that name is
 referencing - it's exactly the same. (That's one of the things I love
 about Python. No silly rules about what you can do with a function
 return value - if you have a function that returns a list, you can
 directly subscript or slice it. Yay!)

Good explanation.

Perhaps what the original poster needs is a container of some kind, e.g. 
a class with the value as an instance variable. Then you can pass around 
references to the container and read or modify the value(s) stored in it 
when you need them.

Here is a simple example:

class Container(object):
   def __init__(self, value):
   self.value = value

c = Container(5)
d = Container(6)
x = [c, d]
e, f = x
c.value = None
d.value = hello
print e.value, f.value
None hello

-- Russell

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


Re: pickle question: sequencing of operations

2012-05-09 Thread Russell E. Owen
In article 
calwzidk3e353cnuuqpwr-4rromx7c9dbzapawurern9uzyu...@mail.gmail.com,
 Ian Kelly ian.g.ke...@gmail.com wrote:

 On Tue, May 8, 2012 at 1:19 PM, Russell E. Owen ro...@uw.edu wrote:
  In article rowen-df116b.12542704052...@news.gmane.org,
   Russell E. Owen ro...@uw.edu wrote:
 
  What is the sequence of calls when unpickling a class with __setstate__?
 
 I believe it just calls object.__new__ followed by
 yourclass.__setstate__.  So at the point __setstate__ is called, you
 have a pristine instance of whatever class you're unpickling.

I was wondering. I override __new__ (and __init__) to print messages and 
was quite surprised to only see __new__being called when the object was 
first created, not when it was being unpickled. But maybe there's 
something funny about my override that caused unpickle to ignore it and 
use the default version. I hope so. I can't see how the object could be 
constructed during unpickle without calling __new__. But that's one 
reason I was curious about the unpickling sequence of operations.

-- Russell

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


Re: pickle question: sequencing of operations

2012-05-08 Thread Russell E. Owen
In article rowen-df116b.12542704052...@news.gmane.org,
 Russell E. Owen ro...@uw.edu wrote:

 What is the sequence of calls when unpickling a class with __setstate__?
 
 From experimentation I see that __setstate__ is called and __init__ is 
 not, but I think I need more info.
 
 I'm trying to pickle an instance of a class that is a subclass of 
 another class that contains unpickleable objects.
 
 What I'd like to do is basically just pickle the constructor parameters 
 and then use those to reconstruct the object on unpickle, but I'm not 
 sure how to go about this. Or an example if anyone has one.

The following seems to work, but I don't know why:
def __getstate__(self):
   ...return the argument dict needed for __init__

def __setstate__(self, argdict):
   self.__init__(**argdict)

-- Russell

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


pickle question: sequencing of operations

2012-05-04 Thread Russell E. Owen
What is the sequence of calls when unpickling a class with __setstate__?

From experimentation I see that __setstate__ is called and __init__ is 
not, but I think I need more info.

I'm trying to pickle an instance of a class that is a subclass of 
another class that contains unpickleable objects.

What I'd like to do is basically just pickle the constructor parameters 
and then use those to reconstruct the object on unpickle, but I'm not 
sure how to go about this. Or an example if anyone has one.

-- Russell

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


Re: Is it necessary to call Tk() when writing a GUI app with Tkinter?

2012-03-05 Thread Russell E. Owen
In article 
3d0bf288-fa5d-48e5-9529-db92d420a...@1g2000yqv.googlegroups.com,
 Rick Johnson rantingrickjohn...@gmail.com wrote:

 On Feb 29, 11:24 pm, Terry Reedy tjre...@udel.edu wrote:
  On 2/29/2012 10:22 PM, Rick Johnson wrote:
 
   PS: I would highly suggest against using the from Tkinter import *.
   Instead, use import Tkinter as tk and prefix all module contents
   with tk..
 
  I have changed the example to do that. I also showed the alternate to
  initialize a widget. Here is the current version, tested on Windows 3.2.2.
 
  import tkinter as tk
 
  class Application(tk.Frame):
       def __init__(self, master=None):
           tk.Frame.__init__(self, master)
           self.pack()
 
 With all due respect, I would also recommend against self packing a
 widget. And i can speak from experience on this issue. There was a
 time when i was self-packing lots of custom compund widgets; then i
 realized later the shortcomings of such action; what if you need to
 use the grid or place geometry mangers instead? So remove the
 self.pack line and add a line to the bottom:
 
  root = tk.Tk()
  app = Application(master=root)
  app.pack() # -- added this line
  app.mainloop()

I agree. Application is simply another widget, like Entry or Canvas. its 
contents should be packed or gridded (as appropriate) into itself, but 
the user should then pack or grid the Application widget as appropriate.

That makes the code much more reusable.

-- Russell

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


Generator problem: parent class not seen

2012-02-01 Thread Russell E. Owen
I have an odd and very intermittent problem in Python script. 
Occasionally it fails with this error:

Traceback (most recent call last):
 File 
/Applications/APO/TTUI.app/Contents/Resources/lib/python2.7/TUI/Base/Bas
eFocusScript.py, line 884, in run
 File 
/Applications/APO/TTUI.app/Contents/Resources/lib/python2.7/TUI/Base/Bas
eFocusScript.py, line 1690, in initAll
TypeError: unbound method initAll() must be called with BaseFocusScript 
instance as first argument (got ScriptClass instance instead)
self=ScriptClass object at 0x2066b410; class hierarchy=[(class 
'TUI.Base.BaseFocusScript.ImagerFocusScript', (class 
'TUI.Base.BaseFocusScript.BaseFocusScript',)), [(class 'ScriptClass', 
(class 'TUI.Base.BaseFocusScript.ImagerFocusScript',))]]

The code looks like this:

def run(self, sr):
try:
self.initAll()

except Exception:
traceback.print_exc(file=sys.stderr)
sys.stderr.write(self=%r; class hierarchy=%s\n % (self, 
inspect.getclasstree([type(self)])))
raise

As a detail that may be important: the code is a generator that is being 
run by a script runner class (an instance of which is passed into the 
run function as argument sr). When the user starts a script the script 
runner calls the script's run generator. The script runner calls the 
run generator again later when conditions are right (e.g. data that is 
being waited for arrives, a time limit is reached...). In this case the 
failure occurs at the very start of the script, so a yield has not yet 
executed.

I am puzzled why Python thinks the class type is wrong, given the output 
of inspect.getclasstree. Any ideas on what might be wrong and how to 
track it down (and why it would be so intermittent)?

-- Russell

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


Re: Decorator question: prefer class, but only function works

2011-11-14 Thread Russell E. Owen
In article 
CALwzidk11rqXjaxcwNKy5C2iotaBO_BcDWL_zFC6Rctue=4...@mail.gmail.com,
 Ian Kelly ian.g.ke...@gmail.com wrote:

 On Thu, Nov 10, 2011 at 2:52 PM, Russell E. Owen ro...@uw.edu wrote:
  I am trying to write a decorator that times an instance method and
  writes the results to a class member variable. For example:
 
  def timeMethod(func):
     def wrapper(self, *args, **keyArgs):
         t1 = time.time()
         res = func(self, *args, **keyArgs)
         duration = time.time() - t1
         self.timings[func.__name__] = duration
         return res
     return wrapper
 
  This works, but I'm not very happy with the way self.timings is obtained.
 
 What do you feel is wrong with it? 

Oops, I stripped so much out of my example that I stripped the ugly bit. 
This is closer to the original and demonstrated the issue:

def timeMethod(func):
name = func.__name__ + Duration
def wrapper(self, *args, **keyArgs):
       t1 = time.time()
       res = func(self, *args, **keyArgs)
       duration = time.time() - t1
       self.timings[name] = duration
       return res
   return wrapper

I don't like the way name is passed into wrapper. It works, but it looks 
like magic. A class offers an obvious place to save the information. Or 
I could just generate the name each time.

I realize I'm showing the limits of my understanding of python binding 
of variable names, but I also think that if I find it confusing then 
others will, as well.

 sum(os.times()[:2]) instead, which (assuming your script is
 single-threaded) will more accurately count the actual CPU time spent
 in the function rather than real time, which could be quite different
 if the CPU is busy.

Thanks for the suggestion. I decided to use time.clock(), which I 
understand gives basically the same information (at a resolution that is 
sufficient for my needs).

 Also, why do you need this?  If you're just trying to evaluate the
 speed of your code, you should consider using a proper profiler or the
 timeit module. The former will tell you how much time is spent in
 each function, while the latter runs the code a large number of times
 in a loop, which gives you better precision for quick methods.

It is for timing stages of a data processing pipeline. Only long-running 
tasks will be timed. Repeatedly running to get better times is neither 
practical nor necessary to get a good feeling of where the time is being 
spent.

  I first tried to write this as a class (for readability), and this did
  NOT work:
 
  class timeMethod(object):
     def __init__(self, func):
         self.func = func
     def __call__(self, *args, **keyArgs):
         t1 = time.time()
         res = self.func(*args, **keyArgs)
         duration = time.time() - t1
         args[0].timings.set(self.func.__name__, duration)
         return res
 
  In the first case the wrapper is called as an unbound function, so it
  works. But in the second case the wrapper is called as a bound method --
  thus args[0] is not func's class instance, and I can't get to the
  timings attribute.
 
 I prefer the function version myself, but to make this work you could
 add something like this (untested) to make your wrapper class a
 descriptor that tacks on the self argument:
 
 def __get__(self, instance, owner):
 from functools import partial
 if instance is None:
 return self
 return partial(self, instance)

Thank you very much. I'll stick to the function, since it works, but 
it's nice to know how to work around the problem.

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


Decorator question: prefer class, but only function works

2011-11-10 Thread Russell E. Owen
I am trying to write a decorator that times an instance method and 
writes the results to a class member variable. For example:

def timeMethod(func):
def wrapper(self, *args, **keyArgs):
t1 = time.time()
res = func(self, *args, **keyArgs)
duration = time.time() - t1
self.timings[func.__name__] = duration
return res
return wrapper

This works, but I'm not very happy with the way self.timings is obtained.


I first tried to write this as a class (for readability), and this did 
NOT work:

class timeMethod(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **keyArgs):
t1 = time.time()
res = self.func(*args, **keyArgs)
duration = time.time() - t1
args[0].timings.set(self.func.__name__, duration)
return res

In the first case the wrapper is called as an unbound function, so it 
works. But in the second case the wrapper is called as a bound method -- 
thus args[0] is not func's class instance, and I can't get to the 
timings attribute.

Unfortunately they are both pretty ugly. Is there a cleaner way to 
access the the instance of which func is a member? I was very 
disappointed it was not available when timeMethod was 
called/instantiated.

-- Russell

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


Re: [Python-Dev] RELEASED Python 2.6.2

2009-04-17 Thread Russell E. Owen
In article nad-304e10.20284516042...@news.gmane.org,
 Ned Deily n...@acm.org wrote:

 In article dd982bd4-02ab-4395-afee-cd3d0eeb7...@u.washington.edu,
  Russell Owen ro...@u.washington.edu wrote:
  I installed the Mac binary on my Intel 10.5.6 system and it works,  
  except it still uses Apple's system Tcl/Tk 8.4.7 instead of my  
  ActiveState 8.4.19 (which is in /Library/Frameworks where one would  
  expect).
  
  I just built python from source and that version does use ActiveState  
  8.4.19.
  
  I wish I knew what's going on. Not being able to use the binary  
  distros is a bit of a pain.
 
 You're right, the tkinter included with the 2.6.2 installer is not 
 linked properly:
 
 Is:
 $ cd /Library/Frameworks/Python.framework/Versions/2.6
 $ cd lib/python2.6/lib-dynload
 $ otool -L _tkinter.so 
 _tkinter.so:
/System/Library/Frameworks/Tcl.framework/Versions/8.4/Tcl 
 (compatibility version 8.4.0, current version 8.4.0)
/System/Library/Frameworks/Tk.framework/Versions/8.4/Tk 
 (compatibility version 8.4.0, current version 8.4.0)
/usr/lib/libSystem.B.dylib [...]
 
 should be:
 _tkinter.so:
/Library/Frameworks/Tcl.framework/Versions/8.4/Tcl (compatibility 
 version 8.4.0, current version 8.4.19)
/Library/Frameworks/Tk.framework/Versions/8.4/Tk (compatibility 
 version 8.4.0, current version 8.4.19)
/usr/lib/libSystem.B.dylib [...]

Just for the record, when I built Python 2.6 from source I got the 
latter output (the desired result).

If someone can point me to instructions I'm willing to try to make a 
binary installer and make it available (though I'd much prefer to debug 
the standard installer).

-- Russell

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


Re: RELEASED Python 2.6.2

2009-04-15 Thread Russell E. Owen
Thank you for 2.6.2.

I see the Mac binary installer isn't out yet (at least it is not listed 
on the downloads page). Any chance that it will be compatible with 3rd 
party Tcl/Tk?

Most recent releases have not been; the only way I know to make a 
compatible build is to build the installer on a machine that already has 
a 3rd party Tcl/Tk installed; the resulting binary is then compatible 
with both 3rd party versions of Tcl/Tk and also with Apple's ancient 
built in version.

-- Russell

--
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 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


Re: ActiveState Python v2.5 doesn't come with Tkinter or Tk installed.

2008-08-14 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Dudeja, Rajat [EMAIL PROTECTED] wrote:

 Hi,
 
 So, now I've finally started using Eclipse and PyDev as an IDE for my
 GUI Application. I just wrote some sample programs as an hands on.
 
 Now I would like to take up Tkinter. I'm using Active State Python
 version 2.5 and found that there is not Tkinter and Tk module in it.
 
 To use Tkinter do I actually require Tk installed on my machine? Please
 suggest and where can I find both these modules?
 
 Also, please direct me to a good and short document on using Tkinter or
 Tk in Python.

What operating system?

For MacOS X this should not happen because Tcl/Tk is already available. 
But the best Python for MacOS X is the binary installer from python.org 
and the best Tcl/Tk is ActiveState version 8.4.19 (the Tcl/Tk that comes 
with MacOS X 10.4 and 10.5 is rather old and buggy).

For Windows: the standard python.org binary Python includes its own 
Tcl/Tk. So the simplest solution is to use that. I know nothing about 
ActiveState's Python for Windows but it is possible that it requires 
ActiveState Tcl/Tk to use Tkinter.

For unix: I'm not sure about ActiveState and unix. But the standard 
package installer that comes with your unix should offer tcl/tk, python 
and _tkinter (possibly as 3 separate packages, possibly not) and at 
least tcl/tk and python should be installed by default.

In general ActiveState puts out a very nice Tcl/Tk installer that 
includes many useful extra packages. But I've never seen the point to 
ActiveState's Python installer. When I last tried it, their Python was 
missing readline and did not add any useful packages to the standard 
python.org version.

For info on Tkinter: http://wiki.python.org/moin/TkInter

-- Russell

P.S. if you do install Tcl/Tk to use with Tkinter, please use 8.4.x, NOT 
8.5. Python 2.5.x is not fully compatible with Tcl/Tk 8.5.
--
http://mail.python.org/mailman/listinfo/python-list


Can't seem to build python against custom tcl/tk

2008-08-13 Thread Russell E. Owen
I'm trying to build a non-framework python on MacOS X 10.5 using a 
custom tcl/tk that lives in an arbitrary directory. (For complicated 
reasons we don't want the system tcl/tk). It is easy to build an X11 
tcl/tk this way (and we are content with X11) so I did that.

Unfortunately I can't seem to build Python in such a way that it sees 
this tcl/tk.

The only documented way to do this I found was to edit Modules/Setup or 
Setup.local, so I did the following:
$ /configure --prefix=/Users/rowen/TestBuild/pythonroot/ 
--disable-framework
Edit Modules/Setup.local to add this text (based on comments in 
Modules/Setup):
_tkinter _tkinter.c tkappinit.c -DWITH_APPINIT \
  -L/Users/rowen/TestBuild/tcltkroot/lib \
  -I/Users/rowen/TestBuild/tcltkroot/include \
  -ltk8.4 -ltcl8.4 \
  -I/usr/X11R6/include \
  -L/usr/X11R6/lib \
  -lX11
$ make
$ make install

This builds, but the resulting python is missing the _tkinter library.

I tried setting CFLAGS:
$ export CFLAGS=-I/Users/rowen/TestBuild/tcltkroot/include 
-L/Users/rowen/TestBuild/tcltkroot/bin
before running configure, but that didn't help.

So...any advice? Any obvious mistake? (I did double-check each path in 
the text I added to Setup.local) Is there some way to convince configure 
to use my tcl/tk (that would potentially be simpler than editing 
Modules/Setup.local).

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


Could someone please review patch 799428: fix Tkinter tk_focusNext?

2008-08-01 Thread Russell E. Owen
Patch http://bugs.python.org/issue799428 is a trivial (one word) fix 
to a long-standing issue with Tkinter: calls to the widget method 
tk_focusNext() fail with unsubscriptable object error.

Admittedly we've lived a long time with this bug. But the fix is so 
simple and so obviously safe that it seems a shame to leave it out.

it would be especially nice to get this into the first Python 2.6 
release so one could assume the fix is present if using any flavor of 
2.6 or newer.

This fix is truly trivial: it just wraps a return from tk in str() to 
avoid the problem of getting an object back in less-than-ancient 
versions of tcl/tk.

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


Re: like py2exe, but on a mac

2008-07-29 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 William McBrine [EMAIL PROTECTED] wrote:

 On Sun, 13 Jul 2008 00:58:59 +0200, Python.Arno wrote:
 
  http://undefined.org/python/py2app.html
 
 py2app bundles Python itself into the app, right? I wonder, is there no 
 way to create an app bundle that relies on the existing installation of 
 Python, since OS X already comes with Python? I have a tiny little 
 program (~20k) that I'd like to make into an app bundle, if only to 
 suppress the console window, and I'd rather not lump in the whole Python 
 interpreter if I can avoid it.

That is exactly what py2app does by default if you run py2app with the 
system python.

If you run py2app with a non-system python then that python is bundled 
with the application.

Note that different versions of MacOS X have different versions of 
system python. So if your application needs any 3rd party packages then 
including python with the app will allow it work with more versions of 
MacOS X.

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


Re: like py2exe, but on a mac

2008-07-29 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Tommy Nordgren [EMAIL PROTECTED] wrote:

 On 28 jul 2008, at 03.59, William McBrine wrote:
 
  On Sun, 13 Jul 2008 00:58:59 +0200, Python.Arno wrote:
 
  http://undefined.org/python/py2app.html
 
  py2app bundles Python itself into the app, right? I wonder, is there  
  no
  way to create an app bundle that relies on the existing installation  
  of
  Python, since OS X already comes with Python? I have a tiny little
  program (~20k) that I'd like to make into an app bundle, if only to
  suppress the console window, and I'd rather not lump in the whole  
  Python
  interpreter if I can avoid it.
 
   There is Platypus, a general open source program to wrap a script
 in an Macintosh (GUI) 

It's an interesting application, but... I tried it to bundle a script 
that puts up a standard Tkinter file save dialog box and I found that 
the dialog box was not in front -- I had to switch applications to get 
to it. Still, it looks useful for fully faceless applications; unlike 
py2applet the text to stdout shows up in a log window.

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


Re: Pass data from Python to C++

2008-05-15 Thread Russell E. Owen
In article [EMAIL PROTECTED], brad [EMAIL PROTECTED] 
wrote:

 I have some c++ binaries that do rather intense number computations. 
 They do it well and rather quickly compared to other languages (not just 
 Python). ...
 
 However, other components can be written in a more user friendly, more 
 easily maintained language. We've chosen Python for this. The main 
 question now is how to pass the computationally heavy info to c++ from 
 within Pyhton. os.system is not ideal. Just wondering how other folks do 
 this? I have source to some of the c++ code, but some of it is in binary 
 from only. It can take stdin or arguments.

You say you have binary only, but I hope you have the header files as 
well. If so I would try SWIG first since it is mature and handles C++ 
quite well. If you don't have headers then I have no idea if it's even 
possible.

(For plain C I would start with ctypes, but that doesn't cover this 
case. There are many other options including boost and Pyrex, but I've 
not used those.)

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


Re: Simple unicode-safe version of str(exception)?

2008-04-29 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Bjoern Schliessmann [EMAIL PROTECTED] 
 wrote:

 Martin v. Löwis wrote:
 
  e is an exception object, not a Unicode object.
 
 Er, sure, thanks for pointing that out. At first sight he should
 substitute e with e.message then since he tries to convert to
 string (for display?).

No. e.message is only set if the exeption object receives exactly one 
argument.

That is why my replacement code reads:
errStr = ,.join([unicode(s) for s in f.args])
self.setState(self.Failed, errStr)
(where e is an Exception of some kind)

Notice that I'm iterating over the args. But again, this is far messier 
than:
self.setState(self.Failed, str(e)

So...to repeat the original question, is there any simpler unicode-safe 
replacement for str(exception)?

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

Re: Simple unicode-safe version of str(exception)?

2008-04-29 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Donn Cave [EMAIL PROTECTED] wrote:

 In article [EMAIL PROTECTED],
  Martin v. Löwis [EMAIL PROTECTED] wrote:
 
   I have code like this:
   except Exception, e:
  self.setState(self.Failed, str(e))
   which fails if the exception contains a unicode argument.
   
   Fails how?
  
  ASCII encoding error, I suppose. It fails only if a) one argument
  is a Unicode object, and b) that Unicode object contains non-ASCII
  parameters.
 
 Seem ironic that this fails even though pretty nearly anything
 else is a valid input to str() -- socket, dict, whatever?

I agree. In fact str(a) works if a is a dict or list that contains 
unicode data! Pity the same is not true of exceptions.

Should I report this as a bug? I suspect it's a misfeature.

 A sort of generic solution might be to follow str's behavior
 with respect to '__str__', extending it to fall back to repr()
 whatever goes wrong.
 
 
 def xtr(a):
 try:
 return str(a)
 except:
 return repr(a)

Yes. That is a more flexible alternative to what I've adopted:
def exStr(ex):
return ,.join([unicode(s) for s in f.args])
the latter gives better output for the case I'm interested in, but only 
handles exceptions.

Oh well. I'll stick to my solution and hope that Python 2.6 and 3.0 fix 
the problem in a more sensible fashion.

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

Re: Simple unicode-safe version of str(exception)?

2008-04-29 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Torsten Bronger [EMAIL PROTECTED] wrote:

 Hallöchen!
 
 Russell E. Owen writes:
 
  [...]
 
  So...to repeat the original question, is there any simpler
  unicode-safe replacement for str(exception)?
 
 Please show us the tracebacks you get becuae unicode(s) must fail,
 too, if there are non-ASCII characters involved.

Why?

What I am trying to do is get a unicode representation of the arguments 
of an exception. str(e), the obvious solution, fails if the exception 
contains one argument that is a unicode string that cannot be decoded to 
ASCII:

UnicodeEncodeError: 'ascii' codec can't encode character...ordinal not 
in range(128)

What I do with the resulting unicode string afterwards is a different 
issue. (As a matter of fact I display it on a widget that can display 
unicode, but if I tried to print it to my Mac Terminal it would complain 
about the non-ASCII characters--something I should look into fixing 
someday).

But in any case, here are the exceptions you wanted to see. This is 
using Python 2.5.2 on a Mac:

 d =u\N{DEGREE SIGN}
 d
u'\xb0'
 str(d)
Traceback (most recent call last):
  File stdin, line 1, in module
UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0' in 
position 0: ordinal not in range(128)
 e = Exception(d)
 str(e)
Traceback (most recent call last):
  File stdin, line 1, in module
UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0' in 
position 0: ordinal not in range(128)
 e
Exception(u'\xb0',)
 ,.join([unicode(s) for s in e.args])
u'\xb0'
 

Based on the dearth of better replacements I've gone with the solution 
that is shown as the last line above, coded as the following function 
(incorporating Donn Cave's excellent suggestion to use repr as a 
fallback). It has the minor issue that it can mask KeyboardInterrupt on 
older versions of Python but it's close enough. A lot of work to replace 
str(exc).

def strFromException(exc):
Unicode-safe replacement for str(exception)
try:
return str(exc)
except Exception:
try:
return ,.join([unicode(s) for s in exc.args])
except Exception:
# in case exc is some unexpected type
return repr(exc)

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

Simple unicode-safe version of str(exception)?

2008-04-28 Thread Russell E. Owen
I have code like this:
except Exception, e:
   self.setState(self.Failed, str(e))
which fails if the exception contains a unicode argument.

I did, of course, try unicode(e) but that fails.

The following works, but seems rather messy:

except Exception, e:
errStr = ,.join([unicode(s) for s in f.args])
self.setState(self.Failed, errStr)

Is there a simpler solution that works in Python 2.3-2.5?

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


Re: Tkinter: Missing the last piece of the puzzle

2008-02-27 Thread Russell E. Owen
In article 
[EMAIL PROTECTED],
 [EMAIL PROTECTED] wrote:

 Simon Forman wrote:
  yes! check out 
  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/464635
 
  HTH,
  ~Simon
 
 Thanks, Simon. Looks like that will do it.
 
 Actually, it looks like that will overdo it. I'll be setting File/Save
 to enabled after every keystroke. Ideally, I'd like to set my statuses
 when the user clicks the File option or types Alt-F. This makes me
 wonder if there's a mixin that could find this event. Hmmm.

Set an internal state variables isChanged based on the Text callback 
and only modify the menu if the variable is set.

It's trickier to detect significant changes vs insigificant ones. 
Personally I would not bother to go that far.

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


Re: pyinstall and matplotlib

2008-02-13 Thread Russell E. Owen
In article 
[EMAIL PROTECTED],
 John Henry [EMAIL PROTECTED] wrote:

 On Feb 9, 2:53 pm, John Henry [EMAIL PROTECTED] wrote:
  Has anybody been able to create an exe of their python applications
  involving matplotlib using pyinstall (ver 1.3)?  I am getting a:
 
   RuntimeError: Could not find the matplotlib data files
 
  when I attempt to run the exe created.
 
  In searching the web, it appears this is an issue when others tried to
  use py2exe as well.  Unfortunately, the few hits I saw doesn't include
  enough details to inspire me as to what I should be doing in my
  pyinstall .spec file.
 
  Does anybody has an example or information about this?
 
  Thanks,
 
 Well, looks like nobody has an answer to this question.
 
 How'bout py2exe or other ways of creating exe files out of matplotlib
 projects?  Has anybody been able to do that?  (I am cross-posting
 these messages to the matploblib mailing list).

For py2exe I have appended a setup script I use to bundle an application 
that includes matplotlib. I am no Windows expert and there are probably 
better ways to do it, but it does work. I have made no attempt to strip 
out extra stuff.

(As for pyinstaller:a year or so ago I tried to use it to make a bundled 
*unix* version of my app. If that had worked I'd have considered trying 
to use it for Windows as well. But after a lot of experimenting I was 
never able to get anything even close to functional. Maybe it's better 
now.)

-- Russell

from distutils.core import setup
import os
import sys
import matplotlib
import py2exe

# The following code is necessary for py2exe to find win32com.shell.
# Solution from 
http://starship.python.net/crew/theller/moin.cgi/WinShell
import win32com
import py2exe.mf as modulefinder
for pth in win32com.__path__[1:]:
modulefinder.AddPackagePath(win32com, pth)
for extra in [win32com.shell]:
__import__(extra)
m = sys.modules[extra]
for pth in m.__path__[1:]:
modulefinder.AddPackagePath(extra, pth)

tuiRoot = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
roRoot = os.path.join(tuiRoot, ROPackage)
sys.path = [tuiRoot, roRoot] + sys.path
import TUI.Version
mainProg = os.path.join(tuiRoot, runtui.py)

NDataFilesToPrint = 0 # number of data files to print, per directory

def addDataFiles(dataFiles, fromDir, toSubDir=None, 
inclHiddenDirs=False):
Find data files and format data for the data_files argument of 
setup.

In/Out:
- dataFiles: a list to which is appended zero or more of these 
elements:
[subDir, list of paths to resource files]

Inputs:
- fromDir: path to root directory of existing resource files
- toSubDir: relative path to resources in package;
if omitted then the final dir of fromDir is used
- inclHiddenDirs: if True, the contents of directories whose names
start with . are included

Returns a list of the following elements:

lenFromDir = len(fromDir)
if toSubDir == None:
toSubDir = os.path.split(fromDir)[1]
for (dirPath, dirNames, fileNames) in os.walk(fromDir):
if not inclHiddenDirs:
numNames = len(dirNames)
for ii in range(numNames-1, -1, -1):
if dirNames[ii].startswith(.):
del(dirNames[ii])
if not dirPath.startswith(fromDir):
raise RuntimeError(Cannot deal with %r files; %s does not 
start with %r %\
(resBase, dirPath, fromDir))
toPath = os.path.join(toSubDir, dirPath[lenFromDir+1:])
filePaths = [os.path.join(dirPath, fileName) for fileName in 
fileNames]
dataFiles.append((toPath, filePaths))

# Add resources
dataFiles = []
# TUI resources
for resBase in (Help, Scripts, Sounds):
toSubDir = os.path.join(TUI, resBase)
fromDir = os.path.join(tuiRoot, toSubDir)
addDataFiles(dataFiles, fromDir, toSubDir)
# RO resources
for resBase in (Bitmaps,):
toSubDir = os.path.join(RO, resBase)
fromDir = os.path.join(roRoot, toSubDir)
addDataFiles(dataFiles, fromDir, toSubDir)

# Add tcl snack libraries
pythonDir = os.path.dirname(sys.executable)
snackSubDir = tcl\\snack2.2
snackDir = os.path.join(pythonDir, snackSubDir)
addDataFiles(dataFiles, snackDir, snackSubDir)

# Add matplotlib's data files.
matplotlibDataPath = matplotlib.get_data_path()
addDataFiles(dataFiles, matplotlibDataPath, matplotlibdata)

if NDataFilesToPrint  0:
print \nData files:
for pathInfo in dataFiles:
print pathInfo[0]
nFiles = len(pathInfo[1])
for resPath in pathInfo[1][0:NDataFilesToPrint]:
print   , resPath
if nFiles  NDataFilesToPrint:
print   ...and %d more % (nFiles - NDataFilesToPrint)

versDate = TUI.Version.VersionStr
appVers = versDate.split()[0]
distDir = TUI_%s_Windows % (appVers,)

inclModules = [
#email.Utils, # needed for Python 2.5.0
]
# packages to include recursively
inclPackages = [
TUI,
RO,
matplotlib,
dateutil, # 

Re: Truncated postings

2008-02-13 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] wrote:

 Hello,

Over the past 24 hours or so, all of my Python-List e-mails have been 
 truncated to subject list only. No posts. 

Are others experiencing this 
 problem? Or is it just on my end?

Thanks,

Lloyd R. Prentice


I'm not seeing that. But:
- I use gmane
- Your posting has some weird characters in it (they show up on my 
screen as sort of box/arrow containing an x) so maybe something about 
your email format is making the list server upset.

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


Re: Tkinter equiv for setPalette

2008-02-11 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Helmut Jarausch [EMAIL PROTECTED] wrote:

 Hi,
 
 I am to convert an old Perl-Tk script to Python.
 It starts by
 my $MW= new MainWindow;
 $MW-setPalette(background = 'AntiqueWhite1', foreground = 'blue');
 
 Is there an equivalent for Tkinter? How can I set default colors for
 background and foreground for the whole application (root window and its
 children)

Tkinter widgets have a tk_setPalette method so you can do this:

root = Tkinter.Tk()
root.tk_setPalette(background = 'AntiqueWhite1', foreground = 'blue')

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


Re: Problem with Tkinter scrollbar callback

2008-01-25 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Ivan Van Laningham [EMAIL PROTECTED] wrote:

 Hi All--
 That helps.  Doing a get() on the scrollbar before a set(0.0,0.0)
 returns a 4-tuple:  (0.0, 0.0, 0.0, 0.0)  !  I did the set(0.0,0.0)
 and now the callback gets the correct number of arguments.
 
 However, I'm still getting the weird behaviour when clicking the
 arrowheads--and the heads are all I want.  They act like they've been
 set to a keybounce timeout of about a millisecond. ...  The arrow
 click increments the number of cells in a table row (effectively), and
 it shoots up from 5 to 26 columns almost instantly (that's the
 internal max I set).

Is the scroll bar's repeatinterval set to a reasonable value?

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


Re: Problem with Tkinter scrollbar callback

2008-01-24 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Ivan Van Laningham [EMAIL PROTECTED] wrote:

 Hi All--
 I'm having two problems with the scrollbar callback on linux systems
 (Fedora 7, Suse 10.1,2 and 3 all exhibit the issues).
 
 Problem one:  on Windows, the callback is called with the arguments as
 specified in the doc:  scroll, 1 or -1, units.  When I run the
 identical code on linux, the callback is invoked with only one
 argument, 1 or -1.  Here's a small program which demos the
 problem:
 
 begin
 #!/usr/bin/env python
 
 from Tkinter import *
 import sys
 
 def die(event):
 sys.exit(0)
 def sDoit(*args):
   for i in args:
 print scrollbar:,i, type(i)
 root=Tk()
 f=Frame(root)
 f.pack(expand=1,fill=BOTH)
 button=Button(f,width=25)
 button[text]=Quit
 button.bind(Button,die)
 button.pack()
 xb=Scrollbar(f,orient=HORIZONTAL,command=sDoit)
 xb.pack()
 root.mainloop()
 =end===
 
 On Windows, it produces the correct output
 
 scrollbar: scroll type 'str'
 scrollbar: 1 type 'str'
 scrollbar: units type 'str'
 
 but on linux, it produces
 
 scrollbar: 1 type 'str'

I see the same bad thing on our RedHat Enteprise unix system which has 
the default tcl/tk 8.4.6. However I found that if you send the scrollbar 
the set command first then it behaves normally. I think it just starts 
out in a funny state where it has no idea how to display itself.

-- Russell

(P.s. it works fine on my MacOS X 10.4.11 system with default tcl 8.4.7 
or with add-on 8.4.14).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When is min(a, b) != min(b, a)?

2008-01-23 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Christian Heimes [EMAIL PROTECTED] wrote:

 Grant Edwards wrote:
  In many applications (e.g. process control) propogating NaN
  values are way too useful to avoid.  Avoiding NaN would make a
  lot of code far more complicated than would using them.
 
 NaNs are very useful for experienced power users but they are very
 confusing for newbies or developers without a numerical background.
 
 It's very easy to create an inf or nan in Python:
 
 inf = 1E+5000
 ninf = -inf
 nan = inf * 0.
 
 1E5000 creates a nan because it is *much* bigger than DBL_MAX (around
 1E+308). In fact it is even larger than LDBL_MAX (around 1E+4932).

Isn't it safer to use float(inf), float(-inf) and float(nan) to 
create the necessary items?

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


Re: Using python as primary language

2007-11-13 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Michel Albert [EMAIL PROTECTED] wrote:

 In our company we are looking for one language to be used as default
 language. So far Python looks like a good choice (slacking behind
 Java). A few requirements that the language should be able cope with
 are:
 
 * Database access to Sybase.
   This seems to be available for python, but the windows-binaries for
 the library
   are not available. Self-Compiling them proved to be non-trivial (As
 always
   on windows).
 * Easy GUI creation.
   Solved using PyQt.
 * Cross Platform (Linux + Windows).
   Again, PyQt, solves this
 * Easy deployment.
   Solved using py2exe + innosetup

How do you deploy python on linux? The only solution I know of is 
pyinstaller and I never could get it to work for me on linux (I never 
bothered to try on Windows since I already had py2exe doing what I 
needed).

In my opinion this is one of Python's few weaknesses compared to Java. 
Others that come to mind are:
- Lack of a built-in networking library that works with GUI toolkits 
(use Twisted Framework and hope it continues to be supported)
- Lack of a good built-in GUI toolkit (but there are several good 
alternatives including Qt)

 * Charting (Histograms, Line charts, bar charts, pie charts, ...)
   I am currently looking into PyQwt, which looks promising.

HippoDraw is very good. I am not familiar with PyQwt so I cannot compare 
them.

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


Re: Build Python 2.5 against Tk 8.5

2007-10-16 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Kevin Walzer [EMAIL PROTECTED] wrote:

 Martin v. Löwis wrote:
  I'd like to experiment with Tk 8.5 (now in beta) in my Python
  application, but Python 2.5 requires Tk 8.4.x.
  
  Why do you say that? AFAIK, that's not the case.
 
 It's been a while, but when I've tried to run my Tkinter app against Tk 
 8.5 with a stock Python installation, I get an error message saying that 
 Tk 8.4.x is required. It's probably tkinter.so that hard-codes the 
 Tcl/Tk version, not Python itself--I should have been clearer on that. 
 However, I still need to know what to patch...

I have no idea how Tkinter does with Tcl/Tk 8.5.

But one way to try it is to build python from source (after installing 
Tcl/Tk 8.5). It's not hard, but it takes awhile and you have to specify 
the right options to get a framework build (these are documented in the 
build instructions).

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

Re: Tkinter pack difficulty

2007-09-12 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Simon Forman [EMAIL PROTECTED] wrote:

 Hi all,
 
 I realize this is more of a Tk question than a python one, but since
 I'm using python and don't know Tcl/Tk I figured I'd ask here first
 before bugging the Tcl folks.
 
 I am having a terrible time trying to get a pack() layout working.
 
 I have three frames stacked top to bottom and stretching across the
 master window from edge to edge.
 
 Crude ASCII Art rendition of the frames:
 
 
 |  header  |
 
 |   body   |
 
 |   log|
 
 
 
 I want the header and log frames to have a fixed height (and stick to
 the top and bottom, respectively, of the master frame) and the body
 frame to expand to fill the rest of the space, for instance if the
 window is maximized.
 
 Here is a simple script that /almost/ does what I want.   I've been
 tweaking the pack() options for three hours and I just can't seem to
 get the effect I want.  This /can't/ really be this hard can it?
 
 If you run the script, be aware that since there are only frame
 widgets the window will initially be very very tiny.  If you expand or
 maximize the window you'll see a thin black frame at the top, yay, a
 thin white frame at the bottom, yay, but the middle grey body frame
 will NOT span the Y axis, boo.
 
 It's there, and stretches from side to side, but it refuses to stretch
 top to bottom.  Adding a widget (say, a Text) doesn't help, the light
 grey non-frame rectangles remain.
 
 My investigations seem to indicate that the light grey bars are part
 of something the Tk docs call a parcel that each slave widget gets
 packed into.  Apparently the header and log frames don't use their
 entire parcels, but I don't know how to get the parcels themselves to
 shrinkwrap to the size of the actual Frame widgets.
 
 In any event,  my head's sore and I'm just about ready to take out
 some graph paper and use the grid() layout manager instead.  But I
 really want the automatic resizing that the pack() manager will do,
 rather than the static layout grid() will give me.

The grid layout manager is the obvious choice for this and it is 
dynamic. (There is a place geometry manager that works with coordinates, 
but I don't recommend that for this case).

Grid the top/middle/bottom frame in row = 0/1/2, column = 0
then use row_configure to set the weight of the middle frame to 1.
You may also have to set sticky to news when you grid all the frames.

In general I suggest you use grid unless it's something simple like a 
row of buttons.

But never try to both grid and pack anything into the in the same parent 
widget. You'll get a crash or an infinite loop. (You can grid frames 
that have widgets packed inside them, but you can't grid grid some items 
into a frame and then pack some more into the same frame)

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


Re: An ordered dictionary for the Python library?

2007-09-12 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Steven D'Aprano [EMAIL PROTECTED] wrote:

 On Wed, 12 Sep 2007 07:33:45 +, Mark Summerfield wrote:
 
  I feel that Python lacks one useful data structure: an ordered
  dictionary.
  
  I find such data structures v. useful in C++.
 [snip]
 
 
 Personally, I've never missed an ordered dict. What do people use them 
 for?
 
 In fact, I'm not sure what people mean by ordered dicts. I assume they 
 mean the keys are ordered, not the values. But ordered by what? Insertion 
 order? Modification order? Alphabetical order?

Opinions vary, but I think of it this way:
- A sorted dict keeps its keys sorted. This has an obvious alternative 
just sort the keys later (though I can imagine cases where it would be 
nicer not to).

- An ordered dict remembers the order of insertion. This is useful when 
you want to retain the order of insertion yet you also want fast lookup 
of individual items. Unlike a sorted dict, there is no trivial 
alternative (though you can argue about trivial) and I really wish 
there was. There are several free versions available.

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


Re: Python and GUI

2007-05-24 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] wrote:

 Just wondering on what peoples opinions are of the GUIs avaiable for
 Python?
 
 All I am doing is prompting users for some data (listbox, radio
 buttons, text box, ect...).  Then I will have some text output, maybe
 a scrolling text message as things are happening.
 
 I have some minor things I need to do, for example, if Checkbutton X
 is clicked, I need to disable TextBox Y, and I would like to display
 the scrolling text (output)
 
 Ultimately, is it worth downloading and learning some of the packages
 avaiable for Python, or should I just stick to the Tkinter stuff that
 is included.
 
 More specifically, has anyone used the Qt stuff for python, easy to
 use?

My opinion is that Tkinter is perfect for the job you describe. It is 
easy to use, fairly pythonic (an issue with some competing toolkits) and 
does not require any fancy installation.

If you want a very professional and native look then you have to work 
harder. Options include Tkinter with tile, wxPython, PyQt and several 
others.

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


Re: Tcl-tk 8.5?

2007-05-02 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Méta-MCI [EMAIL PROTECTED] wrote:

 Hi!
 
 
 See http://wiki.tcl.tk/10630
 
 Any plan to integrate Tcl 8.5 in standard Python?

I'm curious about the plans, also. But I can say this much...Tcl/Tk 8.5 
is still in alpha (and has been for years). I have heard rumors that it 
works pretty well, but it is explicitly not feature stable.

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

Re: Re-running script from Tk shell

2007-04-30 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 gtb [EMAIL PROTECTED] wrote:

 I am testing a simple script by running it in the Tk shell. It imports
 a class from another module. I edit and save the file from which I
 import. When I want to re-run I delete the Tk window  and run the
 module from the Edit window (F5 - Run Module). The script that does
 the importing does not see the changes to the imported class, even if
 I delete the compiled files. For it to see the changes I must close
 all the edit windows and re-open an Idle edit.
 
 Perhaps I need to de-import the class, but I have not found a method
 in the tutorial or the reference (yet).

Try having your script first import the library and then reload it, e.g.:

import foo
reload(foo)

It will load foo more slowly the first time (and a clever if statement 
could avoid that) but it will always use the latest foo.

Warning: this will not work if you use
from foo import...

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


Re: Which are your favorite UML tools?

2007-04-27 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Bruno Desthuilliers [EMAIL PROTECTED] wrote:

 Anastasios Hatzis a écrit :
  Hello,
  
  I'm working on the light-weight MDA tool pyswarm, 
  http://pyswarm.sourceforge.net/ (it is about a code-generator for 
  Python/PostgreSQL-based software. I plan to add support of UML CASE tools 
  other than the one supported currently.
  
  I would like to learn which UML tools you use (if any), 
 
 Any piece of paper and anything that can be used to write on it.
 
  preferrably if it 
  comes to modeling a Python application. 
 
 I stll wait for UML to be able to describe common hi-level dynamic 
 languages idioms and patterns without requiring more space and time than 
   source code.

I am inclined to agree, though my experience is limited. I work on a 
project that is trying to model all its software using Enterprise 
Architect. EA has some nice features, but overall I find it clumsy and 
frustrating.

Some problems are intrinsic to UML (for instance it has no concept of 
linking use case information to other elements). And I don't know of any 
way to model functions (only classes).

Others are EA's fault. For instance it is very slow and clumsy to add or 
edit lists of items (such as class methods or database fields). Also, 
shared development is a pain because there is no concurrent version 
control (it uses CVS to keep track of revisions, but not in a concurrent 
way; checking out a package locks out everybody else).

I tried using a competing product but the interporability was terrible. 
Which brings up another point: it is likely the original poster would 
need to do a lot of work for each CASE tool supported.

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

Re: Welch essential for learning Tkinter well?

2007-04-06 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Kevin Walzer [EMAIL PROTECTED] wrote:

 James Stroud wrote:
 This begs the 
  question, is anyone truly an expert in Tkinter?
 
 Frederick Lundh is, if anyone is.
 
 http://www.pythonware.com/library/tkinter/introduction/index.htm (outdated)
 http://effbot.org/tkinterbook/ (new but incomplete)

I agree that this is an excellent resource.

I find Welch's book and the on-line tcl/tk help very helpful for Tkinter 
programming--especially some of the more obscure details. But to use 
either of these resources comfortably you must learn the basics of 
Tkinter first (including understanding the simple mapping between 
Tkinter and Tcl/Tk).

For learning the basics of Tkinter I suggest the links that Kevin listed 
above and/or Alex Martelli's Python in a Nutshell (an excellent 
reference in any case). Grayson's book is another reasonable alternative 
(and includes enough reference material to keep you from having to refer 
to the tcl/tk documentation very often).

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


Re: Tkinter Toplevel geometry

2007-03-26 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Chris [EMAIL PROTECTED] wrote:

 Hi,
 
 If a user resizes a Toplevel window, or I set a Toplevel's geometry
 using the geometry() method*, is there any way to have the geometry
 reset to that required for all the widgets?
 
 I think I found what I'm looking for in tk itself:
 
 13.3. How can I clear the geometry settings for a toplevel?
 If you want to have Tk resize your toplevel to what the toplevel
 requires (ie: the user might have resized it, or a widget was
 removed), use [wm geometry $toplevel].
 
...

I'm glad you got that figured out.

Here's a variant question that has driven me crazy...how to create a 
general-purpose variation of toplevel that:
- can only be resized in one direction and auto-sizes (to fit widgets) 
in the other direction?
- has a reasonable initial size in the resizable direction.

The first part is easy -- just use the resizable method. I've never 
figured out a clean solution to the second question because:
- tk doesn't allow setting just X or Y size of a toplevel (the geometry 
call requires both or neither)
- one can use a frame to force the resizable dimension to the desired 
initial value, but to do that you either have to know in advance what 
geometry manager the user is using, or make them pack their widgets into 
a frame inside the toplevel

I ended up binding to the Configure event, but it's rather messy for 
such a simple-seeming thing. (The really aggravating part is that perl 
can do this directly because it uses C instead of tcl to talk to tk, and 
tk's C interface is more flexible about setting toplevel geometry!).

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


Re: Project organization and import

2007-03-06 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Martin Unsal [EMAIL PROTECTED] wrote:

 I'm using Python for what is becoming a sizeable project and I'm
 already running into problems organizing code and importing packages.
 I feel like the Python package system, in particular the isomorphism
 between filesystem and namespace, doesn't seem very well suited for
 big projects. However, I might not really understand the Pythonic way.
 I'm not sure if I have a specific question here, just a general plea
 for advice.
 
 1) Namespace. Python wants my namespace heirarchy to match my
 filesystem heirarchy. I find that a well organized filesystem
 heirarchy for a nontrivial project will be totally unwieldy as a
 namespace. I'm either forced to use long namespace prefixes, or I'm
 forced to use from foo import * and __all__, which has its own set
 of problems.

 1a) Module/class collision. I like to use the primary class in a file
 as the name of the file. However this can lead to namespace collisions
 between the module name and the class name. Also it means that I'm
 going to be stuck with the odious and wasteful syntax foo.foo
 everywhere, or forced to use from foo import *.

The issue of module names vs contained class names is one thing I find a 
bit frustrating about python. Fortunately it is fairly easy to work 
around.

My own solution has been to import up just one level. So for example:
pkg/subpkg/foo.py defines class foo and associated stuff
pkg/subpkg/bar.py defines class bar
pkt/subpkg/__init__.py contains:

from foo import *
from bar import *

To use this I then do:
import pkg.subpkg
myfoo = pkg.subpkg.foo(...)

But that's the only from x import that I do. I never raise stuff from 
a sub-package to a higher level.

Once you do this (or in some other way eliminate the foo.foo problem), I 
think you will find that python namespaces work very well for large 
projects.

Overall I personally like having the namespace follow the file structure 
(given that one has to use source files in the first place; my smalltalk 
roots are showing). Java reportedly does much the same thing and it is 
very helpful for finding code.

I'm sure it's partly what you're used to that counts. C++ experts 
probably enjoy the freedom of C++ namespaces, but to me it's just a pain 
that they are totally independent of file structure.

 1b) The Pythonic way seems to be to put more stuff in one file, but I
 believe this is categorically the wrong thing to do in large projects.
 The moment you have more than one developer along with a revision
 control system, you're going to want files to contain the smallest
 practical functional blocks. I feel pretty confident saying that put
 more stuff in one file is the wrong answer, even if it is the
 Pythonic answer.

I don't personally find that python encourages lots of code per file. I 
think this perception only stems from (1a) and once you solve that 
you'll find it's fine to divide your code into small files.

 2) Importing and reloading. I want to be able to reload changes
 without exiting the interpreter. This pretty much excludes from foo
 import *, unless you resort to this sort of hack:
 
 http://www.python.org/search/hypermail/python-1993/0448.html
 
 Has anyone found a systematic way to solve the problem of reloading in
 an interactive interpreter when using from foo import *?

I totally agree here. This is a real weakness to python and makes it 
feel much more static than it ought to be. I know of no solution other 
than restarting. That tends to be fast, but it can be a pain to get back 
to where you were.

Smalltalk solved this problem long ago in a way that makes for very 
dynamic development and debugging. Unfortunately few languages have 
followed suit. The Smalltalk development environment is the one feature 
I really miss in all other languages I've used (I certainly don't miss 
its quirky syntax for control flow :)).

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


Re: Project organization and import

2007-03-06 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Martin Unsal [EMAIL PROTECTED] wrote:

 On Mar 6, 9:34 am, Chris Mellon [EMAIL PROTECTED] wrote:
  It assumes that util.common is a module thats on the PYTHONPATH.
 
 Now we're getting somewhere. :)
 
  The common way to ensure that this is the case is either to handle
  util as a separate project, and install it into the system
  site-packages just as you would any third party package,
 
 This breaks if you ever need to test more than one branch of the same
 code base. I use a release branch and a development branch. Only the
 release branch goes into site-packages, but obviously I do most of my
 work in the development branch.

This is an interesting point that we are just facing. If you have a big 
package for all your stuff and you want to separately version components 
of it, you do run into problems. The solution we are adopting is to 
write a custom import hook, but a simpler solution is to make sure each 
separately versioned component is a top-level package (in which case you 
can manipulate PYTHONPATH to temporarily install a test version).

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


Re: Converting a c array to python list

2007-03-02 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 zefciu [EMAIL PROTECTED] wrote:

 Hi!
 
 I want to embed a function in my python application, that creates a
 two-dimensional array of integers and passes it as a list (preferably a
 list of lists, but that is not necessary, as the python function knows
 the dimensions of this array).  As I read the reference, I see, that I
 must first initialize a list object and then item-by-item put the values
 to the list.  Is there any faster way to do it?  And is it worth to
 implement?  The same problem is resolved in the current version by
 calling a smaller c function (that counts just one element of the array)
 many times.  Will it add much performance to the process?

My first thought is to use the numpy library since it is good at quickly 
creating large arrays (of any dimension) and you can easily get the data 
out as a list if you really need that (but are you sure you need that? 
You may be able to just use the numpy array directly).

It might help to have a clearer idea of why you want to do this. 

-- Russell

P.S. numarray or Numeric would also do the job. They are older, 
deprecated numeric libraries. numpy is recommended for new code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: setting up wxPython on a Mac

2006-11-03 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Kevin Walzer [EMAIL PROTECTED] wrote:

Brian Blais wrote:
I'm not sure about numpy/scipy/matplotlib. I don't think there are
pre-built packages for them; you may have to build them from source. You
could also post to the MacPython mailing list, someone there has
probably looked at this already.

There are prebuilt extension for these for Python 2.4.x available from 
http://pythonmac.org/packages/. Packages for 2.5 will show up 
eventually, but meanwhile if you want prebuilt then use python 2.4.4.

For python itself, I recommend using the Mac installer available from 
the standard python web site (rather than the package available from 
http://pythonmac.org/packages/).

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


Re: Python/Tkinter crash.

2006-10-04 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Hendrik van Rooyen [EMAIL PROTECTED] wrote:

Hi,

I get the following:

[EMAIL PROTECTED]:~/Controller/lib python display.py
UpdateStringProc should not be invoked for type font
Aborted
...
Everything seems to work fine. - there is a thread that runs to move the meter
values around continuously, and this has been stable for some time now, and I
can get the various machine parts to move around the screen by pushing the
buttons...

You mention threads several times in your posting. Do you have multiple 
threads talking to Tkinter? If so, try recoding to avoid this (e.g. by 
having the background threads communicate with the main thread via 
Queues).

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


py2app question: Resources/Python - Resources/lib/python2.4

2006-09-08 Thread Russell E. Owen
I was using an older version of py2app to distribute an application.
This placed the python library code in TUI.app/Contents/Resources/Python

I just upgraded to py2app 0.3.5 and now I find the same stuff is being 
put in TUI.app/Contents/Resources/lib/python2.4

This change breaks my code because resource files need to go in the same 
location, though I can certainly modify the code that copies the 
resource files.

My main question is: am I seeing this change because I'm doing something 
wrong (in which case I'd like to fix it)? Or is it just the new way to 
do things (in which case I can modify my resource copying code)?

If it's the new way to do things, is there a recommended way to find 
this directory automatically (or copy directory trees of files into it 
automatically without knowing its name) -- to insulate myself against 
future such changes?

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


Re: Database access through python using GUI(Tkinter)

2006-06-29 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 arvind [EMAIL PROTECTED] wrote:

 hi all,
 i am accessing  sql+  database through python 2.4.3.
 i am using Tkinter to build my screens.
 how can i pass parameters on the click event of button from one
 function to the another?

What do you mean by this? If you mean clicking a button runs one 
function and passes params to another, write a parent function:

def doit():
   results = func1(...)
   funct2(results)
btn = Tkinter.Button(..., command=doit)

 how can i run another file from current file?

What kind of file? If you mean a command-line executable, see the 
subprocess module (new in python 2.4 but backwards compatible with 2.3 
and worth using).

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


Re: PEP 3102 for review and comment

2006-05-22 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Talin [EMAIL PROTECTED] wrote:

 (Note: PEPs in the 3xxx number range are intended for Python 3000,
 however this particular PEP may be backported if there is support for
 it.)
 
 PEP: 3102
 Title: Keyword-Only Arguments
...
 Syntactically, the proposed changes are fairly simple.  The first
 change is to allow regular arguments to appear after a varargs
 argument:
 
 def sortwords(*wordlist, case_sensitive=False):
...
 
 This function accepts any number of positional arguments, and it
 also accepts a keyword option called 'case_sensitive'.  This
 option will never be filled in by a positional argument, but
 must be explicitly specified by name.

The following is a 2nd syntactical change, and I strongly suggest 
listing it as such (since the first change can be made without this 
change):

 Keyword-only arguments are not required to have a default value.
 Since Python requires that all arguments be bound to a value,
 and since the only way to bind a value to a keyword-only argument
 is via keyword, such arguments are therefore 'required keyword'
 arguments.  Such arguments must be supplied by the caller, and
 they must be supplied via keyword.

...making this the third syntactical change:

 The second syntactical change is to allow the argument name to
 be omitted for a varargs argument. The meaning of this is to
 allow for keyword-only arguments for functions that would not
 otherwise take a varargs argument:
 
 def compare(a, b, *, key=None):

Personally, my feelings are:

+1 on allowing keyword arguments after *args. I have long wanted this 
and feel it is:
- very useful (the alternative of abusing **kargs is ugly and doesn't 
support introspection)
- an obvious and clear extension of current notation
- removes an awkward limitation of current notation

-1 on allowing keywords without values because:
- if it is added, then it means something like the last change is 
required, and as I say next, I don't like it
- why bother? it just makes work for the caller

-1 on the use of * to mean a separator between positional args and 
keyword-only args because:
- I think proposed syntax is confusing (there are more arguments in the 
argument list than the function accepts; yecch!!!) and hard to read
- I don't think the added functionality is important enough to justify 
the awkward notation

If folks are desperate enough for this last feature then please at least 
find a clearer notation. For example:
  def compare(a, b | key=None):
but personally I'd rather skip it.

Now if somebody could figure out a natural notation for boolean flags, 
*that'd* be useful (where the presence, absence or explicit negation of 
a keyword is all that is required to enable or disable a feature).

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


Re: PEP-xxx: Unification of for statement and list-comp syntax

2006-05-22 Thread Russell E. Owen
+1 It does seem like a natural unificiation of the language -- one less 
exception to learn.

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


Re: Tkinter problem on Mac OS X

2006-04-10 Thread Russell E. Owen
In article 
[EMAIL PROTECTED],
 [EMAIL PROTECTED] (Andrew Trevorrow) wrote:

 Our app uses embedded Python to allow users to run arbitrary scripts.
 Scripts that import Tkinter run fine on Windows, but on Mac OS X there
 is a serious problem.  After a script does root = Tk() our app's menus
 are permanently changed in the following way:
 
 - The top item in the application menu changes to About Tcl  Tk
 - The Quit item is disabled.
 - The File and Edit menus are completely replaced.
 - All further menus (except Help) are removed.
 
 Is there a way to prevent Tkinter clobbering our app's menus?
 Or perhaps a way to restore them after the root.mainloop() call?
 
 I've read Fredrik Lundh's excellent tutorial on Tkinter and done a lot
 of googling but haven't been able to find a solution.
 
 I can probably add some Mac-specific code to detect a menu change after
 a script ends and then rebuild our menus, but I'm hoping there's a
 simpler Tkinter (or Tcl?) solution.

I am pretty sure it's the underlying Tcl/Tk that's causing you grief.

Does your application itself use Tcl/Tk anywhere? I'm guessing not, as 
I'd expect you'd already have gone to some trouble to get the menus 
right.

Unfortunately, I can't offer a solution. You may want to post to the 
Tkinter mailing list (via news you can use gmane, group 
gmane.comp.python.tkinter; I'm not sure if you have to sign up for the 
list before posting).

You could import Tcl/Tk yourself up front and then fix your 
application's menus once. But Aqua Tcl/Tk is painfully slow to start up, 
so this could really slow down startup of your own application. (Note 
that you'd have to be prepared for Tkinter to be missing (it certainly 
is by default on 10.3). You might also have to make users use one 
mainloop (see next paragraph) for this to work.

James Stroud also brings up an interesting point--that it could be 
dangerous if there are multiple scripts each trying to run their own 
mainloop. But if only one runs at a time, and cleans up after itself, 
you're probably OK. If that's not the case, you may want to start a Tk 
main loop yourself and ask users to use that loop. Again, though--it'll 
take time, and it'll only help those users who use Tkinter in their 
scripts.

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


Re: Problem w/Tkinter on 2.5 (Panther)

2006-03-29 Thread Russell E. Owen
I don't know, and I'm sorry this isn't more helpful, but...if you don't 
get an answer here, I suggest you post to the python apple mailing list. 
If you prefer a newsgroup interface (as I do), use gmane's news server 
and subscribe to gmane.comp.python.apple (you may still have to join the 
mailing list to post -- I'm not sure -- but if so, you can disable mail 
delivery).

-- Russell

In article [EMAIL PROTECTED],
 w chun [EMAIL PROTECTED] wrote:

 i've built a Python 2.5a0 interpreter on my iBook using gcc 3.3-1666
 using the tarball from last nite..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I test if an argument is a sequence or a scalar?

2006-01-11 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] wrote:

I want to be able to pass a sequence (tuple, or list) of objects to a
function, or only one.

It's easy enough to do:

isinstance(var, (tuple, list))

But I would also like to accept generators. How can I do this?

Anything else is assumed to be a single value (my fault if I pass a
dict or something else to the function) and I make it into a tuple with
a single value (var, ) in order to simplify the algorithm (wasn't there
a special name for a one item tuple? Its been a while since I've
programmed in Python.)

Is there an easy way to do that?

Here is the code I use for that purpose, but it does not handle 
generators or iterators. You could easily combine this with code 
suggested in other replies to accomplish that. (I intentionally excluded 
iterators because I didn't need them and they can be unbounded. Still, 
now that they are so widely used it may be worth reconsidering.)

def isSequence(item):
Return True if the input is a non-string sequential collection,
False otherwise. Note: dicts and sets are not sequential.

try:
item[0:0]
except (AttributeError, TypeError):
return False
return not isString(item)

def isString(item):
Return True if the input is a string-like sequence.
Strings include str, unicode and UserString objects.

From Python Cookbook, 2nd ed.

return isinstance(item, (basestring, UserString.UserString))

def asSequence(item):
Converts one or more items to a sequence,
If item is already a non-string-like sequence, returns it unchanged,
else returns [item].

if isSequence(item):
return item
else:
return [item]

I then use asSequence on each argument that can either be one item or a 
sequence of items (so I can always work on a sequence).

-- Russell

P.S. this code is from RO.SeqUtil 
http://www.astro.washington.edu/rowen/ROPython.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Any wing2.0 users here?

2006-01-03 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Alvin A. Delagon [EMAIL PROTECTED] wrote:

Thanks for all the recommendations! I took a look on wingide2.0 on my 
linux box and it seems pretty good and has a lot of nifty features 
(which is pretty daunting to use since I've been programming with no IDE 
at all) and it debugger work pretty well but for a price tag of $179 I 
think it not worth it.

I've tried various IDEs and like WingIDE by far the best. It is easy to 
use, robust and has great support. The improved productivity is well 
worth the price (especially if your work is buying it for you). I 
qualified for a free license, but would certainly have had my job pay 
for it otherwise. I was tempted to buy it anyway, but felt it would be 
unethical to my employer.

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


Re: Which Python web framework is most like Ruby on Rails?

2005-12-20 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Benji York [EMAIL PROTECTED] wrote:

Russell E. Owen wrote:
 I disagree. Once you've picked a database (not trivial in itself, of 
 course), you typically only have a few options for talking to in in 
 Python.

Perhaps it's off-topic for this thread, but I think picking a database 
is the first mistake most people make.  It's a form of premature 
optimization.

I just wanted to point out that I was responding to somebody who 
complained that the database interface situation on python was somewhat 
fragmented.

Also, when I was looking at web frameworks, I was doing so *precisely* 
to serve one or more databases of information (read only to the users, 
but occasionally loaded with more info as it became available). So it 
happened to be the first question I asked (at the same time as and how 
do I talk to it?).

Anyway, you did warn that your message was possibly off-topic, so I 
guess I'm agreeing with you and perhaps being overly defensive. It was 
an interesting message.

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


Re: Which Python web framework is most like Ruby on Rails?

2005-12-19 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Paul Rubin http://[EMAIL PROTECTED] wrote:

[EMAIL PROTECTED] (Alex Martelli) writes:
 To put it another way: one reason I love Python is that I strongly
 subscribe to the idea that there should preferably be only one obvious
 way to do something.  Unfortunately, this principle is very badly broken
 by the multiplicity of Python web frameworks.

This also has to be a big part of why PHP is kicking the pants off of
Python for popularity in web development.

I agree. It's sad to see such a terrible language as PHP so popular, and 
such a complicated mess in python, my language of choice.

I love python and am lucky enough to be able to do almost all my coding 
in it. Yet even I use PHP to serve a database. I loathe PHP, but:
- it came preinstalled on my system (MacOS X 10.3.x).
- I found a nice simple intro to it (a quickstart guide, which taught me 
all I needed to know for my simple needs).
- I started out by looking at the choices in python. Of course. I read 
the shootout. I asked for help. But the results were utterly 
overwhelming.

I wanted (and I am guessing this isn't too far off for most users -- at 
least most non-web-gurus) a framework that was:
- Well designed, robust, finished (i.e. not alpha).
- Easy to use, especially for simple, basic tasks. (And not a toy, of 
course -- powerful enough to handle reasonable traffic and tasks.)
- Easy to install.
- Well documented, with a good introduction or tutorial.
- Likely to be around for awhile. The plethora of options on Python do 
NOT inspire confidence in that area.

Some choice is good -- especially if the choices solve obviously 
different problems. But too much choice is paralyzing and fragments the 
community.

Anyway, thanks for holding this discussion. Django and TurboGears were 
both new to me. I hope something finally gets popular enough to be worth 
betting on.

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


Re: Which Python web framework is most like Ruby on Rails?

2005-12-19 Thread Russell E. Owen
In article [EMAIL PROTECTED], Mike Meyer [EMAIL PROTECTED] 
wrote:

Ben Sizer [EMAIL PROTECTED] writes:
 I see what you mean, but unfortunately I think there is a lot more
 fuzziness than that. If the separate parts were clearly delineated
 things would be a lot better. I look to the Database API Specification
 as a great example of how this could (should?) be done, allowing for
 easy interchangeability while still providing a well-documented
 standard

Constant queries on c.l.python for Which DB module should I use
would indicate that having a standard and to many choices isn't really
better than having no standard and to many choices.

I disagree. Once you've picked a database (not trivial in itself, of 
course), you typically only have a few options for talking to in in 
Python. Also, typically either:
- One stands out (because others have been abandoned or whatever), so 
there's an easy answer, or
- They all work about the same, so even if you decide to switch for some 
reason it makes little difference.

SQLObject breaks that mold, but for excellent reasons. It's nice to 
start from a standard and then maybe somebody figures out a really nifty 
way to do things. (I haven't used SQLObject yet, but I plan to try it 
out when things calm down a bit).

If we had a standard basic web framework or a standard template language 
it would really help (more folks using it, more folks who can help folks 
learning it, better documentation, more focused development). Something 
better might come along, and then it'd be easier to evaluate and more 
appreciated.

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


Re: A Tcl/Tk programmer learns Python--any advice?

2005-11-08 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Kevin Walzer [EMAIL PROTECTED] wrote:

I'm a Tcl/Tk developer who has been dabbling with Python for some time,...
Well, I have finally found a good reason to learn Python in more depth:...

Any advice, particularly from other programmers with a lot of experience
in Tcl, is appreciated.

In Tkinter you don't name widgets to specify their hierarchy; instead 
when you create a new widget you specify it's parent. A tk name does get 
generated for you, but you'll never need it.

You can set and get properties on Tkinter widgets using dictionary 
notation:
curr_value = wdg[property_name]
wdg[property_name] = new_value
this is very convenient if you don't want to set a lot of properties at 
once.

Grid in Tkinter has less useful defaults than in tk. You should probably 
specify row and column when using Tkinter's gridder.

If you try to mix tk and Tkinter, beware of Tkinter objects that clean 
up after themselves. For instance a tkFont.Font object represents a 
named font in tk, but if you lose all references to it in python, the 
named font in tk is destroyed.

Features of Python that are well integrated and well worth using include:
- objects
- collection classes (including list, dict and set)
- exception handling
- default arguments for functions

tcl is a unusual in its desire to parse every string as a command. It 
has plusses and minuses, but in any case, you'll have to learn to do 
without (as you would when switching to almost any other language).

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


[Ann] RO package 2005-10-31

2005-10-31 Thread Russell E. Owen
RO package 2005-10-31 is now available from
http://www.astro.washington.edu/rowen/ROPython.html

What is it?
A package of python utilities I wrote to support a telescope control 
interface. RO has a strong emphasis on the Tkinter GUI library, 
networking, astronomy and cross-platform support (unix, MacOS X and 
Windows). For more information, follow the link above.

Changes include:
- RO.DS9 is smarter about finding ds9 and xpa and can now handle 
byteswapped arrays.
- RO.Prefs now can map old pref names to new (allowing one to migrate a 
preference name).

For a full version history see:
http://www.astro.washington.edu/rowen/ROVersionHistory.html

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


Re: Tkinter or Python issue?

2005-10-19 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Eric Brunel [EMAIL PROTECTED] wrote:

You should now see why it works here: your first tkFont.Font is remembered at 
Python level in a variable. So it is not discarded once the tag_config is 
over. So the second tkFont.Font is not allocated at the same location, so it 
doesn't have the same id, and it doesn't have the same name at tcl level. This 
is the general solution to the problem: keep your fonts in Python variables, 
so they won't be discarded and their names will never be re-used.

Yes. I consider this dangerous behavior, by the way and submitted a 
patch (that was not accepted) that would prevent this garbage collection.

tkFont is Tkinter's interface to tk named fonts. If you create a tkFont 
instance for a named font and then let it disappear, the named font 
disappears, even if other tkFont instances exist that map the same named 
font.

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


Re: How to get a unique id for bound methods?

2005-08-24 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Fredrik Lundh [EMAIL PROTECTED] wrote:

Russell E. Owen wrote:

 Having looked at it again, it is familiar. I copied it when I wrote my
 own code. I avoided using at the time both because the initial
 underscore suggested it was a private method and because it introduces
 an extra function call.

 _register has the same weakness that my code had when I used id(func) -- 
 it uses the id of the function to generate the unique tk function name,
 but it keeps no reference to that function.

 Either Tkinter is clever about keeping a reference to each callable
 around, or else it has the same bug I was seeing and it just doesn't
 show up often enough to have been caught. I should take some time and
 look into that.

of course it keeps a reference to it; how else do you expect
the Tcl command to find the right PyObjects?

Right. Of course.

I started out emulating the code for _register but over time made 
various incremental changes. Eventually I messed up and started taking 
the id of the wrong thing. I was able to fix that and all is well -- 
without having to use the mysterious hash function.

I also now keep a reference to the tk function name so I can properly 
delete it when finished. That eliminates a small memory leak.

Thanks for all your help.

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


Re: High Level FTP library

2005-08-23 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Paulo Pinto [EMAIL PROTECTED] wrote:

Hello,

Is there any Python library similar to NET::FTP from Perl?
ftplib seems too lowlevel.

I already found a few, but would like to get one that is
endorsed by the community.

Try urllib or urllib2; these are included with python. urllib2 is newer 
but only works for anonymous ftp. Caveat: I ran into trouble doing 
multiple simultaneous ftp using urllib. I have not used urllib2.

Another possibility is Twisted Framework. It has a bit of a learning 
curve but is well regarded. If you plan to do a lot with networking you 
should definitely check it out.

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


Re: How to get a unique id for bound methods?

2005-08-23 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Fredrik Lundh [EMAIL PROTECTED] wrote:

Russell E. Owen wrote:

The current issue is associated with Tkinter. I'm trying to create a tk
callback function that calls a python function (any python callable
entity).

To do that, I have to create a name for tk that is unique to my python
function. A hash-like name would be perfect, meaning a name that is
always the same for a particular python function and always different
for a different python function. That would save a lot of housekeeping.

have you tried Tkinter's built-in _register method?

 import Tkinter
 w = Tkinter.Tk()
 help(w._register)
Help on method _register in module Tkinter:

_register(self, func, subst=None, needcleanup=1) method of Tkinter.Tk 
instance
Return a newly created Tcl function. If this
function is called, the Python function FUNC will
be executed. An optional function SUBST can
be given which will be executed before FUNC.

Thanks. That looks like just the thing. I think I had seen it but was 
deterred by the leading underscore (suggesting an internal method whose 
interface might change). Still, I guess if it gets modified I can just 
change my code.

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


Re: How to get a unique id for bound methods?

2005-08-23 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Fredrik Lundh [EMAIL PROTECTED] wrote:

Russell E. Owen wrote:

The current issue is associated with Tkinter. I'm trying to create a tk
callback function that calls a python function (any python callable
entity).

To do that, I have to create a name for tk that is unique to my python
function. A hash-like name would be perfect, meaning a name that is
always the same for a particular python function and always different
for a different python function. That would save a lot of housekeeping.

have you tried Tkinter's built-in _register method?

 import Tkinter
 w = Tkinter.Tk()
 help(w._register)
Help on method _register in module Tkinter:

_register(self, func, subst=None, needcleanup=1) method of Tkinter.Tk 
instance
Return a newly created Tcl function. If this
function is called, the Python function FUNC will
be executed. An optional function SUBST can
be given which will be executed before FUNC.

Having looked at it again, it is familiar. I copied it when I wrote my 
own code. I avoided using at the time both because the initial 
underscore suggested it was a private method and because it introduces 
an extra function call.

_register has the same weakness that my code had when I used id(func) -- 
it uses the id of the function to generate the unique tk function name, 
but it keeps no reference to that function.

Either Tkinter is clever about keeping a reference to each callable 
around, or else it has the same bug I was seeing and it just doesn't 
show up often enough to have been caught. I should take some time and 
look into that.

It's a frustrating problem. There should be some simple way to get a 
unique hash-like identifier for any callable entity. If one were just 
using functions then id() would be fine. But bound methods are too 
different.

I'll use hash for now, but given that Im not sure what hash is even 
doing, I should recode to something that I know works.

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


Re: Sorta noob question - file vs. open?

2005-08-23 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Peter A. Schott [EMAIL PROTECTED] wrote:

Been reading the docs saying that file should replace open in our code, but 
this
doesn't seem to work:

# Open file for writing, write something, close file
MyFile = file(MyFile.txt, w)
MyFile.write(This is a test.)
MyFile.close()

This should work in a sufficiently recent version of python (I'm hedging 
because I don't recall when file was introduced -- python 2.2? 2.3?). 
What version are you using? What error do you see?

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


Re: How to get a unique id for bound methods?

2005-08-22 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] (Bengt Richter) wrote:

On Fri, 19 Aug 2005 16:33:22 -0700, Russell E. Owen [EMAIL PROTECTED] 
wrote:
[...]

The current issue is associated with Tkinter. I'm trying to create a tk 
callback function that calls a python function (any python callable 
entity).

To do that, I have to create a name for tk that is unique to my python 
function. A hash-like name would be perfect, meaning a name that is 
always the same for a particular python function and always different 
for a different python function. That would save a lot of housekeeping.

Why do you need a name? Can you post an example snippet that shows
a callback function being used with Tkinter as you would wish?
I have a feeling there is a much simpler solution than you are imagining ;-)

Here is an example (simplified from my real code; I may have introduced 
an error in the process). I could switch to the twisted framework, but 
this code has been working very well and it saves my users from having 
to install a 3rd party package.

-- Russell

def addTkCallback(tk, func):
tkName = cb%d % hash(func)
tk.createcommand(tkNname, func)
return tkName

class TkSocket(TkBaseSocket):
def __init__(self,
addr,
port,
binary=False,
readCallback = None,
stateCallback = None,
tkSock = None,
):
...
try:
# create the socket and configure it
self._sock = self._tk.call(socket, ...)
self._tk.call(fconfigure, self._sock, ...)

# add callbacks; the write callback is just used to detect 
state
readName =addTkCallback(self._tk, self._doRead)
self._tk.call('fileevent', self._sock, readable,
readName)
connName = addTkCallback(self._tk, self._doConnect)
self._tk.call('fileevent', self._sock, writable, connName
except Tkinter.TclError, e:
raise RuntimeError(e)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get a unique id for bound methods?

2005-08-19 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Benji York [EMAIL PROTECTED] wrote:

Russell E. Owen wrote:
 The id of two different methods of the same object seems to be the 
 same, and it may not be stable either.

Two facts you're (apparently) unaware of are conspiring against you:

1) the id of an object is consistent for the lifetime of the object, 
but may be reused after the object goes away

2) methods are bound on an as-needed basis and then normally discarded 
(unless you do something to keep them around)

Thank you and Bengt Richter. You both explained it very well.

The current issue is associated with Tkinter. I'm trying to create a tk 
callback function that calls a python function (any python callable 
entity).

To do that, I have to create a name for tk that is unique to my python 
function. A hash-like name would be perfect, meaning a name that is 
always the same for a particular python function and always different 
for a different python function. That would save a lot of housekeeping.

Does the built-in hash function actually do the job?

If I centralize all tk callback management and keep objects that 
represent the tk callback around then I can avoid the whole issue. I was 
hoping to avoid that, because it complicates housekeeping and adds a 
risk of memory leaks (at least I think so; right now tk deallocates its 
callback functions in the few cases I care about so I don't worry about 
it.)

-- Russell

P.S. Paolino: thank you also for your kind reply. Your suggestion sounds 
very useful if I only want a hash for a bound function, but in this case 
since I want a hash for any callable entity I'm not sure it'll work.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter puzzler

2005-05-16 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Paul Rubin http://[EMAIL PROTECTED] wrote:

Martin Franklin [EMAIL PROTECTED] writes:
 I suspect you need to look at the columnconfigure / rowconfigure methods
 of the container (toplevel or frame)

Thanks, columnconfigure turned out to be the answer and Peter Otten's
post showing how to use it was very informative.  For some reason
columnconfigure is not documented in the otherwise excellent tkinter
reference manual from New Mexico Tech.

I'm having sort of a different prob now, which is I want to make a
pulldown menu as commonly seen on web pages.  The NMT reference
suggests using the MenuButton widget, which sort of works, though the
entrycget and entryconfigure methods that are supposedly on the menu
items aren't really there.  The toolkit itself says that MenuButton is
now considered obsolete and Frederik Lundh's manual seems to say
to use Menu somehow instead, but I haven't quite figured out how.

MenuButton is (as far as I know) the recommended way to do this
(and I've been puzzled by F. Lendh's assertion that they are
obsolete). The basics are:

  mbut = Tkinter.Menubutton.(master, text=MyMenu, inicatoron=True)
  mnu = Tkinter.Menu(mbut, tearoff=False)
  mbut[menu] = mnu

where indicatoron=True gives you the this is a pop-up menu indicator 
icon. The circular reference is icky but appears to be necessary (i.e. 
having the menubutton be a parent to the menu and the menu attribute of 
the menubutton point to the menu).

I suggest you buy Grayson's Python and Tkinter Programming
(it has a very useful reference section in the back, though 
unfortunately it is somewhat incomplete). For more serious work you'll 
also want Welch's Practical Programming in Tcl and Tk (lots of good 
details about Tk).

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


Re: tkinter puzzler

2005-05-12 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Paul Rubin http://[EMAIL PROTECTED] wrote:

I have a gui with a bunch of buttons, labels, the usual stuff.  It
uses the grid manager:

   gui = Frame()
   gui.grid()
   gui.Label().grid()  # put some widgets into the gui
   ...# more widgets

Now at the the very bottom of the gui, I want to add two more buttons,
let's say stop and go.  I want stop to appear in the gui's lower
left corner and go to appear in the gui's lower right corner.
Suppose that up to now, row 16 is the last row in the gui.  Then this
works:

Button(gui, text=stop).grid(sticky=W)   # starts row 17
Button(gui, text=go).grid(row=17, column=1, sticky=E)

But I don't really want that hardwired row number and I don't want to
keep counting rows and adjusting stuff if I stick new rows in the gui.

A couple of options here:
- Put the main portion of the gui into one frame and pack or grid the 
button frame below that. That sounds like a natural solution to this 
problem based on the way you describe it. (if you do that, I suggest 
packing the buttons into their frame; although I usually use the gridder 
when in doubt, the packer is often the most natural layout manager for a 
row of buttons).

- Increment as you go:
   row = 0

   wdg.grid(row=row, column=0, ...)
   row += 1

   wdg2.grid(row=row, column=0, ...)
   row += 1

- If you are doing a lot of similar layout, it is worth creating a class 
to do your gridding for you. Each instance grids widgets in a particular 
frame. It keeps  track of the row # for you. For use an existing 
gridder, for instance RO.Wdg.Gridder in the RO package 
http://astro.washington.edu/rowen.


So I try the obvious, make one Frame widget containing both new buttons:
stopgo = Frame(gui)
Button(stopgo, stop).grid(sticky=W)
Button(stopgo, go).grid(sticky=E)

and try to stretch it across the bottom row of the gui:

stopgo.grid(sticky=E+W)

This looks OK to me so I'm not sure what's wrong; I think I'd have to 
see your actual code. I suggest examining the size of the stopgo frame 
by setting its background color.

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


Fast plotting?

2005-04-26 Thread Russell E. Owen
Can anyone recommend a fast cross-platform plotting package for 2-D 
plots?

Our situation:
We are driving an instrument that outputs data at 20Hz. Control is via 
an existing Tkinter application (which is being extended for this new 
instrument) that runs on unix, mac and windows. We wish to update 5-10 
summary plots at approximately 2 Hz and will be offering controls to 
control the instrument and the plots, preferably (but not necessarily) 
mixed in with the plots.

Ideally the package would create plots in the Tkinter application. But 
we realize we're unlikely to get the speed we need that way. So we are 
willing to have the Tkinter app send data to the plotting package  (e.g. 
via a socket) and have it display the plots in a separate process.

We started out with matplotlib, which is a wonderful package (and well 
integrated with most or all GUI toolkits). Unfortunately it is just too 
slow -- at least when driving plots integrated with the Tkinter app. (It  
is getting faster and so are computers, so at some point this will be a 
great way to go. But for now...)

Any suggestions?

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


Re: How to define a window's position (Tkinter)

2005-02-28 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Harlin Seritt [EMAIL PROTECTED] wrote:

I am trying to use the geometry() method with the toplevel window
called root. I know that one can do the following:

root.geometry('400x400+200+200')

This will put the window in 200, 200 position with a size of 400x400.
Now, I don't really want to set the size. I simply want to set the
position of the window. I've tried this:

root.geometry('200+200')

However, this doesn't seem to work. What can I do to set the position
of the window without actually setting the size?

You were almost there, but you need an initial +:
root.geometry(+200+200).

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


Re: tkinter socket client ?

2005-01-25 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Tonino [EMAIL PROTECTED] wrote:

thanks for this info - I had to abandon the createfilehandler() method
as it is not supported in windows and the GUI might be used there at
some time ...

So - I went the threading route - works well - for now - so I will
stick to it ...

BUT - the next question:
In the Text() widget - why - when the text scrolls off the screen -
does the window not follow it ?

I have added a scrollbar to it :

self.center_frame = Frame(self.top_frame, background=tan,
relief=RIDGE)

self.text=Text(self.center_frame,background='white')
scroll=Scrollbar(self.center_frame)
self.text.configure(yscrollcommand=scroll.set)

self.text.pack(side=LEFT, fill=BOTH, expand=YES)
scroll.pack(side=RIGHT,fill=Y)
self.center_frame.pack(side=RIGHT, expand=YES, fill=BOTH)


but the window does not scroll to follow the text ?
Any ideas ?

That's just how it works. But when you append text you can easily tell 
the text widget to display it, e.g. using see. Here is the code I use 
(from RO.Wdg.LogWdg.py), which has these useful features:
- auto-scrolls only if the user is already scrolled to the of text (so 
if a user is staring at some older data, it won't be jerked out from 
under them)
- deletes excess text.

def addOutput(self, astr, category=None):
Add a line of data to the log.

Inputs:
- astr: the string to append. If you want a newline, specify the \n 
yourself.
- category: name of category or None if no category

# set auto-scroll flag true if scrollbar is at end
# there are two cases that indicate auto-scrolling is wanted:
# scrollPos[1] = 1.0: scrolled to end
# scrollPos[1] = scrollPos[0]: window has not yet been painted
scrollPos = self.yscroll.get()
doAutoScroll = scrollPos[1] == 1.0 or scrollPos[0] == scrollPos[1]
if category:
self.text.insert(end, astr, (category,))
else:
self.text.insert(end, astr)
extraLines = int(float(self.text.index(end)) - self.maxLineIndex)
if extraLines  0:
self.text.delete(1.0, str(extraLines) + .0)
if doAutoScroll:
self.text.see(end)

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


Re: Configuring Python for Tk on Mac

2005-01-24 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] (Martyn Quick) wrote:

On my desk here at work I have a Mac G4 running Mac OS X v10.2.8.

When I go into a terminal and type python up comes a nice python
interface and all seems great.  However when I type import Tkinter
I'm greeted by the following error

Assuming you are running MacPython from 
http://homepages.cwi.nl/~jack/macpython/macpython-osx.html...

Install Aqua Tcl/Tk as another poster suggested.

Run Applications/MacPython.../Package Manager and install Tkinter.

Or if your MacPython is out of date, you may just want to download and 
install the current version. If Tcl/Tk is already installed then I think 
it will install Tkinter automatically (but if not, use Package Manager).

If you are running some other python, please tell us more about it. (If 
it's fink python, install the version that includes Tkinter support, but 
this runs on X11 instead of Aqua).

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


Re: tkinter socket client ?

2005-01-24 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 Tonino [EMAIL PROTECTED] wrote:

yeah - had a look at createfilehandler() - was a bit confusing - but
your example helps ;)

Be warned that createfilehandler does not work on Windows, though it 
works well on unix and MacOS X.

So my suggestion is one to try any of these (any of which are preferable 
to threads):
- file handlers for non-Windows code
- use tcl sockets for cross-platform code.
- use Twisted Framework (some work to learn, but supposedly very solid; 
I confess I've never used it myself).

There is a bit of info on the first two options (including a link to the 
RO package that includes a python interface to tcl sockets) here:

http://www.astro.washington.edu/rowen/TkinterSummary.html#FileHandlers

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


Re: what would you like to see in a 2nd edition Nutshell?

2004-12-29 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] (Alex Martelli) wrote:

I'm considering proposing to O'Reilly a 2nd edition of Python in a
Nutshell, that I'd write in 2005, essentially to cover Python 2.3 and
2.4 (the current 1st edition only covers Python up to 2.2).
...

Since you were kind enough to ask...what I'd really like is a better 
better index and better organization, so I can more quickly and easily 
locate info on a particular topic.

Nutshell has some wonderful in-depth discussions of certain topics and 
I'm glad I own it, but I find it too hard to use for everyday questions 
(which was not at all what I expected for a nutshell book). I usually 
start with the html help (if I know the module I need or have a firm 
guess as to which other manual to read) or Python Essential Reference 
(other cases), then go to Nutshell if I'm still lost or if I remember it 
has a good section on the topic of interest.

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


Re: what would you like to see in a 2nd edition Nutshell?

2004-12-29 Thread Russell E. Owen
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] (Alex Martelli) wrote:

Russell E. Owen [EMAIL PROTECTED] wrote:

 In article [EMAIL PROTECTED],
  [EMAIL PROTECTED] (Alex Martelli) wrote:
 
 I'm considering proposing to O'Reilly a 2nd edition of Python in a
 Nutshell, that I'd write in 2005, essentially to cover Python 2.3 and
 2.4 (the current 1st edition only covers Python up to 2.2).
 ...
 
 Since you were kind enough to ask...what I'd really like is a better 
 better index and better organization, so I can more quickly and easily
 locate info on a particular topic.

Thanks for the advice!  What I have now is the best organization I was
able to conceive -- and I have no current ideas on how to enhance it.
Any _suggestions_ will be truly welcome; somehow, I don't see make it
better as a _suggestion_... if I _knew_ how to organize it better, I
would, of course.

Fair enough. I was being lazy, but also wanted to be sure the input 
would be considered useful before going into details.

Here are some issues for me:

* A mini table of contents for each major section would be really 
helpful. List the modules, and (if appropriate) sub-modules with maybe a 
one-liner as to what they do, and a page #.

* The discussion of the os module (p171) could especially use such a 
TOC. p171 starts with a nice, thorough explanation of os and all it 
does, but as a quick reference it is tricky; rather than jumping right 
to what I want, I have to get past a discussion of OSError an the errno 
module before any os methods are discussed, and then I have to flip 
through many pages of stuff to find the right section.

* Please cross-reference using page #s, not just chapter #s or covered 
later in this chapter. For instance the os module text refers one to 
chapter 14 for a discussion of os's handling of processes. Ouch. I 
hope that modern writing tools make page # references safe and easy.

* Some of the page breaks are awkward. I know it eats paper to fix it 
everywhere, but... for example, it'd help to have the re special 
characters table all on one page (or at least on facing pages).

* Exceptions:
- I beg you to include a ONE-PAGE table of exceptions that shows the 
inheritance hierarchy via indentation (e.g. like Python Essential 
Reference). The detailed info will probably have to follow.

Such a table is a much easier way of figuring out who inherits from who, 
and I usually find such a table sufficient (and very efficient) for 
picking out which exception to use.

Having the detailed info is much appreciated, but it's a poor substitute 
for a quick reference table.

- Some discussion of which standard modules raise errors that inheriit 
directly from Exception instead of StandardError would be helpful.

- (nit-pick) The try statement, bottom of p104. The two basic forms are 
listed, but a page # for the 2nd form would help jump there.

- Exception objects, p109. Using strings as exceptions would make a nice 
footnote instead of cluttering up the main text. They've been deprecated 
for a long time.


Also, two content requests:

* please describe the new subprocess module in gory detail and move 
discussion of the older modules which it can replace to an appendix or 
the back of the same chapter or in some other way keep it from 
cluttering up the main text. (I'm sure popen, etc. still has to be 
discussed, if only for folks dealing with older code, but subprocess is 
clearly the right way to go for new code).

* Please describe numarray instead of Numeric (or both, or discuss 
numarray and list some changes from Numeric?)


I'm looking forward to the next edition!

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