Re: PEP 354: Enumerations in Python

2006-03-01 Thread Steven Bethard
Ben Finney wrote:
> Steven Bethard <[EMAIL PROTECTED]> writes:
> 
>> Ben Finney wrote:
>>> This PEP specifies an enumeration data type for Python.
>>> An enumeration is an exclusive set of symbolic names bound to
>>> arbitrary unique values.  Values within an enumeration can be iterated
>>> and compared, but the values have no inherent relationship to values
>>> outside the enumeration.
>> -1 on the proposal as-is.  I don't have many use cases for
>> enumerations, and I don't think they merit appearing in the builtins.
>> If you put them in the collections module instead, I'd probably be +0.
> 
> This seems to be a common distinction.
> 
> Should I amend the PEP to propose "either in the builtins or in the
> collections module"? Or should I propose two PEPs and let them
> compete?

I would probably just amend the PEP.  I have a feeling that python-dev 
is even less likely to accept it as a builtin than python-list is.

>> For the few cases of enumerations that I've needed, I've never
>> wanted them to be comparable with <, >, etc.  If there were two
>> classes, say ``collections.Enum`` and ``collections.OrderedEnum``
>> where only the latter made the enumerated items comparable, you
>> might even get me as high as +0.5.  (I only care about the
>> non-comparable one, but I understand that others may have a need for
>> the comparable one.)
> 
> Replies to your post indicate this is another popular distinction.
> 
> But the terminology is broken. The term "enumerated" seems to me to
> imply that it does have an order.

I didn't get that implication.  From WordNet 2.0:

"""
enumerate

v 1: specify individually; "She enumerated the many obstacles she had 
encountered"; "The doctor recited the list of possible side effects of 
the drug" [syn: recite, itemize, itemise] 2: determine the number or 
amount of; "Can you count the books on your shelf?"; "Count your change" 
[syn: count, number, numerate]
"""

I don't get an ordering out of either of the definitions above.  But 
certainly there are a few precedents (e.g. Java's Enumeration interface)...

> Can you suggest a term other than
> "enumerated" for what you're describing with the unordered property?

I don't have any good names if people think that enumeration implies 
ordering.  Off of thesaurus.reference.com:

* numbering
* inventory
* lexicon
* catalogue

Those were the best I saw, and they're pretty bad.  I guess you could go 
with ``symbols`` maybe...

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


Re: Cross compile generation of .pyc from .py files...

2006-03-01 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> However we cannot figure out how to cross-compile the .py (of
> distribution) files and
> generate the .pyc files for the target ppc from an i686 system.  Is it
> possible to cross
> compile .pyc files from .py files?

I am under the impression that .pyc files are system independent.
Have you tried simply copying them over?

tjr



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


Re: how do I factor a number down to one digit?

2006-03-01 Thread Tim Roberts
"Allan" <[EMAIL PROTECTED]> wrote:
>
>as so forth. I then input a name. How do I treat each letter as a
>single value? That is, instead of print myname I have to do a print
>m+y+n+a+m+e which returns a number. I next want to convert the
>resulting two or three digit number to a single digit. Like 123 would
>be 1+2+3 returning a 5.

Hmm, in most of the rational mathematical universes I've visited, 1+2+3
returns 6, not 5.

On the other hand, numerology doesn't really have much of a place in a
rational mathematical universe.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Make staticmethod objects callable?

2006-03-01 Thread Steven D'Aprano
Nicolas Fleury wrote:

> Hi everyone,
> I was wondering if it would make sense to make staticmethod objects 
> callable, so that the following code would work:

This is one of the more unintuitive areas of Python, 
with side effects and different behaviour depending on 
whether code is called inside or outside a class:

 >>> class Parrot:
... def speak():
... return "dead parrot"
... speak = staticmethod(speak)
... def playdead():
... return "still dead"
...
 >>> type(Parrot.speak)

 >>> type(Parrot.playdead)


So, based on this evidence, staticmethod() converts an 
instance method into an ordinary function. Parrot.speak 
certainly behaves like an ordinary function.

 >>> callable(Parrot.speak)
True
 >>> Parrot.speak()
'dead parrot'


But now try to do the same outside of a class:

 >>> f = staticmethod(Parrot.playdead)
 >>> type(f)


f is not a function?

 >>> Parrot.playdead = staticmethod(Parrot.playdead)
 >>> type(Parrot.playdead)


So, based on this evidence, staticmethod() inside a 
class definition converts instance methods to 
functions. Outside a class definition, staticmethod() 
does one of two things: it either converts an instance 
method to a static method, or if the output is assigned 
to a class attribute, it leaves it as an instance method.

Hmmm.



> class A:
> @staticmethod
> def foo(): pass
> bar = foo()

Here is a work around:

 >>> class A:
... def foo(): return "foo foo foo"
... foo = staticmethod(foo)
... def __init__(self):
... if not hasattr(self.__class__, "bar"):
... self.__class__.bar = self.foo()
...
 >>> dir(A)
['__doc__', '__init__', '__module__', 'foo']
 >>> a = A()
 >>> dir(A)
['__doc__', '__init__', '__module__', 'bar', 'foo']
 >>> a.foo()
'foo foo foo'
 >>> a.bar
'foo foo foo'


Here is a more interesting example:

 >>> class B:
... def foo():
... return lambda x: x+1
... foo = staticmethod(foo)
... def __init__(self):
... if not hasattr(self.__class__, "bar"):
... self.__class__.bar = \
... staticmethod(self.foo())
...
 >>> dir(B)
['__doc__', '__init__', '__module__', 'foo']
 >>> b = B()
 >>> dir(B)
['__doc__', '__init__', '__module__', 'bar', 'foo']
 >>> b.foo()
 at 0xb7f70c6c>
 >>> b.bar
 at 0xb7f70c34>
 >>> b.bar(3)
4


Hope this helps.



-- 
Steven.

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


PIL and PSDraw

2006-03-01 Thread Sybren Stuvel
Hi there,

I'm experimenting with PIL to create a PostScript file. The end result
should be an EPS file with a couple of bar graphs.

At this moment, I have a very simple piece of code:

ps = PIL.PSDraw.PSDraw(file('demo.ps', 'w'))
ps.begin_document()
ps.rectangle((0, 0, 650, 150))
ps.end_document()

Unfortunately, when looking at 'demo.ps' using ghostview, I see an
empty page. This feeling of 'emptyness' is augmented by 'ps2epsi',
which tells me:

$ ps2epsi demo.ps 
blank page!!

Can anyone tell me what I'm doing wrong? I've just started to use PIL,
so if there is something better to create EPS files, please let me
know!

Sybren

The contents of demo.ps:
==
%!PS-Adobe-3.0
save
/showpage { } def
%%EndComments
%%BeginDocument
/S { show } bind def
/P { moveto show } bind def
/M { moveto } bind def
/X { 0 rmoveto } bind def
/Y { 0 exch rmoveto } bind def
/E {findfont
dup maxlength dict begin
{
1 index /FID ne { def } { pop pop } ifelse
} forall
/Encoding exch def
dup /FontName exch def
currentdict end definefont pop
} bind def
/F {findfont exch scalefont dup setfont
[ exch /setfont cvx ] cvx bind def
} bind def
/Vm { moveto } bind def
/Va { newpath arcn stroke } bind def
/Vl { moveto lineto stroke } bind def
/Vc { newpath 0 360 arc closepath } bind def
/Vr {   exch dup 0 rlineto
exch dup neg 0 exch rlineto
exch neg 0 rlineto
0 exch rlineto
100 div setgray fill 0 setgray } bind def
/Tm matrix def
/Ve {   Tm currentmatrix pop
translate scale newpath 0 0 .5 0 360 arc closepath
Tm setmatrix
} bind def
/Vf { currentgray exch setgray fill setgray } bind def
%%EndProlog
0 0 M 650 150 0 Vr
%%EndDocument
restore showpage
%%End
==

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


Failing in a simple embedding example of python

2006-03-01 Thread Themistoklis Bourdenas
Hi I'm trying the following simple test in my application:

FILE* fp = fopen("test.py", "r");
PyRun_SimpleFile(fp, "test.py");
fclose(fp);


However I get seg fault is in PyRun_SimpleFile(fp, "test.py"). "test.py" 
is an existing file with a simple statement (print 7+4).
When I try PyRun_SimpleString("..."); The script is running normally. 
What is the problem with this one?
I don't know if this cause any trouble but I link statically with python.

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


Re: Failing in a simple embedding example of python

2006-03-01 Thread Fredrik Lundh
Themistoklis Bourdenas wrote:

> Hi I'm trying the following simple test in my application:
>
> FILE* fp = fopen("test.py", "r");
> PyRun_SimpleFile(fp, "test.py");
> fclose(fp);
>
>
> However I get seg fault is in PyRun_SimpleFile(fp, "test.py"). "test.py"
> is an existing file with a simple statement (print 7+4).
> When I try PyRun_SimpleString("..."); The script is running normally.
> What is the problem with this one?

since you're passing in a FILE object, you must make sure that you're
using the right runtime library:

http://mail.python.org/pipermail/python-list/1999-July/007766.html

(the above thread is the first hit if you google for PyRun_SimpleFile, btw.)

there's also a FAQ entry about this:

http://www.python.org/doc/faq/windows.html#pyrun-simplefile-crashes-on-windows-but-not-on-unix-why

which discusses some ways to work around this if you cannot fix the
runtime library issue.

hope this helps!





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


Re: PEP 354: Enumerations in Python

2006-03-01 Thread greg
Steven D'Aprano wrote:

>  You can't shell an egg that isn't there.

Yesterday upon the stair
I shelled an egg that wasn't there.
I'd shell the thing again today
If only I could find a way.

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


Re: PEP 354: Enumerations in Python

2006-03-01 Thread greg
Ben Finney wrote:
> On the assumption these might be basic types, though, that
> name doesn't read so easily in lowercase ('enummember').

Maybe 'enumval'?

I also thought of 'enumber' (from munging together
'enum' and 'member') but that looks too much like
'e-number' rather than 'enum-ber'.

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


Re: PEP 354: Enumerations in Python

2006-03-01 Thread greg
Paul Rubin wrote:

> Do you anticipate having parameters like socket.AF_INET that are
> currently integers, become enumeration members in future releases?

Since these are derived from values defined
as integers in C, it's probably better to leave
them that way. There may be code that relies
on them being integers or having those integer
values.

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


Re: PEP 354: Enumerations in Python

2006-03-01 Thread greg
Giovanni Bajo wrote:

> What's the repr of an enumeration value? OTOH, it should be something like
> "Weekdays.wed", so that eval(repr()) holds true. Also, it'd be very useful in
> debug dumps, tracebacks and whatnot.

That would be nice, but I don't think that's possible
with what the PEP proposes, because in

   Weekdays = enum('mon', 'tue', etc...)

there's no way for the enum object to know that it's
meant to be called 'Weekdays'.

A constructor argument could be added for this, but
then you end up having to write the name twice,
making the construct far less elegant.

Maybe *this* is a good argument for making the enum
object a class?

Or maybe it's an argument for allowing decorators
to operate on things other than functions, so you
could write something like

@enum
Weekdays = ('mon', 'tue', etc...)

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


Re: PEP 354: Enumerations in Python

2006-03-01 Thread greg
Dan Sommers wrote:

> In some parts of the world, calendar weeks begin on Monday
> and end on Sunday, and in other parts of the world, work weeks begin on
> Sunday and end on Thursday.

Things like days of the week really have a circular
ordering, so it doesn't inherently make sense to
ask whether one day of the week is less than or
greater than another.

Maybe there should be a circular_enum type, where
order comparisons even among the *same* type are
disallowed?

Another thought -- should enum values have pred()
and succ() methods, like in Pascal? If so, for
a circular_enum these should wrap around.

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


Re: C++ OpenGL rendering, wxPython GUI?

2006-03-01 Thread Tobias Forslöw
Thanks for all the quick help! After reading your posts about how the
canvases actually work it was fairly easy to make my C++ code work
within a wxPython frame.

Now I only have to decide If I'm actually going to use wxPython or if
there is a better alternative but there seem to be plenty of threads on
that subject already.

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


Re: error: argument after ** must be a dictionary

2006-03-01 Thread bruno at modulix
abcd wrote:
> I have class like this...
> 
> import threading
> class MyBlah(object):
> def __init__(self):
> self.makeThread(self.blah, (4,9))
> 
> def blah(self, x, y):
> print "X and Y:", x, y
> 
> def makeThread(self, func, args=(), kwargs={}):
> threading.Thread(target=self.blah, args=args,
> kwargs=kwargs).start()

Shouldn't it be:

def makeThread(self, func, *args, **kwargs):
  threading.Thread(target=self.blah,
   *args,
   **kwargs).start()



-- 
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: time.sleep(1) sometimes runs for 200 seconds under windows

2006-03-01 Thread Magnus Lycka
Mladen Adamovic wrote:
> Magnus Lycka wrote:
> 
>> On Windows that it. At least on Linux and Solaris, time.clock() returns
>> CPU time. If time.clock() returns significantly different values before
>> and after time.sleep(1), there's something seriously broken in sleep on
>> such platforms.
> 
> No!

It seems I can't say anything in this thread without getting 
contradicted! :)

