Re: stderr, stdout, and errno 24

2006-07-15 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 "Wesley Henwood" <[EMAIL PROTECTED]> wrote:

>I've checked and double checked my code and I am closing all files
>explicitly after opening them.

If you're running your program under Linux, a very easy way to confirm 
this is to look in the directory

/proc//fd

where  is the PID of your running program. In here you will see a 
symlink to every file your program has open, the name of the link being 
the file descriptor number.

To make it easier to watch, you may want to stick in a sleep of a few 
seconds in-between iterations of the code that executes the Python 
script.

If you see the entries piling up in this directory, that will confirm 
that you're not closing those files.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a limit to os.popen()?

2006-07-15 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 Steve Holden <[EMAIL PROTECTED]> wrote:

>If you are seeing alot of error messages you shoudl really redirect the 
>standard error to a file to avoid them cluttering up your console.

Surely a better technique would be to fix the errors causing the 
messages.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CPU or MB Serial number

2006-07-15 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 Sybren Stuvel <[EMAIL PROTECTED]> wrote:

>Bayazee enlightened us with:
>> How can I get CPU Serial number , or motherboard serial number with
>> python . I need an idetification of a computer 
>
>Not sure if that'll be sufficient. My serial numbers (according to
>'lshw' on Linux):

Hey, that's pretty cool, I didn't know about lshw before. It doesn't 
come with my SuSE 10.0 system, but it is available under Gentoo.

I tried on my Shuttle SN25P box, and it didn't report serial numbers for 
anything except the onboard Ethernet.

In general, the OP isn't going to get anything like a universally-usable 
serial number, apart from Ethernet MAC addresses.

By the way, lshw seems to think there's a second CPU on my box, but it's 
marked as "DISABLED" and has no capabilities. Is it really there, or 
just a figment of someone's imagination? :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: math symbols not displaying

2006-07-15 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Andrew Dabrowski
wrote:

> I'm working on a simple Python program, with Tkinter, and I need to 
> display the math symbols for set union and intersection, in unicode 
> \N{N-ARY UNION} and \N{N-ARY INTERSECTION}. Everything was displaying 
> correctly (when I ran the program) until I changed my OS distribution 
> from SuSE to Ubuntu. Now those two symbols are not being displayed. I'm 
> not getting any error messages, there are simply blank spaces where the 
> symbols should be. Any ideas what the problem could be? I'm using Gnome 
> under Ubuntu 6.06.

The glyphs have to be present in the font that is used.  Fonts that should
contain almost all mathematical characters are in the `latex-xft-fonts`
package.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python on RedHat AS 2.1?

2006-07-15 Thread Fredrik Lundh
Jeremy Winters wrote:

> Installable package?
> 
> Any ideas?

is RedHat no longer providing pre-built packages for their distributions  ?



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


Re: How can get button's name when cursor move over the button ona web page?

2006-07-15 Thread H J van Rooyen
"Steve Holden" <[EMAIL PROTECTED]> wrote:

8<(snip)-
|Questions nowadays have no idea which groups they belong to. When *I*
|was a lad questions had to know their place. A question that appeared in
||the wrong group would be torched with flames that could be guaranteed to
|burn through asbestos. But you tell these young people and they just
|don't believe you.
|
|A Yorkshireman

- You were lucky...
 - in *my* day, we did not even have fuel for flames, because we had no
internet
   We actually had to use the local library - and *horrors* - you had to learn
to read, and to solve your own queries...
   These youngsters just don't know how easy they have it...

- Hendrik van Rooyen (not a Yorkshireman)




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


PyQT installation /configuration

2006-07-15 Thread [EMAIL PROTECTED]
Hi there. I've been trying to get PyQT working on W2K, but have not yet
found a sufficiently detailed walk-through for my somewhat
command-line-challenged sensibilities. I did find this page:
http://www.diotavelli.net/PyQtWiki/GPLPyQtWindows , but I'm not sure
about installing the whole of Visual Studio .NET as a prerequisite. Can
anyone tell me if the passing of the years has made this process any
more approachable?

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


Re: PyQT installation /configuration

2006-07-15 Thread Phil Thompson
On Saturday 15 July 2006 9:25 am, [EMAIL PROTECTED] wrote:
> Hi there. I've been trying to get PyQT working on W2K, but have not yet
> found a sufficiently detailed walk-through for my somewhat
> command-line-challenged sensibilities. I did find this page:
> http://www.diotavelli.net/PyQtWiki/GPLPyQtWindows , but I'm not sure
> about installing the whole of Visual Studio .NET as a prerequisite. Can
> anyone tell me if the passing of the years has made this process any
> more approachable?

For Qt4 use the binary installer from...

http://www.trolltech.com/developer/downloads/qt/windows

For PyQt4 use the binary installer from...

http://www.riverbankcomputing.co.uk/pyqt/download.php

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


Re: attaching debugger to runinng python program

2006-07-15 Thread Nebur
You may try winpdb.
I find it to be a comfortable debugger that also can attach to running
programs. (You need to add a line in your code where the program should
stop and wait for the debugger to attach.)
I am satisfied with it, but I did not debug a multi theaded app.
However, it can handle threads. I'd be glad to later hear whether it
did what you need, or not:

http://www.digitalpeers.com/pythondebugger/threads.htm

Regards, Ruben

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


Re: Augument assignment versus regular assignment

2006-07-15 Thread Piet van Oostrum
> Gerhard Fiedler <[EMAIL PROTECTED]> (GF) wrote:

