Re: Is it better to use class variables or pass parameters?

2006-03-02 Thread Duncan Booth
Derek Basch wrote:

> This one has always bugged me. Is it better to just slap a "self" in
> front of any variable that will be used by more than one class method
> or should I pass around variable between the methods?

Try to distinguish the state of the object from the parameters to methods.

An object should always have a consistent state. Say you call a method, and 
that method calls a bunch of other methods. At almost any point during 
those method calls execution can leak out to other bits of code (e.g. you 
might think you are adding two values, but perhaps they have a user defined 
addition operator) and that other code might just call methods on the same 
object. This might not happen much in practice, but I think that if you 
imagine all method calls as potentially happening in parallel it avoids a 
lot of problems.

So, for example, if you had a method which returned a formatted 
representation of something, and which took a precision as a parameter, you 
shouldn't be saving the precision in the object: it isn't part of the 
state, and if you save it as such one day you might find it changes under 
your feet mid call.

A lot of objects benefit from being treated as immutable: i.e. initialise 
them on creation, but never modify the attributes after creation. This has 
the great benefit that you never need to worry about whether or not to copy 
an object: you always just keep using the same object until an attribute 
needs to change and then you just create a new one. Obviously this only 
works for lightweight objects, but that should be most of them.

Passing one or two parameters around a host of methods is fine: if you are 
passing more then it probably indicates you need to invent another object 
to encapsulate the state associated with the method call. It is also likely 
that it means you then want to move some of the code logic into the new 
object. In other words, instead of:

   obj.meth1(a, b, c, d) calls obj.meth2(a, b, c, d) calls obj.meth3, ...

(and perhaps meth2 only needs a, b and c so it can pass them on),
you want some helper object constructed with a, b, c & d and parts of the 
original methods then get factored into methods on the help objects.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Runtime Error when loading ".pyd" module

2006-03-02 Thread Fredrik Lundh
Terry Tang wrote:

> it hits a "Runtime Error" (which is shown in a message box saying "abnormal
> program termination") and a message like the following is printed in the
> console:
> Fatal Python error: Interpreter not initialized (version mismatch?)

both the main executable (e.g. python.exe or your own application)
and the various PYD files are linked against the Python core DLL (e.g.
python24.dll), and this error typically indicates that the PYD picks up
another copy of that DLL than the EXE is using.

e.g.

1. python.exe starts
2. when python.exe needs python24.dll, the runtime linker finds
/foo/bar/python24.dll and loads it
3. python.exe initializes the python24.dll instance
4. python.exe starts your python program
5. your python program imports the foobar module
6. python.exe loads /foo/modules/foobar.pyd for you
7. when foobar.pyd needs python24.dll, the runtime linker finds
/flub/python24.dll before /foo/bar/python24.dll
8. foobar.pyd calls /flub/python24.dll, which notices that it hasn't
been properly initialized, and terminates.

another possible option is that foobar.pyd is from an earlier python
version, so you get

7. when foobar.pyd needs python23.dll, the runtime linker finds
/foo/bar/python23.dll and loads it
8. foobar.pyd calls /foo/bar/python23.dll, which notices that it
hasn't been properly initialized, and terminates.

but the PYD loader used in step 6 has extra logic in it to attempt
to detect this case (it checks what python DLLs a PYD file is using
before it loads the PYD), so you usually get a better error message
if this is the case.

anyway, the first thing to do is to look for stray pythonXX.dll files
("python23.dll" in your case).

hope this helps!





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


Re: Rapid web app development tool for database

2006-03-02 Thread bruno at modulix
George Sakkis wrote:
> Is there any tool in python (or with python bindings) like Oracle
> Application Express, former HTML DB
> (http://www.oracle.com/technology/products/database/application_express/index.html)
> ? Ideally it should be dbms-agnostic, e.g. by using SQLObject to talk
> to the database. The closest I can think of is Dabo, but it (currently)
> supports wxPython only for the UI. If there isn't anything like this
> out of the box, what would the best starting point be for implementing
> such a system ? Extending Dabo, a web framework (e.g. Django), or
> something different ? 


AFAICT, Dabo is supposed to grow a web UI someday, so if it's close to
what you're looking for, you may want to make this happens sooner !-)

Else, you could have a look at Django, Turbogears or Pylons.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


compare classes and not class instances

2006-03-02 Thread [EMAIL PROTECTED]
I not only want to compare class *instances* but also the classes
themselves. Something like:

class T(object):
@classmethod
def __cmp__(cls, other):
return cmp(cls.__name__, other.__name__)
@instancemethod
def __cmp__(self, other):
return cmp(self.x, other.x)

class B(T): pass
class A(T): pass

sorted([B, A]) => [A, B]

My motivation for doing so is simply to sort classes based on their
names and not (as it seems is the default behaviour) on the order in
which they were created.

I guess I could always just do something like sorted(classes,
key=lambda cls: cls.__name__)...but where's the fun in that? :-)

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


Re: PythonWin: any way to delete all objects without exiting and without doing it with "del"?

2006-03-02 Thread dananrg
> PythonWin is just an IDE. For what reason you have to delete all objects by
> yourself? Garbage collector is there for that :)

I think the garbage collector is on strike. :-)

Example:

# 1st execution
a = [1,2,3]
print a

>>> [1,2.3]

program ends.

Then I comment out a = [1,2,3] and run the program:

# 2nd execution
# a = [1,2,3]
print a

>>> [1,2,3]

Same result. Why? I know that's not a great example, but it was giving
me grief in the debugging process while using the ODBC module. I'd
really rather not have to exit out of PythonWin each time I want to
clear out all the objects I created during a script, and then
subsequently comment out for future executions of a script for
debugging, if that makes any sense.

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


read sys.stdin, then raw_input

2006-03-02 Thread Rory Campbell-Lange
I'm stumped. I'm piping some content to a python program, but then want
the python program to prompt me for an answer. It goes on reading
the pipe and gives a "EOFError: EOF when reading a line".

eg:
#!/usr/bin/python

import sys
text = sys.stdin.read()
sel = raw_input('Selection? : ')

Selection? : Traceback (most recent call last):
  File "/tmp/z.py", line 5, in ?
sel = raw_input('Selection? : ')
EOFError: EOF when reading a line

Advice much appreciated.

Rory

-- 
Rory Campbell-Lange 
<[EMAIL PROTECTED]>

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


Re: Best python module for Oracle, but portable to other RDBMSes

2006-03-02 Thread Magnus Lycka
[EMAIL PROTECTED] wrote:
> This is from a database I didn't design and can't change. The problem
> is that the ODBC module suffixes an "L" to any integer returned that
> was defined as data type number(p). For example, an integer stored as:
>  56  will be returned as 56L. Numbers that were specified as
> number(p,s), the module has no problem with.
> 
> Anyone know why this would happen?

I'm sure the Python tutorial explains the difference between integer
and long types. Fields of type NUMBER or DECIMAL might well be larger
than sys.maxint, so you always get longs back when you fetch data
from such a column. This is as it should be.

What seems to be the problem?

If you actually get a suffixed L in the resulting text file, you
are using a strange way to convert your data to text. You aren't
simply printing lists or tuples are you? Then other types, such as
datetime objects will also look bizarre. (Not that the ancient
odbc would support that...)

You might want to look at the csv module for text export.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best python module for Oracle, but portable to other RDBMSes

2006-03-02 Thread Magnus Lycka
[EMAIL PROTECTED] wrote:
> The other thing I didn't do a good job of explaining is that I want to
> have a layer of abstraction between the underlying RDBMS and the
> business logic. It's the business logic I want to use Python for, so
> that would stay roughly the same between RDBMS changes, if we ever have
> an RDBMS change. I agree that I probably have more things to worry if I
> was to change RDBMS vendors than what I'm describing here.

Have a look at SQLAlchemy.


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


Re: compare classes and not class instances

2006-03-02 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> I not only want to compare class *instances* but also the classes
> themselves. Something like:
 
> sorted([B, A]) => [A, B]
> 
> My motivation for doing so is simply to sort classes based on their
> names and not (as it seems is the default behaviour) on the order in
> which they were created.
> 
> I guess I could always just do something like sorted(classes,
> key=lambda cls: cls.__name__)...but where's the fun in that? :-)

A class is just an instance of its metaclass. Therefore the metaclass is the
right place to implement the __cmp__() method:

>>> class T:
... class __metaclass__(type):
... def __cmp__(cls, other):
... return cmp(cls.__name__, other.__name__)
...
>>> class B(T): pass
...
>>> class A(T): pass
...
>>> class C(T): pass
...
>>> sorted([C, B, A])
[, , ]

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


Problem with dbi, odbc module and Oracle 9.2 - suffixed "L" with number data type

2006-03-02 Thread dananrg
I was messing around with the native ODBC module (I am using Python in
a Win32 environment), e.g:

import dbi, odbc

...and it seems to meet my needs. I'd rather use a module that comes
natively with Python if it works (don't care about performance in this
particular use case; just that it works).

The only issue I've had so far is retrieving data from Oracle when an
integer has been defined like:

   number(p)[same thing as number(p,0) evidently]

This is from a database I didn't design and can't change. Evidently
there are new ways to declare integer data types in Oracle.

The problem is that the ODBC module suffixes an "L" to any integer
returned that
was defined as data type number(p). For example, an integer stored as:
56  will be returned as 56L. Actually, it now seems to be doing the
same thing, at least in some cases, for number data types declared as
number(p,s). What gives? Anyone know why this would happen?

Can't use mxODBC because it's a commercial product and can't use
cx_oracle at the moment because I am stuck with Python 2.1 (for ESRI
geoprocessing), and there is no cx_oracle for Python 2.1 (starts with
Python 2.2 and refuses to install for 2.1). I could install a later
version of Python independently, but I need to be able to do the
geoprocessing that 2.1 allows as well as ODBC calls to Oracle all in
the same script. This means dbi,odbc seems to be my only choice.

Thanks for the help so far y'all. As a former Perl devotee, I now
worship at the altar of Python.

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


ODBC module and strange date reference <...>