I'm sorry if I wasn't clear in explaining the concept of CPU
time in Unix (and other multi user operating systems). This is
an entity that is registered per process. Roughly, the code below
means that calling f(arg) used s CPU seconds *in* *this* *process*.

c0 = time.clock()
f(arg)
s = time.clock() - c0

If f is time.sleep, s should be 0, or at least very close to 0
on systems such as Linux where time.clock() measures CPU time.
Otherwise something is broken. (On Linux, where CPU time has a
low resolution (100 ms?) I've never seen any other figure than
0.0.) There will obviously be other processes using the CPU while
this process is sleeping, but this process should use no CPU time.

Wall time delays will obviously depend on the load of the machines
in question. I rarely see > 1 ms on Linux boxes with a low load.
With a higher load, or many users, I see delays of up to 10 ms or
so now and then, but rarely more.

I suspect that observations from Java might not be completely
relevant for Python. I suspect the Java implementation might add
additional delays.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Modify the local scope inside a function

2006-03-01 Thread Fabio Zadrozny
Hi Sandra,

Well, first, I'm not sure if you'd be interested, but Pydev Extensions 
(http://www.fabioz.com/pydev) should be able to make remote debugging in 
the way you want...Now, in order to do what you are trying to do, 
debuggers (or at least the pydev debugger) go for the frame you want to 
execute things (that contains the locals and globals in some scope).

In pydev extensions, in interactive debugging, the code to evaluate 
expressions is something like:

frame = findFrame(thread_id, frame_id)
exec expression in frame.f_globals, frame.f_locals

So, you'd just need to get the frame... pydev does multithreaded 
debugging, so, it needs to know the thread too, but if you just want to 
debug the current thread, you could just go to curFrame = 
sys._getframe() and then go iterating back in the frames to reach the 
one you want at frame.f_back (that's basically what the findFrame 
function does).

Cheers,

Fabio

Sandra-24 wrote:

>Hey Crutcher, thanks for the code, that would work. I'm now debating
>using that, or using function arguments to get the variables into the
>namespace. This would require knowing the variables in the dict ahead
>of time, but I suppose I can do that because it's part of the same
>system that creates the dict. I'm just not very fond of having code
>relating to one thing in more than one place, because it puts the onus
>on the programmer to remember to change it in both places. Here I might
>forgive it because it would make the generated code more readable.
>
>It seems I created a fair amount of confusion over what I'm trying to
>do. I use special psp like templates in my website. The template engine
>was previously execing the generated template code. It uses special
>environment variables that give it access to the functionality of the
>web engine. These are what are in that scope dictionary of mine, and
>why I exec the code in that scope.
>
>However, I want to integrate a debugger with the web engine now, and
>debugging execed generated code is a nightmare. So I save the generated
>code as a function in a module that is generated by the template
>engine. Unless I'm missing something about what you're saying, this
>should now be faster as well, because afaik execed code has to be
>compiled on the spot, wheras a module when you load it, is compiled (or
>loaded from a .pyc file) at import time. So one import and repeated
>function calls would be cheaper than repeated exec.
>
>Thanks,
>-Sandra
>
>  
>


-- 
Fabio Zadrozny
--
Software Developer

ESSS - Engineering Simulation and Scientific Software
www.esss.com.br

Pydev Extensions
www.fabioz.com/pydev

PyDev - Python Development Enviroment for Eclipse
pydev.sf.net
pydev.blogspot.com


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


pysqlite problem

2006-03-01 Thread bapolis
Hello,

I'm getting the following error:

pysqlite2.dbapi2.OperationalError: no such table: tbl1

Here's my code:

from pysqlite2 import dbapi2 as sqlite
con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES)
cur = con.cursor()
cur.execute("select * from tbl1")
data = cursor.fetchall()
for record in date:
record[0], record[1]

my installation versions:

python 2.4.2
pysqlite 2.0.7
sqlite 3.3.4

I checked to make sure I have a table called tbl1. I don't understand
what's going on. Any ideas?

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


RE: pysqlite problem

2006-03-01 Thread Tim Golden
[EMAIL PROTECTED]

| I'm getting the following error:
| 
| pysqlite2.dbapi2.OperationalError: no such table: tbl1
| 
| Here's my code:
| 
| from pysqlite2 import dbapi2 as sqlite
| con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES)
| cur = con.cursor()
| cur.execute("select * from tbl1")

It may be that you've misunderstood something here (or that I have).
You appear to be attaching to a sqlite in-memory database which
does not exist before you connect to it. Therefore you
are guaranteed *not* to have a table called tbl1 unless
you create it first.

Have you missed out some code for the purposes of brevity?
Or have you misunderstood what the :memory: pseudo-filename
is for?

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: telnetlib problems

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

>I'm trying to use a python script to access an embedded computer
>running linux and connected via a crossover ethernet cable using the
>following script...

>...and I realize the username and password is not realistic... I'm
>still in "proof of concept" stage here :)

>#
>import telnetlib

>tn = telnetlib.Telnet('192.168.100.11')
>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_very_eager()


>As a script, this doesn't work.  However, if I execute the same
>commands interactively, it works fine.  If I insert some time delays as
>follows...

What doesn't work about it?  Have you checked the return value from the
read_until()s to see if they're returning anything sensible? are any of them
timing out?

Anyway, my first guess would be the use of read_very_eager(), it's something
you normally only descend to when you're stuck for something to match on.
Normally you would do another read_until() for the prompt.

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


Re: pysqlite problem

2006-03-01 Thread bapolis
my bad. that was the wrong code, here is my code:

from pysqlite2 import dbapi2 as sqlite
con = sqlite.connect("ex1")
cur = con.cursor()
cur.execute("select * from tbl1")
print cur.fetchall()

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


Re: pysqlite problem

2006-03-01 Thread looping
Is it the complete code ?

If so then you have to create the table each time you connect to the
DB.

You use an in-memory DB (":memory:") so all the data of the DB is lost
when you close the connection, including the schema of the DB.

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


RE: pysqlite problem

2006-03-01 Thread Tim Golden
[EMAIL PROTECTED]

| my bad. that was the wrong code, here is my code:
| 
| from pysqlite2 import dbapi2 as sqlite
| con = sqlite.connect("ex1")
| cur = con.cursor()
| cur.execute("select * from tbl1")
| print cur.fetchall()

Just a thought... is the file containing
your database called -- exactly -- ex1? It's
not called ex1.db or something? Because sqlite
will happily create a new database when you
connect, and if it did, it would obviously not
contain your table.

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: pysqlite problem

2006-03-01 Thread looping
OK, it's better.

You use relative path to your file 'ex1', are you really sure that you
open the right file and not creating another DB in another path ?

Try to use absolute path (r'c:\temp\ex1').

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


Re: pysqlite problem

2006-03-01 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> I'm getting the following error:
>
> pysqlite2.dbapi2.OperationalError: no such table: tbl1
>
> Here's my code:
>
> from pysqlite2 import dbapi2 as sqlite
> con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES)
> cur = con.cursor()
> cur.execute("select * from tbl1")
> data = cursor.fetchall()
> for record in date:
> record[0], record[1]
>
> my installation versions:
>
> python 2.4.2
> pysqlite 2.0.7
> sqlite 3.3.4
>
> I checked to make sure I have a table called tbl1.

where?

> I don't understand what's going on. Any ideas?

last time I checked, connect(":memory:") creates a new blank database
every time it is called.





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


Re: An isalpha() that accepts underscores as well

2006-03-01 Thread egbert
In the discussion about isalpha()_mutants that accept 
underscores as well, we did not talk about regular expressions.

Afterwards I did some timings.
My first observation was that the whole experiment is rather futile,
because it takes only about a second to do a million tests.
If you take the trouble to collect a million words,
you might as well spend an extra second to analyze them.

Apart from that, a simple regular expression is often faster
than a test with replace. The last one, replace, does better
with shorter tokens without underscores. Nothing to replace.
Regular expressions are less sensitive to the length of the tokens.
Regular expressions are not monsters of inefficiency.

This is my script:

#!/usr/bin/env python
import sys
from timeit import Timer

import re
pat  = re.compile(r'^[a-zA-Z_]+$')

if len(sys.argv) > 1:
token = sys.argv[1]
else:
token = "contains_underscore"

t = Timer("''.join(token.split('_')).isalpha()", "from __main__ import token")
print t.timeit()  # 1.94

t = Timer("token.replace('_','X').isalpha()", "from __main__ import token")
print t.timeit()  # 1.36

t = Timer("pat.search(token)", "from __main__ import token, pat")
print t.timeit()  # 1.18

t = Timer("token.isalpha()", "from __main__ import token")
print t.timeit()  # 0.28

#egbert

-- 
Egbert Bouwman - Keizersgracht 197 II - 1016 DS  Amsterdam - 020 6257991

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


Re: pysqlite problem

2006-03-01 Thread Ganesan Rajagopal
> bapolis  <[EMAIL PROTECTED]> writes:

> con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES)
   ^^
   
Did you really intend this? Since you're opening a database in memory, you
will have access to tbl1 only if you create the table after the connect.

Ganesan

-- 
Ganesan Rajagopal (rganesan at debian.org) | GPG Key: 1024D/5D8C12EA
Web: http://employees.org/~rganesan| http://rganesan.blogspot.com


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


Re: pysqlite problem

2006-03-01 Thread bapolis
I tried using the path "c:\ex1.db" and it worked. I was using "ex1.db"
before.

Thanks everyone for the help. This is a great community and maybe next
time I will ask a harder question :)

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


Re: error: argument after ** must be a dictionary

2006-03-01 Thread Kent Johnson
bruno at modulix wrote:
> abcd wrote:
> 
>>def makeThread(self, func, args=(), kwargs={}):
>>threading.Thread(target=self.blah, args=args,
>>kwargs=kwargs).start()
> 
> Shouldn't it be:
> 
> def makeThread(self, func, *args, **kwargs):
>   threading.Thread(target=self.blah,
>*args,
>**kwargs).start()

No. threading.Thread() doesn't use *args, **kwargs, it uses explicit 
named parameters.

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


Re: PEP 354: Enumerations in Python

2006-03-01 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 greg <[EMAIL PROTECTED]> wrote:

> Paul Rubin wrote:
> 
> > Do you anticipate having parameters like socket.AF_INET that are
> > currently integers, become enumeration members in future releases?
> 
> Since these are derived from values defined
> as integers in C, it's probably better to leave
> them that way. There may be code that relies
> on them being integers or having those integer
> values.

On a thin API like python's socket module, adding anything which isn't 
there in the lower level is a mistake (and making AF_INET an enum member 
would be adding something which isn't there).

I just finished adding IPv6 support to a product that didn't have it 
before.  We've got a "platform independent" socket interface which treats 
the address family as opaque data.  It turns out, I had to make ZERO 
changes to this shim layer.  Had the layer known more about address 
families, I would have had a lot more work to do.

Consider, for example, Python running on a system with experimental 
AF_INET8 support at some point in the future.  As it stands now, the Python 
library code doesn't need to know there's a new address family if all you 
want to do is open raw AF_INET8 sockets.
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2006-03-01 Thread Magnus Lycka
Jonathan Gardner wrote:
> On database portability...
> 
> While it is noble to try to have a generic interface to these
> libraries, the end result is that the databases are always different
> enough that the interface just has to work differently. 

Considering the use case in question...

"What I'd like to do is use Python to access an Oracle 9.X database for
exporting a series of tables into one aggregated table as a text file,
for import into a mainframe database."

...it certainly seems reasonable to achieve this without too much
modifications between database engines. The problem I see directly
is if it uses the system tables to figure out what to export, but
if it doesn't, I don't forsee any big problems. There are even
ebcdic codecs in Python! :)

Read the DB-API 2 spec well. You might also want to look at
http://www.thinkware.se/cgi-bin/thinki.cgi/DatabaseProgrammingWithPython

I guess the main differences would be the connect string and
parameter passing.

Using ODBC (e.g. via mxODBC) should remove these problems.
Assuming that you use a subset of SQL which is supported by all
your engines (seems reasonable for this use case) it should be
enough to change ODBC data source to select data from either
Oracle or some other server.

Once upon a time, ODBC meant a significant performance penalty.
I don't know if that is still true.

Note that mxODBC has a licence that doesn't allow it to be used
freely in commercial contexts.

There is also an ODBC driver in the Python Windows extensions,
but I don't think it's been actively developed for many years.
It's not complient with DB API 2. There is another DB API 2
driver for ODBC sources on Windows called adodbapi, but in my
experience, it's slow and has problems with unicode strings in
its error handling.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem solved: Re: time.sleep(1) sometimes runs for 200 seconds under windows

2006-03-01 Thread Magnus Lycka
Paul Probert wrote:
> Thanks everyone for your help.
>   It was the "Abouttime.exe" program, a time synch utility. To get the 
> problem, you have to run it as a service, and possibly it has to have 
> trouble connecting to its time servers. It would cause time.sleep(1) to 
> sometimes block for 200 seconds. Not "about" 200 seconds but always 
> within 199 to 202 seconds. Very strange, but it is good to have the 
> problem gone.

So did you understand what happened? Was the system call time.time()
just hanging while abouttime.exe was synching time?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Indentation Problems

2006-03-01 Thread Petr Jakes
Eric3 works great with spaces, tabs and even when imported code
indentation is "mixed". I have got problems trying to import "mixed)
code from other people.

Settings > Preferences > Editor > General
Tab width 8 Indentation width 4 (reasons why 8 and 4 are mentioned in
previous postings in this thread)

Than you can set the checkboxes:
- Use tabs for indentation
- Convert tabs upon open
- Tab key indents
- Auto indentation
- Show Indentation Guides

You can also see the different marks for tabs and for spaces in Eric3
(if set), so you will see, where is the problem in you code.

My favorite options (I am trying to use spaces for indentation
strictly) are:
=
- "Use tabs for indentation" - unchecked
- "Convert tabs upon open" - checked
=

Because of that I am not getting to the troubles with indentation
anymore.

HTH
Petr Jakes

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


Re: Is Python a Zen language?

2006-03-01 Thread Robert Boyd
On 25 Feb 2006 15:00:37 -0800, Paul Rubin
<"http://phr.cx"@nospam.invalid> wrote:
> "Kay Schluehr" <[EMAIL PROTECTED]> writes:
> > I have at times the impression that many people who talk about Zen
> > philosophy confuse it with some home brewn mixture of platonism with
> > its transgressive move towards the true reality, a stoic hedonism of
> > contemplation and the taoistic being-in-doing. Zen on the other side is
> > more radical: if you erase yourself there is no-one "who" is in the
> > flow but chances are that you and the computer over there are the same
> > thing.
>
> QOTW or something.
> --

How about, cue the "Philosophers' Song"?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-03-01 Thread Tim Chase
>> Do you anticipate having parameters like socket.AF_INET
>> that are currently integers, become enumeration members
>> in future releases?
> 
> Since these are derived from values defined as integers
> in C, it's probably better to leave them that way. There
> may be code that relies on them being integers or having
> those integer values.

I'd say that "because something is done in C, it's the best 
way to do it in Python" is a bad line of reasoning :)  If I 
wanted C, I'd use C.  ("some C API functions take pointers 
to arbitrary blocks of memory...python should [natively] 
implement pointers to arbitrary blocks of memory..." kinda 
scares me to be frank...that's why there's the ability to 
write clean wrappers in C or C++ to expose such things)

The backwards-compatibility-with-existing-code is a much 
better reason :)

-tkc





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


Re: how to write file with cp1250 encodings?

2006-03-01 Thread Magnus Lycka
Grzegorz Smith wrote:
> Hi all. I have got situation: i load data from database(MSSQL) wchich are
> encoded cp1250 

Are you sure that you are getting cp1250 from the database?
How do you communicate with the database? With the database
APIs I used in Windows, I always got Unicode objects from
databases, how ever things were internally stored in the DB.

If you have just managed to get your data correctly into
Unicode objects, you can convert them into whatever code
page you like with the .encode(encoding) method. Just make
sure you encode with the same encoding that yo state in
the meta element charset attribute.

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


Re: PIL and PSDraw

2006-03-01 Thread Kjell Magne Fauske
PIL is, as far as i know,primarily a tool for creating and manipulating
raster graphics. If you want to create eps vector graphics with Python
I recommend PyX:
http://pyx.sourceforge.net/
Take a look at the examples to see some of the possibilities:
http://pyx.sourceforge.net/examples/index.html

If you want to create charts and plots, matplotlib is also an excellent
tool: http://matplotlib.sourceforge.net/

Regards,
Kjell Magne Fauske
http://fauskes.net

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


Re: looking for help about python-sane

2006-03-01 Thread JW
Every time, or just this run?

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


Writing an applilcation that can easily adapt to any language

2006-03-01 Thread Chance Ginger
I am rather new at Python so I want to get it right. What I am doing
is writing a rather large application with plenty of places that 
strings will be used. Most of the strings involve statements of
one kind or another. 

I would like to make it easy for the support people to port the
application from one language to another, German, Spanish, etc. 
Rather than make them search all over for the strings to replace
is there a library that I can use to make this all easier? I
keep thinking of resources in Java, as an example. Is there 
anything like it in Python?

Peace,
Chance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-03-01 Thread Roy Smith
Tim Chase  <[EMAIL PROTECTED]> wrote:
>>> Do you anticipate having parameters like socket.AF_INET
>>> that are currently integers, become enumeration members
>>> in future releases?
>> 
>> Since these are derived from values defined as integers
>> in C, it's probably better to leave them that way. There
>> may be code that relies on them being integers or having
>> those integer values.
>
>I'd say that "because something is done in C, it's the best 
>way to do it in Python" is a bad line of reasoning :)  If I 
>wanted C, I'd use C.

The problem is that the C language binding in this case is simply
exposing the even lower level operating system interface.  At that
level, the address family is indeed just an arbitrary integer.

The socket man page on (for example) Solaris-9 says things like, "The
currently understood formats are", and "If a protocol is specified by
the caller, then it will be packaged into a socket level option
request and sent to the underlying pro- tocol layers".  You don't
really know for sure if you used a valid value until the low-level
protocol drivers look at the number you passed in.  This doesn't sound
like an enum to me.

There are plenty of places where we pass around integers that would be
better served by enums.  Address families and protocol numbers in the
socket interface just isn't one of them.

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


Re: Use empty string for self

2006-03-01 Thread John Salerno
James Stroud wrote:

> py> def doittoit(it):
> ...   print it.whatzit
> ...
> py> class It:
> ...   whatzit = 42
> ...   def doittoit(self):
> ... print self.whatzit
> ...
> py> anit = It()
> py> doittoit(anit)
> 42
> py> It.doittoit(anit)
> 42
> py> anit.doittoit()
> 42
> 
> 
> If you get this example, I'm pretty sure you will understand "self" and 
> its necessity.

I do get it. I think I will just have to get used to seeing the 'self' 
argument but understanding that it's not really something that is always 
passed in. I'm trying to train myself to see

def doittoit(self) as def doittoit()

Of course, that might not be a good strategy, because I know when it 
isn't used as an instance method (is that C terminology?), then you must 
explicitly pass the self argument.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing an applilcation that can easily adapt to any language

2006-03-01 Thread bruno at modulix
Chance Ginger wrote:
> I am rather new at Python so I want to get it right. What I am doing
> is writing a rather large application with plenty of places that 
> strings will be used. Most of the strings involve statements of
> one kind or another. 

> I would like to make it easy for the support people to port the
> application from one language to another, German, Spanish, etc. 
> Rather than make them search all over for the strings to replace
> is there a library that I can use to make this all easier? I
> keep thinking of resources in Java, as an example. Is there 
> anything like it in Python?

http://www.python.org/doc/2.4.2/lib/module-gettext.html

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: PyGUI 1.6: A Note for MacOSX Users

2006-03-01 Thread Alex Martelli
greg <[EMAIL PROTECTED]> wrote:

> A small problem has come to light with PyGUI 1.6
> on MacOSX systems.
> 
> If you get the following exception:
> 
> File "GUI/Generic/BaseAlertFunctions.py", line 5, in ?
> ImportError: No module named Alerts
> 
> it's probably because you don't have PyObjC installed.

I'm getting quite a different error:

[[snipped earlier parts of traceback]]
  File
"/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-pa
ckages/GUI/Cocoa/Applications.py", line 184, in init_application_name
ns_info['CFBundleName'] = GApplications.application_name
TypeError: object does not support item assignment

That's when I try (after installing PyGUI):

helen:~/Desktop/PyGUI-1.6/Demos alex$ python blobedit.py 

MacOSX, XCode, Python and PyObjC all at the latest binary-released
levels, I believe (10.4.5, 2.2, 2.4.1, 1.3.6 respectively).


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


Re: Cross compile generation of .pyc from .py files...

2006-03-01 Thread ookoi
You should look at this blog entry:
http://www.voidspace.org.uk/python/weblog/arch_d7_2006_02_11.shtml#e222

But if you have the original .py it's quite insane to want to hack the
.pyc only for porting it under others architectures. Instead, use
setuptools.

-- 
sebastien - http://seb.dbzteam.com

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


Accessing 'mangled' class attrbutes

2006-03-01 Thread Gerard Flanagan
Hello all

I would like to do the following:

  from elementtree.SimpleXMLWriter import XMLWriter

  class HtmlWriter(XMLWriter, object):
  def write_raw(self, text):
  super( HtmlWriter, self ).flush()
  super( HtmlWriter, self ).__write(text)

but because of the name-mangling caused by '__write' I get:

AttributeError: 'super' object has no attribute '_HtmlWriter__write'.

Is there any simple way round this situation in general?

(I just want to write out a HTML 'DOCTYPE' declaration)

Thanks

Gerard

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


Re: Make staticmethod objects callable?

2006-03-01 Thread Steven Bethard
Steven D'Aprano wrote:
> So, based on this evidence, staticmethod() inside a class definition 
> converts instance methods to functions. Outside a class definition, 
> staticmethod() does one of two things: it either converts an instance 
> method to a static method, or if the output is assigned to a class 
> attribute, it leaves it as an instance method.

This is exactly why I'm concerned about augmenting staticmethod's 
behavior.  When people run into this, it should be the opportunity to 
explain to them how descriptors work.  Descriptors are hugely important 
in the new object system, and even if we hide them by giving 
staticmethod a __call__, we'll still run into problems when people try 
to do:

 class C(object):
 @classmethod
 def foo(cls):
 print cls
 bar = foo(None)

Then, not only do we have to explain how descriptors work, but we also 
have to explain why staticmethod has a __call__, and classmethod doesn't.

(For anyone else out there reading who doesn't already know this, Steven 
D'Aprano's comments are easily explained by noting that the __get__ 
method of staticmethod objects returns functions, and classes always 
call the __get__ methods of descriptors when those descriptors are class 
attributes:

 >>> class C(object):
... @staticmethod
... def foo():
... pass
... print foo
...

 >>> print C.foo

 >>> @staticmethod
... def foo():
... pass
...
 >>> print foo

 >>> print foo.__get__(C, None)


Yes, you have to explain descriptors, but at the point that you start 
trying to do funny things with staticmethods and classmethods, I think 
you need to start learning about them anyway.)

All that said, you should probably just submit a patch and see what 
happens.  I'll make a brief comment on it along the above lines, but 
since I'm not a committer, it's not really worth your time to try to 
convince me. ;)

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


is Queue.Queue() serializable with cPickle?

2006-03-01 Thread john peter
i have the following custom extenstion of Queue.Queue() to save and load  queue contents but I think there's a problem with it.  Does anybody know qhether Queue.Queue() is pickle-able? if so,  can I get sample code? If not, can anybody recommend a pickle-able  Queue from another library that I might be able to use?  Thank you for any help!     Here's my "PersistentQueue" extension:     import cPickleimport Queueimport osfrom os.path import *  class PersistentQueue(Queue.Queue):   def __init__(self, maxsize=0):  #print "init"  Queue.Queue.__init__(self,maxsize)     def saveState(self, file):  fullFilePath = join(os.getcwd(),'savedStates', file)!
 ; 
 #print fullFilePath  f = open(fullFilePath, 'w')  l = []  while not self.empty(): l.append(self.get())  cPickle.dump(l, f)  f.close()     def loadState(self, file):  fullFilePath = join(os.getcwd(),'savedStates', file)  #print fullFilePath  f = open(fullFilePath)  l = cPickle.load(f)  f.close()  for i in l: self.put(i)  if __name__ == '__main__':   q = PersistentQueue(20)   q.loadState("q1.sav")   print q.get()    
 q.put("four")   q.saveState("q1.sav")
	
		 Yahoo! Mail 
Use Photomail to share photos without annoying attachments.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: unicode question

2006-03-01 Thread Walter Dörwald
Edward Loper wrote:

> Walter Dörwald wrote:
>> Edward Loper wrote:
>>
>>> [...]
>>> Surely there's a better way than converting back and forth 3 times?  Is
>>> there a reason that the 'backslashreplace' error mode can't be used 
>>> with codecs.decode?
>>>
>>>  >>> 'abc \xff\xe8 def'.decode('ascii', 'backslashreplace')
>>> Traceback (most recent call last):
>>>File "", line 1, in ?
>>> TypeError: don't know how to handle UnicodeDecodeError in error callback
>>
>> The backslashreplace error handler is an *error* *handler*, i.e. it 
>> gives you a replacement text if an input character can't be encoded. 
>> But a backslash character in an 8bit string is no error, so it won't 
>> get replaced on decoding.
> 
> I'm not sure I follow exactly -- the input string I gave as an example 
> did not contain any backslash characters.  Unless by "backslash 
> character" you mean a character c such that ord(c)>127.  I guess it 
> depends on which class of errors you think the error handler should be 
> handling. :)  The codec system's pretty complex, so I'm willing to
> accept on faith that there may be a good reason to have error handlers 
> only make replacements in the encode direction, and not in the decode 
> direction.

Both directions are completely non-symmetric. On encoding an error can 
only happen when the character is unencodable (e.g. for charmap codecs 
anything outside the set of 256 characters). On decoding an error means 
that the byte stream violates the internal format of the encoding. But a 
0x5c byte (i.e. a backslash) in e.g. a latin-1 byte sequence doesn't 
violate the internal format of the latin-1 encoding (nothing does), so 
the error handler never kicks in.

>> What you want is a different codec (try e.g. "string-escape" or 
>> "unicode-escape").
> 
> This is very close, but unfortunately won't quite work for my purposes, 
> because it also puts backslashes before "'" and "\\" and maybe a few 
> other characters.  :-/

OK, seems you're stuck with your decode/encode/decode call.

>  >>> print "test: '\xff'".encode('string-escape').decode('ascii')
> test: \'\xff\'
> 
>  >>> print do_what_i_want("test:\xff'")
> test: '\xff'
> 
> I think I'll just have to stick with rolling my own.

Bye,
Walter Dörwald
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing a file

2006-03-01 Thread Fabian Steiner
Hi!

Thank you so far, but now I got stuck again :-/


Jeremy Sanders wrote:
> QPrinter is easy to use. You just draw to the page the same way as you talk
> to the screen with a QPainter.
> 
> prnt = qt.QPrinter()
> # you can also vary options like colour, doc name, dpi here
> 
> # display dialog box to user (you can actually leave this out)
> if prnt.setup():
>  painter = qt.QPainter()
>  painter.begin(printer)
>  # do stuff to draw to painter
>  painter.end(printer)
>  # do this between each page
>  printer.newPage()


This is what I have so far:

app = QApplication(sys.argv)
printer = QPrinter(QPrinter.PrinterResolution)
if printer.setup():
 printer.setPageSize(printer.A4)
 painter = QPainter(printer)
 metrics = QPaintDeviceMetrics(painter.device())
 marginHeight = 6
 marginWidth =  8
 body = QRect(marginWidth, marginHeight, metrics.widthMM() - 2 * 
marginWidth, metrics.heightMM() - 2 * marginHeight)
 painter.drawRect(body)
 painter.end()

Doing so I hoped to get a rectangle which is as big as an A4 paper (with 
a small border), but unfortunately it is much smaller. Moreover, I ask 
myself whether it is necessary that in order to write text on the paper, 
I always have to pass the proper x, y values to QPainter.drawText(). 
Isn't there any other possibility? How do I get these values?


Thanks in advance,
Fabian Steiner
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use empty string for self

2006-03-01 Thread Roy Smith
John Salerno  <[EMAIL PROTECTED]> wrote:
>I do get it. I think I will just have to get used to seeing the 'self' 
>argument but understanding that it's not really something that is always 
>passed in. I'm trying to train myself to see
>
>def doittoit(self) as def doittoit()

That's OK as far as using your C++ experience to help understand
Python by analogy, but don't fall into the trap of trying to write C++
in Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numerical solver

2006-03-01 Thread Laszlo Zsolt Nagy
Robert Kern wrote:

>In [7]: scipy.optimize.fmin_cobyla?
>
>Type:   function
>Base Class: 
>String Form:
>Namespace:  Interactive
>File:
>/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/scipy-
>0.4.7.1607-py2.4-macosx-10.4-ppc.egg/scipy/optimize/cobyla.py
>Definition: scipy.optimize.fmin_cobyla(func, x0, cons, args=(),
>consargs=None, rhobeg=1.0, rhoen
>d=0.0001, iprint=1, maxfun=1000)
>Docstring:
>Minimize a function using the Contrained Optimization BY Linear
>Approximation (COBYLA) method
>  
>
...

>Returns:
>
>x -- the minimum
>  
>
I'm going to try this. I hope x and x0 can be a vectors. :-)


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


Searching for uniqness in a list of data

2006-03-01 Thread rh0dium
Hi all,

I am having a bit of difficulty in figuring out an efficient way to
split up my data and identify the unique pieces of it.

list=['1p2m_3.3-1.8v_sal_ms','1p2m_3.3-1.8_sal_log']

Now I want to split each item up on the "_" and compare it with all
others on the list, if there is a difference I want to create a list of
the possible choices, and ask the user which choice of the list they
want.  I have the questioning part under control.   I can't seem to get
my hands around the logic - the list could be 2 items or 100 long.  The
point of this is that I am trying to narrow a decision down for an end
user.  In other words the end user needs to select one of the list
items, and by breaking it down for them I hope to simplify this.

list=['1p2m_3.3-1.8v_sal_ms','1p6m_3.3-1.8_sal_log']
 would only question the first data set ['1p2m', '1p6m' ]

list=['1p2m_3.3-1.8v_sal_ms','1p2m_3.3-1.8v_pol_ms','1p3m_3.3-18.v_sal_ms']
 If on the list ['1p2m','1p2m','1p3m'] the user selected 1p2m then the
next list would only be ['sal','pol']
 but if the user initially only selected 1p3m they would be done..

I hope this clarifies what I am trying to do.  I just can't seem to get
my hands around this - so an explaination of logic would really be
helpfull.  I picture a 2d list but I can't seem to get it..

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


why? [win32com/WMI]

2006-03-01 Thread Sergey
import win32com.client

loc = win32com.client.Dispatch("WbemScripting.SWbemLocator")
svc = loc.ConnectServer("srv", "root/cimv2", "[EMAIL PROTECTED]", "**")
sys = svc.get("Win32_Process")
sys.create("notepad.exe")

=>

Traceback (most recent call last):
File "remote.py", line 6, in ?
sys.create("notepad.exe")
TypeError: 'int' object is not callable 


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


Re: Searching for uniqness in a list of data

2006-03-01 Thread Claudio Grondi
rh0dium wrote:
> Hi all,
> 
> I am having a bit of difficulty in figuring out an efficient way to
> split up my data and identify the unique pieces of it.
> 
> list=['1p2m_3.3-1.8v_sal_ms','1p2m_3.3-1.8_sal_log']
> 
> Now I want to split each item up on the "_" and compare it with all
> others on the list, if there is a difference I want to create a list of
> the possible choices, and ask the user which choice of the list they
> want.  I have the questioning part under control.   I can't seem to get
> my hands around the logic - the list could be 2 items or 100 long.  The
> point of this is that I am trying to narrow a decision down for an end
> user.  In other words the end user needs to select one of the list
> items, and by breaking it down for them I hope to simplify this.
> 
> list=['1p2m_3.3-1.8v_sal_ms','1p6m_3.3-1.8_sal_log']
>  would only question the first data set ['1p2m', '1p6m' ]
> 
> list=['1p2m_3.3-1.8v_sal_ms','1p2m_3.3-1.8v_pol_ms','1p3m_3.3-18.v_sal_ms']
>  If on the list ['1p2m','1p2m','1p3m'] the user selected 1p2m then the
> next list would only be ['sal','pol']
>  but if the user initially only selected 1p3m they would be done..
> 
> I hope this clarifies what I am trying to do.  I just can't seem to get
> my hands around this - so an explaination of logic would really be
> helpfull.  I picture a 2d list but I can't seem to get it..
> 

list=['1p2m_3.3-1.8v_sal_ms','1p2m_3.3-1.8v_pol_ms','1p3m_3.3-18.v_sal_ms']
dictQlevel_1={}
dictQlevel_2={}
dictQlevel_3={}
for item in list:
   splitted = item.split('_')
   dictQlevel_1[splitted[0]] = True
   dictQlevel_2[splitted[1]] = True
   dictQlevel_3[splitted[2]] = True

print 'choose one of: '
for key_1 in dictQlevel_1.keys():
   print key_1
print
usrInput = raw_input()

if usrInput == '':
   print 'choose one of: '
   for key_1 in dictQlevel_1.keys():
 for key_2 in dictQlevel_2.keys():
   print key_1, key_2
   print
   usrInput = raw_input()
else:
   pass
   # or do something

# etc.


Hope it is what you are looking for.

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


Re: Default Section Values in ConfigParser

2006-03-01 Thread mwt
Thanks, Terry. That's an interesting way to go about it.

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


Re: PIL and PSDraw

2006-03-01 Thread Sybren Stuvel
Kjell Magne Fauske enlightened us with:
> PIL is, as far as i know,primarily a tool for creating and
> manipulating raster graphics.

I was afraid of that.

> If you want to create eps vector graphics with Python I recommend
> PyX:

That looks exactly what I was looking for. Thanks a lot!

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: Thread Question

2006-03-01 Thread Aahz
In article <[EMAIL PROTECTED]>,
Kent Johnson  <[EMAIL PROTECTED]> wrote:
>D wrote:
>>
>> My question is, how would I go
>> about creating the thread?  I have seen examples that used classes, and
>> other examples that just called one thread start command - when should
>> you use one over another?
>
>For simple use it doesn't matter. Use a class when you want to add more 
>state or behaviour - for example you might want a flag that tells the 
>thread to stop, or a Queue to communicate with the thread. A class might 
>be more convenient in these cases.
>
>IOW if you can write it as a single function it doesn't matter much 
>which form you use; for more complex usage you may want a class.

OTOH, always subclassing requires less thinking.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"19. A language that doesn't affect the way you think about programming,
is not worth knowing."  --Alan Perlis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use empty string for self

2006-03-01 Thread Grant Edwards
On 2006-03-01, John Salerno <[EMAIL PROTECTED]> wrote:

> I do get it. I think I will just have to get used to seeing
> the 'self' argument but understanding that it's not really
> something that is always passed in.

But it _is_ always passed to the function.  You can even pass
it explicity when you call the method if you want:

  #!/usr/bin/python
  
  class MyClass:
  def mymethod(self,p1,p2):
  print self,p1,p2

  instance = MyClass()

  MyClass.mymethod(instance,1,2)

  instance.mymethod(1,2)

The two calls are equivalent.  

> I'm trying to train myself to see
>
> def doittoit(self) as def doittoit()

You would be misleading yourself.

> Of course, that might not be a good strategy, because I know
> when it isn't used as an instance method (is that C
> terminology?), then you must explicitly pass the self
> argument.

Exactly.

-- 
Grant Edwards   grante Yow!  I guess we can live
  at   on his POT FARM in HADES!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why? [win32com/WMI]

2006-03-01 Thread Claudio Grondi
Sergey wrote:
> import win32com.client
> 
> loc = win32com.client.Dispatch("WbemScripting.SWbemLocator")
> svc = loc.ConnectServer("srv", "root/cimv2", "[EMAIL PROTECTED]", "**")
> sys = svc.get("Win32_Process")
> sys.create("notepad.exe")
> 
> =>
> 
> Traceback (most recent call last):
> File "remote.py", line 6, in ?
> sys.create("notepad.exe")
> TypeError: 'int' object is not callable 
> 
> 
I have no idea what are you doing in your code or if the following has 
something to do with your problem, but sometimes it good to know, that 
Windows requires Unicode strings as parameter and giving full path file 
names is always better than to rely on some default mechanisms.

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


Re: Numerical solver

2006-03-01 Thread Robert Kern
Laszlo Zsolt Nagy wrote:
> Robert Kern wrote:
> 
>>In [7]: scipy.optimize.fmin_cobyla?
>>
>>Type:   function
>>Base Class: 
>>String Form:
>>Namespace:  Interactive
>>File:
>>/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/scipy-
>>0.4.7.1607-py2.4-macosx-10.4-ppc.egg/scipy/optimize/cobyla.py
>>Definition: scipy.optimize.fmin_cobyla(func, x0, cons, args=(),
>>consargs=None, rhobeg=1.0, rhoen
>>d=0.0001, iprint=1, maxfun=1000)
>>Docstring:
>>   Minimize a function using the Contrained Optimization BY Linear
>>   Approximation (COBYLA) method
>> 
> ...
> 
>>   Returns:
>>
>>   x -- the minimum
> 
> I'm going to try this. I hope x and x0 can be a vectors. :-)

Yes, of course.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: Accessing 'mangled' class attrbutes

2006-03-01 Thread Steve Juranich
Gerard Flanagan wrote:

> I would like to do the following:
> 
>   from elementtree.SimpleXMLWriter import XMLWriter
> 
>   class HtmlWriter(XMLWriter, object):
>   def write_raw(self, text):
>   super( HtmlWriter, self ).flush()
>   super( HtmlWriter, self ).__write(text)
> 
> but because of the name-mangling caused by '__write' I get:
> 
> AttributeError: 'super' object has no attribute '_HtmlWriter__write'.
> 
> Is there any simple way round this situation in general?
> 
> (I just want to write out a HTML 'DOCTYPE' declaration)

Try: (not the Python keyword, but a directive to you)

super(HtmlWriter, self)._XMLWriter__write(text)

In general, to access the name-mangled members, simply add 
_ to the front of the member name and you should be able to get
at it.  But be careful, since this is a reference to the base class, so if
it's inherited from some other class, you'll need to know from which class
the member is inherited.

HTH

-- 
Steve Juranich
Tucson, AZ
USA

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


Re: Use empty string for self

2006-03-01 Thread John Salerno
Grant Edwards wrote:

> But it _is_ always passed to the function.  You can even pass
> it explicity when you call the method if you want:

I meant it isn't always explicitly passed.

> 
>   #!/usr/bin/python
>   
>   class MyClass:
>   def mymethod(self,p1,p2):
>   print self,p1,p2
> 
>   instance = MyClass()
> 
>   MyClass.mymethod(instance,1,2)
> 
>   instance.mymethod(1,2)
> 
> The two calls are equivalent.  

can you also say instance.mymethod(instance, 1, 2)  ?
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: why? [win32com/WMI]

2006-03-01 Thread Tim Golden
[Sergey]

| import win32com.client
| 
| loc = win32com.client.Dispatch("WbemScripting.SWbemLocator")
| svc = loc.ConnectServer("srv", "root/cimv2", "[EMAIL PROTECTED]", "**")
| sys = svc.get("Win32_Process")
| sys.create("notepad.exe")
| 
| =>
| 
| Traceback (most recent call last):
| File "remote.py", line 6, in ?
| sys.create("notepad.exe")
| TypeError: 'int' object is not callable 

I could explain (it's to do with the way in which
WMI method calls are set up) but I suggest you look at
this module :

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

which makes WMI much easier to work with.

Your example then becomes:


import wmi

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


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: Accessing 'mangled' class attrbutes

2006-03-01 Thread [EMAIL PROTECTED]
>>Is there any simple way round this situation in general?

It might be safer to use composition instead of inheritance in this
case. Assuming that XMLWriter has a write method to write what you
want, you could hold a reference to an XMLWriter within your class and
pass along write command like:

writer = XMLWriter()
writer.write(stuff)

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


Re: Searching for uniqness in a list of data

2006-03-01 Thread Alexander Schmolck
"rh0dium" <[EMAIL PROTECTED]> writes:

> Hi all,
> 
> I am having a bit of difficulty in figuring out an efficient way to
> split up my data and identify the unique pieces of it.
> 
> list=['1p2m_3.3-1.8v_sal_ms','1p2m_3.3-1.8_sal_log']
> 
> Now I want to split each item up on the "_" and compare it with all
> others on the list, if there is a difference I want to create a list of
> the possible choices, and ask the user which choice of the list they
> want.  I have the questioning part under control.   I can't seem to get
> my hands around the logic - the list could be 2 items or 100 long.  The
> point of this is that I am trying to narrow a decision down for an end
> user.  In other words the end user needs to select one of the list
> items, and by breaking it down for them I hope to simplify this.
> 
> list=['1p2m_3.3-1.8v_sal_ms','1p6m_3.3-1.8_sal_log']
>  would only question the first data set ['1p2m', '1p6m' ]
> 
> list=['1p2m_3.3-1.8v_sal_ms','1p2m_3.3-1.8v_pol_ms','1p3m_3.3-18.v_sal_ms']
>  If on the list ['1p2m','1p2m','1p3m'] the user selected 1p2m then the
> next list would only be ['sal','pol']
>  but if the user initially only selected 1p3m they would be done..
> 
> I hope this clarifies what I am trying to do.  I just can't seem to get
> my hands around this - so an explaination of logic would really be
> helpfull.  I picture a 2d list but I can't seem to get it..

The easiest way to do this is to have a nested dictionary of prefixes: for
each prefix as key add a nested dictionary of the rest of the split as value
or an empty dict if the split is empty. Accessing the dict with an userinput
will give you all the possible next choices.

Spoiler Warning -- sample implementation follows below.
































(mostly untested)

def addSplit(d, split):
if len(split):
if split[0] not in d:
d[split[0]] = addSplit({}, split[1:])
else:
addSplit(d[split[0]], split[1:])
return d
def queryUser(chosen, choices):
next = raw_input('So far: %s\nNow type one of %s: ' %
(chosen,choices.keys()))
return chosen+next, choices[next]

wordList=['1p2m_3.3-1.8v_sal_ms','1p2m_3.3-1.8v_pol_ms','1p3m_3.3-18.v_sal_ms']
choices = reduce(addSplit,(s.split('_') for s in wordList),  {})
chosen = ""
while choices:
chosen, choices = queryUser(chosen, choices)
print "You chose:", chosen

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


Re: telnetlib problems

2006-03-01 Thread vercingetorix52
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.

Any ideas?

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


Re: Thread Question

2006-03-01 Thread Just
In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] (Aahz) 
wrote:

> In article <[EMAIL PROTECTED]>,
> Kent Johnson  <[EMAIL PROTECTED]> wrote:
> >D wrote:
> >>
> >> My question is, how would I go
> >> about creating the thread?  I have seen examples that used classes, and
> >> other examples that just called one thread start command - when should
> >> you use one over another?
> >
> >For simple use it doesn't matter. Use a class when you want to add more 
> >state or behaviour - for example you might want a flag that tells the 
> >thread to stop, or a Queue to communicate with the thread. A class might 
> >be more convenient in these cases.
> >
> >IOW if you can write it as a single function it doesn't matter much 
> >which form you use; for more complex usage you may want a class.
> 
> OTOH, always subclassing requires less thinking.

Same for never subclassing :)

I always felt that subclassing Thread is very unpythonic. It seems like 
an unfortunate leftover Javaism (much of threading.py was inspired by 
Java, but I don't need to tell you that). If I need some state, I create 
my own class, with a reference to the Thread object if needed. Has-a vs. 
is-a.

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


Re: Searching for uniqness in a list of data

2006-03-01 Thread johnzenger
You can come quite close to what you want without splitting the string
at all.  It sounds like you are asking the user to build up a string,
and you want to keep checking through your list to find any items that
begin with the string built up by the user.  Try something like this:

mylist = ['1p2m_3.3-1.8v_sal_ms','1p2m_3.3-1.8_sal_log']
sofar = ""

loop = True
while loop:
selections = [ x[len(sofar):x.index("_", len(sofar) + 1)]
   for x in mylist if x.startswith(sofar) ]
loop = len(selections) > 1
if loop:
print selections
sofar += raw_input("Pick one of those: ")

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


Re: Printing a file

2006-03-01 Thread David Boddie
Fabian Steiner wrote:

> This is what I have so far:
>
> app = QApplication(sys.argv)
> printer = QPrinter(QPrinter.PrinterResolution)
> if printer.setup():
>  printer.setPageSize(printer.A4)
>  painter = QPainter(printer)
>  metrics = QPaintDeviceMetrics(painter.device())
>  marginHeight = 6
>  marginWidth =  8
>  body = QRect(marginWidth, marginHeight, metrics.widthMM() - 2 *
> marginWidth, metrics.heightMM() - 2 * marginHeight)
>  painter.drawRect(body)
>  painter.end()
>
> Doing so I hoped to get a rectangle which is as big as an A4 paper (with
> a small border), but unfortunately it is much smaller.

Surely you meant to use

body = QRect(marginWidth, marginHeight,
 metrics.width() - 2 * marginWidth,
 metrics.height() - 2 * marginHeight)

> Moreover, I ask myself whether it is necessary that in order to write
> text on the paper, I always have to pass the proper x, y values to
> QPainter.drawText().
> Isn't there any other possibility? How do I get these values?

That depends on what kind of text you're drawing (paragraphs of text
vs. simple labels). See the application.py example in the examples3
directory of the PyQt3 distribution for code that implements a simple
text editor with support for printing. Information about text and font
metrics can be found with the QFontMetrics class:

http://doc.trolltech.com/3.3/qfontmetrics.html

PyQt4 supports Qt 4's new rich text facilities, so it's easier to
format text for printing than it is in Qt 3. A more advanced rich text
editor is only available in the C++ Qt 4 demos, but there are other
examples bundled with PyQt4 that show how to print "simple" documents:

http://www.riverbankcomputing.co.uk/

Finally, it's worth pointing out that there's a higher concentration of
people with experience in these matters reading the PyQt/PyKDE mailing
list:

http://mats.imk.fraunhofer.de/mailman/listinfo/pykde

Good luck with your printing,

David

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


Re: Cross compile generation of .pyc from .py files...

2006-03-01 Thread venkatbo

Terry Reedy wrote:
> ...
> I am under the impression that .pyc files are system independent.
> Have you tried simply copying them over?
>
> tjr

Hi Terry,

It appears that python on the target ppc system is expecting to see
ppc-related info in the .pyc files. These .pyc were generated at cross
compile time (on i686 system) and packaged, deployed, installed on the
ppc system.  The "...has bad magic..."  appears to indicate that
ppc-version of python is expecting to see ppc-specific .pyc files, but
is encountering i686-specific .pyc files... For some reason, the
cross-compile step that results in the .pyc files is not generating
them for the proper ppc-target, but is building them for the i686
system where they were being cross-compiled...

Thanks,
/venkat

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


Re: Make staticmethod objects callable?

2006-03-01 Thread Nicolas Fleury
Steven Bethard wrote:
> ...
> Yes, you have to explain descriptors, but at the point that you start 
> trying to do funny things with staticmethods and classmethods, I think 
> you need to start learning about them anyway.)

That's all good points, but IMHO, descriptors are a much more advanced 
Python feature than static methods, especially for programmers from 
other backgrounds, like Java/C#/C++.  We basically have the choice 
between hiding something unnecessarily complex or force to understand a 
useful feature;)

> All that said, you should probably just submit a patch and see what 
> happens.  I'll make a brief comment on it along the above lines, but 
> since I'm not a committer, it's not really worth your time to try to 
> convince me. ;)

I might do it, but even if I'm not a commiter, I'll continue trying to 
convince myself;)

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


Re: Cross compile generation of .pyc from .py files...

2006-03-01 Thread Just
In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] wrote:

> Terry Reedy wrote:
> > ...
> > I am under the impression that .pyc files are system independent.
> > Have you tried simply copying them over?
> >
> > tjr
> 
> Hi Terry,
> 
> It appears that python on the target ppc system is expecting to see
> ppc-related info in the .pyc files.

There is no such thing.

> These .pyc were generated at cross
> compile time (on i686 system) and packaged, deployed, installed on the
> ppc system.  The "...has bad magic..."  appears to indicate that
> ppc-version of python is expecting to see ppc-specific .pyc files, but
> is encountering i686-specific .pyc files... For some reason, the
> cross-compile step that results in the .pyc files is not generating
> them for the proper ppc-target, but is building them for the i686
> system where they were being cross-compiled...

.pyc files are only compatible with the same major Python version, so it 
sounds like you're using different versions on both platforms.

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


Trouble with numpy-0.9.4 and numpy-0.9.5

2006-03-01 Thread drife
Hello,

I use the Python Numeric package extensively, and had been an
avid user of the "old" scipy. In my view, both pieces of software
are truly first rate, and have greatly improved my productivity in
the area of scientific analysis. Thus, I was excited to make the
transition to the new scipy core (numpy).

Unfortunately, I am experiencing a problem that I cannot sort
out. I am running Python 2.4.2 on a Debian box (V3.1), using
gcc version 3.3.5, and ATLAS, BLAS, and LAPACK libraries
built from scratch. When building numpy everything seems to
go AOK. But trouble soon follows.

As a sanity check, I run the diagnostic tests that come as
part of the numpy package:

from numpy import *
from scipy import *

test(level=N)  #  N can vary from 1 to 10. :


No matter which test I run, Python crashes hard with only
the following output: "Floating exception".

I thought perhaps numpy would still work Ok, even though
it seemed to have failed this "sanity" test.

Thus, I tried using the numpy.linalg.eig functionality, and
upon calling numpy.linalg.eig I get the same behavior:
Python crashes hard with the same output "Floating
exception".

Can someone help me sort out what might be wrong?
Perhaps I have overlooked a crucial step in the build/
install of numpy.


Thanks very much,


Daran

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


Re: Cross compile generation of .pyc from .py files...

2006-03-01 Thread venkatbo
Hi Sebastian,

Thanks for that link and your notes.

I was under the impression, that the .pyc files will be used (if found)
by python to speed up execution of scripts... and so we packaged,
deployed and installed the .py/.pyc files on to the ppc-target system.
That package includes, site.py(c), types.py(c) etc., among others.

Though I see these errors when I invokde 'python -v', I'm able to
execute the .py files... but was hoping to use the .pyc files to
benefit from the enhanced speed of execution. Like I mentioned to
Terry, for some reason only the cross compile generation of .pyc for
the ppc-target is not getting done right, whereas the actual
ppc-specific python (2.4.2) binaries and extension (.so) modules are
getting created properly.

We were not trying to just ship the .pyc files and reverse-engineer the
.py files from them on the target ppc system.

Thanks,
/venkat

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


Re: Accessing 'mangled' class attrbutes

2006-03-01 Thread Gerard Flanagan

Steve Juranich wrote:
> Gerard Flanagan wrote:
>
> > I would like to do the following:
> >
> >   from elementtree.SimpleXMLWriter import XMLWriter
> >
> >   class HtmlWriter(XMLWriter, object):
> >   def write_raw(self, text):
> >   super( HtmlWriter, self ).flush()
> >   super( HtmlWriter, self ).__write(text)
> >
> > but because of the name-mangling caused by '__write' I get:
> >
> > AttributeError: 'super' object has no attribute '_HtmlWriter__write'.
> >
> > Is there any simple way round this situation in general?
> >
> > (I just want to write out a HTML 'DOCTYPE' declaration)
>
> Try: (not the Python keyword, but a directive to you)
>
> super(HtmlWriter, self)._XMLWriter__write(text)
>
> In general, to access the name-mangled members, simply add
> _ to the front of the member name and you should be able to get
> at it.  But be careful, since this is a reference to the base class, so if
> it's inherited from some other class, you'll need to know from which class
> the member is inherited.
>
> HTH
>
> --
> Steve Juranich
> Tucson, AZ
> USA

I tried that Steve but it didn't work, and i don't think I can do what
I want in any case.  There is no method '__write' in the base class, it
is only declared as an instance attribute in the constructor, like so:

def __init__(self, file, encoding="us-ascii"):
...
self.__write = file.write
...

I tried putting  '__write = None' at the class level (in the base class
XMLWriter) but then, although '_XMLWriter__write' appears in
'dir(HtmlWriter)', I get  'NoneType is not callable'.

I also tried 'def __write(self, text) : pass ' in the base class, but
then the code runs but doesn't write the text I want -  and anyway, if
I'm going to change the base class, then i may as well just add the
'write_raw' method to the base directly!

It's just some toy code at any rate, and I've learnt something new!
Thanks for your reply.

Gerard

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


Re: Trouble with numpy-0.9.4 and numpy-0.9.5

2006-03-01 Thread Travis E. Oliphant
drife wrote:
> Hello,
> 
> I use the Python Numeric package extensively, and had been an
> avid user of the "old" scipy. In my view, both pieces of software
> are truly first rate, and have greatly improved my productivity in
> the area of scientific analysis. Thus, I was excited to make the
> transition to the new scipy core (numpy).
> 
> Unfortunately, I am experiencing a problem that I cannot sort
> out. I am running Python 2.4.2 on a Debian box (V3.1), using
> gcc version 3.3.5, and ATLAS, BLAS, and LAPACK libraries
> built from scratch. When building numpy everything seems to
> go AOK. But trouble soon follows.
> 
> As a sanity check, I run the diagnostic tests that come as
> part of the numpy package:
> 
> from numpy import *
> from scipy import *
> 
> test(level=N)  #  N can vary from 1 to 10. :
> 
> 
> No matter which test I run, Python crashes hard with only
> the following output: "Floating exception".
> 

This could be related to the Debian glibc bug that has been discussed 
before.   Aparently the Debian version of glibc had some issues with 
SSE.  This is the same behavior experienced by others on the Debian 
platform.  There is a patch, but I'm not sure what it is.

See, for example:

http://aspn.activestate.com/ASPN/Mail/Message/numpy-discussion/2207861

Come over to the [EMAIL PROTECTED] and/or 
[EMAIL PROTECTED]

lists for more help.

-Travis

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


Re: Accessing 'mangled' class attrbutes

2006-03-01 Thread Gerard Flanagan
[EMAIL PROTECTED] wrote:
> >>Is there any simple way round this situation in general?
>
> It might be safer to use composition instead of inheritance in this
> case. Assuming that XMLWriter has a write method to write what you
> want, you could hold a reference to an XMLWriter within your class and
> pass along write command like:
>
> writer = XMLWriter()
> writer.write(stuff)

No, XMLWriter doesn't have a 'write' method, if it did I could have
done:

super(HtmlWriter, self).write(stuff)

I think the XMLWriter class has been designed so you can't just write
any old text because this better ensures that tags are properly closed
and so on.  There is a public 'data' method:

writer.data( text )

but it escapes angle brackets, and what i wanted was to write
'http://mail.python.org/mailman/listinfo/python-list


Re: Searching for uniqness in a list of data

2006-03-01 Thread Alexander Schmolck
Alexander Schmolck <[EMAIL PROTECTED]> writes:

> The easiest way to do this is to have a nested dictionary of prefixes: for
> each prefix as key add a nested dictionary of the rest of the split as value
> or an empty dict if the split is empty. Accessing the dict with an userinput
> will give you all the possible next choices.

Oops I was reading this too hastily -- forgot to compact and take care of sep.
You might also want to google 'trie', BTW.


(again, not really tested)


def addSplit(d, split):
if len(split):
if split[0] not in d:
d[split[0]] = addSplit({}, split[1:])
else:
addSplit(d[split[0]], split[1:])
return d
def compactify(choices, parentKey='', sep=''):
if len(choices) == 1:
return compactify(choices.values()[0],
  parentKey+sep+choices.keys()[0], sep)
else:
for key in choices.keys():
newKey, newValue = compactify(choices[key], key, sep)
if newKey != key: del choices[key]
choices[newKey] = newValue
return (parentKey, choices)
def queryUser(chosen, choices, sep=''):
next = raw_input('So far: %s\nNow type one of %s: ' %
(chosen,choices.keys()))
return chosen+sep+next, choices[next]
wordList=['1p2m_3.3-1.8v_sal_ms','1p2m_3.3-1.8v_pol_ms','1p3m_3.3-18.v_sal_ms']
choices = compactify(reduce(addSplit,(s.split('_') for s in wordList),  {}),
 sep='_')[1]
chosen = ""

while choices:
chosen, choices = queryUser(chosen, choices, '_')
print "You chose:", chosen


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


Re: PEP 354: Enumerations in Python

2006-03-01 Thread Raymond Hettinger
[Ben Finney]
> It is possible to simply define a sequence of values of some other
> basic type, such as ``int`` or ``str``, to represent discrete
> arbitrary values.  However, an enumeration ensures that such values
> are distinct from any others, and that operations without meaning
> ("Wednesday times two") are not defined for these values.

It would be useful for the PEP to add a section that discussed the pros
and cons of this approach (preferably with examples).

For instance, having values distinct from one another is only useful in
the absence of namespace qualifiers (such as Weekdays.fri).

Also, it would be useful to contrast this approach with that used for
Booleans which were implemented as an int subclass.  There, the
interoperability with other numbers turned out to be useful on
occasion:

   Q = lambda predicate, iterable: sum(predicate(val) for val in
iterable)

Likewise, the PEP's approach precludes a broad class of use cases such
as:

   Weekday.fri - Weekday.wed == 2

(where Weekday.fri > Weekday.wed implies that the difference has a
positive value).

If enumerations were implemented as an int subclass, they could serve
as a base class for booleans and enter the language in a unified way.
Likewise, they could be more readily applicable in use cases like
calendar.py which relies on math ops being defined for the days of the
week.

I would like to see the PEP develop these arguments more fully so that
the correct approach will be self evident based on the merits.


Raymond

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


Re: Use empty string for self

2006-03-01 Thread Douglas Alan
Roy Smith <[EMAIL PROTECTED]> writes:

> Terry Hancock <[EMAIL PROTECTED]> wrote:

>> However, there is a slightly less onerous method which
>> is perfectly legit in present Python -- just use "s"
>> for "self":

> This is being different for the sake of being different.  Everybody *knows* 
> what self means.  If you write your code with s instead of self, it just 
> makes it that much harder for other people to understand it.

I always use "s" rather than "self".  Are the Python police going to
come and arrest me?  Have I committed the terrible crime of being
unPythonic?  (Or should that be un_pythonic?)

I rarely find code that follows clear coding conventions to be hard to
understand, as long as the coding convention is reasonable and
consistent.

Something that I do find difficult to understand, as a contrasting
example, is C++ code that doesn't prefix instance variables with "_"
or "m_" (or what have you), or access them via "this".  Without such a
cue, I have a hard time figuring out where such variables are coming
from.

Regarding why I use "s" rather than "self", I don't do this to be
different; I do it because I find "self" to be large enough that it is
distracting.  It's also a word, which demands to be read.  (Cognitive
psychologists have shown that when words are displayed to you your
brain is compelled to read them, even if you don't want to.  I
experience this personally when I watch TV with my girlfriend who is
hearing impaired.  The captioning is very annoying to me, because
it's hard not to read them, even though I don't want to.  The same
thing is true of "self".)

With too many "self"s everywhere, my brain finds it harder to locate
the stuff I'm really interested in.  "s." is small enough that I can
ignore it, yet big enough to see when I need to know that information.
It's not a word, so my brain doesn't feel compelled to read it when I
don't want to, and it's shorter, so I can fit more useful code on a
line.  Breaking up some code onto multiple lines often makes it
significantly less readable.  (Just ask a typical mathematician, who
when shown notations that Computer Science people often use, laugh in
puzzlement at their verbosity.  Mathematicians probably could not do
what they do without having the more succinct notations that they
use.)

Don't take any of this to mean that succinctness is always better than
brevity.  It quite often is not.  Brevity is good for things that you
do over and over and over again.  Just ask Python -- it often knows
this.  It's why there are no "begin" and "end" statements in Python.
It's why semicolons aren't required to separate statements that are on
different lines.  That stuff is extra text that serves little purpose
other than to clutter up the typical case.

|>oug
-- 
http://mail.python.org/mailman/listinfo/python-list


Path completion in 'raw-input'?

2006-03-01 Thread Johannes Graumann
When interactively asking for a path on the cmdl, I'd like to go beyond just
'raw_input' and provide shell like path completion. My research has made me
believe that a combination of the cmd and glob modules is what I need, but
I find the doc HIGHLY unintuitive and wasn't able to come by any examples.
Does anybody have a code example for something like that lying around? 

There's also the rlcompleter module, but in the interest of better platform
agnosis I'd like to stick with cmd ...

Thanks for any hints,

Joh

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


Re: why? [win32com/WMI]

2006-03-01 Thread rtilley
Tim Golden wrote:
> [Sergey]
> 
> | import win32com.client
> | 
> | loc = win32com.client.Dispatch("WbemScripting.SWbemLocator")
> | svc = loc.ConnectServer("srv", "root/cimv2", "[EMAIL PROTECTED]", "**")
> | sys = svc.get("Win32_Process")
> | sys.create("notepad.exe")
> | 
> | =>
> | 
> | Traceback (most recent call last):
> | File "remote.py", line 6, in ?
> | sys.create("notepad.exe")
> | TypeError: 'int' object is not callable 
> 
> I could explain (it's to do with the way in which
> WMI method calls are set up) but I suggest you look at
> this module :
> 
> http://timgolden.me.uk/python/wmi.html
> 
> which makes WMI much easier to work with.

I second that! Tim's WMI module works really well. Of course, you can do 
it however you like, but you should at least check out his WMI work. We 
use it with first class windows services, etc w/o problem.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looking for help about python-sane

2006-03-01 Thread none
JW wrote:
> Every time, or just this run?
> 
every time
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing 'mangled' class attrbutes

2006-03-01 Thread Steve Juranich
Gerard Flanagan wrote:

> I tried that Steve but it didn't work, and i don't think I can do what
> I want in any case.  There is no method '__write' in the base class, it
> is only declared as an instance attribute in the constructor, like so:
> 
> def __init__(self, file, encoding="us-ascii"):
> ...
> self.__write = file.write
> ...
> 
> I tried putting  '__write = None' at the class level (in the base class
> XMLWriter) but then, although '_XMLWriter__write' appears in
> 'dir(HtmlWriter)', I get  'NoneType is not callable'.
> 
> I also tried 'def __write(self, text) : pass ' in the base class, but
> then the code runs but doesn't write the text I want -  and anyway, if
> I'm going to change the base class, then i may as well just add the
> 'write_raw' method to the base directly!
> 
> It's just some toy code at any rate, and I've learnt something new!
> Thanks for your reply.
> 
> Gerard
> 

Make sure you're calling the super's constructor before you try and access
the mangled member.  Then (I forgot this part), you can just call the
mangled member from `self'.  Example follows.


class A(object):
def __init__(self):
self.__foo = lambda x, y : x + y

class B(A):
def __init__(self, x, y):
# Make sure you're calling the super's constructor first.
super(B, self).__init__()
self.sum = self._A__foo(x, y)


>>> import foo
>>> b = foo.B(3, 4)
>>> b.sum
7
>>> 

-- 
Steve Juranich
Tucson, AZ
USA

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


Re: Searching for uniqness in a list of data

2006-03-01 Thread Paul McGuire
"rh0dium" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hi all,
>
> I am having a bit of difficulty in figuring out an efficient way to
> split up my data and identify the unique pieces of it.
>
> list=['1p2m_3.3-1.8v_sal_ms','1p2m_3.3-1.8_sal_log']
>
> Now I want to split each item up on the "_" and compare it with all
> others on the list, if there is a difference I want to create a list of
> the possible choices, and ask the user which choice of the list they
> want.


Check out difflib.

>>> data=['1p2m_3.3-1.8v_sal_ms','1p2m_3.3-1.8_sal_log']
>>> data[0].split("_")
['1p2m', '3.3-1.8v', 'sal', 'ms']
>>> data[1].split("_")
['1p2m', '3.3-1.8', 'sal', 'log']
>>> from difflib import SequenceMatcher
>>> s = SequenceMatcher(None, data[0].split("_"), data[1].split("_"))
>>> s.matching_blocks
[(0, 0, 1), (2, 2, 1), (4, 4, 0)]

I believe one interprets the tuples in matching_blocks as:
(seq1index,seq2index,numberOfMatchingItems)

In your case, the sequences have a matching element 0 and matching element
2, each of length 1.  I don't fully grok the meaning of the (4,4,0) tuple,
unless this is intended to show that both sequences have the same length.

Perhaps from here, you could locate the gaps in the
SequenceMatcher.matching_blocks property, and prompt for the user's choice.

-- Paul


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


asynchat network send problems

2006-03-01 Thread Andreas R.
Hello,
I'm using Python's asynchat module for network support in a Python-based 
game, and I run into two problems, both of which occur at random times.
Most of the time, the network sending and receiving is perfect, but 
about 1 out of 10 times, it fails with one of these errors:

-- Problem 1. When sending data, I sometimes the following exception:

Handler connected 127.0.0.1:1242 at 0x2977800> (socket.error:(9, 'Bad 
file descriptor') [C:\Python24\lib\asynchat.py|initiate_send|219] 
[C:\Python24\lib\asyncore.py|send|332] 
[C:\Python24\lib\socket.py|_dummy|144])

-- Problem 2. Receiving data on the client is not always the same size
as the data which is sent from the server.

Network server is found here
http://svn.gna.org/viewcvs/openrts/trunk/openrts/client/networkclient.py?rev=39&view=markup

Network client is found here:
http://svn.gna.org/viewcvs/openrts/trunk/openrts/server/clienthandler.py?rev=41&view=markup

This is the sequence for sending data:

1.  In clienthandler.py the method send_to_client() is called with 
whatever data should be sent to the client.

2. send_to_client() compresses the data, and passes it to the push() 
method of asynchat.

3. Client receives the data, and called found_terminator() in 
networkclient.py

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.

Complete source code is available at 
http://svn.gna.org/daily/openrts-snapshot.tar.gz


Thanks anyone for the help,

- Andreas R.
www.openrts.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use empty string for self

2006-03-01 Thread Duncan Booth
John Salerno wrote:

>> The two calls are equivalent.  
> 
> can you also say instance.mymethod(instance, 1, 2)  ?

Only if mymethod is defined to take all 4 arguments you just passed to it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Default Section Values in ConfigParser

2006-03-01 Thread Fuzzyman

mwt wrote:
> I want to set default values for a ConfigParser. So far, its job is
> very small, so there is only one section heading, ['Main']. Reading the
> docs, I see that in order to set default values in a ConfigParser, you
> initialize it with a dictionary or defaults. However, I'm not quite
> sure of the syntax to add the section headings in to the dictionary of
> defaults. For now, I'm doing it like this:
>
> default_values = {'username' : 'put username here',
> 'teamnumber': 'team number here',
> 'update_interval' : 'update interval'}
> self.INI = ConfigParser.ConfigParser(default_values)
> self.INI.add_section('Main')
>
> This works, but clearly won't last beyond the adding of a second
> section. What is the correct way to initialize it with a full
> dictionary of defaults, including section names?
>

An alternative approach is to use `ConfigObj
`_. It has two ways
of specifying default values.

The first way is to provide a configspec. This is a schema (that looks
very like a config file itself) that specifies the type (and paramater
bounds if you want) for each member. It can also include a default
value.

Simpler (although without the benefit of validation and type
conversion) is to use the ``merge`` method which is a recursive update.
(Although for config files that are a maximum of one section deep, the
dictionary method ``update`` will do the same job).

 default_values = {'username' : 'put username here',
 'teamnumber': 'team number here',
 'update_interval' : 'update interval'}
 user_values = ConfigObj(filename)
 cfg = ConfigObj(default_values)
 cfg.merge(user_values)

Note that for a config file with only a few values in it, ConfigObj
doesn't force you to use a section if it's not needed. To put your
default values into a 'Main' section you would actually do :

 default_values = { 'Main': {'username' : 'put username here',
 'teamnumber': 'team number here',
 'update_interval' : 'update interval'}
}
 #
 user_values = ConfigObj(filename)
 cfg = ConfigObj(default_values)
 cfg.merge(user_values)

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml


> Thanks.

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


ihooks and Python eggs

2006-03-01 Thread Christoph Zwerschke
Is it a known problem that ihooks is incompatible with Python eggs?

When I do the following:

import ihooks
ihooks.install(ihooks.ModuleImporter())

then I cannot import any Python egg afterwards.

Can there be anything done about this?

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


Re: Use empty string for self

2006-03-01 Thread John Salerno
Duncan Booth wrote:
> John Salerno wrote:
> 
>>> The two calls are equivalent.  
>> can you also say instance.mymethod(instance, 1, 2)  ?
> 
> Only if mymethod is defined to take all 4 arguments you just passed to it.

Got it. I understand how it works now.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: error: argument after ** must be a dictionary

2006-03-01 Thread abcd
Not sure if it matters, but this occurs when running a unittest.

The trace back is:
Traceback (most recent call last):
  File "C:\Python24\Lib\threading.py", line 442, in __bootstrap
self.run()
  File "C:\Python24\Lib\threading.py", line 422, in run
self.__target(*self.__args, **self.__kwargs)
TypeError: MyTestCase object argument after ** must be a dictionary

Unhandled exception in thread started by >

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


Suggestions for documentation generation?

2006-03-01 Thread kpd
Hello,

I have written a C++ library that I've then wrapped with Pyrex.
Any suggestions to the best-in-class tool to create documentation for
the libraries?

I would love to document things in one spot (could be the code) and
generate html and PDF from there.

Doxygen (www.doxygen.org) looks to be about the best so far. 

Thanks,

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


Re: Thread Question

2006-03-01 Thread Jarek Zgoda
Just napisał(a):

> I always felt that subclassing Thread is very unpythonic. It seems like 
> an unfortunate leftover Javaism (much of threading.py was inspired by 
> Java, but I don't need to tell you that). If I need some state, I create 
> my own class, with a reference to the Thread object if needed. Has-a vs. 
> is-a.

For me, it's not a "javaism", but "delphism" (since I know
Delphi/ObjectPascal much better than Java). In fact, in most OO
languages I know, threads are modeled as classes. Followning common
practice in this matter makes sense when you program in many languages -
your threads will be always classes with similar repertoire of methods
and attributes.

-- 
Jarek Zgoda
http://jpa.berlios.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: error: argument after ** must be a dictionary

2006-03-01 Thread abcd
i was missing "self" in my method signature!

doh!

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


Re: type = "instance" instead of "dict"

2006-03-01 Thread Terry Reedy

"Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Cruella DeVille wrote:
>
>> This is off topic, but if read the documentation is the answere to
>> everything why do we need news groups?
>
> Because "read the documentation" is NOT the answer to
> everything. However, it was the answer to your question.

Google can also answer some questions posted here in less time than it 
takes to post here.

>> I wouldn't ask here without trying to find the solution on my own
>> first.

Unfortunately, such enterprise is not universal.  More than once, someone 
has asked something like "Hey, Newbie here.  Are there any Python programs 
that can mung frobits?"  So I type "Python program mung frobits" into the 
Google bar of my browser and an answer pops up in a second.

tjr



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


Is it better to use class variables or pass parameters?

2006-03-01 Thread Derek Basch
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?

FlamewarNOW!

jk, I really do want other opinions.

Thanks,
Derek

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


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

2006-03-01 Thread Mc Osten
On 1 Mar 2006 11:32:02 -0800, 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?

I think there is no clear "general" answer. A criterion could be that
instance variables should be those who define the state of the object, that
define its "meaning".

About the others to me it's a matter of taste.

-- 
USB Priests for only 10$
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Path completion in 'raw-input'?

2006-03-01 Thread Mc Osten
On Wed, 01 Mar 2006 10:00:43 -0800, Johannes Graumann wrote:

> There's also the rlcompleter module, but in the interest of better platform
> agnosis I'd like to stick with cmd ...

I would have suggested readline..

This works on Windows:


This about readline on MacOS:


[ you don't need if you use Python 2.4 from undefined.org
 ]



-- 
USB Priests for only 10$
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cross compile generation of .pyc from .py files...

2006-03-01 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> ppc system.  The "...has bad magic..."  appears to indicate that

The format of .pyc files, which are generated for greater speed of repeat 
runs, is considered an internal implementation detail subject to change.
The exact details are generally specific to each x,y version.  (For 
instance, byte codes are occasionally added.)  So each version generally 
has a version-specific magic number and will only run .pyc files with the 
same magic number.  If you get 'bad magic' from the interpreter, then you 
have a mismatch.

If you are shipping .py files, there is no need to also ship .pyc files. 
Let them be generated as needed or run compileall at installation.

Terry Jan Reedy



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


newbie question

2006-03-01 Thread orangeDinosaur
Hi,

I'm brand new to using/playing with Python, and I have what is likely a
very simple question but can't seem to figure it out.

I wrote up a script in my preferred text editor.  It contains maybe ten
lines of code.  I want to be able to execute those code lines with a
single command either from the inline mode or from IDLE.  How do I do
this?  I saved the file (myscript.py) in a folder that I've specified
in my PYTHONPATH environment variable, and when I type

>>> import myscript

the script runs.  If, later during the same session, I type

>>> myscript

all I get for output is



Somwhere in the beginning tutorial there's this line:

"The script can be given a executable mode, or permission, using the
chmod command:

$ chmod +x myscript.py"

Which I took to mean that if I enter that I would be able to do what I
wanted.  But no, it just highlights 'myscript' in red and says it's a
syntax error.  

What am I missing?

thanks for your help!

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


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

2006-03-01 Thread dananrg
Thanks Gerhard and Magnus. Magnus, thanks for the references. I will
follow up on those.

I was messing around with the native ODBC module you mentioned (I am
using Python in a Win32 environment), e.g:

import dbi, odbc

...and it seems to meet my needs. 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. 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?

Incidentally, performance isn't an issue for this particular use case.

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


  1   2   >