>GF> On 2006-07-14 16:07:28, Piet van Oostrum wrote:
>AP> 2a) In case you answer yes to question (1). Can you explain me how
>AP> I have to read the language reference in order to deduce this
>AP> is indeed the way things should be understood.
>>> 
>>> Just read what it says. `It is only evaluated once' is quite clear I would
>>> say. Your problem is that you thought __setitem__ is part of evaluation,
>>> but it isn't. It is part of assignment, while __getitem__ is part of
>>> evaluation. See the definitions of __getitem__ and __setitem__ in the
>>> language reference manual.

>GF> Sorry to butt in here... I really don't know much more about this than I
>GF> read in this thread :) 

>GF> But wasn't stated earlier that one of the differences between a += b and a
>GF> = a + b is that a gets evaluated once in the first case and twice in the
>GF> second case? If __getitem__ was part of the evaluation (as you seem to
>GF> say), shouldn't it be called twice in the second case? It doesn't seem to
>GF> get called twice; see this snippet from an earlier message:

> t['a'] = t['a'] + 1
>GF> __getitem__, key = a
>GF> __setitem__, key = a
> t['a'] += 1
>GF> __getitem__, key = a
>GF> __setitem__, key = a


>GF> Seems like the __get/setitem__ thing has not much to do with what the
>GF> manual calls evaluation, but rather with what the name implies: setting and
>GF> getting the value of the item. And therefore, since in both the a += b case
>GF> and the a = a + b case the value of a is gotten once and set once,
>GF> __getitem__ gets called once and __setitem__ gets called once. No?

Yes, in both cases you get the value once, and you set the value once.

In an assignment, the lefthand side is evaluated differently from the
righthand side, of course. Because in the righthand side you need the value
of the object, but in the lefthand side you need only the 'location' (this
is not a Python term).
Therefore in the righthand side __getitem__ is part of the evaluation.
In the lefthand side when it is a[i], only a and i are evaluated, but then
the evaluation stops. Next the assignment is done with __setitem__.

Now if it is an augmented assignment like a[i]+=b, It is only evaluated
once. But we need it both as a lefthand side and a righthand side. So this
means that a and i are evaluated (but only once!). For the lefthand side
this completes the evaluation. And then the results of these are used as
parameters to __getitem__ to complete the evaluation of the righthand side.
Assuming b had already been evaluated, next the assignment is performed
by calling __setitem__.

Your example above doesn't show any difference because t['a'] doesn't have
any side effects. But if you use for both t and the index a function that
prints something you will see the difference.
-- 
Piet van Oostrum <[EMAIL PROTECTED]>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python for Embedded Systems?

2006-07-15 Thread H J van Rooyen

"Carl J. Van Arsdall" <[EMAIL PROTECTED]> Wrote:
To: 
Sent: Friday, July 14, 2006 7:36 PM
Subject: Re: Python for Embedded Systems?


| Grant Edwards wrote:
| > On 2006-07-14, Jack <[EMAIL PROTECTED]> wrote:
| >
| >> Is there a Python packaging that is specifically for
| >> embedded systems? ie, very small and configurable so the
| >> user gets to select what modules to install?
| >>
| >> For Linux-based embedded systems in particular?
| >>
| >> I'm thinking of running it on the Linksys's Linux-based open
| >> source router WRT54G. It has 4MB flash and 16MB RAM. I think
| >> another model has 16MB flash. Any possibilities of running
| >> Python on these systems?
| >>
| >
| > A few years back there was a "deeply embedded python" project,
| > but it's been dead for quite a while:
| >
| >  http://www.tucs.fi/magazin/output.php?ID=2000.N2.LilDeEmPy
| >
http://mail.python.org/pipermail/python-announce-list/1999-August/000157.html
| >
| >
| This raises a good question.  Is there a need for python to change
| somewhat to work better in an embedded profile?  Are there many people
| in the community interested in using python for embedded projects?
|

I for one would be interested in using it - if it can be made small enough - I
do not see it helping me with the nitty gritty of getting a system running on
bare metal, as the low level stuff in a small system is still best done in
assembler - but if there is a display and some sort of keyboard and you can
stick to character based stuff it will ease the "application" part of the work a
lot - its a natural for doing things like logging and simple transactions - and
if the hardware is strong enough to get IP running - then it will open up the
systems to be web based...

It will also be of use as you could prototype on a PC - emulators and simulators
of small systems are mostly a pain as it takes a lot of effort to describe the
actual hardware before these are useful...

"Small" in this context is an eight bit processor (like an 80x1 | x = 3, 5 )
with some tricks done in the hardware to expand the native 16 bit address space
to address say half a Meg of battery backed up static ram as data space, with
about 62k of code space available for the interpreter and the custom OS to run
in - (Harvard architecture, not von Neumann) - These processors have lately been
improved from the original about half a MIP to now give sustained performance of
better than 10 MIPS - So they may just be able to cripple along doing the
interpreting - But its *Quite a Challenge* to fit the interpreter in, though...

It is easily possible to expand these processor's address space to 24 bits -
that is 16 Meg - and it may be a better approach to make a 'Virtual Processor'
to run the python stuff - is there a definition for that sort of thing, akin to
Java's Virtual Processor? - It would be a better approach, as the resultant
higher level work would be more portable - to port to another class of
processor, you need merely write the Virtual Machine - in whatever Language
takes your fancy...

What is the minimum set of instructions and structure needed to make a
simplistic Python? - does anybody know?

Might just be a pipe dream...

- Hendrik van Rooyen


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


Re: Accessors in Python (getters and setters)

2006-07-15 Thread mystilleef
On State and Behavior:

To understand objects in terms of state and behavior you need to
absolve yourself from implementation details of languages and think at
an abstract level.

Take a button object, for example. It has state and behavior. Possible
states may include, is_active, is_focused, is_mapped, etc. Behavior is
what the button does when it responds to events, (e.g when you click on
it, or drag it, or position a pointer over it.) If you've done any form
of event based programming (GUI/Games/Simulation), this method of
thinking becomes natural.

As you can see, when I'm designing a button object, I don't care what
Python does with is_active. I don't care how it accesses. I don't care
what is_active means to Python. I don't care about Python's __get__
/__set__ special/latent functions or implementation details. is_active
to me and every other developer is a state of the button object. And at
that level that's all that matters. Python can tell me it's just ones
and zeros for all I care.

In very well designed systems, the state of an object should only be
changed by the object. For example, a third party randomly changing
is_active, (which Python lets you do freely and easily) from False to
True may crash your GUI. And I'm not making this up. Things like this
do really happen depending on the whackyness of your toolkit. So
sometimes, it is my duty to protect the state of an object. Especially
if its state cannot afford to be corrupted rendering the system
unstable. And situations like this are found a plenty in event based
programming. Which is programming objects based almost entirely on
state and behavior. As you can see this has nothing to do with Python
vs Java's vs X's implementation of accessors and how using them sucks,
or how they aren't Pythonic. Some domains just require this stuff.

One of the requirements for designing robust object systems is ensuring
the state of objects aren't easily contaminated. That "state" is the
objects data (read: stuff the object needs to do something "reliably").
And this is why many overzealous OO languages do "force" you to use
accessors. It's not because they hate you or aren't aware of the
convenience of having direct access to an object's attributes. It's
just because these languages convenience/robustness ratios are
different.

Thinking in terms of callable vs non-callable is not helpful for me,
because it isn't high level enough. Thinking in terms of state and
behavior is, because it works regardless of programming language or
implementations. This is the reason I like working with Python. I
wanted a language that didn't bore me with it semantics and allowed me
to focus on design. Let me reiterate, I'm not obsessing over language
semantics, I just need practical, not religious, solutions for my
problem domain.

Bruno Desthuilliers wrote:
> mystilleef wrote:
> (snip)
> >
> > Okay, I feel I need to make myself clear. I certainly I'm not blaming
> > Python for my mistakes. And I don't think language X is better than
> > Python or vice-versa. Okay scrap the vice-versa. It was silly of me to
> > name the variable tmp regardless of whatever excuses I have. This also
> > doesn't mean in the future I wouldn't use shitty names for my
> > attributes. :-) I most likely will. But at least now I know how to
> > minimize its impact of such carelessness. I mentioned them above but I
> > repeat it hear again.
> >
> > 1). Make all attributes of a class private/protected .
>
> Please re-read my answer to your previous mention of this and my other
> remarks in this thread (and below in this thread) about the profound
> differences between Python and Java wrt/ object model and attribute
> access semantics.
>
> > 2). If a "non-callable" attribute is going to be used outside a class,
> > think about making it a property
>
> Unless you don't need to.
>
> > and name the property well,
>
> Indeed !-)
>
> > Other than that we are just arguing semantics of language. For example,
> > your view of objects is by categorizing its attributes in callable and
> > non-callable.
>
> And also API/implementation. These are to orthogonal problems - even in
> Java FWIW !-)
>
> > However, my categorization is state(data) and
> > behavior(methods).
>
> If properties are an equivalent of getters/setters, are properties state
> or behaviour ? According to your views, they are behaviour, if I
> understood you. In that case, what's the difference between 'directely'
> (which in fact implies going thru __getattribute__) accessing a public
> "data" attribute and accessing an implementation attribute by the mean
> of a descriptor (property or custom) ?
>
> * before:
>
> # mylib.py
> class Knight(object):
>def __init__(self, name):
>  self.name = name
>
>def sayHello(self):
>  print "hello, I'm %s" % self.name
>
> # mymain.py
> from mylib import Knight
> k = Knight("Robin")
> print k.name
> k.sayHello()
> k.name = "Lancelot"
> k.sayHello()
>
> * after
> # mylib.py
> class Knight(object):

Re: PyQT installation /configuration

2006-07-15 Thread [EMAIL PROTECTED]

Phil Thompson wrote:
> On Saturday 15 July 2006 9:25 am, [EMAIL PROTECTED] wrote:
> > Hi there. I've been trying to get PyQT working on W2K, but have not yet
> > found a sufficiently detailed walk-through for my somewhat
> > command-line-challenged sensibilities. I did find this page:
> > http://www.diotavelli.net/PyQtWiki/GPLPyQtWindows , but I'm not sure
> > about installing the whole of Visual Studio .NET as a prerequisite. Can
> > anyone tell me if the passing of the years has made this process any
> > more approachable?
>
> For Qt4 use the binary installer from...
>
> http://www.trolltech.com/developer/downloads/qt/windows
>
> For PyQt4 use the binary installer from...
>
> http://www.riverbankcomputing.co.uk/pyqt/download.php

Ah thanks, I'm a dork. Why didn't I see that before ?

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


Re: Python for Embedded Systems?

2006-07-15 Thread Sébastien Boisgérault
Jack a écrit :

> If Python is not the best candidate for embedded systems because
> of the size, what (scripting) language would you recommend?
>
> PHP may fit but I don't quite like the language. Anything else?
> Loa is small but it does not seem to be powerful enough.

You mean Lua ? Not powerful enough ? What do you mean by
that ? Lua is great IMHO. Sure it does not come with thousands
of libraries, but the language design is extremely clean, the
language constructs powerful and the footprint very small.

16kloc of C code can't hurt your embedded device can they ? ;)

Please tell us what kind of limitation you find in Lua ...

Cheers,

SB

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


Re: Python for Embedded Systems?

2006-07-15 Thread Paul Rubin
"H J van Rooyen" <[EMAIL PROTECTED]> writes:
> What is the minimum set of instructions and structure needed to make a
> simplistic Python? - does anybody know?

There have been lots of Lisps for the PDP-11 and comparable machines.
Python's runtime semantics are close enough to Lisp that you could
probably get something Python-like running in that kind of machine,
maybe not exactly Python.  You would probably want to use small-Lisp
implementation techniques like BIBOP ("big bag of pages", Google for
it) memory organization.  But I don't think any of those Lisps were
really all that useful.  They were written mostly as toys.

SIOD was a well known very small Scheme interpreter that you might
like to play with:

http://en.wikipedia.org/wiki/SIOD
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Configuring IDLE on Linux

2006-07-15 Thread Ten
On Friday 14 July 2006 04:26, Satya Kiran wrote:
> Hello,
> I have upgraded to Python2.4 on my Red Hat 9.0 Linux box.
> I want to work with IDLE and ran a search to check it's presence.
>  Here is what I get.
>
> [EMAIL PROTECTED] bin]# find / -iname idlelib
> /usr/local/lib/python2.4/idlelib
>
> [EMAIL PROTECTED] bin]# cd /usr/local/lib/python2.4/idlelib
> [EMAIL PROTECTED] idlelib]# python PyShell.py
> ** IDLE can't import Tkinter.  Your Python may not be configured for Tk. **
>
> How do I resolve this and get IDLE working?
>
> thanks in advance,
> Kiran Satya

You need to install python's tkinter functionality separately in some 
RPM-based distros (suse and redhat off the top of my head).

Search your package repository for the package called python-tkinter (it may 
be named slightly differently on redhat - ie: python_tkinter, but whichever, 
that's the one)

HTH

Ten
-- 
There are 10 types of people in this world,
those who understand binary, and those who don't.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python for Embedded Systems?

2006-07-15 Thread Paul Rubin
Paul Rubin  writes:
> SIOD was a well known very small Scheme interpreter that you might
> like to play with:
> 
> http://en.wikipedia.org/wiki/SIOD

Here's another one that I like.  I haven't actually used it but
studied it for possible integration in an embedded project that I
worked on but that got cancelled.  It seems very good for this type of
thing.  The runtime system is just 20k bytes or so:

   http://hedgehog.oliotalo.fi/

Picolisp is also pretty neat but maybe not aimed the same way:

   http://software-lab.de/down.html

Take the challenge: it is very impressive.  Of course they tailored it
to Pico Lisp's capabilities, but you can see the challenge problem is
very sensible, and the Pico Lisp solution is much easier to get to
than a Python solution:

  http://software-lab.de/succ.html
-- 
http://mail.python.org/mailman/listinfo/python-list


NB question on global/local variables in functions

2006-07-15 Thread Wolfgang
Hi all,

I've started to write some functions but I have some problems with 
common variables in that functions.

So I have some variables which should be accessible by all my functions 
but not accessible by the rest of my code. How can I do this?

Thanks
Wolfgang

###function.py:

c1=123.0
c2=134.0

def fun(temp):
return temp+c1-c2

def fun1(temp):
return temp-c1


### caller.py
from function import *
print fun(10.0)
print c1

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


Re: NB question on global/local variables in functions

2006-07-15 Thread skip

Wolfgang> So I have some variables which should be accessible by all my
Wolfgang> functions but not accessible by the rest of my code. How can I
Wolfgang> do this?

Wolfgang> ###function.py:

Wolfgang> c1=123.0
Wolfgang> c2=134.0

Wolfgang> def fun(temp):
Wolfgang>   return temp+c1-c2

Wolfgang> def fun1(temp):
Wolfgang>   return temp-c1


Wolfgang> ### caller.py
Wolfgang> from function import *
Wolfgang>   print fun(10.0)
Wolfgang>   print c1

First, avoid "from function import *" as it pollutes your namespace.  Either
import specific symbols or just the module:

from function import fun, fun1
import function

Second, if you really must, add an __all__ list to function.py, generally
right at the top:

__all__ = ['fun', 'fun1']

(Note that __all__ is a list of strings.)  The "from star" import will only
import the names in the __all__ list.  You can also "hide" individual names
from a "from star" import by prefixing them with a single underscore (e.g.,
"_c1" instead of "c1").

Third, one of Python's key concepts is "we're all adults here".  You can't
really and truly hide c1 and c2, so just act responsibly and don't mess with
them from outside the function module.

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


Re: NB question on global/local variables in functions

2006-07-15 Thread Wolfgang

> 
> First, avoid "from function import *" as it pollutes your namespace.  Either
> import specific symbols or just the module:
> 
> from function import fun, fun1
> import function

thanks for the hint! But what is the difference between
from module import *
and
import module
?

> 
> Second, if you really must, add an __all__ list to function.py, generally
> right at the top:
> 
> __all__ = ['fun', 'fun1']

I've read this already, but to keep the example short I've skipped that 
part.

> 
> (Note that __all__ is a list of strings.)  The "from star" import will only
> import the names in the __all__ list.  You can also "hide" individual names
> from a "from star" import by prefixing them with a single underscore (e.g.,
> "_c1" instead of "c1").
> 

the _ before the variable did the trick! Thanks a lot!

> Third, one of Python's key concepts is "we're all adults here".  You can't
> really and truly hide c1 and c2, so just act responsibly and don't mess with
> them from outside the function module.

It is more to prevent myself from my own stupidness by changing global 
variables incidentally.

Wolfgang

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


[ANN] XPN 0.5.7 released

2006-07-15 Thread Nemesis
XPN (X Python Newsreader) is a multi-platform newsreader with Unicode
support. It is written with Python+GTK. It has features like
scoring/actions, X-Face and Face decoding, muting of quoted text,
newsrc import/export, find article and search in the body, spoiler
char/rot13, random taglines and configurable attribution lines.

You can find it on:

http://xpn.altervista.org/index-en.html

or

http://sf.net/projects/xpn


Changes in this release:

* fixed a bug that caused XPN not to open empty articles
* fixed a bug that occurs with newer GTK releases that caused XPN not
  to show bold face fonts in Groups Pane and Threads Pane
* added a key-combo that lets you scroll up the article
* fixed an issue with orderings save.
* reorganized and changed the appearance of the Config Window
* changed the appearance of the Score Window
* changed the way article headers and X-Face are shown in the Article Pane
* added a groups context menu
* added some new voices in the threads context menu


XPN is translated in Italian French and German, if you'd like to translate it
in your language and you are familiar with gettext and po-files
editing please contact me ([EMAIL PROTECTED]).
-- 
Never run after buses or women: you'll always get left behind.
 
 |\ |   |HomePage   : http://nem01.altervista.org
 | \|emesis |XPN (my nr): http://xpn.altervista.org

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


Re: NB question on global/local variables in functions

2006-07-15 Thread Wolfgang
Wolfgang schrieb:
>> First, avoid "from function import *" as it pollutes your namespace.  Either
>> import specific symbols or just the module:
>>
>> from function import fun, fun1
>> import function
> 
> thanks for the hint! But what is the difference between
> from module import *
>   and
> import module
> ?
> 

I've figured it out!

when I use "from module import *" then I can call my functions directly

when I use "import module" I need module.function

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


Re: ctypes wrapping libpam.so on FreeBSD 6.1 - Python Bus Error

2006-07-15 Thread Martin P. Hellwig
Frederik & Ganesan,

Thanks for the explanation, it did me realize that I should learn some C 
first before I'm going to start wrapping something :-)

At least I got a reason now to do something with C, though it should 
take me some time.

But again, thanks!

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


Re: NB question on global/local variables in functions

2006-07-15 Thread skip

Wolfgang> thanks for the hint! But what is the difference between
Wolfgang> from module import *
Wolfgang>   and
Wolfgang> import module
Wolfgang> ?

Try it and see.  I happen to have a.py laying about:

import atexit

def work():
  print "whew! work is hard"

def exit():
  print "module a is cleaned up"

atexit.register(exit)

At the top level there are three names, atexit, work and exit.
When I first start the interpreter I don't have much available:

>>> vars().keys()
['__builtins__', '__name__', '__doc__']

If I import the module a, a reference to a is added to the namespace, but
not (directly) the objects it contains:

>>> import a
>>> vars().keys()
['__builtins__', '__name__', '__doc__', 'a']

I can still get at the objects in a though:

>>> dir(a)
['__builtins__', '__doc__', '__file__', '__name__', 'atexit', 'exit', 
'work']
>>> a.work


Get rid of a:

>>> del a
>>> vars().keys()
['__builtins__', '__name__', '__doc__']

Now import everything in a:

>>> from a import *
>>> vars().keys()
['__builtins__', 'work', 'atexit', 'exit', '__name__', '__doc__']

There are two practical differences to importing names from a module
vs. just importing the module.  As I indicated in my previous note, the
"from star" import pollutes your namespace.  It might not seem like much if
you're only grabbing three objects you are interested in, but imagine if a
contained a lot of names, many of which you weren't going to use in your
program:

>>> from Tkinter import *
>>> vars().keys()
['getdouble', 'MULTIPLE', 'TypeType', 'mainloop', 'Canvas', 'AtSelLast',
'CodeType', 'TRUE', 'getboolean', 'LAST', 'TclVersion', 'BOTTOM', 'Wm',
'NUMERIC', 'Toplevel', 'DictProxyType', 'ObjectType', 'DictType',
'EXTENDED', 'OFF', 'SEL', 'LongType', 'CURRENT', 'CallWrapper',
'Scrollbar', 'ListType', 'X', 'GeneratorType', 'FIRST', 'ON',
'image_names', 'ClassType', 'YES', 'LambdaType', 'GROOVE', 'XRangeType',
'Scale', 'NORMAL', 'SW', 'BUTT', 'Label', 'ROUND', 'image_types',
'AtInsert', 'StringType', 'NONE', 'CENTER', 'FloatType', 'Spinbox',
'UnicodeType', 'Checkbutton', 'Grid', 'StringTypes', 'ModuleType',
'FileType', 'FLAT', 'END', 'VERTICAL', '__builtins__', 'MITER',
'Widget', 'DISABLED', 'S', 'COMMAND', 'EllipsisType', 'W', 'ACTIVE',
'__name__', 'EW', 'FrameType', 'BASELINE', 'CHORD', 'tkinter',
'FunctionType', 'Image', 'BitmapImage', 'Event', 'RADIOBUTTON',
'SliceType', 'Place', 'HIDDEN', 'PAGES', 'NoDefaultRoot', 'ANCHOR',
'CHAR', 'SEPARATOR', 'BooleanType', 'HORIZONTAL', 'TclError', 'MOVETO',
'WORD', 'SUNKEN', 'NO', 'DictionaryType', 'NotImplementedType',
'READABLE', 'NE', 'CHECKBUTTON', 'Variable', 'Pack', '__doc__', 'NW',
'RAISED', 'AtEnd', 'RIDGE', 'BooleanVar', 'Tributton', 'SOLID', 'N',
'CASCADE', 'SEL_FIRST', 'TkVersion', 'UNDERLINE', 'UNITS', 'TupleType',
'OptionMenu', 'ALL', 'NS', 'FALSE', 'Text', 'Frame', 'SEL_LAST', 'Misc',
'OUTSIDE', 'LabelFrame', 'getint', 'Radiobutton', 'LEFT', 'Listbox',
'wantobjects', 'SE', 'EXCEPTION', 'IntType', 'Menu', 'TOP', 'DoubleVar',
'DOTBOX', 'SINGLE', 'Tk', 'IntVar', 'AtSelFirst', 'UnboundMethodType',
'PanedWindow', 'INSERT', 'BuiltinMethodType', 'BROWSE', 'Tcl',
'BuiltinFunctionType', 'BaseWidget', 'PROJECTING', 'MethodType',
'TracebackType', 'BEVEL', 'E', 'InstanceType', 'BOTH', 'PIESLICE',
'Button', 'sys', 'Y', 'Entry', 'Message', 'PhotoImage', 'RIGHT',
'BufferType', 'Studbutton', 'INSIDE', 'Menubutton', 'WRITABLE',
'StringVar', 'ARC', 'At', 'ComplexType', 'NSEW', 'SCROLL', 'NoneType'] 

The chance that one of those names would rebind an already existing name in
your namespace is much higher.

The second practical difference is that if the object referenced by a name
is immutable (say, an integer), the name in the current namespace doesn't
get rebound if the module modifies the value.  Consider b.py:

total_work = 0
def work():
  global total_work
  print "not as hard as it might be"  
  total_work += 1

If I execute

from b import total_work, work

names are created in my current namespace that reference the objects bound
to those names *at that moment* in the b module's namespace.  If I then call
work(), it rebinds the name total_work in b's namespace (because integers
are immutable), however, I don't see the effect, because the name
"total_work" in my namespace is still bound to the object 0:

>>> from b import total_work, work
>>> total_work
0
>>> work()
not as hard as it might be
>>> total_work
0
>>> work()
not as hard as it might be
>>> total_work
0

Apparently work is really pretty easy...

If, on the other hand, I import b, I get the expected behavior:

>>> import b
>>> b.total_work
0
>>> b.work()
not as hard as it might be
>>> b.total_work
1
>>> b.work()
not 

Re: Accessors in Python (getters and setters)

2006-07-15 Thread Gerhard Fiedler
On 2006-07-15 06:55:14, mystilleef wrote:

> In very well designed systems, the state of an object should only be
> changed by the object. 

IMO that's not quite true. Ultimately, the state always gets changed by
something else (user interaction, physical events); very few objects are
completely self-contained in their behavior.

In most systems (and you possibly have written some of them) are objects
whose state gets changed by other objects -- possibly through the
intermediation of setter methods that do nothing else but set the state.
There's no conceptual difference between directly setting the state or
calling a setter function that does nothing else but directly setting the
state -- except for one unnecessary level of indirection in the latter.

> For example, a third party randomly changing is_active, (which Python
> lets you do freely and easily) from False to True may crash your GUI.
> And I'm not making this up. Things like this do really happen depending
> on the whackyness of your toolkit. 

That's quite true, but a setter that does nothing but change is_active
doesn't prevent this. If there is logic necessary to prevent state changes
in certain situations, this should be implemented. But whether you then
call this a part of the "behavior" (looking at the implementation as being
a setter method) or a part of the "state" (looking at the implementation as
being an added feature of the attribute) doesn't really make an objective
difference.

> So sometimes, it is my duty to protect the state of an object. 

Of course.

> Which is programming objects based almost entirely on state and behavior.
> As you can see this has nothing to do with Python vs Java's vs X's
> implementation of accessors and how using them sucks, or how they aren't
> Pythonic. Some domains just require this stuff.

Yes, but you seem to still be stuck in the paradigm that setting the state
is behavior if it comes from the outside -- probably because some languages
implement that way. 

I'm not (yet) a Python programmer. To be honest, the one single feature
that attracted me to Python is the structuring by indenting... I never
understood why we have to indent (to be able to read) /and/ brace (to make
the compiler happy) in other languages -- I always thought that if
indenting helps me to understand the structure, the compiler should be able
to read exactly that :)

I come from a mostly C/C++/Java/PHP background, apparently similar to
yours. GUI, embedded, whatever. But I can understand that the difference
you are making is not based in a concept, it is based in an implementation.

It is an artificial difference to say that 

  o.is_active = true

is modifying state, whereas

  o.set_active( true )

is dealing with behavior. Either way you are changing the state. Behavior,
that is, doing something, implies state change, one way or another,
sometimes relevant, sometimes not. There are (often embedded) systems, and
well-designed ones, that basically don't deal with what you call behavior
at all and handle everything through state change (of signals). Such
systems can be rock-solid and quite complex, and have a lot of "behavior".
And there are systems that do everything through what you call behavior
(e.g. getter/setter type implementations). Both types can work, both can
achieve the exactly same; this is just an implementation detail. 

> And this is why many overzealous OO languages do "force" you to use
> accessors. 

I'm not sure why you keep on harping on this. It seems to have been clearly
stated that in Python, every attribute /is/ an implied getter/setter pair
-- it's up to you to just let the language use the default (simple)
implementation, or override it with your own logic. It is also up to you to
call this added logic then a feature of "behavior" or of "state".

> Thinking in terms of state and behavior is, because it works regardless
> of programming language or implementations. 

Agreed. But the distinction is not universal, objective, it is subjective.
Where you make it is your choice. As the examples above show, there are
well-working solid systems out there that work on both ends of your
spectrum: only behavior is exposed, or only state is exposed. Both can
achieve the same. It is a subjective choice to call this 

  o.is_active = true
  
state or behavior... the underlying setter implementation for is_active can
do everything you want your behavior to be -- or it can be the simple
straightforward default setter. It's just a subjective thing to say that
this is in the realm of behavior or of state. Didn't you say that state
changes can crash a system? That's behavior, as far as I am concerned :)
And there is little if any behavior that doesn't change the state --
especially setters are known to do that :)

Gerhard

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


Re: NB question on global/local variables in functions

2006-07-15 Thread Wolfgang
Thanks! I've learned a lot today!

Wolfgang

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


Re: NB question on global/local variables in functions

2006-07-15 Thread Fredrik Lundh
Wolfgang wrote:

>> First, avoid "from function import *" as it pollutes your namespace.  Either
>> import specific symbols or just the module:
>>
>> from function import fun, fun1
>> import function
> 
> thanks for the hint! But what is the difference between
> from module import *
>   and
> import module
> ?

http://effbot.org/zone/import-confusion.htm#many-ways



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


Re: newbie graphing recommendations ?

2006-07-15 Thread jc
Adam wrote:
> Where should a py newbie start to do some 2D graphs on screen ? 
> 
> PythonGraphApi, 
> Gato, looks interesting 
> pygraphlib, 
> matplotlib, 
> 
> is there a best native Python place to start ? 
> 
> 
> 
If you are going to be in wxPython try the 'PyPlot.py' examples in the 
wxDemo.  You will need to read the source cos' there is no official 
documentation.  Matlibplot is also good but difficult because of all the 
options and lack of documentation API.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting focused window of another app

2006-07-15 Thread Jim Lewis
Never mind ...
wHnd = win32gui.GetForegroundWindow()
Caption = win32gui.GetWindowText (wHnd)

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


Re: dict = no ordered keys = no slicing

2006-07-15 Thread Antoon Pardon
On 2006-07-14, Nick Vatamaniuc <[EMAIL PROTECTED]> wrote:
>>I have a tree class, a tree acts like a dictionary, but when you
>> iterate over it, it always iterates over the keys in order.
>
> Antoon,
>
> First of all there is a distinction between ordered and un-ordered data
> types. You can only slice ordered data types. Lists and tuples are
> ordered while the keyset (note the _set_ part) of a dictionary is a set
> - it is un-ordered and consists of unique elements, the keys.

That doesn't has to be. Let as talk about a mapping. A mapping is
a way to associate a key with a value. Now one way to implement
a mapping is a hash table, this is how python dictionaries
are implemented. 

Now I have an other mapping implementation, look at:

  http://www.pardon-sleeuwaegen.be/antoon/avltree.html

Now this mapping type has as a property that the order
of the keys is somehow stored with it, so that each
time you call the keys, values, or items methods, you
will get a list according the order of the keys. (The
same goes for the itervariants).

> Besides, I don't really understand what you mean by saying "a tree acts
> like a dictionary"? You don't really iterate over the dictionary
> because the keys are not in order! Remeber that. The confusing part is
> that ks=dic.keys() will return a list so that makes you think ks[0] is
> somehow first for some reason, but it shouldn't be.

My module is implemented to have that property. It is called a tree
because the implementation is a tree. May be with the API provided
you think a tree is not a good name for this class and you may
have a point there, but that is not what this discussion is about.

> You see, dictionaries were there in Python before sets(), that is why
> when sets are supposed to be used a dictionary or list is used. keys()
> is one of these example. Hopefully this will change in P3K so that the
> key_set_ of a dictionary is a set() so people don't get confused.

And what do you think should be the result of keys of my Tree class?

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


Re: Accessors in Python (getters and setters)

2006-07-15 Thread mystilleef

Gerhard Fiedler wrote:
> On 2006-07-15 06:55:14, mystilleef wrote:
>
> > In very well designed systems, the state of an object should only be
> > changed by the object.
>
> IMO that's not quite true. Ultimately, the state always gets changed by
> something else (user interaction, physical events); very few objects are
> completely self-contained in their behavior.
>

Then in those cases the system becomes a victim of high coupling.

> In most systems (and you possibly have written some of them) are objects
> whose state gets changed by other objects -- possibly through the
> intermediation of setter methods that do nothing else but set the state.
> There's no conceptual difference between directly setting the state or
> calling a setter function that does nothing else but directly setting the
> state -- except for one unnecessary level of indirection in the latter.
>

It depends. If certain conditions need to be met before changing the
state of an object, then arbitrarily changing it can be dangerous. I
gave an example earlier.

> > For example, a third party randomly changing is_active, (which Python
> > lets you do freely and easily) from False to True may crash your GUI.
> > And I'm not making this up. Things like this do really happen depending
> > on the whackyness of your toolkit.
>
> That's quite true, but a setter that does nothing but change is_active
> doesn't prevent this. If there is logic necessary to prevent state changes
> in certain situations, this should be implemented. But whether you then
> call this a part of the "behavior" (looking at the implementation as being
> a setter method) or a part of the "state" (looking at the implementation as
> being an added feature of the attribute) doesn't really make an objective
> difference.
>

Of course using setters for the sake of just using them is pointless.
The reason to use them is if pre-conditions or post-conditions need to
be met. Or to control access to an objects states.

> > So sometimes, it is my duty to protect the state of an object.
>
> Of course.
>
> > Which is programming objects based almost entirely on state and behavior.
> > As you can see this has nothing to do with Python vs Java's vs X's
> > implementation of accessors and how using them sucks, or how they aren't
> > Pythonic. Some domains just require this stuff.
>
> Yes, but you seem to still be stuck in the paradigm that setting the state
> is behavior if it comes from the outside -- probably because some languages
> implement that way.
>

Not at all. Behaviors are just methods of an object. They are behaviors
whether they are called internally or externally.

> I'm not (yet) a Python programmer. To be honest, the one single feature
> that attracted me to Python is the structuring by indenting... I never
> understood why we have to indent (to be able to read) /and/ brace (to make
> the compiler happy) in other languages -- I always thought that if
> indenting helps me to understand the structure, the compiler should be able
> to read exactly that :)
>
> I come from a mostly C/C++/Java/PHP background, apparently similar to
> yours. GUI, embedded, whatever. But I can understand that the difference
> you are making is not based in a concept, it is based in an implementation.
>
> It is an artificial difference to say that
>
>   o.is_active = true
>
> is modifying state, whereas
>
>   o.set_active( true )
>
> is dealing with behavior. Either way you are changing the state. Behavior,
> that is, doing something, implies state change, one way or another,
> sometimes relevant, sometimes not. There are (often embedded) systems, and
> well-designed ones, that basically don't deal with what you call behavior
> at all and handle everything through state change (of signals). Such
> systems can be rock-solid and quite complex, and have a lot of "behavior".
> And there are systems that do everything through what you call behavior
> (e.g. getter/setter type implementations). Both types can work, both can
> achieve the exactly same; this is just an implementation detail.
>

If all set_active does is change is_active's state, then set_active is
pointless. See above for my point on the issue.

> > And this is why many overzealous OO languages do "force" you to use
> > accessors.
>
> I'm not sure why you keep on harping on this. It seems to have been clearly
> stated that in Python, every attribute /is/ an implied getter/setter pair
> -- it's up to you to just let the language use the default (simple)
> implementation, or override it with your own logic. It is also up to you to
> call this added logic then a feature of "behavior" or of "state".
>
> > Thinking in terms of state and behavior is, because it works regardless
> > of programming language or implementations.
>
> Agreed. But the distinction is not universal, objective, it is subjective.
> Where you make it is your choice. As the examples above show, there are
> well-working solid systems out there that work on both ends of your
> sp

Re: EuroPython 2006 and Py3.0

2006-07-15 Thread Antoon Pardon
On 2006-07-14, Lawrence Oluyede <[EMAIL PROTECTED]> wrote:
> Antoon Pardon <[EMAIL PROTECTED]> wrote:
>
>> I have a tree class, a tree acts like a dictionary, but when you
>> iterate over it, it always iterates over the keys in order. This
>> makes it usefull to iterate over a slice. So it would be usefull
>> if methods like keys, values and items could take a slice as
>> an argument and use the same notation for it. Something like
>> 
>>   for k, v in t.items('a':'b'):
>> 
>> Which would iterate over all items where the key starts with
>> an 'a'. 
>
> I keep thinking that means changing the meaning of "slice"

Why? This doesn't need any new functionality of slice. I already
can have this behaviour, but just would have to write it as follows:

   for k, v in t.items(slice('a','b')):

This is just a question of literal slice notation. Do we
limit the notation of a:b to indexing and for the slice(a,b)
notation everywhere else or do we allow the a:b notation for
a slice in other places where it seems usefull.

>> > -1. First: you have to introduce new syntax for an old thing.
>> 
>> That syntax already exists, it just is only available as an
>> index.
>
> Slicing and indexing is inside square brackets. (start:stop) seems
> confusing to me.

The notation is just start:stop the parenthesis will in practice
be added often to avoid disambiguities, like with the compound
statements when the colon is also used to start a suite, a bit
like tuples where parenthesis are often added too, although
they are not really needed to form a tuple literal.

> And I seriously doubt that Guido or someone on his
> behalf will go through introducing another syntax for something that can
> be already done in one way. I came to Python because of it's clean
> syntax and I've always tought "one good way to do one thing" is better
> than Perlish style. That's why I don't like powering up slice objects to
> do that.

My proposal will make the python syntax cleaner. Now you have
slices in python. The general way to have a slice is:

  slice(start, stop, step)

But in one particular place, when used as an index you are allowed
to write that slice as:

  start:stop:step

lst[start:stop:step] is just another way of writing lst[slice(start,stop,step)]

In my opionion that is not very clean. The first part of my proposal
entail no powering up whatsoever. It is just a proposal to make
the syntax of python more clean, so that the start:stop:step notation
for a literal slice is available everywhere, where a literal can
occur, instead of only in one particular place.

>> Need is such a strong word. In the end we don't need python, but
>> it seems very usefull to have it around. I understand that should this
>> be introduced it could make people uneasy, but I also think it
>> could be very usefull.
>
> I'm not the person in charge to make decisions about Python syntax,
> power and limitations but I really don't see a useful use case to have a
> slice++. Even decorators (that few people really understand) have a lot
> of use cases more than slice++

You should look at my points as different proposals. I think each
proposal is usefull in its own way. Allow the priveleged synax
for indexing anywhere is usefull even if nothing else is accepted.
Allowing slice to be subclassed is usefull even of nothing else is
accepted.  It is not a package deal that is to be accpeted or rejected
as a whole.

>> Because it would have made things a lot of easier for me in
>> a number of cases. I have a table class that is like a
>> list but can start at any index, it sure would have been
>> easier to write with some of the possibilities above. I
>> though to just write my own slice class, but slice is not
>> subclassable, and when I just wrote my own from scratch,
>> with a start, stop and step attribute I got an error that
>> it wasn't an integer so couldn't be used as an index.
>> So much for duck taping.
>
> I understand. So maybe asking for subclassable slices is better :-)

Well that was one of the things I proposed.

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


Re: Letting a Python application phone home

2006-07-15 Thread Nils Oliver Kröger
Am Freitag, 14. Juli 2006 15:26 schrieb Dieter Vanderelst:

This is surely possible. You need to define a protocol for the communication 
between client and server. As you are planning to send data over the internet 
you should build it on top of tcp. Look at the python module "socket" resp. 
"SocketServer" for low level tcp functions.

As the data should not be visible to everyone you need some kind of 
encryption. Either you rely on the ssl capabilities of the "socket" module, 
this way securing the transport layer (tcp) or you build encryption into your 
newly designed application layer protocol. For the latter have a look at the 
"python cryptography toolkit". Sorry I have no url at hand, simply google.

Concerning the question of stopping the program when the internet connection 
breaks: let your program contact the server periodically. If this fails quit 
the program.

Regards

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


Re: Python for Embedded Systems?

2006-07-15 Thread Paul McGuire
Jack wrote:
> Is there a Python packaging that is specifically for
> embedded systems? ie, very small and configurable so the
> user gets to select what modules to install?
>
You might also look at the gumstix embedded system, Linux running on an
ARM processor in an extremely small form factor.
(http://www.gumstix.net/)

And here is a page with a link to a gumstix Python binary:
http://cs.gmu.edu/~eclab/projects/robots/flockbots/pmwiki.php?n=Main.Python

I'm trying this out as soon as I get home!

-- Paul

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


Re: Python for Embedded Systems?

2006-07-15 Thread Paul McGuire
Jack wrote:
> Is there a Python packaging that is specifically for
> embedded systems? ie, very small and configurable so the
> user gets to select what modules to install?
>
> For Linux-based embedded systems in particular?
>
> I'm thinking of running it on the Linksys's Linux-based open
> source router WRT54G. It has 4MB flash and 16MB RAM. I think
> another model has 16MB flash. Any possibilities of running
> Python on these systems?

Here's another recently announced hobbyist microcontroller system:
http://makezine.com/controller/

Uses Atmel SAM7X processor, ARM7, 32-bit, 256K Flash, 64K SRAM, up to
55MHz.

On-board Ethernet and CAN (Controller Area Network - wireless)

Various I/O blocks and on-board sensors

~US$150

Start shipping Aug 1st.

No Python binary yet, but cross-platform tools are available.  The guys
at this magazine could really get a jump with a Python build.  Here's a
related site for this kit: www.uCHobby.com 

-- Paul

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


Re: Python for Embedded Systems?

2006-07-15 Thread Paul McGuire
>
> On-board Ethernet and CAN (Controller Area Network - wireless)
>
Ooops, my bad - CAN is not wireless, it is a serial network
specifically for linking with other ucontroller boards.

I was thinking of the onboard Bluetooth of the gumstix boards.

-- Paul

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


Re: Python for Embedded Systems?

2006-07-15 Thread Jack
Yes, I mean Lua, not Loa  :-p

Lua is a nice language. Like you said, it doesn't have many libraries
as Python does. Plus, it's still evolving and the libraries are changing.
I found a few functions not working last time I tried kepler libraries.
It's good for embedded systems though because of its small footprint.
Extensions implemented in C makes it possible that the installation size
doesn't blow up when new stuff is added, like in Python.

But I still like Python better for its power and for the style of the 
language
itself. And I was hoping to find a Python implementation that bears the
principles of Lua to make it suitable for embedded systems :)

>> PHP may fit but I don't quite like the language. Anything else?
>> Loa is small but it does not seem to be powerful enough.

>You mean Lua ? Not powerful enough ? What do you mean by
>that ? Lua is great IMHO. Sure it does not come with thousands
>of libraries, but the language design is extremely clean, the
>language constructs powerful and the footprint very small.

>16kloc of C code can't hurt your embedded device can they ? ;)

>Please tell us what kind of limitation you find in Lua ...

>Cheers,

>SB


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


Re: Detecting socket connection failure

2006-07-15 Thread Dieter Maurer
[EMAIL PROTECTED] writes on 10 Jul 2006 08:42:11 -0700:
> I've tried to RTFM this and am having no luck.First off, I am using
> Mac OSX 10.4.7 with python 2.4.2 from fink.  I am trying to connect to
> a server that should be rejecting connections and I was surprised when
> it did not throw an exception or do something otherwise equally nasty.
> It just connects and never returns any data.  First, the proof that
> something is there and rejecting the connection (or is it that this
> thing actually accepts the connection and then drops it?)...
> 
> telnet localhost 31414
> Trying 127.0.0.1...
> Connected to localhost.
> Escape character is '^]'.
> Connection closed by foreign host.

What you see here is that the connection was opened successfully
(the connect succeeded) and then closed again.

> ...
> In [1]: import socket, select
> 
> In [2]: remote = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
> 
> In [3]: remote.connect(('localhost',31414))
> 
> In [4]: remote.recv(200)
> Out[4]: ''

The means, that you see the same in Python:
"recv" returning an empty string indicates that the connection
was closed.

> 
> In [5]: r,w,e=select.select([remote],[remote],[remote],1)
> 
> In [6]: print r,w,e
> [] [ object at 0x7e48d0>] []

I have seen something similar recently:

  I can write ("send" to be precise) to a socket closed by
  the foreign partner without error
  (but of course, the written data does not arrive at the remote side).
  Only the second "send" raises an exception.

  I expect this is a TCP bug.


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


Re: newbie graphing recommendations ?

2006-07-15 Thread bearophileHUGS
Adam wrote:
> Where should a py newbie start to do some 2D graphs on screen ?
> PythonGraphApi,
> Gato, looks interesting
> pygraphlib,
> matplotlib,
> is there a best native Python place to start ?

The only good and simple way I have found so far to do some free
graphics with Python in a Window is using PyGame. (You can also use
TKinter, but it's slower).
MatPlotLib is very good to graph functions, datasets, etc. and to save
them to an image file.
There are other good libs if/when you want 3D graphics.

Bye,
bearophile

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


Re: InteractiveConsole History on Linux

2006-07-15 Thread vbgunz
> Why does code.InteractiveConsole support command history on Windows, but
> not in a Gnome terminal (all I get is ^[[A^[[B)? Or does it not support
> history at all, and the Windows console is implementing it's own? Is
> there any way to get command history working with InteractiveConsole on
> Linux?

The only time I see [A[B on Linux in a console is when I am not logged
in. Check to see if you're logged in and then try again. AFAIK, Linux
does support console history. I hope this helps :)

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


Re: InteractiveConsole History on Linux

2006-07-15 Thread vbgunz

vbgunz wrote:
> > Why does code.InteractiveConsole support command history on Windows, but
> > not in a Gnome terminal (all I get is ^[[A^[[B)? Or does it not support
> > history at all, and the Windows console is implementing it's own? Is
> > there any way to get command history working with InteractiveConsole on
> > Linux?
>
> The only time I see [A[B on Linux in a console is when I am not logged
> in. Check to see if you're logged in and then try again. AFAIK, Linux
> does support console history. I hope this helps :)

Sorry, I missed "code.InteractiveConsole" *but* maybe being logged in
has something to do with it?

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


Re: InteractiveConsole History on Linux

2006-07-15 Thread Robert Kern
Chris Spencer wrote:
> Why does code.InteractiveConsole support command history on Windows, but 
> not in a Gnome terminal (all I get is ^[[A^[[B)? Or does it not support 
> history at all, and the Windows console is implementing it's own? Is 
> there any way to get command history working with InteractiveConsole on 
> Linux?

Be sure that the readline module is installed.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

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


Re: What is a type error?

2006-07-15 Thread Chris F Clark
Joachim Durchholz wrote:
 >
 > You can have aliasing without pointers; e.g. arrays are fully sufficient.
 > If i = j, then a [i] and a [j] are aliases of the same object.

"Marshall" <[EMAIL PROTECTED]> writes:

> I am having a hard time with this very broad definition of aliasing.
> Would we also say that a[1+1] and a[2] are aliases? It seems
> to me, above, that we have only a, and with only one variable
> there can be no aliasing.

As you can see from the replies, all these things which you do not
consider aliasing are considered aliasing (by most everyone else, in
fact these are exactly what is meant by aliasing).  There is good
reason for this.  Let us explain this by looking again at the SQL
example that has been kicked around some.

>>SELECT * FROM persons WHERE name = "John"
>> and
>>SELECT * FROM persons WHERE surname = "Doe"

Some set of records are shared by both select clauses.  Those records
are the aliased records.  If the set is empty there is no problem.  If
we do not update the records from one of the select clauses, we also
have no problem.  However, if we update the records for one of the
select clauses and the set of aliased records is not empty, the
records returned by the other select clause have changed.  Therefore,
everything we knew to be true about the "other" select clause may or
may not still be true.  It's the may not case we are worried about.

For example, in the "imperative Mi-5" Q asks Moneypenny to run the
first query (name = John) to get a list of agents for infiltrating
Spectre.  In another department, they're doing sexual reassignments
and updating the database with the second query (surname = Doe) and
making the name become Jane (along with other changes to make the
transformation correct).  So, when Q select "John Doe" from the first
list and sends that agent on a mission Q is really sending "Jane Doe"
and Spectre realizes that the agent is one and kills her.  Not a happy
result.

In the "functional Mi-5", the sexual reassignment group, makes clones
of the agents reassigned, so that there is now both a "John Doe" and a
"Jane Doe".  Of course, the payroll is a little more bloated, so that
when Q says "John Doe" isn't needed for any further assignments, the
"Garbage Collection" department does a reduction in force and gets rid
of "John Doe".  The good news is that they didn't send Jane Doe to her
death.

The problem with aliasing, we want the things we knew true in one part
of our program, i.e. the Johns on Q's list are still Johns and not
Janes, to be true after we've run another part of our program.  If the
second part of our program can change what was true after the first
part of our program, we can't depend on the results from the first
part of our program, i.e. Q can send Jane Doe into certain death.

The problem is compounded by the complexities of our programs.  When Q
selected his list, he didn't know of the department doing the
reassignments (and couldn't know because they were part of a
top-secret project).  So, since bureaucracies grow to meet the
increasing needs of the bureaucracy, often the solution is increased
complexity, more regulations and paperwork to fill out, semaphores and
locks to hold on critical data, read-only data, status requests, etc.
All to keep Q from killing Jane by accident.  Sometimes they work. the
reassignment department has to wait 30-days for the clearance to
perform their operation in which time John Doe completes the
infiltration of Spectre saves the world from destruction and is ready
for his next assignment.

The key point is that each record (and even each field in each record)
if it can be known by two names, is an alias.  It is not sufficient to
talk about "whole" variables as not being aliased if there is some way
to refer to some part of the variable and change that part of the
variable.  Thus, a[1+1] is an alias for a[2] if you can have one part
of the code talking about one and another part of the code talking
about the other.

To put it one still final way, consider the following code;
assert(sorted(array a));
a[1] = 2;
assert(sorted(array a)); // is this still true?

Because a[1] is an alias of array a, you cannot be certain that the
2nd assert will not fire (fail) without additional analysis.

assert(sorted(array a));
assert(a[0] <= 2);
assert(2 <= a[2]);
a[1] = 2;
assert(sorted(array a)); // this is still true!

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


reading specific lines of a file

2006-07-15 Thread Yi Xing
Hi All,

I want to read specific lines of a huge txt file (I know the line #). 
Each line might have different sizes. Is there a convenient and fast 
way of doing this in Python? Thanks.

Yi Xing

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


Re: reading specific lines of a file

2006-07-15 Thread Pierre Quentel
If the line number of the first line is 0 :

source=open('afile.txt')
for i,line in enumerate(source):
if i == line_num:
break
print line

Pierre

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


Re: reading specific lines of a file

2006-07-15 Thread Piet van Oostrum
> Yi Xing <[EMAIL PROTECTED]> (YX) wrote:

>YX> Hi All,
>YX> I want to read specific lines of a huge txt file (I know the line #). Each
>YX> line might have different sizes. Is there a convenient and fast way of
>YX> doing this in Python? Thanks.

Not fast. You have to read all preceding lines.
If you have to do this many times while the file does not change, you could
build an index into the file.
-- 
Piet van Oostrum <[EMAIL PROTECTED]>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Package organization

2006-07-15 Thread Mike Wyatt
I've been playing around with Python for a few months now, and I just 
recently started looking at packages to organize my growing project.  So 
far, I've been organizing my application into one class per module.  
This has been working pretty well.  For example, I simply "import 
timer", then use "t = timer.Timer()" to allocate a new Timer object, .  
Unfortunately, this is yielding some pretty odd syntax when I use 
packages.  Here is a sample of my package structure:

/engine
/graphics
/input
/world
/timer
timer.py   # contains Timer class
main.py

Let's say I want to create a Timer object in main.py.  I would need to 
do something like this:

import engine.timer.timer.Timer
t = engine.timer.timer.Timer()

Maybe I shouldn't have a module and package with the same name, but it 
seems the most logical design.  Unfortunately, the code is a bit ugly 
with "timer" included in the import three times.

Is there a better way to do this?  How do you guys organize your 
packages and modules?
-- 
http://mail.python.org/mailman/listinfo/python-list


How to lock files (the easiest/best way)?

2006-07-15 Thread Elmo Mäntynen
Is there something better than using fnctl? It seems a bit intimidating
with a quick look.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is a type error?

2006-07-15 Thread Marshall
Joachim Durchholz wrote:
> Marshall schrieb:
>
> >> In some cases, you need an additional level of conceptual indirection -
> >> instead of *doing* the updates, you write a function that *describes* them.
> >
> > But then what do you do with that function?
>
> I pass it to an engine that's imperative.
>
> However, that engine doesn't need to do aliasing anymore.
>
> In other words, I'm separating mutability and aliasing, so that they
> can't combine and explode.

This would seem to be identical to what I am proposing.


>  > Let's say I have an
> > employee database. John Smith just got hired on 1/1/2006 with
> > a salary of $10,000. I need to record this fact somewhere. How
> > do I do that without variables? Current-employees is a variable.
> > Even if I have the space to keep all historical data, so I'm not
> > deleting anything, I still have to have a variable for the latest
> > version of the accumulated data. I can solve this without
> > pointers, but I can't solve it without variables.
>
> As I said elsewhere, the record has an identity even though it isn't
> explicit in SQL.

H. What can this mean?

In general, I feel that "records" are not the right conceptual
level to think about.

In any event, I am not sure what you mean by non-explicit
identity. I would say, records in SQL have value, and their
identity is exactly their value. I do not see that they have
any identity outside of their value. We can uniquely identify
any particular record via a key, but a table may have more
than one key, and an update may change the values of one
key but not another. So it is not possible in general to
definitely and uniquely assign a mapping from each record
of a table after an update to each record of the table before
the update, and if you can't do that, then where
is the record identity?

(The situation is even more dire when one considers that
SQL actually uses bag semantics and not set semantics.)


[...]

> > I should like to learn more about these. I have some vague
> > perception of the existence of linear logic, but not much
> > else. However, I also already have an excellent solution
> > to the pointer aliasing problem, so I'm less motivated.
>
> Pointers are just the most obvious form of aliasing. As I said
> elsewhere, there are others: array indexing, by-reference parameters, or
> even WHERE clauses in SQL statements. In fact, anything that selects an
> updatable piece of data from a collection is an alias, and incurs the
> same problems as pointers, though they may come in different disguises.

Okay. At this point, though, the term aliasing has become extremely
general. I believe "i+1+1" is an alias for "i+2" under this definition.
That is so general that I am concerned it has lost its ability to
identify problems specific to pointers.


> >> Actually SQL has references - they are called "primary keys", but they
> >> are references nevertheless.
> >
> > I strongly object; this is quite incorrect. I grant you that from the
> > 50,000 foot level they appear identical, but they are not. To
> > qualify as a reference, there need to be reference and dereference
> > operations on the reference datatype; there is no such operation
> > is SQL.
> >
> > Would you say the relational algebra has references?
>
> Yes.
>
> > Or, consider the classic prolog ancestor query. Let's say we're
> > setting up as follows
> >
> > father(bob, joe).
> > father(joe, john).
> >
> > Is "joe" a reference, here? After all, when we do the ancestor
> > query for john, we'll see his father is joe and then use that to
> > find joe's father. Keys in SQL are isomorphic to joe in the
> > above prolog.
>
> Agreed. They are both references ;-P

Again, by generalizing the term this far, I am concerned with a
loss of precision. If "joe" in the prolog is a references, then
"reference" is just a term for "data" that is being used in a
certain way. The conection with a specfic address space
has been lost in favor of the full domain of the datatype.


> >> (Some SQL dialects also offer synthetic
> >> "ID" fields that are guaranteed to remain stable over the lifetime of a
> >> record.
> >
> > Primary keys are updatable; there is nothing special about them.
>
> Right - I was wrong with identifying keys and identities. In fact the
> identity of an SQL record cannot be directly obtained (unless via those
> ID fields).
> The records still have identities. It's possible to have two WHERE
> clauses that refer to the same record, and if you update the record
> using one WHERE clause, the record returned by the other WHERE clause
> will have changed, too.

Is this any different from saying that an expression that includes
a variable will produce a different value if the variable changes?

In other words, "i+1" will return a different value if we update i.

It seems odd to me to suggest that "i+1" has identity. I can see
that i has identity, but I would say that "i+1" has only value.

But perhaps the ultimate upshoot of this thread is that my use

Re: Python for Embedded Systems?

2006-07-15 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Jack <[EMAIL PROTECTED]> wrote:
>Yes, I mean Lua, not Loa  :-p
>
>Lua is a nice language. Like you said, it doesn't have many libraries
>as Python does. Plus, it's still evolving and the libraries are changing.
>I found a few functions not working last time I tried kepler libraries.
>It's good for embedded systems though because of its small footprint.
>Extensions implemented in C makes it possible that the installation size
>doesn't blow up when new stuff is added, like in Python.
>
>But I still like Python better for its power and for the style of the 
>language
>itself. And I was hoping to find a Python implementation that bears the
>principles of Lua to make it suitable for embedded systems :)
>
>>> PHP may fit but I don't quite like the language. Anything else?
>>> Loa is small but it does not seem to be powerful enough.
>
>>You mean Lua ? Not powerful enough ? What do you mean by
>>that ? Lua is great IMHO. Sure it does not come with thousands
>>of libraries, but the language design is extremely clean, the
>>language constructs powerful and the footprint very small.
>
>>16kloc of C code can't hurt your embedded device can they ? ;)
>
>>Please tell us what kind of limitation you find in Lua ...
.
.
.
PHP is about as bad a choice as there is for this domain.
Let's talk about it some other time.

The usual contestants are Forth, Lua, Tcl, and various Lisps.  
Python could play quite well at least in some situations, but
entirely no one has done much since 1.5.2 times (which doesn't
seem to me like a long time).

If you're to the point of sniffing at Lua's relative poverty
of libraries, you need to detail your requirements more pre-
cisely.  What's "small" and "embedded" to some people is a 
full-featured host to others.  Generally speaking, yes, Lua
is still advancing significantly, or, from a different per-
spective, it hasn't stabilized yet.  The point is that there's
necessarily no "Pareto optimizer" which is simultaneously
smallest, fastest, newest, most mature, most Unicode-aware,
most featureful, lowest-level, highest-level, ...  That's why
there's a point to the engineering we do here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python for Embedded Systems?

2006-07-15 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Carl J. Van Arsdall <[EMAIL PROTECTED]> wrote:
.
.
.
>This raises a good question.  Is there a need for python to change 
>somewhat to work better in an embedded profile?  Are there many people 
>in the community interested in using python for embedded projects?
.
.
.
Yes and no.  Python could thrive for the next decade while
utterly surrendering the small-and-embedded domain to Forth,
Lua, Tcl, Scheme, and so on, so, no, there's no *need* for a
TinyPython.  On the other hand, yes, there are at least several
of us with an interest and occasional opportunities for Python
in such applications.  While http://www.engcorp.com/acf/RecentChanges > looks dormant, it
was set up to serve just such constituencies, and we might yet
breathe life into it--just as any of the other several TinyPython
initiatives might, or might not, revivify.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading specific lines of a file

2006-07-15 Thread Bill Pursell

Yi Xing wrote:
> I want to read specific lines of a huge txt file (I know the line #).
> Each line might have different sizes. Is there a convenient and fast
> way of doing this in Python? Thanks.

#!/usr/bin/env python

import os,sys
line = int(sys.argv[1])
path = sys.argv[2]
os.system("sed -n %dp %s"%(line,path))


Some might argue that this is not really doing
it in Python.  In fact, I would argue that!  But if
you're at a command prompt and you want to
see line 7358, it's much easier to type
% sed -n 7358p
than it is to write the python one-liner.

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


Re: How to lock files (the easiest/best way)?

2006-07-15 Thread Elmo Mäntynen
On Sat, 15 Jul 2006 23:28:21 +0200, Sybren Stuvel wrote:

> Elmo Mäntynen enlightened us with:
>> Is there something better than using fnctl? It seems a bit
>> intimidating with a quick look.
> 
> Locking files is a complex business. What do you want to lock? Why?
> Lock it with respect to what? It's easier to lock a file for local
> use, compared to when the file also has to be locked from, say, use
> via the network.
> 
> Sybren

Only locally. I want to be able to read/write to a single file from
multiple possibly parallel processes. Would 'touch lock' (or something
like that) work reliably (this just occured to me)?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How to lock files (the easiest/best way)?

2006-07-15 Thread Elmo Mäntynen
On Sat, 15 Jul 2006 23:52:10 +0200, Sybren Stuvel wrote:

> Elmo Mäntynen enlightened us with:
>> Only locally. I want to be able to read/write to a single file from
>> multiple possibly parallel processes. Would 'touch lock' (or
>> something like that) work reliably (this just occured to me)?
> 
> I use a lock directory for that, os.mkdir('/var/lock/somedir').
> If you use a file, you need two steps:
> 1) Check whether the lock-file exists
> 2) Create the lock-file
> 
> This is not atomic. With a directory, creating it will fail if it
> already exists. This means you can atomically check for the lock, and
> if it doesn't exist already, you've immediately created it too.
> 
> Sybren

Thanks. Is that what atomic basically means?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: reading specific lines of a file

2006-07-15 Thread Simon Forman
Yi Xing wrote:
> Hi All,
>
> I want to read specific lines of a huge txt file (I know the line #).
> Each line might have different sizes. Is there a convenient and fast
> way of doing this in Python? Thanks.
>
> Yi Xing

I once had to do a lot of random access of lines in a multi gigabyte
log file.  I found that a very fast way to do this was to build an
index file containing the int offset in bytes of each line in the log
file.

I could post the code if you're interested.

Peace,
~Simon

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


Re: What is a type error?

2006-07-15 Thread Joachim Durchholz
Marshall schrieb:
> Joachim Durchholz wrote:
>> As I said elsewhere, the record has an identity even though it isn't
>> explicit in SQL.
> 
> H. What can this mean?
> 
> In general, I feel that "records" are not the right conceptual
> level to think about.

They are, when it comes to aliasing of mutable data. I think it's 
justified by the fact that aliased mutable data has a galling tendency 
to break abstraction barriers. (More on this on request.)

> In any event, I am not sure what you mean by non-explicit
> identity.

The identity isn't visible from inside SQL. (Unless there's an OID 
facility available, which *is* an explicit identity.)

 > I would say, records in SQL have value, and their
> identity is exactly their value.

Definitely not. You can have two equal records and update just one of 
them, yielding non-equal records; by my definition (and by intuition), 
this means that the records were equal but not identical.

 > I do not see that they have
> any identity outside of their value. We can uniquely identify
> any particular record via a key, but a table may have more
> than one key, and an update may change the values of one
> key but not another. So it is not possible in general to
> definitely and uniquely assign a mapping from each record
> of a table after an update to each record of the table before
> the update, and if you can't do that, then where
> is the record identity?

Such a mapping is indeed possible. Simply extend the table with a new 
column, number the columns consecutively, and identify the records via 
that column.

But even if you don't do that, there's still identity. It is irrelevant 
whether the programs can directly read the value of the identity field; 
the adverse effects happen because updates are in-place. (If every 
update generated a new record, then we'd indeed have no identity.)

> Okay. At this point, though, the term aliasing has become extremely
> general. I believe "i+1+1" is an alias for "i+2" under this definition.

No, "i+1+1" isn't an alias in itself. It's an expression - to be an 
alias, it would have to be a reference to something.

However, a[i+1+1] is an alias to a[i+2]. Not that this is particularly 
important - 1+1 is replacable by 2 in every context, so this is 
essentially the same as saying "a[i+2] is an alias of a[i+2]", which is 
vacuously true.

There's another aspect here. If two expressions are always aliases to 
the same mutable, that's usually easy to determine; this kind of 
aliasing is usually not much of a problem.
What's more of a problem are those cases where there's occasional 
aliasing. I.e. a[i] and a[j] may or may not be aliases of each other, 
depending on the current value of i and j, and *that* is a problem 
because the number of code paths to be tested doubles. It's even more of 
a problem because testing with random data will usually not uncover the 
case where the aliasing actually happens; you have to go around and 
construct test cases specifically for the code paths that have aliasing. 
Given that references may cross abstraction barriers (actually that's 
often the purpose of constructing a reference in the first place), this 
means you have to look for your test cases at multiple levels of 
software abstraction, and *that* is really, really bad.

> That is so general that I am concerned it has lost its ability to
> identify problems specific to pointers.

If the reference to "pointers" above means "references", then I don't 
know about any pointer problems that cannot be reproduced, in one form 
or the other, in any of the other aliasing mechanisms.

> Again, by generalizing the term this far, I am concerned with a
> loss of precision. If "joe" in the prolog is a references, then
> "reference" is just a term for "data" that is being used in a
> certain way. The conection with a specfic address space
> has been lost in favor of the full domain of the datatype.

Aliasing is indeed a more general idea that goes beyond address spaces.

However, identity and aliasing can be defined in fully abstract terms, 
so I welcome this opportunity to get rid of a too-concrete model.

>> The records still have identities. It's possible to have two WHERE
>> clauses that refer to the same record, and if you update the record
>> using one WHERE clause, the record returned by the other WHERE clause
>> will have changed, too.
> 
> Is this any different from saying that an expression that includes
> a variable will produce a different value if the variable changes?

Yes.
Note that the WHERE clause properly includes array indexing (just set up 
a table that has continuous numeric primary key, and a single other column).

I.e. I'm not talking about how a[i] is an alias of a[i+1] after updating 
i, I'm talking about how a[i] may be an alias of a[j].

> It seems odd to me to suggest that "i+1" has identity.

It doesn't (unless it's passed around as a closure, but that's 
irrelevant to this discussion).
"i" does have identity. "a[i]" does h

Re: Accessors in Python (getters and setters)

2006-07-15 Thread Gerhard Fiedler
On 2006-07-15 12:04:20, mystilleef wrote:

> State - behavior is not something I made up, so it isn't subjective. It
> is a common term used in OO literature. In fact, the only reason I used
> it is because I thought is was common knowledge. 

Of course. But your association of state with attributes and behavior with
methods is arbitrary to a specific implementation. Of course you probably
will have always something like attributes to store state, but you may
trigger behavior just as well through state changes as you may trigger it
through method calls or other means. (Remember, this is about the public
API, not about implementation details.)

Gerhard

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


Re: How to lock files (the easiest/best way)?

2006-07-15 Thread Gerhard Fiedler
On 2006-07-15 18:52:10, Sybren Stuvel wrote:

> Elmo Mäntynen enlightened us with:
>> Only locally. I want to be able to read/write to a single file from
>> multiple possibly parallel processes. Would 'touch lock' (or
>> something like that) work reliably (this just occured to me)?
> 
> I use a lock directory for that, os.mkdir('/var/lock/somedir').
> If you use a file, you need two steps:
> 1) Check whether the lock-file exists
> 2) Create the lock-file

cvsnt for example used to use lock files. Now it uses a lock server: a
server app that just sits there and allows different processes to acquire,
check for and release locks on files. More implementation work, probably,
but more efficient.

Gerhard

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


Re: Package organization

2006-07-15 Thread Matt Good
Mike Wyatt wrote:
> I've been playing around with Python for a few months now, and I just
> recently started looking at packages to organize my growing project.  So
> far, I've been organizing my application into one class per module.
> This has been working pretty well.  For example, I simply "import
> timer", then use "t = timer.Timer()" to allocate a new Timer object, .
> Unfortunately, this is yielding some pretty odd syntax when I use
> packages.  Here is a sample of my package structure:
>
> /engine
> /graphics
> /input
> /world
> /timer
> timer.py   # contains Timer class
> main.py
>
> Let's say I want to create a Timer object in main.py.  I would need to
> do something like this:
>
> import engine.timer.timer.Timer
> t = engine.timer.timer.Timer()
>
> Maybe I shouldn't have a module and package with the same name, but it
> seems the most logical design.  Unfortunately, the code is a bit ugly
> with "timer" included in the import three times.
>
> Is there a better way to do this?  How do you guys organize your
> packages and modules?

One class per module?  Sounds like you've been programming in Java (or
C#) for too long :)

But skipping the package structure for a moment you can simplify your
use of the Timer class by changing your imports:

from engine.timer.timer import Timer
t = Timer()

OR

from engine.timer import timer
t = timer.Timer()

Ok, back to package structure.  In Python putting 1 class per module
basically means you're adding an extra level of nesting beyond the
equivalent structure in languages like Java and C# that require you to
create a new file per-class.

In Java defining "engine/timer/Timer.java" you'd get an
"engine.timer.Timer" class.
As you saw in Python defining Timer in "engine/timer/timer.py" the
class is now "engine.timer.timer.Timer".

Dropping that extra level by combining the classes in engine.timer into
a single module will simplify things.

-- Matt Good

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


Re: reading specific lines of a file

2006-07-15 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Yi Xing wrote:

> I want to read specific lines of a huge txt file (I know the line #). 
> Each line might have different sizes. Is there a convenient and fast 
> way of doing this in Python? Thanks.

Don't know how efficient the `linecache` module in the standard library is
implemented but you might have a look at it.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Letting a Python application phone home

2006-07-15 Thread Gerhard Fiedler
On 2006-07-15 12:45:16, Nils Oliver Kröger wrote:

> This is surely possible. You need to define a protocol for the communication 
> between client and server. As you are planning to send data over the internet 
> you should build it on top of tcp. Look at the python module "socket" resp. 
> "SocketServer" for low level tcp functions.

You may consider using https and html forms for sending your data. The
advantage is that code for the server part is readily available, and a
server often already running on a target server system.

Gerhard

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


Using MapPoint with Python

2006-07-15 Thread Eric Frost
New article on using Python scripting to automate map-making with example 
code, see screenshots.

[MP2K Magazine] Using Python to Control MapPoint, Part 2
«Second of a two-part article by Richard Marsden on scripting MapPoint using 
Python.»
http://www.mp2kmag.com/a134--python.winwaed.automation.mappoint.html

Eric Frost
http://www.mp2kmag.com - The Magazine for MapPoint 

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


Re: Accessors in Python (getters and setters)

2006-07-15 Thread Ben C
On 2006-07-15, Gerhard Fiedler <[EMAIL PROTECTED]> wrote:
> On 2006-07-15 06:55:14, mystilleef wrote:
>
>> In very well designed systems, the state of an object should only be
>> changed by the object. 
>
> IMO that's not quite true. Ultimately, the state always gets changed by
> something else (user interaction, physical events); very few objects are
> completely self-contained in their behavior.
>
> In most systems (and you possibly have written some of them) are objects
> whose state gets changed by other objects -- possibly through the
> intermediation of setter methods that do nothing else but set the state.
> There's no conceptual difference between directly setting the state or
> calling a setter function that does nothing else but directly setting the
> state -- except for one unnecessary level of indirection in the latter.

The conceptual difference is that a function call is more like an "event",
a variable is more like a "process".

An object that provides a setter is a process that is prepared to engage
in this "set event". An object that exposes a variable is a process that
interacts with this variable which the user is also invited to interact
with concurrently.

So with a setter in the API, conceptually, there are two processes
sharing the set event: the object itself, and the process that's calling
the setter. With an exposed variable, there are three: the object, the
variable in between, and the calling process.

Restricting yourself to setters and getters is a bit like saying we
build a machine that only has touch-keys and lights on the outside.
Shared variables are more like a machine with levers and dials you set,
and bits that pop up, like the numbers on mechanical cash-registers.
They have "state" on the outside, not just on the inside. Such designs
can be less tolerant of unsympathetic input-- think how easy it is to
jam up an old-fashioned typewriter if you just press a few keys at the
same time.

There isn't any practical difference, as you say, if all the setter does
is set. But it might easily do a few other subtle things, in particular
wait for a good moment to actually effect the change.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading specific lines of a file

2006-07-15 Thread bearophileHUGS
Pierre Quentel:
> If the line number of the first line is 0 :
> source=open('afile.txt')
> for i,line in enumerate(source):
> if i == line_num:
> break
> print line

I don't know if something like this can be called an improvement:

from itertools import islice
afile = file('data.txt')
line_n = 10
print islice(afile, line_n, line_n+1).next()

Bye,
bearophile

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


Re: automatic debugger?

2006-07-15 Thread R. Bernstein
[EMAIL PROTECTED] writes:

> hi
> is there something like an automatic debugger module available in
> python? Say if i enable this auto debugger, it is able to run thru the
> whole python program, print variable values at each point, or print
> calls to functions..etc...just like the pdb module, but now it's
> automatic.
> thanks

pydb (http://bashdb.sourceforge.net) has a linetrace option sort of
like what's done in POSIX shells. 

Here's an example:

#!/usr/bin/python
"""Towers of Hanoi"""
import sys,os

def hanoi(n,a,b,c):
if n-1 > 0:
   hanoi(n-1, a, c, b) 
print "Move disk %s to %s" % (a, b)
if n-1 > 0:
   hanoi(n-1, c, b, a) 

i_args=len(sys.argv)
if i_args != 1 and i_args != 2:
print "*** Need number of disks or no parameter"
sys.exit(1)

n=3

if i_args > 1:
  try: 
n = int(sys.argv[1])
  except ValueError, msg:
print "** Expecting an integer, got: %s" % repr(sys.argv[1])
sys.exit(2)

if n < 1 or n > 100: 
print "*** number of disks should be between 1 and 100" 
sys.exit(2)

hanoi(n, "a", "b", "c")


$ pydb --basename --trace hanoi.py
(hanoi.py:2): 
+ """Towers of Hanoi"""
(hanoi.py:3): 
+ import sys,os
(hanoi.py:5): 
+ def hanoi(n,a,b,c):
(hanoi.py:12): 
+ i_args=len(sys.argv)
(hanoi.py:13): 
+ if i_args != 1 and i_args != 2:
(hanoi.py:17): 
+ n=3
(hanoi.py:19): 
+ if i_args > 1:
(hanoi.py:26): 
+ if n < 1 or n > 100: 
(hanoi.py:30): 
+ hanoi(n, "a", "b", "c")
--Call--
(hanoi.py:5):  hanoi
+ def hanoi(n,a,b,c):
(hanoi.py:6):  hanoi
+ if n-1 > 0:
(hanoi.py:7):  hanoi
+hanoi(n-1, a, c, b) 
--Call--
(hanoi.py:5):  hanoi
+ def hanoi(n,a,b,c):
(hanoi.py:6):  hanoi
+ if n-1 > 0:
(hanoi.py:7):  hanoi
+hanoi(n-1, a, c, b) 
--Call--
(hanoi.py:5):  hanoi
+ def hanoi(n,a,b,c):
(hanoi.py:6):  hanoi
+ if n-1 > 0:
(hanoi.py:8):  hanoi
+ print "Move disk %s to %s" % (a, b)
Move disk a to b
(hanoi.py:9):  hanoi
+ if n-1 > 0:
--Return--
(hanoi.py:9):  hanoi
+ if n-1 > 0:
(hanoi.py:8):  hanoi
+ print "Move disk %s to %s" % (a, b)
Move disk a to c
(hanoi.py:9):  hanoi
+ if n-1 > 0:
(hanoi.py:10):  hanoi
+hanoi(n-1, c, b, a) 
--Call--
(hanoi.py:5):  hanoi
+ def hanoi(n,a,b,c):
(hanoi.py:6):  hanoi
+ if n-1 > 0:
(hanoi.py:8):  hanoi
+ print "Move disk %s to %s" % (a, b)
Move disk b to c
(hanoi.py:9):  hanoi
+ if n-1 > 0:
--Return--
(hanoi.py:9):  hanoi
+ if n-1 > 0:
--Return--
(hanoi.py:10):  hanoi
+hanoi(n-1, c, b, a) 
(hanoi.py:8):  hanoi
+ print "Move disk %s to %s" % (a, b)
Move disk a to b
(hanoi.py:9):  hanoi
+ if n-1 > 0:
(hanoi.py:10):  hanoi
+hanoi(n-1, c, b, a) 
--Call--
(hanoi.py:5):  hanoi
+ def hanoi(n,a,b,c):
(hanoi.py:6):  hanoi
+ if n-1 > 0:
(hanoi.py:7):  hanoi
+hanoi(n-1, a, c, b) 
--Call--
(hanoi.py:5):  hanoi
+ def hanoi(n,a,b,c):
(hanoi.py:6):  hanoi
+ if n-1 > 0:
(hanoi.py:8):  hanoi
+ print "Move disk %s to %s" % (a, b)
Move disk c to a
(hanoi.py:9):  hanoi
+ if n-1 > 0:
--Return--
(hanoi.py:9):  hanoi
+ if n-1 > 0:
(hanoi.py:8):  hanoi
+ print "Move disk %s to %s" % (a, b)
Move disk c to b
(hanoi.py:9):  hanoi
+ if n-1 > 0:
(hanoi.py:10):  hanoi
+hanoi(n-1, c, b, a) 
--Call--
(hanoi.py:5):  hanoi
+ def hanoi(n,a,b,c):
(hanoi.py:6):  hanoi
+ if n-1 > 0:
(hanoi.py:8):  hanoi
+ print "Move disk %s to %s" % (a, b)
Move disk a to b
(hanoi.py:9):  hanoi
+ if n-1 > 0:
--Return--
(hanoi.py:9):  hanoi
+ if n-1 > 0:
--Return--
(hanoi.py:10):  hanoi
+hanoi(n-1, c, b, a) 
--Return--
(hanoi.py:10):  hanoi
+hanoi(n-1, c, b, a) 
--Return--
(hanoi.py:30): 
+ hanoi(n, "a", "b", "c")
--Return--
(:1): 
+  (bdb.py:366):  run
+ exec cmd in globals, locals
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python for Embedded Systems?

2006-07-15 Thread Paul Rubin
[EMAIL PROTECTED] (Cameron Laird) writes:
> Yes and no.  Python could thrive for the next decade while
> utterly surrendering the small-and-embedded domain to Forth,
> Lua, Tcl, Scheme, and so on, so, no, there's no *need* for a
> TinyPython.  On the other hand, yes, there are at least several
> of us with an interest and occasional opportunities for Python
> in such applications. 

I think we should see what happens with PyPy, which might be easier to
target at embedded platforms than CPython is.  Main thing needed would
be a static compiler--I haven't followed PyPy enough to know if it
relies on having Psyco at runtime.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to lock files (the easiest/best way)?

2006-07-15 Thread Paul Rubin
Sybren Stuvel <[EMAIL PROTECTED]> writes:
> I use a lock directory for that, os.mkdir('/var/lock/somedir').
> If you use a file, you need two steps:
> 1) Check whether the lock-file exists
> 2) Create the lock-file
> This is not atomic. With a directory, creating it will fail if it
> already exists. This means you can atomically check for the lock, and
> if it doesn't exist already, you've immediately created it too.

The classic way in Unix was to make a link:

   1) link('some_other_file', 'lockfile')

This was atomic and would fail if lockfile already existed.

I'm not sure whether it can still be reliable, in current environments
that can involve remote file systems etc.  But I'm not sure if the
mkdir approach works either.

Maybe you want to use something like shm or posh?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQT installation /configuration

2006-07-15 Thread [EMAIL PROTECTED]

[EMAIL PROTECTED] wrote:
> Phil Thompson wrote:

> > For Qt4 use the binary installer from...
> >
> > http://www.trolltech.com/developer/downloads/qt/windows
> >
> > For PyQt4 use the binary installer from...
> >
> > http://www.riverbankcomputing.co.uk/pyqt/download.php
>
> Ah thanks, I'm a dork. Why didn't I see that before ?

Waitaminute, didn't you write it? Oh dear.

I've got another problem, I'm afraid - I've installed Qt 4.1.4 and PyQt
GPL v4.0 over Python 2.4, and the demos for both run happily enough,
but when I try to run the first example (in IDLE) from Boudewijn
Rempt's GUI Programming with Python: QT Edition I just get
"ImportError: No module named qt". Is there something I need to add to
my sys.path here?

Sorry to bother you with the newbie questions.

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


Re: newbie graphing recommendations ?

2006-07-15 Thread Bryan
[EMAIL PROTECTED] wrote:
> Adam wrote:
>> Where should a py newbie start to do some 2D graphs on screen ?
>> PythonGraphApi,
>> Gato, looks interesting
>> pygraphlib,
>> matplotlib,
>> is there a best native Python place to start ?
> 
> The only good and simple way I have found so far to do some free
> graphics with Python in a Window is using PyGame. (You can also use
> TKinter, but it's slower).
> MatPlotLib is very good to graph functions, datasets, etc. and to save
> them to an image file.
> There are other good libs if/when you want 3D graphics.
> 
> Bye,
> bearophile
> 

do you think that pygame would be a good alternative to matplotlib to create 
some graphs such simple bar and line graphs?  i want to animate them as new 
data 
comes comes in.  i would also like to have the bars and graphs have nice 
shading 
if possible to give it a really attractive look.  also, do you know if a pygame 
windows can be embedded in a wxPython app?

thanks,

bryan

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


Re: PyQT installation /configuration

2006-07-15 Thread David Boddie
[EMAIL PROTECTED] wrote:

> I've got another problem, I'm afraid - I've installed Qt 4.1.4 and PyQt
> GPL v4.0 over Python 2.4, and the demos for both run happily enough,
> but when I try to run the first example (in IDLE) from Boudewijn
> Rempt's GUI Programming with Python: QT Edition I just get
> "ImportError: No module named qt". Is there something I need to add to
> my sys.path here?

The module structures for PyQt3 and PyQt4 are quite different: the
monolithic qt module from PyQt3 has been replaced by a number of
modules in PyQt4. Despite this, there is a similar way to "import qt"
in PyQt4:

  from PyQt4 import Qt

However, you will have difficulty using the examples in that book
because it was written for PyQt3. Work is underway to "port" the book
to PyQt4, but it will take some time. (You can help with this and learn
about PyQt4 at the same time, if you want.)

In the meantime, the set of slides from a talk at EuroPython 2006 is
probably the only learning material on the web for PyQt4:

http://indico.cern.ch/contributionDisplay.py?contribId=33&sessionId=41&confId=44

There's plenty of learning material for Qt 4; the official
documentation at http://doc.trolltech.com/4.1 contains examples
and overviews that are readable if you already know C++. Those of us
who use PyQt4 are still catching up!

All the best,

David

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


Re: Python for Embedded Systems?

2006-07-15 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Paul Rubin   wrote:
>[EMAIL PROTECTED] (Cameron Laird) writes:
>> Yes and no.  Python could thrive for the next decade while
>> utterly surrendering the small-and-embedded domain to Forth,
>> Lua, Tcl, Scheme, and so on, so, no, there's no *need* for a
>> TinyPython.  On the other hand, yes, there are at least several
>> of us with an interest and occasional opportunities for Python
>> in such applications. 
>
>I think we should see what happens with PyPy, which might be easier to
>target at embedded platforms than CPython is.  Main thing needed would
>be a static compiler--I haven't followed PyPy enough to know if it
>relies on having Psyco at runtime.

PyPy indeed presents exciting prospects.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQT installation /configuration

2006-07-15 Thread [EMAIL PROTECTED]

David Boddie wrote:

> The module structures for PyQt3 and PyQt4 are quite different: the
> monolithic qt module from PyQt3 has been replaced by a number of
> modules in PyQt4. Despite this, there is a similar way to "import qt"
> in PyQt4:
>
>   from PyQt4 import Qt
>
> However, you will have difficulty using the examples in that book
> because it was written for PyQt3.

Ah yes, it doesn't recognise "QApplication" now. Never mind.

> Work is underway to "port" the book
> to PyQt4, but it will take some time. (You can help with this and learn
> about PyQt4 at the same time, if you want.)

Er...you might be overestimating my potential unless there's some
*really* entry-level material to be dealt with there. Though they do
say it's a good way to learn. Is there a forum?

> In the meantime, the set of slides from a talk at EuroPython 2006 is
> probably the only learning material on the web for PyQt4:
>
> http://indico.cern.ch/contributionDisplay.py?contribId=33&sessionId=41&confId=44
>
> There's plenty of learning material for Qt 4; the official
> documentation at http://doc.trolltech.com/4.1 contains examples
> and overviews that are readable if you already know C++.

One of the reasons I chose Python was so I wouldn't have to, alas.

Thanks!

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


Re: What is a type error?

2006-07-15 Thread Marshall
Joachim Durchholz wrote:
> Marshall schrieb:
> > Joachim Durchholz wrote:
> >> As I said elsewhere, the record has an identity even though it isn't
> >> explicit in SQL.
> >
> > H. What can this mean?
> >
> > In general, I feel that "records" are not the right conceptual
> > level to think about.
>
> They are, when it comes to aliasing of mutable data. I think it's
> justified by the fact that aliased mutable data has a galling tendency
> to break abstraction barriers. (More on this on request.)

I can see how pointers, or other kinds of aliasing
(by my more restricted definition) break abstraction barries;
it is hard to abstract something that can change out from
under you uncontrollably.


> > In any event, I am not sure what you mean by non-explicit
> > identity.
>
> The identity isn't visible from inside SQL. (Unless there's an OID
> facility available, which *is* an explicit identity.)

Agreed about OIDs.


>  > I would say, records in SQL have value, and their
> > identity is exactly their value.
>
> Definitely not. You can have two equal records and update just one of
> them, yielding non-equal records; by my definition (and by intuition),
> this means that the records were equal but not identical.

This sort of thing comes up when one has made the mistake of
not defining any keys on one's table and needs to rectify the
situation. It is in fact considered quite a challenge to do.
My preferred technique for such a situation is to create
a new table with the same columns and SELECT DISTINCT ...
INTO ... then recreate the original table. So that way doesn't
fit your model.

How else might you do it? I suppose there are nonstandard
extensions, such as UPDATE ... LIMIT. And in fact there
might be some yucky thing that made it in to the standard
that will work.

But what you descrbe is certainly *not* possible in the
relational algebra; alas that SQL doesn't hew closer
to it. Would you agree? Would you also agree that
if a language *did* adhere to relation semantics,
then relation elements would *not* have identity?
(Under such a language, one could not have two
equal records, for example.)

[The above paragraph is the part of this post that I
really care about; feel free to ignore the rest if it's naive
or annoying or whatever, but please do respond to this.]


>  > I do not see that they have
> > any identity outside of their value. We can uniquely identify
> > any particular record via a key, but a table may have more
> > than one key, and an update may change the values of one
> > key but not another. So it is not possible in general to
> > definitely and uniquely assign a mapping from each record
> > of a table after an update to each record of the table before
> > the update, and if you can't do that, then where
> > is the record identity?
>
> Such a mapping is indeed possible. Simply extend the table with a new
> column, number the columns consecutively, and identify the records via
> that column.

That doesn't work for me. It is one thing to say that for all
tables T, for all elements e in T, e has identity. It is a different
thing to say that for all tables T, there exists a table T' such
that for all elements e in T', e has identity.


> But even if you don't do that, there's still identity. It is irrelevant
> whether the programs can directly read the value of the identity field;
> the adverse effects happen because updates are in-place. (If every
> update generated a new record, then we'd indeed have no identity.)
>
> > Okay. At this point, though, the term aliasing has become extremely
> > general. I believe "i+1+1" is an alias for "i+2" under this definition.
>
> No, "i+1+1" isn't an alias in itself. It's an expression - to be an
> alias, it would have to be a reference to something.
>
> However, a[i+1+1] is an alias to a[i+2]. Not that this is particularly
> important - 1+1 is replacable by 2 in every context, so this is
> essentially the same as saying "a[i+2] is an alias of a[i+2]", which is
> vacuously true.

To me, the SQL with the where clause is like i+2, not like a[2].
A query is simply an expression that makes mention of a variable.
However I would have to admit that if SQL table elements have
identity, it would be more like the array example.

(The model of SQL I use in my head is one with set semantics,
and I am careful to avoid running in to bag semantics by, for
example, always defining at least one key, and using SELECT
DISTINCT where necessary. But it is true that the strict set
semantics in my head are not the wobbly bag semantics in
the standard.)


> There's another aspect here. If two expressions are always aliases to
> the same mutable, that's usually easy to determine; this kind of
> aliasing is usually not much of a problem.
> What's more of a problem are those cases where there's occasional
> aliasing. I.e. a[i] and a[j] may or may not be aliases of each other,
> depending on the current value of i and j, and *that* is a problem
> because the number of code paths t

about Python types and objects

2006-07-15 Thread pipehappy
Hi everyone:

I have read the booth python types and objects.  I think its book for
clearificating types and objects in python.  It says there will be a
book named python attributes and methods.  Do you know any information
about this book.  I am interested in it.

Thanks

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


Re: InteractiveConsole History on Linux

2006-07-15 Thread Chris Spencer
vbgunz wrote:
> vbgunz wrote:
>>> Why does code.InteractiveConsole support command history on Windows, but
>>> not in a Gnome terminal (all I get is ^[[A^[[B)? Or does it not support
>>> history at all, and the Windows console is implementing it's own? Is
>>> there any way to get command history working with InteractiveConsole on
>>> Linux?
>> The only time I see [A[B on Linux in a console is when I am not logged
>> in. Check to see if you're logged in and then try again. AFAIK, Linux
>> does support console history. I hope this helps :)
> 
> Sorry, I missed "code.InteractiveConsole" *but* maybe being logged in
> has something to do with it?

Heh, how could I run Python if I weren't logged in :P
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: InteractiveConsole History on Linux

2006-07-15 Thread Chris Spencer
Robert Kern wrote:
> Chris Spencer wrote:
>> Why does code.InteractiveConsole support command history on Windows, 
>> but not in a Gnome terminal (all I get is ^[[A^[[B)? Or does it not 
>> support history at all, and the Windows console is implementing it's 
>> own? Is there any way to get command history working with 
>> InteractiveConsole on Linux?
> 
> Be sure that the readline module is installed.

Yeah, "import readline" works just fine. My problem isn't hard to 
replicate. Can anyone else on Linux get command history to work with the 
following code? Note, it should be saved and run from a file.

from code import InteractiveConsole
i = InteractiveConsole(globals())
i.interact()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: InteractiveConsole History on Linux

2006-07-15 Thread Robert Kern
Chris Spencer wrote:
> Robert Kern wrote:
>> Chris Spencer wrote:
>>> Why does code.InteractiveConsole support command history on Windows, 
>>> but not in a Gnome terminal (all I get is ^[[A^[[B)? Or does it not 
>>> support history at all, and the Windows console is implementing it's 
>>> own? Is there any way to get command history working with 
>>> InteractiveConsole on Linux?
>> Be sure that the readline module is installed.
> 
> Yeah, "import readline" works just fine. My problem isn't hard to 
> replicate. Can anyone else on Linux get command history to work with the 
> following code? Note, it should be saved and run from a file.
> 
> from code import InteractiveConsole
> i = InteractiveConsole(globals())
> i.interact()

You will also have to make sure that you import readline, too. This works for 
me:

import readline
from code import InteractiveConsole
i = InteractiveConsole(globals())
i.interact()

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

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


Re: reading specific lines of a file

2006-07-15 Thread Nick Vatamaniuc
Yi,
Use the linecache module. The documentation states that :
"""
The linecache module allows one to get any line from any file, while
attempting to optimize internally, using a cache, the common case where
many lines are read from a single file.
>>> import linecache
>>> linecache.getline('/etc/passwd', 4)
'sys:x:3:3:sys:/dev:/bin/sh\012'
"""

Please note that you cannot really skip over the lines unless each has
a fixed known size. (and if all lines have a fixed, known size then
they can be considered as 'records' and you can use seek() and other
random access magic. That is why sometimes it is a lot faster to use
fixed length rows in a database => increase the speed of search but at
the expense of wasted space! - but this is a another topic for another
discussion...).

So the point is that you won't be able to jump to line 15000 without
reading lines 0-14999. You can either iterate over the rows by yourself
or simply use the 'linecache' module like shown above. If I were you I
would use the linecache, but of course you don't mention anything about
the context of your project so it is hard to say.

Hope this helps,
Nick Vatamaniuc


Yi Xing wrote:
> Hi All,
>
> I want to read specific lines of a huge txt file (I know the line #).
> Each line might have different sizes. Is there a convenient and fast
> way of doing this in Python? Thanks.
> 
> Yi Xing

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


Re: reading specific lines of a file

2006-07-15 Thread John Machin
On 16/07/2006 2:54 PM, Nick Vatamaniuc top-posted:
> Yi,
> Use the linecache module.

Yi, *don't* use the linecache module without carefully comparing the 
documentation and the implementation with your requirements.

You will find that you have the source code on your computer -- mine 
(Windows box) is at c:\Python24\Lib\linecache.py. When you read right 
down to the end (it's not a large file, only 108 lines), you'll find this:

 try:
 fp = open(fullname, 'rU')
 lines = fp.readlines()
 fp.close()
 except IOError, msg:
##  print '*** Cannot open', fullname, ':', msg
 return []
 size, mtime = stat.st_size, stat.st_mtime
 cache[filename] = size, mtime, lines, fullname

Looks like it's caching the *whole* of *each* file. Not unreasonable 
given it appears to have been written to get source lines to include in 
tracebacks.

It might just not be what you want if as you say you have "a huge txt 
file". How many megabytes is "huge"?

Cheers,
John

  The documentation states that :
> """
> The linecache module allows one to get any line from any file, while
> attempting to optimize internally, using a cache, the common case where
> many lines are read from a single file.
 import linecache
 linecache.getline('/etc/passwd', 4)
> 'sys:x:3:3:sys:/dev:/bin/sh\012'
> """
> 
> Please note that you cannot really skip over the lines unless each has
> a fixed known size. (and if all lines have a fixed, known size then
> they can be considered as 'records' and you can use seek() and other
> random access magic. That is why sometimes it is a lot faster to use
> fixed length rows in a database => increase the speed of search but at
> the expense of wasted space! - but this is a another topic for another
> discussion...).
> 
> So the point is that you won't be able to jump to line 15000 without
> reading lines 0-14999. You can either iterate over the rows by yourself
> or simply use the 'linecache' module like shown above. If I were you I
> would use the linecache, but of course you don't mention anything about
> the context of your project so it is hard to say.
> 
> Hope this helps,
> Nick Vatamaniuc
> 
> 
> Yi Xing wrote:
>> Hi All,
>>
>> I want to read specific lines of a huge txt file (I know the line #).
>> Each line might have different sizes. Is there a convenient and fast
>> way of doing this in Python? Thanks.
>>
>> Yi Xing
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: InteractiveConsole History on Linux

2006-07-15 Thread Chris Spencer
Robert Kern wrote:
> Chris Spencer wrote:
>> Robert Kern wrote:
>>> Chris Spencer wrote:
 Why does code.InteractiveConsole support command history on Windows, 
 but not in a Gnome terminal (all I get is ^[[A^[[B)? Or does it not 
 support history at all, and the Windows console is implementing it's 
 own? Is there any way to get command history working with 
 InteractiveConsole on Linux?
>>> Be sure that the readline module is installed.
>>
>> Yeah, "import readline" works just fine. My problem isn't hard to 
>> replicate. Can anyone else on Linux get command history to work with 
>> the following code? Note, it should be saved and run from a file.
>>
>> from code import InteractiveConsole
>> i = InteractiveConsole(globals())
>> i.interact()
> 
> You will also have to make sure that you import readline, too. This 
> works for me:
> 
> import readline
> from code import InteractiveConsole
> i = InteractiveConsole(globals())
> i.interact()

Actually, it seems redirecting sys.stdout for my logger was the issue. 
Thanks for your help though.

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