2006-03-02 Thread dananrg
Been using the ODBC module for Python 2.1 (Win32) and had another
question. When I return data from date columns, it's in a strange
object form, e.g.  (don't have the output in front
of me>.

What's an easy way to convert date objects into a human-readable
string? I'm using this module to extract data from an Oracle database,
then converting it to a flat-file for import into an old flat-file
database on a mainframe. I need to be able to change the date object
into something the mainframe database will recognize.

Incidentally, I have just ordered:

* Learning Python
* Python Cookbook
* Python Pocket Reference

Are there any other books y'all would recommend as essential Python
references and/or books for becoming fluent in Python?

Thanks again.

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


Re: read sys.stdin, then raw_input

2006-03-02 Thread Rory Campbell-Lange
To clarify, how can I get a normal terminal prompt for raw_input to
enable me to insert a value into variable 'sel'?

The program wants to keep reading from the piped file, it seems.

Rory

On 01/03/06, Rory Campbell-Lange ([EMAIL PROTECTED]) wrote:
> I'm stumped. I'm piping some content to a python program, but then want
> the python program to prompt me for an answer. It goes on reading
> the pipe and gives a "EOFError: EOF when reading a line".
> 
> eg:
> #!/usr/bin/python
> 
> import sys
> text = sys.stdin.read()
> sel = raw_input('Selection? : ')
> 
> Selection? : Traceback (most recent call last):
>   File "/tmp/z.py", line 5, in ?
> sel = raw_input('Selection? : ')
> EOFError: EOF when reading a line
> 
> Advice much appreciated.

-- 
Rory Campbell-Lange 
<[EMAIL PROTECTED]>

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


Re: Problem with dbi, odbc module and Oracle 9.2 - suffixed "L" with number data type

2006-03-02 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> I was messing around with the native ODBC module (I am using Python in
> a Win32 environment), e.g:
> 
> import dbi, odbc
> 
> ...and it seems to meet my needs. I'd rather use a module that comes
> natively with Python if it works (don't care about performance in this
> particular use case; just that it works).
> 
> The only issue I've had so far is retrieving data from Oracle when an
> integer has been defined like:
> 
>number(p)[same thing as number(p,0) evidently]
> 
> This is from a database I didn't design and can't change. Evidently
> there are new ways to declare integer data types in Oracle.
> 
> The problem is that the ODBC module suffixes an "L" to any integer
> returned that
> was defined as data type number(p). For example, an integer stored as:
> 56  will be returned as 56L. Actually, it now seems to be doing the
> same thing, at least in some cases, for number data types declared as
> number(p,s). What gives? Anyone know why this would happen?

Well, it is a legal python umber literal. Fire up your python interpreter
and do

>>> long(1)
1L

It simply says that it is a long, not an int (which means 64 rather than 32
bits of precision I think)

So - no need to worry.

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


Re: spaces at ends of filenames or directory names on Win32

2006-03-02 Thread Christos Georgiou
On Thu, 23 Feb 2006 17:49:31 -0600, rumours say that Larry Bates
<[EMAIL PROTECTED]> might have written:

>IMHO leading and/or trailing spaces in filenames is asking for
>incompatibilities with cross-platform file access.  Much like
>using single-quote in filenames which are perfectly legal in
>DOS/Windows, but Linux doesn't like much.

Just for those who don't know, in general *nix operating systems (and the
various *nix file systems) disallow only '\0' and '/' in filenames.  The '/'
because obviously is the path separator, and '\0' because it's the
end-of-string marker in C.

When Larry said "Linux", he actually meant the shell he uses.
-- 
TZOTZIOY, I speak England very best.
"Dear Paul,
please stop spamming us."
The Corinthians
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie in python

2006-03-02 Thread Simon Brunning
On 3/2/06, - C Saha - <[EMAIL PROTECTED]> wrote:
>
> Hello Python Experts
>
> I am Chirantan, a beginner in python programming world. I have some
> programming knowledge in SHELL, BATCH and little bit PERL. I subscribed to
> this list with the hope that I will get support and help from all of you.
>
> To start with, I thought it will be a good idea to start reading the
> tutorials which I got from google search (search by name "python tutorial").
> It would be great if anyone knows about some other tutorial which can help
> me to start learning python quickly.

You'll find plenty to choose from here: .

Welcome to Python!

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proper class initialization

2006-03-02 Thread Christoph Zwerschke
Steven Bethard wrote:
> I assume the intention was to indicate that the initialization required 
> multiple statements.  I just couldn't bring myself to write that 
> horrible for-loop when the sum() function is builtin. ;)

Yes, this was just dummy code standing for something that really 
requires multiple statements and auxiliary variables.

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


Re: Proper class initialization

2006-03-02 Thread Christoph Zwerschke
Steven Bethard wrote:
> I don't run into this often, but when I do, I usually go Jack 
> Diederich's route::
> 
> class A(object):
> class __metaclass__(type):
> def __init__(cls, name, bases, classdict):
> cls.sum = sum(xrange(10))

Good idea, that is really nice and readable. Now all the init code is 
defined inline at the top of the class definition.

> But you can also go something more akin to your route::
> 
> class A(object):
> def _get_sum():
> return sum(xrange(10))
> sum = _get_sum()
> 
> Note that you don't need to declare _get_sum() as a classmethod, because 
> it's not actually a classmethod -- it's getting used before the class 
> yet exists.  Just write it as a normal function and use it as such -- 
> that is, no ``self`` or ``cls`` parameter.

Often it's so simple ;-) But the disadvantage is then that you cannot 
set the class variables directly inside that function. So if you have to 
initialize several of them, you need to define several functions, or 
return them as a tuple and it gets a bit ugly. In this case, the first 
solution may be better.

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


Newbie errors :-( Need help

2006-03-02 Thread - C Saha -
Hi All      I am getting the result but along with this error, any idea what could be the reason?        fibo.fib(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987Traceback (most recent call last):  File "", line 1, in ?  File "fibo.py", line 8, in fib    return resultNameError: global name 'result' is not defined        Code is given below        # Fibonacci numbers moduledef fib(n): # write Fibonacci series up to n    a, b = 0, 1    while b < n:    print b,    a, b = b, a+b    return result      Thanks a lot to all !
 in
 advance Thanks & Regards CSaha
		Yahoo! Mail
Bring photos to life! New PhotoMail  makes sharing a breeze. 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Printing a file

2006-03-02 Thread Jeremy Sanders
David Boddie wrote:

> That's where QPrintDialog comes in:
> 
>   http://doc.trolltech.com/4.1/qprintdialog.html
> 
> It's also secretly available in Qt 3 via the QPrinter.setup() method:
> 
>   printer = QPrinter()
>   printer.setup()
>   # Now, paint onto the printer as usual.

No - that was in my example. The work I was refering to was taking the
user's input to the dialog and writing the pages to the device in the right
order (I don't think this is done automatically).

Jeremy

-- 
Jeremy Sanders
http://www.jeremysanders.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie errors :-( Need help

2006-03-02 Thread Rory Campbell-Lange
There is no variable called result in your function or, presumably, in
the global scope of the programme.

As you aren't returning anything you may as well omit that line.

On 02/03/06, - C Saha - ([EMAIL PROTECTED]) wrote:
>   I am getting the result but along with this error, any idea what could be 
> the reason?
>
>   fibo.fib(1000)
>  1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987Traceback (most recent call 
> last):
>   File "", line 1, in ?
>   File "fibo.py", line 8, in fib
> return result
> NameError: global name 'result' is not defined
-- 
Rory Campbell-Lange 
<[EMAIL PROTECTED]>

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


Re: Newbie errors :-( Need help

2006-03-02 Thread Simon Brunning
On 3/2/06, - C Saha - <[EMAIL PROTECTED]> wrote:
> I am getting the result but along with this error, any idea what could be
> the reason?
>
> fibo.fib(1000)
>  1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987Traceback (most recent call
> last):
>   File "", line 1, in ?
>   File "fibo.py", line 8, in fib
> return result
> NameError: global name 'result' is not defined
>
> Code is given below
> # Fibonacci numbers module
> def fib(n): # write Fibonacci series up to n
> a, b = 0, 1
> while b < n:
> print b,
> a, b = b, a+b
> return result

You are returning something called 'result', but you never create
anything with that name.

Since in your function you are printing your results, you should be
able to just drop that line and it'll work just fine.

If OTOH you want your function to return something that can be used
elsewhere, you might try something like (untested):

def fib(n):
a, b = 0, 1
result = list()
while b < n:
result.append(b)
a, b = b, a+b
return result

(You might also do this with a generator - in fact that's not a bad
idea - but generators are an advanced subject, so I'd steer clear for
the moment)

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


puzzled by ImageDraw line

2006-03-02 Thread alexandre_irrthum
Hi there,

I am puzzled by the comportment of the line function from the ImageDraw
module with regard to the way it draws or does not draw the last pixel
of a line.

Below I test this function on a 3x3 image and show schematic
representations of obtained images (where o means a drawn pixel)

import Image, ImageDraw
im = Image.new("L", (3,3))
draw = ImageDraw.Draw(im)
draw.line((0,0,2,2), fill=255)
im.save("test.tif")

Gives:

o--
-o-
---

So the last pixel of the line is not drawn.

Similarly, draw.line((0,2,2,0), fill=255) gives:

---
-o-
o--

And draw.line((1,0,1,2), fill=255) gives:

-o-
-o-
---

But, surprisingly, draw.line((0,1,2,1), fill=255) gives:

---
ooo
---

Where the last pixel of the line -is- drawn, as I expected it would be
for all lines.

This seems to be true for various image sizes and line angles: the last
pixel is never drawn unless the line is horizontal.

Any clues ?

Thanks

alex

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


Re: Printing a file

2006-03-02 Thread David Boddie
Sorry about that. I must have just skipped over the setup() call in
your code. If you're creating highly customized content then I think
you'll always need to think about getting the pages to the printer in
the right order.

For rich text documents, there's code that does this in the Qt 3 text
drawing demo (see the filePrint() method in the
examples/demo/textdrawing/textedit.cpp file).

In Qt 4, the demos/textedit demo does this with a lot less code.

Or are you think of something else?

David

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


Shell Navigation

2006-03-02 Thread William Meyer
I am having trouble with the python interactive shell. The arrow keys render as
^[[D, ^[[A, etc making line editing impossible. The arrow keys (and function
keys) work fine in bash, but in the python shell they are printed. Any ideas
what is going on?

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


Re: Shell Navigation

2006-03-02 Thread Simon Brunning
On 3/2/06, William Meyer <[EMAIL PROTECTED]> wrote:
> I am having trouble with the python interactive shell. The arrow keys render 
> as
> ^[[D, ^[[A, etc making line editing impossible. The arrow keys (and function
> keys) work fine in bash, but in the python shell they are printed. Any ideas
> what is going on?

Sounds like a readline problem. Your OS? How did you install Python?

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: telnetlib problems

2006-03-02 Thread Eddie Corns
[EMAIL PROTECTED] writes:

>Thanks for the reply. I've replaced the call to read_very_eager() with
>read_until() and enabled debugging messages.  My script now looks like
>this...

>#
>import telnetlib

>tn = telnetlib.Telnet('192.168.100.11')

>tn.set_debuglevel(9)

>tn.read_until('login: ', 5)

>tn.write('user\n')

>tn.read_until('Password: ', 5)

>tn.write('password\n')

>tn.read_until('bash-2.05$ ', 5)

>tn.write('ls\n')

>print tn.read_until('bash-2.05$ ', 5)
>#

>Each call to read_until() returns a valid string except for the second
>one, i.e.,
>tn.read_until('Password: ', 5) returns a null string.

>Here's the program output with debugging enabled...
>#
>Telnet(192.168.100.11,23): recv "\xff\xfd\x18\xff\xfd
>\xff\xfd#\xff\xfd'"
>Telnet(192.168.100.11,23): IAC DO 24
>Telnet(192.168.100.11,23): IAC DO 32
>Telnet(192.168.100.11,23): IAC DO 35
>Telnet(192.168.100.11,23): IAC DO 39
>Telnet(192.168.100.11,23): recv
>'\xff\xfb\x03\xff\xfd\x01\xff\xfd\x1f\xff\xfb\x05\xff\xfd!'
>Telnet(192.168.100.11,23): IAC WILL 3
>Telnet(192.168.100.11,23): IAC DO 1
>Telnet(192.168.100.11,23): IAC DO 31
>Telnet(192.168.100.11,23): IAC WILL 5
>Telnet(192.168.100.11,23): IAC DO 33
>Telnet(192.168.100.11,23): recv '\xff\xfb\x03'
>Telnet(192.168.100.11,23): IAC WILL 3
>Telnet(192.168.100.11,23): recv '\xff\xfb\x01Embedded Systems, 2050
>Single Board Computer.\r\nR'
>Telnet(192.168.100.11,23): IAC WILL 1
>Telnet(192.168.100.11,23): recv 'uning \\s Kernel \\r.\r\nEmbedded:
>2050 Special Feature'
>Telnet(192.168.100.11,23): recv 's Enabled.\r\n\r\n'
>Telnet(192.168.100.11,23): recv 'login: '
>Telnet(192.168.100.11,23): send 'user\n'
>Telnet(192.168.100.11,23): send 'password\n'
>Telnet(192.168.100.11,23): recv 'Password: '
>Telnet(192.168.100.11,23): send 'ls\n'
>Telnet(192.168.100.11,23): recv '\r\n'
>Telnet(192.168.100.11,23): recv 'Login incorrect\r\n\r\nlogin: '


>Login incorrect



>login:
>#
>It looks like it's sending the password before receiving the password
>prompt.

It looks more like it's taking longer than 5 seconds to receive the Password:
prompt so it times out, returns to your code and you send the next string
anyway but (assuming this is a valid password) the far end might throw away
any pending input when it finally does send the Password: prompt (otherwise it
would probably have got back in sync).

In short you shouldn't go past each stage unless you've verified that you got
the expected response.  I can't actually remember exactly what the responses
signify but at a minimum I assume the empty string means there's no point in
continuing because what you expected to see wasn't there so you need to either
abort or try some recovery process.  And also make sure you give it a
reasonable time to respond.

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


Re: in need of some sorting help

2006-03-02 Thread Kent Johnson
ianaré wrote:
> Hey all,
> 
> if i use a os.walk() to append files to a list like so...
> 
> files = []
> root = self.path.GetValue() # wx.TextCtrl input
> filter = self.fileType.GetValue().lower()  # wx.TextCtrl input
> not_type = self.not_type.GetValue()  # wx.CheckBox input
> 
> for base, dirs, walk_files in os.walk(root):
> main.Update()
> # i only need the part of the filename after the
> user selected path:
> base = base.replace(root,"")
> 
> for entry in walk_files:
> entry = os.path.join(base,entry)
> if filter != "":
> if filter in entry.lower() and not
> not_type:
> files.append(entry)
> if filter not in entry.lower() and
> not_type:
> files.append(entry)
> else:
> files.append(entry)
> 
> ... will it sort properly on mac and *nix? if not, is there a tried an
> true sorting method someone could graciously let me know of?

The lists of files and directories yielded by os.walk() will be in the 
order that the OS returns them from os.listdir(). According to the docs 
this list is in "arbitrary" order.

You can sort the lists yourself. If you modify dirs in place it will 
affect the subsequent walk. So you could use
for base, dirs, walk_files in os.walk(root):
   dirs.sort(key=str.lower) # note no need for lambda
   walk_files.sort(key=str.lower)
   # etc

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


Re: Shell Navigation

2006-03-02 Thread William Meyer
Simon Brunning  brunningonline.net> writes:

> Sounds like a readline problem. Your OS? How did you install Python?

Yea, that was it. I just had to copy readline.so from another installation.
Thanks for the quick reply



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


logging to a text widget

2006-03-02 Thread Alexandre Guimond
Hi. I'm using the logging package. I would like to send my log messages
to a Text widget creating using Tkinter. I was wondering if there was a
logging handler class that would do this. It seems that the standard
handlers do not support this. Has anyone tried to do this?

Thx for any help,

alex

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


Re: why? [win32com/WMI]

2006-03-02 Thread Sergey

"Tim Golden" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
[Sergey]

>import wmi
>c = wmi.WMI (computer="srv", user="[EMAIL PROTECTED]", password="")
>pid, retval = c.Win32_Process.Create (CommandLine="notepad.exe")

Wonderful... It works.

But I tryed the module, by the sample from help(wmi):

>>> remote_process = wmi.WMI (computer="pms-dc", user="...", 
>>> password="...").new ("Win32_Process")

And got:

Traceback (most recent call last):
  File "", line 1, in ?
  File "C:\Python24\Lib\site-packages\wmi.py", line 624, in new
return getattr (self, class_name).new (**kwargs)
  File "C:\Python24\Lib\site-packages\wmi.py", line 539, in new
obj.set (**kwargs)
  File "C:\Python24\Lib\site-packages\wmi.py", line 394, in set
handle_com_error (error_info)
  File "C:\Python24\Lib\site-packages\wmi.py", line 199, in handle_com_error
raise x_wmi, "\n".join (exception_string)
wmi.x_wmi: -0x7ffdfff7 - Exception occurred.
  Error in: SWbemObjectEx
  -0x7ffbefdc - Provider is not capable of the attempted operation


So I decided to fallback to clean COM.


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


Re: read sys.stdin, then raw_input

2006-03-02 Thread Fredrik Lundh
Rory Campbell-Lange wrote:

> To clarify, how can I get a normal terminal prompt for raw_input to
> enable me to insert a value into variable 'sel'?
>
> The program wants to keep reading from the piped file, it seems.
>
> Rory
>
> On 01/03/06, Rory Campbell-Lange ([EMAIL PROTECTED]) wrote:
> > I'm stumped. I'm piping some content to a python program, but then want
> > the python program to prompt me for an answer. It goes on reading
> > the pipe and gives a "EOFError: EOF when reading a line".
> >
> > eg:
> > #!/usr/bin/python
> >
> > import sys
> > text = sys.stdin.read()
> > sel = raw_input('Selection? : ')
> >
> > Selection? : Traceback (most recent call last):
> >   File "/tmp/z.py", line 5, in ?
> > sel = raw_input('Selection? : ')
> > EOFError: EOF when reading a line
> >
> > Advice much appreciated.

since there's only one input channel for a program (stdin), and raw_input
reads from that channel, I don't think there's a portable way to do this.

on unixoid systems, something like this could work:

import sys

text = sys.stdin.read()

# rebind sys.stdin to my tty
sys.stdin = open("/dev/tty")
sel = raw_input("Selection? : ")





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


Re: Suggestions for documentation generation?

2006-03-02 Thread kpd
Thanks - I took at both. Also at 'percepts', which I used a long time
ago (had forgotten about  it). Percepts has a great little java applet
for viewing the class hierarchy.  I don't think it works for python,
just C++ though.  Looks like doxygen will fit the bill.

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


Re: Proper class initialization

2006-03-02 Thread Kent Johnson
Steven Bethard wrote:
> I don't run into this often, but when I do, I usually go Jack 
> Diederich's route::
> 
> class A(object):
> class __metaclass__(type):
> def __init__(cls, name, bases, classdict):
> cls.sum = sum(xrange(10))

I think you should call the superclass __init__ as well:

 class __metaclass__(type):
 def __init__(cls, name, bases, classdict):
 super(__metaclass__, cls).__init__(name, bases, classdict)
 cls.sum = sum(xrange(10))

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


RE: why? [win32com/WMI]

2006-03-02 Thread Tim Golden
[Sergey]

| "Tim Golden" <[EMAIL PROTECTED]> wrote in 
| message news:[EMAIL PROTECTED]
| [Sergey]
| 
| >import wmi
| >c = wmi.WMI (computer="srv", user="[EMAIL PROTECTED]", password="")
| >pid, retval = c.Win32_Process.Create (CommandLine="notepad.exe")
| 
| Wonderful... It works.
| 
| But I tryed the module, by the sample from help(wmi):
| 
| >>> remote_process = wmi.WMI (computer="pms-dc", user="...", 
| password="...").new ("Win32_Process")
| 
| And got:
| 
| Traceback (most recent call last):
|   File "", line 1, in ?
|   File "C:\Python24\Lib\site-packages\wmi.py", line 624, in new
| return getattr (self, class_name).new (**kwargs)
|   File "C:\Python24\Lib\site-packages\wmi.py", line 539, in new
| obj.set (**kwargs)
|   File "C:\Python24\Lib\site-packages\wmi.py", line 394, in set
| handle_com_error (error_info)
|   File "C:\Python24\Lib\site-packages\wmi.py", line 199, in 
| handle_com_error
| raise x_wmi, "\n".join (exception_string)
| wmi.x_wmi: -0x7ffdfff7 - Exception occurred.
|   Error in: SWbemObjectEx
|   -0x7ffbefdc - Provider is not capable of the attempted operation
| 
| 
| So I decided to fallback to clean COM.

Ah. Apologies; that example is a little out of date. I'll have to
clean up my docs. Obviously, if you want to use "clean COM" then
feel free, but the example you cite above which works for you

pid, retval = c.Win32_Process.Create (...)

does the same thing as the out-of-date example. Although I'm
not entirely sure why that fails. What version of Windows
are you using, by the way? It's possible that I've put something
XP-specific into the module.


Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import wmi
>>> remote_process = wmi.WMI (computer="vogbp364").new ("Win32_Process")

>>>
>>> for i in wmi.WMI ().Win32_OperatingSystem ():
...   print i.Caption
...
Microsoft Windows XP Professional
>>>


If you want to go for raw COM, I'm quite happy to give
examples of what you need if you can't work it out; likewise,
I'm happy to work with you to get the wmi module working on
your system if it's something I can easily fix/alter.

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: read sys.stdin, then raw_input

2006-03-02 Thread Rory Campbell-Lange
That works great for me on my unixoid system.

Thanks, Fredrik.

On 02/03/06, Fredrik Lundh ([EMAIL PROTECTED]) wrote:
> since there's only one input channel for a program (stdin), and raw_input
> reads from that channel, I don't think there's a portable way to do this.
> 
...
> # rebind sys.stdin to my tty
> sys.stdin = open("/dev/tty")
-- 
Rory Campbell-Lange 
<[EMAIL PROTECTED]>

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


Re: ODBC module and strange date reference <...>

2006-03-02 Thread Frank Millman

[EMAIL PROTECTED] wrote:
> Been using the ODBC module for Python 2.1 (Win32) and had another
> question. When I return data from date columns, it's in a strange
> object form, e.g.  (don't have the output in front
> of me>.
>
> What's an easy way to convert date objects into a human-readable
> string? I'm using this module to extract data from an Oracle database,
> then converting it to a flat-file for import into an old flat-file
> database on a mainframe. I need to be able to change the date object
> into something the mainframe database will recognize.
>

odbc returns something called a DbiDate object.

You can convert this into a datetime object like this -

import datetime
dat = datetime.datetime.fromtimestamp(int(dbidate_object))

Now you can use any of the datetime attributes or methods to convert it
to human-readable form, such as dat.year, dat.month, str(dat), etc

I use odbc with MS Sql Server. I have never used Oracle, so I can't be
sure that it works the same way. Try it and see what happens.

HTH

Frank Millman

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


Re: in need of some sorting help

2006-03-02 Thread Peter Otten
Kent Johnson wrote:

> dirs.sort(key=str.lower) # note no need for lambda

However, this will raise a TypeError for unicode directory names while the
lambda continues to work. 

Peter

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


Re: Problem with dbi, odbc module and Oracle 9.2 - suffixed "L" with number data type

2006-03-02 Thread dananrg
Great, thanks Diez! Should I just use str(n) to convert it to a format
I can write out to a flat file? I'm also struggling with the strange
date object format that the ODBC module returns when I fetch rows. I
need to convert that to a text string in a format that a mainframe
flatfile database requires. Any advice there?

Diez B. Roggisch wrote:
> [EMAIL PROTECTED] wrote:
>
> > I was messing around with the native ODBC module (I am using Python in
> > a Win32 environment), e.g:
> >
> > import dbi, odbc
> >
> > ...and it seems to meet my needs. I'd rather use a module that comes
> > natively with Python if it works (don't care about performance in this
> > particular use case; just that it works).
> >
> > The only issue I've had so far is retrieving data from Oracle when an
> > integer has been defined like:
> >
> >number(p)[same thing as number(p,0) evidently]
> >
> > This is from a database I didn't design and can't change. Evidently
> > there are new ways to declare integer data types in Oracle.
> >
> > The problem is that the ODBC module suffixes an "L" to any integer
> > returned that
> > was defined as data type number(p). For example, an integer stored as:
> > 56  will be returned as 56L. Actually, it now seems to be doing the
> > same thing, at least in some cases, for number data types declared as
> > number(p,s). What gives? Anyone know why this would happen?
>
> Well, it is a legal python umber literal. Fire up your python interpreter
> and do
>
> >>> long(1)
> 1L
>
> It simply says that it is a long, not an int (which means 64 rather than 32
> bits of precision I think)
> 
> So - no need to worry.
> 
> Diez

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


Re: ODBC module and strange date reference <...>

2006-03-02 Thread dananrg
Thanks Frank. Much appreciated. I will give it a go.

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


Re: ODBC module and strange date reference <...>

2006-03-02 Thread dananrg
Thanks Frank. Much appreciated. I will give it a go.

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


RE: why? [win32com/WMI]

2006-03-02 Thread Tim Golden
[Sergey]

| "Tim Golden" <[EMAIL PROTECTED]> wrote in 
| message news:[EMAIL PROTECTED]
| [Sergey]
| 
| >import wmi
| >c = wmi.WMI (computer="srv", user="[EMAIL PROTECTED]", password="")
| >pid, retval = c.Win32_Process.Create (CommandLine="notepad.exe")
| 
| Wonderful... It works.

Also, in case you haven't, have a look at the cookbook page:

http://timgolden.me.uk/python/wmi_cookbook.html

which has several useful examples.

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: Problem with dbi, odbc module and Oracle 9.2 - suffixed "L" with number data type

2006-03-02 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> Great, thanks Diez! Should I just use str(n) to convert it to a format
> I can write out to a flat file? I'm also struggling with the strange

I guess so, yes.

> date object format that the ODBC module returns when I fetch rows. I
> need to convert that to a text string in a format that a mainframe
> flatfile database requires. Any advice there?

No, I do use cx_Oracle - no strange dateformats there.

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


Re: logging to a text widget

2006-03-02 Thread Martin Franklin
Alexandre Guimond wrote:
> Hi. I'm using the logging package. I would like to send my log messages
> to a Text widget creating using Tkinter. I was wondering if there was a
> logging handler class that would do this. It seems that the standard
> handlers do not support this. Has anyone tried to do this?
> 

Alex,

To be honest I haven't used the logging package (it's on my todo list ;)
but I normally sub class the Text widget, give it a write method then
send stdout / stderr to it normally (sys.stdout = mytextWidget)

At the same time I also add scrollbars and in the write method I scroll 
to the latest message.

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


Re: Removing .DS_Store files from mac folders

2006-03-02 Thread David Pratt
Hi Ben. I hadn't realize that walk was just giving the file name so the 
join did the job just great. Many thanks for helping me out with this.

Regards,
David

Ben Cartwright wrote:
> David Pratt wrote:
> 
>>OSError: [Errno 2] No such file or directory: '.DS_Store'
> 
> 
> 
> Ah.  You didn't mention a traceback earlier, so I assumed the code was
> executing but you didn't see the file being removed.
> 
> 
> 
for f in file_names:
current_file = os.path.basename(f)
print 'Current File: %s' % current_file

# Clean mac .DS_Store
if current_file == '.DS_Store':
print 'a DS_Store item encountered'
os.remove(f)
> 
> 
> 
> How are you creating file_names?  More importantly, does it contain a
> path (either absolute or relative to the current working directory)?
> If not, you need an os.path.join, e.g.:
> 
> import os
> for root_path, dir_names, file_names in os.walk('.'):
> # file_names as generated by os.walk contains file
> # names only (no path)
> for f in file_names:
> if f == '.DS_Store':
> full_path = os.path.join(root_path, f)
> os.remove(full_path)
> 
> --Ben
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why? [win32com/WMI]

2006-03-02 Thread Sergey

"Tim Golden" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
[Sergey]

>| >import wmi
>| >c = wmi.WMI (computer="srv", user="[EMAIL PROTECTED]", password="")
>| >pid, retval = c.Win32_Process.Create (CommandLine="notepad.exe")
>|
>| Wonderful... It works.
>Also, in case you haven't, have a look at the cookbook page:
>http://timgolden.me.uk/python/wmi_cookbook.html
>which has several useful examples.

Yes, I had run it.

And, just now I updated python, pythonwin and wmi.py to latest version. And got:

>>> a=wmi.WMI()
>>> a.Win32_Process.Create(CommandLine="notepad.exe")# --- it works
>>> a.Win32_Process.new().Create(CommandLine="notepad.exe")  # it still fail
Traceback (most recent call last):
  File "", line 1, in ?
  File "wmi.py", line 361, in __call__
handle_com_error (error_info)
  File "wmi.py", line 208, in handle_com_error
raise x_wmi, "\n".join (exception_string)
wmi.x_wmi: -0x7ffdfff7 - Exception occurred.
  Error in: SWbemObjectEx
  -0x7ffbefff - Generic failure

Without 'new' everything works. And does everything I need from it.

And, I have another question. Is there way to access WMI from linux?


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


RE: why? [win32com/WMI]

2006-03-02 Thread Tim Golden
[Sergey]

| Yes, I had run it.
| 
| And, just now I updated python, pythonwin and wmi.py to 
| latest version. And got:
| 
| >>> a=wmi.WMI()
| >>> a.Win32_Process.Create(CommandLine="notepad.exe")# 
| --- it works
| >>> a.Win32_Process.new().Create(CommandLine="notepad.exe")  
| # it still fail
| Traceback (most recent call last):
|   File "", line 1, in ?
|   File "wmi.py", line 361, in __call__
| handle_com_error (error_info)
|   File "wmi.py", line 208, in handle_com_error
| raise x_wmi, "\n".join (exception_string)
| wmi.x_wmi: -0x7ffdfff7 - Exception occurred.
|   Error in: SWbemObjectEx
|   -0x7ffbefff - Generic failure
| 
| Without 'new' everything works. And does everything I need from it.

Yes, I think the simple answer is: don't use .new unless you're sure
you need to. When I wrote the wmi module originally, I misunderstood 
the use of SpawnInstance_ (which is the method behind .new). To create 
a process, or a share, or anything which has a .Create method, use the 
.Create method. Use .new only for things like  Win32_ProcessStartup, 
as in this example here:

http://timgolden.me.uk/python/wmi_cookbook.html#run-process-minimised

where the instance is created only to pass as a parameter
into the .Create method of the Win32_Process.

I've updated the module docstring for the next release, and have changed
the cookbook examples which used .new where they shouldn't have, so
thanks 
for highlighting the deficiency.

| And, I have another question. Is there way to access WMI from linux?

Not using this module, which is very Windows-specific; there was some 
work recently on WBEM (which is the industry standard behind WMI) on 
Linux, but I've not tried to use it myself:

http://pywbem.sourceforge.net/

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: Is it better to use class variables or pass parameters?

2006-03-02 Thread bruno at modulix
Derek Basch wrote:
> This one has always bugged me. Is it better to just slap a "self" in
> front of any variable that will be used by more than one class method

s/class method/method/

In Python, a "class method" is a method working on the class itself (not
on a given instance).

> or should I pass around variable between the methods?

One of the first rules I learned (from experience...) was to restrict as
much as possible the scope of a variable. It usually makes code more
readable, more robust, and more modular. In fact, I sometime even pass
attributes of an object as args to a method of the same object, and/or
assign values returned from a method of an object to attributes of the
same object. This is more explicit than relying on side-effects.

So (as pointed by almost everyone in this thread...) the best criteria
here is : is this variable part of the state of an object, or is it just
a value used for a given computation ?

Note that if you find yourself passing the same huge set of variables
from method to method for a given computation, this may calls for a
refactoring... Python objects can be callable (ie function-like), so a
complex computation with lot of shared state (independant from the rest
of the object) may be best implemented as a separate temporary callable
object - which can take the calling object as a parameter if it needs to
access other attributes from it.

My 2 cents...
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ODBC module and strange date reference <...>

2006-03-02 Thread dananrg
Sorry for the double-thanks Frank.

I'm using Python 2.1 for Win32 and import datetime fails.

Does the datetime module come standard with later releases of Python?
If so, which release? If not, will datetime with with Python 2.1, if it
will, where can I get it? I'm still such a newbie with Python that I'm
not even sure where in the directory structure modules go. My Python
reference books from Amazon.com are in the mail.

Thanks again for your help.

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



XSLT and gettext?

2006-03-02 Thread KW
I'm looking for a nice way to do i18n with XSLT, preferably using the
gettext framework. Currently I'm using 4Suite for XSLT processing. Do
you know of any solutions to this problem?

If no solutions currently exist, I'll try to write something myself. Any
ideas on how to do this properly? Any existing python code to start with?

I was thinking about wrappingg the text in a new XML tag, say  and
processing this to generate an XSL for alle languages, but it will also
require printf like substitution to do this properly.

Kind regards,
-- 
Konrad
-- 
http://mail.python.org/mailman/listinfo/python-list


How to find cause for Python/Pythonwin crash only on Dual Core Machines ?

2006-03-02 Thread robert
There is a strange freeze/crash only on dual core machines:

I have a python app (Python 2.3.5 /Pythonwin build 203 / Windows) 
running with no stability problems on normal machines (Or a crash is so 
rare, that absolutely nobody obverses it, though the overall majority of 
users uses single core machines). Threads, network & pythonwin/win32ui 
all in use.

Yet, from 3 users, _all_ using a Dual Processor System (XEON, amd x2 
3800+) computer, I have reports, that the application freezes hard 
and/or crashes with a kind of random stack dump (operating system). I 
cannot experiment with those machines.

I found no hints other than:

http://groups.google.de/group/comp.lang.python/browse_frm/thread/64ca033e1a7f6c61/719b147e870bd5e6

http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=480325

.. both discussions remaining in uncertainty.

Are there (known) problems with Python/Pythonwin specific for dual 
core's  (py2.3.5 / pywin203) ?

What could I do to find the problem?

Robert


--

PS: there is very little C extension-code (SWIG) involved, yet I looked 
over that so often, I guess its save:


//

#include "stdafx.h"
#include "commctrl.h"
#include "ext.h"

BOOL APIENTRY DllMain( HANDLE hModule,
DWORD  ul_reason_for_call,
LPVOID lpReserved
 )
{
 return TRUE;
}

class CAllowThreads {
public:
PyThreadState *_save; \
CAllowThreads() {
_save = PyEval_SaveThread();
}
~CAllowThreads() {
PyEval_RestoreThread(_save);
}
};

PyObject* PyListView_GetSubItemRect(
 HWND hwndLV,
 int iItem,
 int iSubItem,
 int code
//LPRECT lpRect
)
{
RECT r;
{
  CAllowThreads _t;
  ListView_GetSubItemRect(
hwndLV,
iItem,
iSubItem,
code,
&r );
}
return Py_BuildValue("", r.left,r.top,r.right,r.bottom);

}

int GetStringAddr(const char* s) {
return (int)s;
}

int PlaySoundResource(int resid, HMODULE hmod)
{
CAllowThreads _t;
return PlaySound(MAKEINTRESOURCE(resid), hmod, SND_RESOURCE);
}

int PlaySoundFile(const char* fname, int flag)
{
CAllowThreads _t;
return PlaySound(fname, NULL, flag);
}

PyObject* py_ToolTipRelayMsg(  PyObject* self, PyObject* args )
{
MSG msg;
HWND hwTT;
 if(!PyArg_ParseTuple(args,"i(i(ii)):ToolTipRelayMsg",
 &hwTT,
 
&msg.hwnd,&msg.message,&msg.wParam,&msg.lParam,&msg.time,
  &msg.pt, ((int*)&msg.pt)+1) )
return NULL;


{
  CAllowThreads _t;
  SendMessage(hwTT,TTM_RELAYEVENT,0,(LPARAM)&msg);
}

Py_INCREF( Py_None );
return Py_None;
}

---

"GetStringAddress" is used only once like this (leades to correct NUL 
termination I think):
 
self.sb.SendMessage(commctrl.SB_SETTEXT,iPane,extension.GetStringAddr(text))

--- swig:
static PyObject *_wrap_GetStringAddr(PyObject *self, PyObject *args) {
 PyObject *resultobj;
 char *arg0 ;
 int result ;

 if(!PyArg_ParseTuple(args,(char *)"s:GetStringAddr",&arg0)) return 
NULL;
 result = (int )GetStringAddr((char const *)arg0);
 resultobj = PyInt_FromLong((long)result);
 return resultobj;
}
-- 
http://mail.python.org/mailman/listinfo/python-list


Creating a text adventure

2006-03-02 Thread DannyB
I am in the process of learning Python.  I have the basics down and I
now want to test my abilitiy to use them in a (very) small project.  I
have the idea for a (very) small text based game mapped out in my head.
 It will include two rooms, random creatures (amounts and type) in each
room and random chests in each room.  The basic "battle system" giving
the user the ability to run or attack.  Creatures will have hp, attack,
defense, and name attributes.  The player will have the same.  Treasure
chests will be populated with random treasure.

I'm not adding anything fancy - like I said its just a small project to
gell my newfound knowledge.

What I am looking for is a resource (preferably via the web) that will
give me an idea of how to set things up.  I'm not looking to add any
libraries to the project (so no pygame or livewires).  I'm just using
2.4.2.  I'll add other things when I feel I have 'mastered' the
fundamental concepts of Python.

Thanks for your help!! :)

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


Re: ODBC module and strange date reference <...>

2006-03-02 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> Sorry for the double-thanks Frank.
> 
> I'm using Python 2.1 for Win32 and import datetime fails.
> 
> Does the datetime module come standard with later releases of Python?
> If so, which release? If not, will datetime with with Python 2.1, if it
> will, where can I get it? I'm still such a newbie with Python that I'm
> not even sure where in the directory structure modules go. My Python
> reference books from Amazon.com are in the mail.

I think datetime became available around 2.3. And it's a binary module, so
chances are slim that you can backport it.

However, what Frank suggested should work with module time. too:

import time
dat = time.localtime(int(dbidate_object))

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


Re: Creating a text adventure

2006-03-02 Thread [EMAIL PROTECTED]
This  (unabashed plug) might help.  Most of the tutorial is about
networking, but just skip that stuff.  Hopefully the architecture
section helps.  But it sounds like you're pretty much on your way
already.  Just read through your first paragraph, circle every noun,
and determine whether that noun should be a class or an attribute of a
class.

http://sjbrown.ezide.com/games/writing-games.html#hModel

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


filename variables

2006-03-02 Thread cyborg4
If in  Windows XP I use:

openstring= "test.py  >foo.txt"
os.system(openstring)

it works.


But if I use:

file1='foo.txt'
openstring= "test.py  >"+file1

It gives an IOError about no such file or directory as
\\mydidr\\foo.txt

What does it mean ?

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


Re: in need of some sorting help

2006-03-02 Thread ianaré
thank you for the help, i didn't know you could sort in place like
that. definitly will come in handy.
However, i need the sorting done after the walk, due to the way the
application works... should have specified that, sorry.

TIA

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


Re: filename variables

2006-03-02 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> If in  Windows XP I use:
> 
> openstring= "test.py  >foo.txt"
> os.system(openstring)
> 
> it works.
> 
> 
> But if I use:
> 
> file1='foo.txt'
> openstring= "test.py  >"+file1
> 
> It gives an IOError about no such file or directory as
> \\mydidr\\foo.txt
> 
> What does it mean ?

That you obviously didn't give us the actual (non-) working code, but
something you believe is essential. Because

file1='foo.txt'
openstring= "test.py  >"+file1

certainly doesn't give that error.

Post a running, self contained examplpe, and we might be able to help you.

Diez

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


Re: Proper class initialization

2006-03-02 Thread gry
Christoph Zwerschke wrote:
> Usually, you initialize class variables like that:
>
> class A:
> sum = 45
>
> But what is the proper way to initialize class variables if they are the
> result of some computation or processing as in the following silly
> example (representative for more:
>
> class A:
>  sum = 0
>  for i in range(10):
>  sum += i
>
> The problem is that this makes any auxiliary variables (like "i" in this
> silly example) also class variables, which is not desired.
>
> Of course, I could call a function external to the class
>
> def calc_sum(n):
>  ...
>
> class A:
>  sum = calc_sum(10)
>
> But I wonder whether it is possible to put all this init code into one
> class initialization method, something like that:
>
> class A:
>
>  @classmethod
>  def init_class(self):
>  sum = 0
>  for i in range(10):
>  sum += i
>  self.sum = sum
>
>  init_class()
>
> However, this does not work, I get
> TypeError: 'classmethod' object is not callable
>
> Is there another way to put an initialization method for the class A
> somewhere *inside* the class A?
Hmm, the meta-class hacks mentioned are cool, but for this simple a
case how about just:

class A:
   def __init__(self):
  self.__class__.sum = self.calculate_sum()
   def calculate_sum(self):
  do_stuff
  return sum_value

Instead of __class__ you could say:
  A.sum = self.calculate_sum()
but that fails if you rename the class.  I believe either works fine
in case of classes derived from A.

-- George Young

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


Write a GUI for a python script?

2006-03-02 Thread Glurt Wuntal
I am a newbie with Python. It's a great language, but I would like to be
able to present a simple gui menu for some of my scripts; something better
than using 'raw_input' prompts.

Any recommendations for a program that will allow me to create the gui
screens? Something useable in Linux.

thanks.

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


Re: Pyserial never read

2006-03-02 Thread luca72
Hello

i how can set with pyserial the following data?


> byte delay= 4

> serial control line:
> dtr = high
> rts= low 

Thanks Luca

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


Re: Write a GUI for a python script?

2006-03-02 Thread Michele Simionato
Tkinter is the GUI toolkit that comes with Python and is available on
all platform without any
installation effort. It is quite OK for simple things and I would
recommend it for any beginner.
Google for "An Introduction to Tkinter" by F. Lund.

 Michele Simionato

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


Re: Stopping Windows Service

2006-03-02 Thread D
I must be missing something..in my SvcDoRun function, first line is
"self.timeout=1" , followed by my "while 1:" loop which listens for
the connection, processes the data, etc.  Where should I place the
"rc=win32event.." and "if rc" lines?  I have a feeling I'm pretty close
here.. :)  Thanks very much.

Doug

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


import, from and reload

2006-03-02 Thread John Salerno
I understand that after you import something once, you can reload it to 
pick up new changes. But does reload work with from statements? I tried 
this:

from X import *

and then did my testing. I changed X and tried to reload it, but that 
didn't seem to work. I figure the reason is because the module itself 
doesn't exist as an object, only its names do. But I couldn't figure out 
how to pick up my new changes at this point. I think eventually I did

import X

and that sort of started me back from the beginning, with my changes. 
But is there a way to continue to use a from statement instead, and then 
reload your changes?
-- 
http://mail.python.org/mailman/listinfo/python-list


white space in expressions and argument lists

2006-03-02 Thread John Salerno
A minor concern, but I'm curious if there is any kind of best practice 
for using whitespace within expressions and argument lists in the Python 
world. For example:

1 + 2  or   1+2

func(1,2) or func(1, 2)

To me, the space makes it nicer and more readable, but I was surprised 
to read in Guido's blog that he thinks 1+2 should be the normal way to 
write it. What does everyone else think?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: white space in expressions and argument lists

2006-03-02 Thread Lawrence Oluyede
John Salerno <[EMAIL PROTECTED]> writes:

> 1 + 2  or   1+2
>
> func(1,2) or func(1, 2)

I prefer and use 1 + 2 and func(1, 2)
I don't do whitespaces only in argument defaults like

func(foo=baz)



-- 
Lawrence - http://www.oluyede.org/blog
"Anyone can freely use whatever he wants but the light at the end
of the tunnel for most of his problems is Python"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: white space in expressions and argument lists

2006-03-02 Thread rtilley
John Salerno wrote:
> A minor concern, but I'm curious if there is any kind of best practice 
> for using whitespace within expressions and argument lists in the Python 
> world. For example:
> 
> 1 + 2  or   1+2

IMO, good style calls for spaces. Most companies have style guides for 
programmers to follow. Read this PEP:

http://www.python.org/peps/pep-0008.html
-- 
http://mail.python.org/mailman/listinfo/python-list


_tkinter.TclError: can't set "PY_VAR0": invalid command name "-1210125972check"

2006-03-02 Thread Gregor Horvath
Hi,

I searched the web and docs but cannot figure out whats wrong with this 
code:

#!/usr/bin/python

import Tkinter as Tk

class testtk(Tk.Frame):

   def __init__(self):
 self.root = Tk.Tk()
 Tk.Frame.__init__(self,self.root)
 self.frame = Tk.Frame(self.root)
 self.var = Tk.StringVar()
 self.var.trace_variable('w',self.check)
 Tk.Entry(self.frame, textvariable = self.var).pack()
 self.frame.pack()
 Tk.mainloop()

   def check():
 pass

if __name__ == "__main__":
   t = testtk()
   t.var.set("TEST")

Result:

Traceback (most recent call last):
   File "", line 22, in ?
   File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 191, in set
 return self._tk.globalsetvar(self._name, value)
_tkinter.TclError: can't set "PY_VAR0": invalid command name 
"-1210125972check"


Any ideas, why I cant set the variable var?

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


Re: white space in expressions and argument lists

2006-03-02 Thread Sybren Stuvel
John Salerno enlightened us with:
> To me, the space makes it nicer and more readable, but I was
> surprised to read in Guido's blog that he thinks 1+2 should be the
> normal way to write it. What does everyone else think?

I usually write 1 + 2 and func(a, b). Sometimes I even use more spaces
to align stuff:

foo= 'bar'
foobar = 42
azimov = 3

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ODBC module and strange date reference <...>

2006-03-02 Thread Frank Millman

Diez B. Roggisch wrote:
> [EMAIL PROTECTED] wrote:
>
> > Sorry for the double-thanks Frank.
> >
> > I'm using Python 2.1 for Win32 and import datetime fails.
> >
> > Does the datetime module come standard with later releases of Python?
> > If so, which release? If not, will datetime with with Python 2.1, if it
> > will, where can I get it? I'm still such a newbie with Python that I'm
> > not even sure where in the directory structure modules go. My Python
> > reference books from Amazon.com are in the mail.
>
> I think datetime became available around 2.3. And it's a binary module, so
> chances are slim that you can backport it.
>
> However, what Frank suggested should work with module time. too:
>
> import time
> dat = time.localtime(int(dbidate_object))
>
> Diez

Yes, this works fine on my setup.

You can then use time.strftime() to format it into human-readable
output.

Frank

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


os.popen3 delivers no error exist status ?

2006-03-02 Thread robert
os.popen3 delivers no error exit status on .close()  - while os.popen does

Is this intended or a bug? How do I get the status?

Robert

Python 2.4.1 (#2, May  5 2005, 11:32:06)
[GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import os
 >>> csi,cso,cse=os.popen3('recodex latin1:utf8 >> csi.close();cso.read();cso.close();cse.read();cso.close()
''
'/bin/sh: line 1: text.lat1-noexist.txt: No such file or directory\n'
 >>> cso=os.popen('recode latin1:utf8 >> sh: line 1: text.lat1-noexist.txt: No such file or directory

 >>> cso.read();cso.close()
''
256
 >>>



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


Exception not raised - May be the end

2006-03-02 Thread Michele Petrazzo
Hi group,
some days ago I posted here and say that python "forgot" to raise an
exception, but my code was too long for make some tries possible.
But now I can reproduce the problem into another, little, project:

(Need wx 2.6)

Here is the code:

www.unipex.it/vario/wxFrameSchedule.py
www.unipex.it/vario/metamenus.py.py

Execute the wxFrameSchedule.py into a terminal (or where you want) and
select on menu bar:
Show -> Only work hour

The program print and "forgot" to raise an exception:

12  #e number before the call that "must", but don't raise the exception
 False # variable type and if the value are inside the keys
 # (str in dict)
#Here the program don't raise the KeyError exception.

Le lines are:
- 44 in wxFrameSchedule (self._mb.GetMenuState("ShowOnlyworkhour"))
- 802 in metamenus (this = self.MBStrings[_prefixMB + menu_string])

Hope that someone can reproduce this error. I see it on win2k (terminal
usage) and debian (terminal and eric3 )...

py 2.3.5 and wx 2.6


Thanks a lot,
Michele
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: white space in expressions and argument lists

2006-03-02 Thread John Salerno
Sybren Stuvel wrote:
> John Salerno enlightened us with:
>> To me, the space makes it nicer and more readable, but I was
>> surprised to read in Guido's blog that he thinks 1+2 should be the
>> normal way to write it. What does everyone else think?
> 
> I usually write 1 + 2 and func(a, b). Sometimes I even use more spaces
> to align stuff:
> 
> foo= 'bar'
> foobar = 42
> azimov = 3
> 
> Sybren

Guido listed a few rules that he'd like to see implemented in 2.5, and 
one of them was no more than one consecutive white space. I don't know 
how realistic some of those suggestions are, but they seem to be getting 
a little to restrictive.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Write a GUI for a python script?

2006-03-02 Thread ianaré
wxPython is another good option, especially since there is
boa-constructor, which is a great GUI builder, almost makes it too easy
to make a nice looking app in no time at all.

http://www.wxpython.org/download.php

http://boa-constructor.sourceforge.net/

if you decide to give wxPython a go, make sure to download the demo, it
has tons of usefull code samples.

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


Simple System Tray Icon

2006-03-02 Thread 3c273
Hello,
I have a short looping script that runs in the background (Windows 2000) and
I want to have a tray icon so I know that it is running. I have looked at
wxTaskBarIcon and the examples on the web and in the demo, but it seems
pretty complex and I haven't had any success even getting one to show up.
Can someone point me to a simple example that just shows an icon? I don't
need it to anything but show up. Any help is appreciated.
Louis


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


Re: white space in expressions and argument lists

2006-03-02 Thread Fredrik Lundh
John Salerno wrote:

> Guido listed a few rules that he'd like to see implemented in 2.5, and
> one of them was no more than one consecutive white space. I don't know
> how realistic some of those suggestions are, but they seem to be getting
> a little to restrictive.

in his april 1st, 2005 paper ?

http://www.artima.com/weblogs/viewpost.jsp?thread=101968





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


Re: Suggestions for documentation generation?

2006-03-02 Thread Michael Ekstrand
On 2 Mar 2006 04:06:17 -0800
"kpd" <[EMAIL PROTECTED]> wrote:
> Thanks - I took at both. Also at 'percepts', which I used a long time
> ago (had forgotten about  it). Percepts has a great little java applet
> for viewing the class hierarchy.  I don't think it works for python,
> just C++ though.  Looks like doxygen will fit the bill.

An excellent choice IMHO.

Doxygen has recently added support for Python, so if there is
pure-Python code interfacing with the rest of your work, that can be
documented also.

- Michael

-- 
mouse, n: a device for pointing at the xterm in which you want to type.
-- Fortune
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Stopping Windows Service

2006-03-02 Thread D
Sorry for the many messages, but I've been looking into it further -
since I have the server services listening and waiting for incoming
connections, how would I interrupt it to let the program know that a
stop request has been issued?  For example, if I put the stop check
before it listens, I would think it'd have to wait until it loops back
around after the next client connects.  If I put it after the listen, a
client would have to connect in order for it to run the check..?

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


Re: Simple System Tray Icon

2006-03-02 Thread Michele Petrazzo
3c273 wrote:
> Hello, I have a short looping script that runs in the background
> (Windows 2000) and I want to have a tray icon so I know that it is
> running. I have looked at wxTaskBarIcon and the examples on the web
> and in the demo, but it seems pretty complex and I haven't had any
> success even getting one to show up.

wxTaskBarIcon is very, very simple!
Into the demo, inside 80 line, you can find all the taskbar work, the
menu connected with the rclick and its image change...
Where do you find this complex?

Try to make the windows taskbar with the win32 api ... :)

> Can someone point me to a simple example that just shows an icon? I
> don't need it to anything but show up. Any help is appreciated.

Copy and paste that lines into your code and remove the lines that you
don't need. I think that with 15/20 lines you will your taskbar work!

> Louis
> 
> 


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


Re: looking for help about python-sane

2006-03-02 Thread JW
Sorry, I can't help much with the issue.  You are getting a low-level
hardware fault, and
not much information is being propagated up throught the system.  It's
not a Python problem, but something with SANE, and the Python wrapper
is just propagating the SANE error to you.  I have a few suggestions:

- Use a try block, and see if you can recover:

try:
 grabImage(webcam)
except _sane.Error, se:
 print se
 # but continue

See if all you get is errors, or if it's just a once-in-a-while thing.
Maybe you should sleep longer when you get an error, to give the system
a chance to do something else.

- Try to figure out if SANE is printing any logging message.  Check the
kernel log (dmesg), the normal system log, read SANE man pages, etc.
- Read the sane-v4l man page.  The one I found on the Internet says it
is Alpha software, which means it is highly experimental, but maybe it
has improved.
- Try a similar task using the native sane tools (sane-find-scanner,
scanimage, etc.).  This may generate more useful error messages.
- Post a question to the SANE mailing lists:
http://www.sane-project.org/mailing-lists.html

Once you have a happy SANE setup, then it should be trivial modify the
Python code to do the same thing.  Hope this is some help,
JW

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


setattr question

2006-03-02 Thread Gerard Flanagan
Hello

I have the following code:

 builder.py #
class HtmlBuilder(object):

@staticmethod
def page(title=''):
return HtmlPage(title)

@staticmethod
def element(tag, text=None, **attribs):
return HtmlElement(tag, text, **attribs)

@staticmethod
def literal(text):
return HtmlLiteral(text)

class HtmlElementFactory(object):

def __init__(self):
for tag in ['li', 'ul']:
setattr( self, tag, HtmlBuilder.element(tag) )

#

and so I can do the following:

html = HtmlElementFactory()
ul = html.ul
ul.attrib['class'] = 'default'
for i in range(3):
li = html.li
li.text = 'ghfhj'
ul.append(li)
print ul.to_string()

but what I'd like to do is:

html = HtmlElementFactory()
ul = html.ul( class='default' )
for i in range(3):
ul.append( html.li( 'ghfhj' )
print ul.to_string()

ie. to pass along *args and **kwargs to the HtmlElement constructor.
Any suggestions?  Or is there a better way to this kind of thing?

thanks

Gerard

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


Re: white space in expressions and argument lists

2006-03-02 Thread Sybren Stuvel
John Salerno enlightened us with:
> Guido listed a few rules that he'd like to see implemented in 2.5,
> and one of them was no more than one consecutive white space. I
> don't know how realistic some of those suggestions are, but they
> seem to be getting a little to restrictive.

I just read the PEP where my way of alignment is under a 'NO' header.
Too bad, since I think it can make things a lot clearer.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: white space in expressions and argument lists

2006-03-02 Thread rtilley
Fredrik Lundh wrote:
> in his april 1st, 2005 paper ?
> 
> http://www.artima.com/weblogs/viewpost.jsp?thread=101968

That was an April's Fools joke, right? I like it though :)
Maybe it'll happen!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: white space in expressions and argument lists

2006-03-02 Thread John Salerno
Fredrik Lundh wrote:
> John Salerno wrote:
> 
>> Guido listed a few rules that he'd like to see implemented in 2.5, and
>> one of them was no more than one consecutive white space. I don't know
>> how realistic some of those suggestions are, but they seem to be getting
>> a little to restrictive.
> 
> in his april 1st, 2005 paper ?
> 
> http://www.artima.com/weblogs/viewpost.jsp?thread=101968
> 
> 
> 
> 
> 

Yes, that's the one.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple System Tray Icon

2006-03-02 Thread Thomas Heller
3c273 wrote:
> Hello,
> I have a short looping script that runs in the background (Windows 2000) and
> I want to have a tray icon so I know that it is running. I have looked at
> wxTaskBarIcon and the examples on the web and in the demo, but it seems
> pretty complex and I haven't had any success even getting one to show up.
> Can someone point me to a simple example that just shows an icon? I don't
> need it to anything but show up. Any help is appreciated.
> Louis
> 
> 
Simon Bruning has made something that should you get started.

http://www.brunningonline.net/simon/blog/archives/001835.html

Thomas

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


Re: os.popen3 delivers no error exist status ?

2006-03-02 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 robert <[EMAIL PROTECTED]> wrote:

> os.popen3 delivers no error exit status on .close()  - while os.popen does
> 
> Is this intended or a bug? How do I get the status?


http://docs.python.org/lib/popen3-objects.html

Worth reading the rest of the documentation about these
functions, too.  They are not just like popen.

   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: white space in expressions and argument lists

2006-03-02 Thread John Salerno
rtilley wrote:
> John Salerno wrote:
>> A minor concern, but I'm curious if there is any kind of best practice 
>> for using whitespace within expressions and argument lists in the 
>> Python world. For example:
>>
>> 1 + 2  or   1+2
> 
> IMO, good style calls for spaces. Most companies have style guides for 
> programmers to follow. Read this PEP:
> 
> http://www.python.org/peps/pep-0008.html

Thanks, this is great. Is it the most up-to-date?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: white space in expressions and argument lists

2006-03-02 Thread John Salerno
rtilley wrote:
> Fredrik Lundh wrote:
>> in his april 1st, 2005 paper ?
>>
>> http://www.artima.com/weblogs/viewpost.jsp?thread=101968
> 
> That was an April's Fools joke, right? I like it though :)
> Maybe it'll happen!

All of it was a joke?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple System Tray Icon

2006-03-02 Thread 3c273

"Michele Petrazzo" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> wxTaskBarIcon is very, very simple!
> Into the demo, inside 80 line, you can find all the taskbar work, the
> menu connected with the rclick and its image change...
> Where do you find this complex?

I guess since it is in a class and I am not very familiar with OOP. I was
hoping there was a simple procedural way to do something like:

myIcon=wx.TaskBarIcon('path to my icon file')
myIcon.ShowIcon()

but I guess it's not that simple. Thanks for your reply, I will keep trying.

> Try to make the windows taskbar with the win32 api ... :)

I saw an example of that. No thanks!

Thanks again.
Louis


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


Re: Simple System Tray Icon

2006-03-02 Thread 3c273

"Thomas Heller" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> 3c273 wrote:
> > Can someone point me to a simple example that just shows an icon? I
don't
> > need it to anything but show up. Any help is appreciated.
> > Louis
> >
> >
> Simon Bruning has made something that should you get started.
>
> http://www.brunningonline.net/simon/blog/archives/001835.html
>
> Thomas

I guess I should have capitalized the word 'simple' in my request :-) Thanks
for your reply. I had already found this and it made the wx example look
like a one-liner. I didn't realize that this was such a chore. Thanks again,
I will keep trying.
Louis


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


Re: os.popen3 delivers no error exist status ?

2006-03-02 Thread [EMAIL PROTECTED]
As allternative you might want to try the commands.getstatusoutput()
method, it returns a tuple with the exit code and output of the command
you run, see http://docs.python.org/lib/module-commands.html

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


Re: newbie question

2006-03-02 Thread orangeDinosaur
Thanks!!

This makes sense. And you were right about my misunderstanding.


Michael Tobis wrote:
> I think the answers so far are unnecessarily confusing and off the
> mark.
>
> Here is what I think you think you want to know:
>
> 1) import only works once. If you try import again, it will see the
> module already exists, and will ignore you
>
> 2) the functionality you think you want is reload.
> >>> reload mymodule
> will essentially reimport mymodule after the first time.
>
> However, what you think you want is not what you want, which is why the
> experienced people are giving misleading and overcomplicated answers.
> Normally reload is a fairly advanced feature and beginners don't need
> it.
>
> Usually, an import statement invokes a module containing a bunch of
> definitions (usually functions or classes, but sometimes even
> constants), but it doesn't DO anything unless it is invoked as the main
> program.
>
> So after you satisfy yourself that "reload" does what you want, try to
> think about how you would work things so you don't need it.
>
> For instance, instead of something like
>
> #mystuff.py
>
> print "hello ",
> print "world"
>
> # end of file
>
>
>
> >>> import mystuff
> hello world
> >>> import mystuff
>
> >>>
>
> is
>
>
>
> ### newstuff.py
>
> def newstuff():
>print "hello",
>print " world"
>
> # end of file
>
>
>
> >>> from newstuff import newstuff
> >>> newstuff()
> hello, world
> >>> newstuff()
> hello, world
> 
> 
> hth
> mt

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


Re: _tkinter.TclError: can't set "PY_VAR0": invalid command name "-1210125972check"

2006-03-02 Thread Gregor Horvath
Gregor Horvath schrieb:

> if __name__ == "__main__":
>   t = testtk()
>   t.var.set("TEST")
> 
> Result:
> 
> _tkinter.TclError: can't set "PY_VAR0": invalid command name 
> "-1210125972check"
> 
> 
> Any ideas, why I cant set the variable var?

Ok. The problem is that the program enters the mainloop on t = testtk() 
and t.var.set("TEST") is executed when the program ends.

But, what I want to do is to let another program create my tkinter GUI 
via initiating my class through COM. Then the COM-Client should be able 
to set values of the tkinter variables from "the outside".

How to do this?

Do I have to make my GUI program threaded ? like described here:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965

The mainloop resides in one thread and the other thread provides the COM
object and queues the foreign COM method calls to the GUI thread?

Is there a simpler solution?

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


Re: import, from and reload

2006-03-02 Thread Dave Benjamin
On Thu, 2 Mar 2006, John Salerno wrote:

> I understand that after you import something once, you can reload it to pick 
> up new changes. But does reload work with from statements? I tried this:
>
> from X import *
>
> and then did my testing. I changed X and tried to reload it, but that didn't 
> seem to work. I figure the reason is because the module itself doesn't exist 
> as an object, only its names do. But I couldn't figure out how to pick up my 
> new changes at this point. I think eventually I did
>
> import X
>
> and that sort of started me back from the beginning, with my changes. But is 
> there a way to continue to use a from statement instead, and then reload your 
> changes?

"reload" is an ordinary procedure that takes a module as an argument. When 
you use a "from X import *" statement, "X" is not imported, so you have no 
module object to pass to "reload". In addition, even if you do import "X" 
and reload it, you won't update your bindings; you'll still have to do 
"from X import *" again to update any names imported from X before.

So, to make a long story short, you have to do something like:

import X
reload(X)
del X # to keep your namespace clean
from X import *

In general, "from X import *" should be avoided anyway, for reasons that 
have been discussed many times in the past. The annoyance with reloading 
is just one more reason. Better to just use "import X" in the first place.

-- 
.:[ dave benjamin -( ramen/sp00 )- http://spoomusic.com/ ]:.
"one man's constant is another man's variable" - alan perlis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rapid web app development tool for database

2006-03-02 Thread petrov
TurboGears has Catwalk. Have a look at that. It is a web UI that let's
you manipulate the db. Have a look at the the TG Toolbox.

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


Re: setattr question

2006-03-02 Thread bruno at modulix
Gerard Flanagan wrote:
> Hello
> 
> I have the following code:
> 
>  builder.py #
> class HtmlBuilder(object):
> 
> @staticmethod
> def page(title=''):
> return HtmlPage(title)
> 
> @staticmethod
> def element(tag, text=None, **attribs):
> return HtmlElement(tag, text, **attribs)
> 
> @staticmethod
> def literal(text):
> return HtmlLiteral(text)

Je ne vois pas très bien à quoi sert cette classe (à moins bien sûr
qu'il y ait d'autre code). Pour ce que je vois là, pourquoi ne pas
appeler directement les classes HtmlPage, HtmlElement et HtmlLiteral ?

Err... I don't see the point of this class. Why not just calling the
HtmlPage|Element|Literal classes directly ?

> class HtmlElementFactory(object):
> 
> def __init__(self):
> for tag in ['li', 'ul']:
> setattr( self, tag, HtmlBuilder.element(tag) )
> 
> #
> 
> and so I can do the following:
> 
> html = HtmlElementFactory()
> ul = html.ul
> ul.attrib['class'] = 'default'
> for i in range(3):
> li = html.li
> li.text = 'ghfhj'
> ul.append(li)
> print ul.to_string()
> 
> but what I'd like to do is:
> 
> html = HtmlElementFactory()
> ul = html.ul( class='default' )



> for i in range(3):
> ul.append( html.li( 'ghfhj' )
> print ul.to_string()

'to_string' ?
Let's see... 'to_string', a class with only staticmethods in it...
You're coming from Java, aren't you ?-)

(if yes, google for "python is not java", it may be helpful)

> ie. to pass along *args and **kwargs to the HtmlElement constructor.
> Any suggestions?  

yes : pass along *args and **kwargs to the HtmlElement constructor !-)


> Or is there a better way to this kind of thing?

yes again : kiss (Keep It Simple Stupid)

There's not enough code to really grasp what you're trying to do, but
from what I see, I'd say you're having a bad case of arbitrary
overcomplexification.

What's wrong with:

# nb: class is a reserved word in Python
ul = HtmlElement('ul', css_class='default')
for i in range(3):
  ul.append(HtmlElement('li', 'baaz%d' % i)

# nb2: use the __str__() method of HtmlElement
print str(ul)

Python's philosophy is to make simple things simple (don't worry,
there's still space for complex things -> descriptors, metaclasses etc).

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: asynchat network send problems

2006-03-02 Thread Scott David Daniels
Andreas R. wrote:
> 4. In the found_terminator() method, the data is attempted to be 
> uncompressed, but it failes, since the received data does not have the 
> same size as the data which is sent. Sometimes, the difference in size 
> is often 512 between client and server, when running len(packet) on the 
> *compressed* packed. The len() of a large packet is usually about 64969.

Just a guess, but do you know "send" and "receive" are not guaranteed to
send all bytes or receive all bytes?  The network itself is allowed to
re-pack packets at any point in the path, and delays may happen at any
packet boundary (including those boundaries created by the network).
You need to do something like "sendall" and your receiver needs to know
when it needs to wait for more data (as a matter of protocol design).

-- 
-Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proper class initialization

2006-03-02 Thread Steven Bethard
Kent Johnson wrote:
> Steven Bethard wrote:
>> I don't run into this often, but when I do, I usually go Jack 
>> Diederich's route::
>>
>> class A(object):
>> class __metaclass__(type):
>> def __init__(cls, name, bases, classdict):
>> cls.sum = sum(xrange(10))
> 
> I think you should call the superclass __init__ as well:
> 
> class __metaclass__(type):
> def __init__(cls, name, bases, classdict):
> super(__metaclass__, cls).__init__(name, bases, classdict)
> cls.sum = sum(xrange(10))

Yes, thanks for the catch.

I'd like to use super there, but I think you'll find that it doesn't 
work because of the order in which A and __metaclass__ get created:

 >>> class A(object):
... class __metaclass__(type):
... def __init__(cls, name, bases, cdict):
... super(__metaclass__, cls).__init__(name, bases, cdict)
... cls.sum = sum(xrange(10))
...
Traceback (most recent call last):
   File "", line 1, in ?
   File "", line 4, in __init__
NameError: global name '__metaclass__' is not defined


 >>> class A(object):
... class __metaclass__(type):
... def __init__(cls, name, bases, classdict):
... super(A.__metaclass__, cls).__init__(name, bases, classdict)
... cls.sum = sum(xrange(10))
...
Traceback (most recent call last):
   File "", line 1, in ?
   File "", line 4, in __init__
NameError: global name 'A' is not defined


I played around with a few solutions to this problem, but it seems like 
the cleanest one is just to avoid super:

 >>> class A(object):
... class __metaclass__(type):
... def __init__(cls, name, bases, cldict):
... type.__init__(cls, name, bases, cldict)
... cls.sum = sum(xrange(10))
...

Of course, this means you can't use some sorts of multiple inheritance 
with A.__metaclass__...

STeVe

P.S.  Here's the best way I found that still uses super:

 >>> class A(object):
... class __metaclass__(type):
... def __init__(cls, name, bases, cldict):
... try:
... meta = A.__metaclass__
... except NameError:
... meta = cldict['__metaclass__']
... super(meta, cls).__init__(name, bases, cldict)
... cls.sum = sum(xrange(10))
...
-- 
http://mail.python.org/mailman/listinfo/python-list


Shared memory

2006-03-02 Thread Sebastjan Trepca
Hey!

Are there any "live" modules for working with shared memory in Python?
I found some but they are all dead(posh,shm)...

Thanks, Sebastjan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: import, from and reload

2006-03-02 Thread John Salerno
Dave Benjamin wrote:

> In general, "from X import *" should be avoided anyway, for reasons that 
> have been discussed many times in the past. The annoyance with reloading 
> is just one more reason. Better to just use "import X" in the first place.
> 

Thanks. I kind of figured it's better to use import instead of from 
anyway, but I was following along with some examples that use from 
(despite the fact that earlier in the book they even say that from is 
problematic and you should use import instead!)  :)
-- 
http://mail.python.org/mailman/listinfo/python-list


instances from bound methods

2006-03-02 Thread Nick Craig-Wood
I needed to find the instance from a bound method.  Eg

  >>> class C(object):
  ... def fn(self): print "hello"
  ... 
  >>> c=C()
  >>> fn=c.fn
  >>> fn
  >
  >>> fn.im_self
  <__main__.C object at 0xb7dd2acc>
  >>> fn.__self__
  Traceback (most recent call last):
File "", line 1, in ?
  AttributeError: 'function' object has no attribute '__self__'
  >>>

But I discovered that builtin objects work in a completely different
way

  >>> fd=open("myfile","w")
  >>> fn=fd.write
  >>> fn.im_self
  Traceback (most recent call last):
File "", line 1, in ?
  AttributeError: 'builtin_function_or_method' object has no attribute 'im_self'
  >>> fn.__self__
  
  >>> 

I wonder why?

Is there a canonical way of doing it?

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


how do you move to a new line in your text editor?

2006-03-02 Thread John Salerno
This is a real small point, but I'd like to hear what others do in this 
case. It's more an 'administrative' type question than Python code 
question, but it still involves a bit of syntax.

One thing I like to do is use tabs for my indentation, because this 
makes it easy to outdent when I need to start a new line in column 1. I 
can press backspace once and move 4 spaces to the left.

But I read in the PEP that spaces are recommended over tabs. If this is 
the case, it would involve pressing backspace 4 times (or 8, etc.) to 
get back to column 1.

So I'm wondering, how do you all handle moving around in your code in 
cases like this? Is there some sort of consistency to these things that 
you can write rules for your text editor to know when to outdent? It 
doesn't seem like you can do this reliably, though.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >