SonomaSunshine Get's a Little Peppier

2007-04-30 Thread SamFeltus
http://samfeltus.com/as3/codetalking.html

SonomaSunshine - The Redneck Riviera's Best Python Powered Folk Art
Server

:)

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


Re: My python annoyances so far

2007-04-30 Thread Antoon Pardon
On 2007-04-27, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
> Antoon Pardon a écrit :
>> On 2007-04-27, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
>> 
>>>7stud a écrit :
>>>
[EMAIL PROTECTED] wrote:

>Annoyances:
>

Every language has annoyances.  Python is no exception.  
>>>
>>>Sure. But we may disagree on what are actually Python's annoyances !-)
>> 
>> 
>> That is probably why the subject says: "my annoyances"
>> 
> May I suggest that before finding something annyoing, one has to use it? 

Sure you may. But what do you mean by use? Are the first exetcices a
newbee tries out already using or do you think these don't count?

> When I first discovered Python - and before having any experience with 
> it - I thought that not having declarative static typing and access 
> restriction was kind of an annoyement. Real world experience made me 
> change my mind...

That people may (probably) change their mind later doesn't make it any
less annoying at the moment. The frustrations of the moment don't
disappear just because the more experienced knows these will fade in
the future.

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


Re: fastest way to find the intersection of n lists of sets

2007-04-30 Thread Raymond Hettinger
[Prateek]
> I have 3 variable length lists of sets. I need to find the common
> elements in each list (across sets) really really quickly.
. . .
> l1 = reduce(operator.add, list(x) for x in l1)
> l2 = reduce(operator.add, list(x) for x in l2)
> l3 = reduce(operator.add, list(x) for x in l3)
> s = frozenset(l1) & frozenset(l2) & frozenset(l3)

I would write it like this:

def multi_union(listofsets):
result = set()
for s in listofsets:
result |= s
return result

def multi_intersection(listofsets):
return reduce(set.intersection, sorted(listofsets, key=len))

s = multi_intersection(map(multi_union, [l1, l2, l3]))


> I'm assuming frozensets are (somehow) quicker than sets because
> they're immutable.

Frozensets share the same implementation code as regular sets.
They are not more efficient.


> Any code suggestions? Maybe using something in the new fancy-schmancy
> itertools module?

The sets.py module shows how to implement set operations using
itertools.
In general, real set objects should do as well or better than anything
you can cook-up using itertools.

Real set objects have the advantage of knowing the hash values of
their
elements.  Accordingly, binary set operations can run without any
calls to element.__hash__().


Raymond Hettinger

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


Re: fastest way to find the intersection of n lists of sets

2007-04-30 Thread Raymond Hettinger
[Prateek]
> The reason why I'm casting to a list first is because I found that
> creating a long list which I convert to a set in a single operation is
> faster (although probably less memory efficient - which I can deal
> with) than doing all the unions.

That would be a surprising result because set-to-set operations do
not have to recompute hash values.  Also, underneath-the-hood,
both approaches share the exact same implementation for inserting
new values one the hash value is known.

If you've seen an unfavorable speed comparison, then you most likely
had code that built new intermediate sets between step:

   common = s1 | s2 | s3 | s4 | s5 | s6 | s7 | s8 | s9

Instead, it is faster to build-up a single result set:

common = set()
for s in s1, s2, s3, s4, s5, s6, s7, s8, s9:
common |= s


Raymond Hettinger

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


I/O Operations .....

2007-04-30 Thread saif . shakeel
Hi,
 I am parsing an XML file and sending the output to two files.The
code asks the user to enter the input file,something like:

file_input = raw_input("Enter The ODX File Path:")
input_xml = open(file_input,'r')

  Now suppose the user enters the path as :
C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.odx.xml

 I have 2 output files to which i have to redirect the output.The
output file name should be same as input file in the same path ( the
extension has to change to a format "ini" which is basically text file
opened using notepad).Eg..
output files should be :
C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.ini,   and,
C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.xls

Can someone help me in this.
 cheers

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


Qustion about struct.unpack

2007-04-30 Thread OhKyu Yoon
Hi!
I have a really long binary file that I want to read.
The way I am doing it now is:

for i in xrange(N):  # N is about 10,000,000
time = struct.unpack('=', infile.read(8))
# do something
tdc = struct.unpack('=LiLiLiLi',self.lmf.read(32))
# do something

Each loop takes about 0.2 ms in my computer, which means the whole for loop 
takes 2000 seconds.
I would like it to run faster.
Do you have any suggestions?
Thank you very much.

OhKyu 

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


regexp match string with word1 and not word2

2007-04-30 Thread Flyzone
Hello,
i have again problem with regexp :-P
I need to match all lines that contain one word but not contain
another.
Like to do "grep one | grep -v two:"
The syntax of the string is:
(any printable char)two:(any printable char)one(any printable char)
Example:
Apr 30 00:00:09 v890neg0 two: [ID 702911 daemon.one] findings:
blablabla

I tried with:
.*[^t][^w][^o].*one.*
but is not working, the string is always match and in other tries
using "less logic" i get always some different match :-(

P.S: i can't have more re.search, so i just need ONE regexp

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


Re: Free Windows Vista Download

2007-04-30 Thread DCA
Spin Dryer wrote:
> On Sun, 29 Apr 2007 20:23:22 -0400, ["Alvin Bruney [MVP]"  without an email address>] said :-
>
>   
>> That's a misleading post, you should indicate that this is an evaluation 
>> copy.
>> 
>
>
> You did it again Sonny, making yourself look a total fool.
>
> Will you stop top posting replies to spam and _leaving the spamed site
> attached_.
>
>   
Fool - probably not
Oversight - probably yes
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fastest way to find the intersection of n lists of sets

2007-04-30 Thread Prateek
On Apr 30, 12:37 pm, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
> [Prateek]
>
> > The reason why I'm casting to a list first is because I found that
> > creating a long list which I convert to a set in a single operation is
> > faster (although probably less memory efficient - which I can deal
> > with) than doing all the unions.
>
> That would be a surprising result because set-to-set operations do
> not have to recompute hash values.  Also, underneath-the-hood,
> both approaches share the exact same implementation for inserting
> new values one the hash value is known.
>
> If you've seen an unfavorable speed comparison, then you most likely
> had code that built new intermediate sets between step:
>
>common = s1 | s2 | s3 | s4 | s5 | s6 | s7 | s8 | s9
>
> Instead, it is faster to build-up a single result set:
>
> common = set()
> for s in s1, s2, s3, s4, s5, s6, s7, s8, s9:
> common |= s
>
> Raymond Hettinger

Thanks Raymond,

This was my old code:
self.lv is a dictionary which retrieves data from the disk or cache
v_r = reduce(operator.or_, [self.lv[x.id] for x in v], set())

This code ran faster:
v_r = reduce(operator.add, [list(self.lv.get(x.id, [])) for x in v],
[])
v_r = set(v_r)

I was doing 3 of these and then intersecting them.

Now, I'm doing...
v_r = set()
_efs = frozenset()
for y in [self.lv.get(x.id, _efs) for x in v]:
v_r |= y

Since the number of sets is always 2 or 3, I just do the intersections
explicitly like so:
if len(list_of_unioned_sets) == 3:
result = list_of_unioned_sets[0]
result &= list_of_unioned_sets[1]
result &= list_of_unioned_sets[2]
elif len(list_of_unioned_sets) == 2:
result = list_of_unioned_sets[0]
result &= list_of_unioned_sets[1]
else:
   # Do something else...

Sorry for the relatively non-descript variable names.
Prateek

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


Dict Copy & Compare

2007-04-30 Thread Robert Rawlins - Think Blue
Hello Guys,

 

I'm looking for a little advice on dicts, firstly I need to learn how to
copy a dict, I suppose I could just something like.

 

Self.newdict = self.olddict

 

But I fear that this only creates a reference rather than an actual copy,
this means that as soon as I clear out the old one, the new one will
effectively be empty. What's the best way to ACTUALY copy a dict into a new
variable?

 

Next up I'm looking to compare two different dictionaries, then loop through
the unique results that are in each and print them out. Is there a more
efficient way of doing this other than a loop with an if/else statement?

 

For a in self.dict1:

If a not in self.dict2:

Print 'Found %s' % (a)

 

For b in self.dict2:

If b not in self.dict1:

Print 'Found %s'  % (b)

 

That would firstly loop through the first dict and output any of its unique
values, it then loops through the second dict and output any of its unique
values, is this the best way of doing this? Or is there something more
efficient?

 

Thanks,

 

Rob Rawlins

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

Reading From an Excel Sheet

2007-04-30 Thread sagar
Hi all,
  I want to write a python script which reads in data from the
excel sheet .Can any one help out in this ...any help will be
appreciated.

Thanks in Advance
Sagar Meesala

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


Reading Data From an Excel Sheet

2007-04-30 Thread sagar
Hi all,
   I want a python script which takes in input an EXCEL sheet
and then reads the data in it.
Any code snippets will be fine and this i want this in windows
XP .

   Thanks in Advance
  Sagar Meesala

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


Re: Dict Copy & Compare

2007-04-30 Thread Tim Golden
Robert Rawlins - Think Blue wrote:
> I'm looking for a little advice on dicts, firstly I need to learn how to
> copy a dict, I suppose I could just something like.

> Self.newdict = self.olddict

> But I fear that this only creates a reference rather than an actual copy,
> this means that as soon as I clear out the old one, the new one will
> effectively be empty. What's the best way to ACTUALY copy a dict into a new
> variable?

Unless you have specialised needs, you can just say:

d2 = dict (d1)

which will initialise d2 from d1's key/value pairs:


d1 = dict (a=1, b=2)
d2 = dict (d1)
d2['a'] = 5
print d1
print d2




> Next up I'm looking to compare two different dictionaries, then loop through
> the unique results that are in each and print them out. Is there a more
> efficient way of doing this other than a loop with an if/else statement?

This comes up not infrequently on the list. I think there's
even a few recipes in the cookbook. One (fairly recent)
technique is to use set versions of your dictionary keys,
but it depends on what you want to do next. From my example
above:


# relies on the fact that dictionary iterators
# iterate over the keys of the dict.

s1 = set (d1)
s2 = set (d2)

# do whatever set-ops you want, eg

s3 = s1 | s2

for key in s3:
   print "Key:", key
   print "d1 =>", d1[key]
   print "d2 =>", d2[key]



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


Re: Qustion about struct.unpack

2007-04-30 Thread Steven D'Aprano
On Mon, 30 Apr 2007 00:45:22 -0700, OhKyu Yoon wrote:

> Hi!
> I have a really long binary file that I want to read.
> The way I am doing it now is:
> 
> for i in xrange(N):  # N is about 10,000,000
> time = struct.unpack('=', infile.read(8))
> # do something
> tdc = struct.unpack('=LiLiLiLi',self.lmf.read(32))

I assume that is supposed to be infile.read()


> # do something
> 
> Each loop takes about 0.2 ms in my computer, which means the whole for loop 
> takes 2000 seconds.

You're reading 400 million bytes, or 400MB, in about half an hour. Whether
that's fast or slow depends on what the "do something" lines are doing.


> I would like it to run faster.
> Do you have any suggestions?

Disk I/O is slow, so don't read from files in tiny little chunks. Read a
bunch of records into memory, then process them.

# UNTESTED!
rsize = 8 + 32  # record size
for i in xrange(N//1000):
buffer = infile.read(rsize*1000) # read 1000 records at once
for j in xrange(1000): # process each record
offset = j*rsize
time = struct.unpack('=', buffer[offset:offset+8])
# do something
tdc = struct.unpack('=LiLiLiLi', buffer[offset+8:offset+rsize])
# do something


(Now I'm just waiting for somebody to tell me that file.read() already
buffers reads...)


-- 
Steven D'Aprano 

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


Re: Reading Data From an Excel Sheet

2007-04-30 Thread Tim Golden
sagar wrote:
> Hi all,
>I want a python script which takes in input an EXCEL sheet
> and then reads the data in it.
> Any code snippets will be fine and this i want this in windows
> XP .

Might I humbly suggest that, instead of posting several
somewhat demanding requests for help with no evidence of
any effort on your part, that you put your subject line
into Google (or your search engine of choice), add the
word Python and then look at the results?

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


Importing a csv file

2007-04-30 Thread sagar
Hi all ,
   I want to read data in a csv file using the python scripts.
when i gave the following code :
 import csv
reader = csv.reader(open("some.csv", "rb"))
for row in reader:
print row

it is showing :

Traceback (most recent call last):
  File "csv.py", line 1, in 
import csv
  File "C:\Documents and Settings\meesa02\csv.py", line 2, in 
reader = csv.reader(open("some.csv", "rb"))
AttributeError: 'module' object has no attribute 'reader'

im a total fresher to this python...SO can any one help me out in
this...

Thanks in advance
   Sagar Meesala

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


RE: Dict Copy & Compare

2007-04-30 Thread Robert Rawlins - Think Blue
Thanks for that Tim,

The first part for copying the dict seems to work nicely but I'm struggling
to get the second part working properly. Let me explain a little more
specifically what I'm trying to do.

I have two dicts, one named 'this' and the other named 'that'.

I want to get all the unique keys from 'this' and log them into a file, I
then want to take all the unique values from 'that' and log them into a
separate file.

I have functions set up for the logging, so I can call it like
logThis(uniquekey) and logThat(uniquekey).

So it's just a case of firstly returning a list of all keys that are in
'this' but NOT in 'that' and then visa versa, then loop over them performing
the function.

Rob

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED]
On Behalf Of Tim Golden
Sent: 30 April 2007 09:41
Cc: python-list@python.org
Subject: Re: Dict Copy & Compare

Robert Rawlins - Think Blue wrote:
> I'm looking for a little advice on dicts, firstly I need to learn how to
> copy a dict, I suppose I could just something like.

> Self.newdict = self.olddict

> But I fear that this only creates a reference rather than an actual copy,
> this means that as soon as I clear out the old one, the new one will
> effectively be empty. What's the best way to ACTUALY copy a dict into a
new
> variable?

Unless you have specialised needs, you can just say:

d2 = dict (d1)

which will initialise d2 from d1's key/value pairs:


d1 = dict (a=1, b=2)
d2 = dict (d1)
d2['a'] = 5
print d1
print d2




> Next up I'm looking to compare two different dictionaries, then loop
through
> the unique results that are in each and print them out. Is there a more
> efficient way of doing this other than a loop with an if/else statement?

This comes up not infrequently on the list. I think there's
even a few recipes in the cookbook. One (fairly recent)
technique is to use set versions of your dictionary keys,
but it depends on what you want to do next. From my example
above:


# relies on the fact that dictionary iterators
# iterate over the keys of the dict.

s1 = set (d1)
s2 = set (d2)

# do whatever set-ops you want, eg

s3 = s1 | s2

for key in s3:
   print "Key:", key
   print "d1 =>", d1[key]
   print "d2 =>", d2[key]



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

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


What's the life time of the variable defined in a class function?

2007-04-30 Thread 人言落日是天涯,望极天涯不见家
Please see the followed example:
class A:
def __init__(self):
pass

class X:
def __init__(self):
n = 200
if True:
j = 200
m = j
k = A()
print m, j

a = X()
# ?? what about the m, n and j? is it still alive?
del a

--
In C/C++, the life time of m,n and j was the nearest block.  but
obviously, python doen't have this syntax, but I would like to know
that whether the life time of  m, n, j  is base on function range or
the object range.

We can not access the m, n, and j from the outside of class X. Now I'm
writing a program base on the wxpython. In the __init__ function of
wx.Panel, I use normal varable(just like the m,n and j) created some
widgets. It could be show in the window.  Does it indicated the life
time of varable m,n,j is base on the object range?

Sorry for my poor english!
It seems

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


Re: I/O Operations .....

2007-04-30 Thread Daniel Nogradi
> I am parsing an XML file and sending the output to two files.The
> code asks the user to enter the input file,something like:
>
> file_input = raw_input("Enter The ODX File Path:")
> input_xml = open(file_input,'r')
>
>   Now suppose the user enters the path as :
> C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.odx.xml
>
>  I have 2 output files to which i have to redirect the output.The
> output file name should be same as input file in the same path ( the
> extension has to change to a format "ini" which is basically text file
> opened using notepad).Eg..
> output files should be :
> C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.ini,   and,
> C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.xls

If you only would like to know how to write files, this might help:

content1 = ..
content2 = ...

f = open( 'file1', 'w' )
f.write( content1 )
f.close( )

f = open( 'file2', 'w' )
f.write( content2 )
f.close( )


HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dict Copy & Compare

2007-04-30 Thread Tim Golden
Robert Rawlins - Think Blue wrote:
> I have two dicts, one named 'this' and the other named 'that'.
> 
> I want to get all the unique keys from 'this' and log them into a file, I
> then want to take all the unique values from 'that' and log them into a
> separate file.

Couple of points which are confusing me:

1) Any dict can *only* have unique keys, ie you can't have
a key appearing more than once in a dictionary by
definition.

2) You speak of unique keys in "this" but unique values
in "that". Is that deliberate on your part? Might be, but
I'm not quite clear.

> I have functions set up for the logging, so I can call it like
> logThis(uniquekey) and logThat(uniquekey).

Here you refer to "uniquekey" in both cases, so maybe a
mistake above?

> So it's just a case of firstly returning a list of all keys that are in
> 'this' but NOT in 'that' and then visa versa, then loop over them performing
> the function.

OK, well following by example earlier:


d1 = dict (a=1, b=2, c=3)
d2 = dict (b=4, c=5, d=6)

s1 = set (d1) # => set of 'a', 'b', 'c'
s2 = set (d2) # => set of 'b', 'c', 'd'

s1_not_in_s2 = s1 - s2 # => set of 'a'
s2_not_in_s1 = s2 - s1 # => set of 'd'

for key in s1_not_in_s2:
   print key, "=>", d1[key]

for key in s2_not_in_s1:
   print key, "=>", d2[key]



Obviously there are more concise ways of representing
this; I'm just spelling the whole thing out to make it
clearer (I hope). If this approach seems fruitful, have
a look at the set typeit's a recentish addition to
Python but very useful for this kind of thing:

   http://docs.python.org/lib/types-set.html

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


Re: I/O Operations .....

2007-04-30 Thread saif . shakeel
On Apr 30, 2:13 pm, "Daniel Nogradi" <[EMAIL PROTECTED]> wrote:
> > I am parsing an XML file and sending the output to two files.The
> > code asks the user to enter the input file,something like:
>
> > file_input = raw_input("Enter The ODX File Path:")
> > input_xml = open(file_input,'r')
>
> >   Now suppose the user enters the path as :
> > C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.odx.xml
>
> >  I have 2 output files to which i have to redirect the output.The
> > output file name should be same as input file in the same path ( the
> > extension has to change to a format "ini" which is basically text file
> > opened using notepad).Eg..
> > output files should be :
> > C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.ini,   and,
> > C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.xls
>
> If you only would like to know how to write files, this might help:
>
> content1 = ..
> content2 = ...
>
> f = open( 'file1', 'w' )
> f.write( content1 )
> f.close( )
>
> f = open( 'file2', 'w' )
> f.write( content2 )
> f.close( )
>
> HTH,
> Daniel- Hide quoted text -
>
> - Show quoted text -

 Hi,
File writing can be done in that way,but my query is
something different.I have to rename the output file by default with
input file name(only changing the extension.
  Thanks

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


Re: Importing a csv file

2007-04-30 Thread Tim Golden
sagar wrote:
> Hi all ,
>I want to read data in a csv file using the python scripts.
> when i gave the following code :
>  import csv
> reader = csv.reader(open("some.csv", "rb"))
> for row in reader:
> print row
> 
> it is showing :
> 
> Traceback (most recent call last):
>   File "csv.py", line 1, in 
> import csv
>   File "C:\Documents and Settings\meesa02\csv.py", line 2, in 
> reader = csv.reader(open("some.csv", "rb"))
> AttributeError: 'module' object has no attribute 'reader'

You almost certainly have a file called "csv.py" in
the current directory. (Maybe even the one that's
running this script?). Rename it to "mycsv.py" or
whatever and try again.

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


Re: What's the life time of the variable defined in a class function?

2007-04-30 Thread Diez B. Roggisch
人言落日是天涯,望极天涯不见家 wrote:

> Please see the followed example:
> class A:
> def __init__(self):
> pass
> 
> class X:
> def __init__(self):
> n = 200
> if True:
> j = 200
> m = j
> k = A()
> print m, j
> 
> a = X()
> # ?? what about the m, n and j? is it still alive?
> del a
> 
> --
> In C/C++, the life time of m,n and j was the nearest block.  but
> obviously, python doen't have this syntax, but I would like to know
> that whether the life time of  m, n, j  is base on function range or
> the object range.
> 
> We can not access the m, n, and j from the outside of class X. Now I'm
> writing a program base on the wxpython. In the __init__ function of
> wx.Panel, I use normal varable(just like the m,n and j) created some
> widgets. It could be show in the window.  Does it indicated the life
> time of varable m,n,j is base on the object range?

Python has no variables. It has objects, which can be bound to names. Each
binding to a name will increase a reference counter. Each unbinding will
decrease it. so

a = SomeObject()
b = a
del a

will result in the SomeObject-instance still be alive. But when you add

del b

it will be garbage collected.

Now in your example A() bound to k will not survive the exit of the method,
as that means that k goes out of scope, and the object is bound to - the
A-instance - gets its reference-counter decreased, resulting in it being
freed.

The wxwidgets example though is a different thing. If the panel stores a
reference to the object, e.g. via a list (being part of a list or dict also
increases the reference count), it will be kept around.

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

anyone has experience on cross-compile python 2.5.1?

2007-04-30 Thread Leo Jay
i have a development board based on s3c2410 arm cpu. and i want to
port python on it.
after googling some threads, i successfully cross compiled python.
but i still encountered a weird issue that when i ran
/lib/python2.5/test/testall.py,
the process stuck at test_asynchat.py, i located the stuck point here:

   def test_numeric_terminator(self):
   # Try reading a fixed number of bytes
   s = echo_server()
   s.start() # <- stuck here  !!!
   time.sleep(1) # Give server time to initialize
   c = echo_client(6L)
   c.push("hello ")
   c.push("world\n")
   asyncore.loop()
   s.join()


but the weirdest thing is, if i run python test_asynchat.py directly,
everything is ok.
anybody could help me?

thanks in advance.

ps, my linux box is an ubuntu 6.10.

-- 
Best Regards,
Leo Jay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: While we're talking about annoyances

2007-04-30 Thread Arnaud Delobelle
On Apr 30, 2:50 am, [EMAIL PROTECTED] (Alex Martelli) wrote:
> Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
>
>...
>
> > > >> decorated.sort()
>...
> > > def index(sequence):
> > >  return sorted(range(len(sequence)), key=sequence.__getitem__)
>...
> > But really these two versions of rank are slower than the original one
> > (as sorting a list is O(nlogn) whereas filling a table with
> > precomputed values is O(n) ).
>
> Wrong, because the original one also had a sort step, of course, so it
> was also, inevitably, O(N log N) -- I've quoted the .sort step above.

I am fully aware of the meaning of O(...).  Nevertheless (speed !=
asymptotic speed) and one sort is still better than two sorts IMHO.
Moreover the second sort is redundant and less clear than a simple
loop.

> > Anyway I would like to contribute my own index function:
>
> > def index(seq):
> >  return sum(sorted(map(list,enumerate(seq)), key=list.pop), [])
>
> > It's short and has the advantage of being self-documenting, which will
> > save Steven a lot of annoying typing I hope ;)  Who said Python
> > couldn't rival with perl?
>
> sum is for summing NUMBERS -- using it on lists is O(N squared).
>
> So, this solution is asymptotically VERY slow, as well as obfuscated.

And it was also a JOKE.  There were some clues:
   * I claimed that the function was self-documenting, even though it
was obviously obfuscated (as you rightly pointed out).
   * It relies on a side effect of the 'key' function list.pop, which
is very bad form.
   * It is indeed very slow (yes, sum() is not the best for lists)
   * I mentioned that Python could rival perl.

I was meant to be a clumsy but 'concise' amalgam that would perform
the task (although not efficiently) while being difficult to make
sense of.

--
Arnaud

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


Re: What's the life time of the variable defined in a class function?

2007-04-30 Thread 人言落日是天涯,望极天涯不见家
On Apr 30, 5:20 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> 人言落日是天涯,望极天涯不见家 wrote:
> > Please see the followed example:
> > class A:
> >     def __init__(self):
> >         pass
>
> > class X:
> >     def __init__(self):
> >         n = 200
> >         if True:
> >             j = 200
> >         m = j
> >         k = A()
> >         print m, j
>
> > a = X()
> > # ?? what about the m, n and j? is it still alive?
> > del a
>
> > --
> > In C/C++, the life time of m,n and j was the nearest block.  but
> > obviously, python doen't have this syntax, but I would like to know
> > that whether the life time of  m, n, j  is base on function range or
> > the object range.
>
> > We can not access the m, n, and j from the outside of class X. Now I'm
> > writing a program base on the wxpython. In the __init__ function of
> > wx.Panel, I use normal varable(just like the m,n and j) created some
> > widgets. It could be show in the window.  Does it indicated the life
> > time of varable m,n,j is base on the object range?
>
> Python has no variables. It has objects, which can be bound to names. Each
> binding to a name will increase a reference counter. Each unbinding will
> decrease it. so
>
> a = SomeObject()
> b = a
> del a
>
> will result in the SomeObject-instance still be alive. But when you add
>
> del b
>
> it will be garbage collected.
>
> Now in your example A() bound to k will not survive the exit of the method,
> as that means that k goes out of scope, and the object is bound to - the
> A-instance - gets its reference-counter decreased, resulting in it being
> freed.
>
> The wxwidgets example though is a different thing. If the panel stores a
> reference to the object, e.g. via a list (being part of a list or dict also
> increases the reference count), it will be kept around.
>
> Diez- Hide quoted text -
>
> - Show quoted text -
Yes, I see.  Many thanks for you !

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

Re: I/O Operations .....

2007-04-30 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, saif.shakeel
wrote:

> File writing can be done in that way,but my query is
> something different.I have to rename the output file by default with
> input file name(only changing the extension.

Take a look at the functions in `os.path`.

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


How do I parse a string to a tuple??

2007-04-30 Thread Soren
Hi!

I have a string that contains some text and newline characters. I want
to parse the string so that the string just before a newline character
goes in as an element in the tuple.

ex:

"text1 \n text2 \n text3 \n text4"   --> (text1, text2, text3, text4)

Is there an easy way to do this?

Thanks!,
Soren

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


Re: While we're talking about annoyances

2007-04-30 Thread Michael Hoffman
Alex Martelli wrote:
> Michael Hoffman <[EMAIL PROTECTED]> wrote:
> 
>> Alex Martelli wrote:
>>> Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
>>>...
>>> decorated.sort()
>>>...
> def index(sequence):
>  return sorted(range(len(sequence)), key=sequence.__getitem__)
>>>...
 But really these two versions of rank are slower than the original one
 (as sorting a list is O(nlogn) whereas filling a table with
 precomputed values is O(n) ).
>>> Wrong, because the original one also had a sort step, of course, so it
>>> was also, inevitably, O(N log N) -- I've quoted the .sort step above.
>> Well, counting the index() function that is called in both cases, the
>> original rank() had one sort, but my version has two sorts.
> 
> That doesn't affet the big-O behavior -- O(N log N) holds whether you
> have one sort, or three, or twentyseven.

I've taught programming classes before, and I would have had to fail 
anybody who misunderstood speed badly enough to claim that something 
repeating an O(N log N) algorithm 27 times was no faster than doing it 
once. ;-)

As Arnaud points out, asymptotic behavior is not the same as speed. His 
original statement that the more recently proposed definitions of rank() 
are slower than the OP's may be correct. And if it's not, it's not 
because they're all O(N log N).
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I parse a string to a tuple??

2007-04-30 Thread Steven D'Aprano
On Mon, 30 Apr 2007 02:47:32 -0700, Soren wrote:

> Hi!
> 
> I have a string that contains some text and newline characters. I want
> to parse the string so that the string just before a newline character
> goes in as an element in the tuple.
> 
> ex:
> 
> "text1 \n text2 \n text3 \n text4"   --> (text1, text2, text3, text4)
> 
> Is there an easy way to do this?

the_string = "text1 \n text2 \n text3 \n text4"
tuple(the_string.split('\n'))

If you don't need a tuple, and a list will do:

the_string.split('\n')

If you want to get rid of the white space after each chunk of text:

[s.strip() for s in the_string.split('\n')]




-- 
Steven D'Aprano 

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


Re: How do I parse a string to a tuple??

2007-04-30 Thread James Stroud
Soren wrote:
> Hi!
> 
> I have a string that contains some text and newline characters. I want
> to parse the string so that the string just before a newline character
> goes in as an element in the tuple.
> 
> ex:
> 
>--> (text1, text2, text3, text4)
> 
> Is there an easy way to do this?
> 
> Thanks!,
> Soren
> 

For this particular, very narrow, example, following the example as 
closely as I possibly can:

import re

atext = "text1 \n text2 \n text3 \n text4"
atup = tuple(re.split(r'\s*\n', atext))

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


Re: Dict Copy & Compare

2007-04-30 Thread Steven D'Aprano
On Mon, 30 Apr 2007 09:40:53 +0100, Tim Golden wrote:

> Robert Rawlins - Think Blue wrote:
>> I'm looking for a little advice on dicts, firstly I need to learn how to
>> copy a dict, I suppose I could just something like.
> 
>> Self.newdict = self.olddict
> 
>> But I fear that this only creates a reference rather than an actual copy,
>> this means that as soon as I clear out the old one, the new one will
>> effectively be empty. What's the best way to ACTUALY copy a dict into a new
>> variable?
> 
> Unless you have specialised needs, you can just say:
> 
> d2 = dict (d1)



Or you can say 

d2 = d1.copy()



-- 
Steven D'Aprano 

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


RE: Dict Copy & Compare

2007-04-30 Thread Robert Rawlins - Think Blue
Hello Tim,

Sorry, that 'value' was a slip up on my part, we're just dealing with keys
here.

I get that a dict stores unique keys only but we're comparing the two dicts,
so when I say 'unique keys in dict 1' I basically mean all those keys that
are in dict one but not in dict 2. So imagine my 2 dicts with the following
keys.

Dict 1  Dict 2
--  ---
00:00:00:00 00:00:00:00
11:11:11:11 11:11:11:11
22:22:22:22 33:33:33:33
44:44:44:44 44:44:44:44
55:55:55:55

Now, 22:22:22:22 and 55:55:55:55 is unique to dict one, and 33:33:33:33 is
unique to dict 2, does that make sense? Sorry for not explaining this stuff
very well, being so new to dicts its easy to get confused with my terms.

I then want to pass those keys as a string value into my function as an
argument, like.

thisFunction('22:22:22:22')
thisFunction('55:55:55:55')

thatFunction('33:33:33:33')

I'm hoping that your method will work for me, I've just got to spend my time
understanding what each step of it does.

Thanks again for all your help Tim,

Rob

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED]
On Behalf Of Tim Golden
Sent: 30 April 2007 10:15
Cc: python-list@python.org
Subject: Re: Dict Copy & Compare

Robert Rawlins - Think Blue wrote:
> I have two dicts, one named 'this' and the other named 'that'.
> 
> I want to get all the unique keys from 'this' and log them into a file, I
> then want to take all the unique values from 'that' and log them into a
> separate file.

Couple of points which are confusing me:

1) Any dict can *only* have unique keys, ie you can't have
a key appearing more than once in a dictionary by
definition.

2) You speak of unique keys in "this" but unique values
in "that". Is that deliberate on your part? Might be, but
I'm not quite clear.

> I have functions set up for the logging, so I can call it like
> logThis(uniquekey) and logThat(uniquekey).

Here you refer to "uniquekey" in both cases, so maybe a
mistake above?

> So it's just a case of firstly returning a list of all keys that are in
> 'this' but NOT in 'that' and then visa versa, then loop over them
performing
> the function.

OK, well following by example earlier:


d1 = dict (a=1, b=2, c=3)
d2 = dict (b=4, c=5, d=6)

s1 = set (d1) # => set of 'a', 'b', 'c'
s2 = set (d2) # => set of 'b', 'c', 'd'

s1_not_in_s2 = s1 - s2 # => set of 'a'
s2_not_in_s1 = s2 - s1 # => set of 'd'

for key in s1_not_in_s2:
   print key, "=>", d1[key]

for key in s2_not_in_s1:
   print key, "=>", d2[key]



Obviously there are more concise ways of representing
this; I'm just spelling the whole thing out to make it
clearer (I hope). If this approach seems fruitful, have
a look at the set typeit's a recentish addition to
Python but very useful for this kind of thing:

   http://docs.python.org/lib/types-set.html

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

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


Re: How do I parse a string to a tuple??

2007-04-30 Thread 人言落日是天涯,望极天涯不见家
On Apr 30, 5:47 pm, Soren <[EMAIL PROTECTED]> wrote:
> Hi!
>
> I have a string that contains some text and newline characters. I want
> to parse the string so that the string just before a newline character
> goes in as an element in the tuple.
>
> ex:
>
> "text1 \n text2 \n text3 \n text4"   --> (text1, text2, text3, text4)
>
> Is there an easy way to do this?
>
> Thanks!,
> Soren

tuple("text1 \n text2 \n text3 \n text4".split('\n'))

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

RE: Dict Copy & Compare

2007-04-30 Thread Steven D'Aprano
On Mon, 30 Apr 2007 10:05:40 +0100, Robert Rawlins - Think Blue wrote:

> I have two dicts, one named 'this' and the other named 'that'.
> 
> I want to get all the unique keys from 'this' and log them into a file, I
> then want to take all the unique values from 'that' and log them into a
> separate file.


The most straight-forward way is doing a simple pair of loops:

for key in this:
if key not in that:
logThis(key)
for key in that:
if key not in this:
logThat(key)



> So it's just a case of firstly returning a list of all keys that are in
> 'this' but NOT in 'that' and then visa versa, then loop over them performing
> the function.

Well, if you really do need to collect the list up front (why???) you can
do this:

uniqueFromThis = [key for key in this if key not in that]
uniqueFromThat = [key for key in that if key not in this]


Membership testing in dicts is efficient, so that should run quite fast
unless you have millions of keys common to both dictionaries.



-- 
Steven D'Aprano 

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


Re: How do I parse a string to a tuple??

2007-04-30 Thread Soren

Thanks alot everyone!

Soren

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


Re: regexp match string with word1 and not word2

2007-04-30 Thread James Stroud
Flyzone wrote:
> Hello,
> i have again problem with regexp :-P
> I need to match all lines that contain one word but not contain
> another.
> Like to do "grep one | grep -v two:"
> The syntax of the string is:
> (any printable char)two:(any printable char)one(any printable char)
> Example:
> Apr 30 00:00:09 v890neg0 two: [ID 702911 daemon.one] findings:
> blablabla
> 
> I tried with:
> .*[^t][^w][^o].*one.*
> but is not working, the string is always match and in other tries
> using "less logic" i get always some different match :-(
> 
> P.S: i can't have more re.search, so i just need ONE regexp
> 

The P.S: suggests homework, but this can't be homework because python 
regex won't do this, so your teacher gets an F if its homework. You 
require a negative look-behind assertion of variable length--not 
possible in python regex. You will have to use something else--or maybe 
you don't understand the homework problem.

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


Re: How do I parse a string to a tuple??

2007-04-30 Thread Michael Hoffman
Steven D'Aprano wrote:
> On Mon, 30 Apr 2007 02:47:32 -0700, Soren wrote:
>> "text1 \n text2 \n text3 \n text4"   --> (text1, text2, text3, text4)
> 
> the_string = "text1 \n text2 \n text3 \n text4"
> tuple(the_string.split('\n'))
> 
> If you don't need a tuple, and a list will do:
> 
> the_string.split('\n')

or the_string.splitlines()

> If you want to get rid of the white space after each chunk of text:
> 
> [s.strip() for s in the_string.split('\n')]
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dict Copy & Compare

2007-04-30 Thread Tim Golden
Robert Rawlins - Think Blue wrote:
> Hello Tim,
> 
> Sorry, that 'value' was a slip up on my part, we're just dealing with keys
> here.
> 
> I get that a dict stores unique keys only but we're comparing the two dicts,
> so when I say 'unique keys in dict 1' I basically mean all those keys that
> are in dict one but not in dict 2. So imagine my 2 dicts with the following
> keys.
> 
> Dict 1Dict 2
> -----
> 00:00:00:00   00:00:00:00
> 11:11:11:11   11:11:11:11
> 22:22:22:22   33:33:33:33
> 44:44:44:44   44:44:44:44
> 55:55:55:55
> 
> Now, 22:22:22:22 and 55:55:55:55 is unique to dict one, and 33:33:33:33 is
> unique to dict 2, does that make sense? Sorry for not explaining this stuff
> very well, being so new to dicts its easy to get confused with my terms.
> 
> I then want to pass those keys as a string value into my function as an
> argument, like.
> 
> thisFunction('22:22:22:22')
> thisFunction('55:55:55:55')
> 
> thatFunction('33:33:33:33')
> 
> I'm hoping that your method will work for me, I've just got to spend my time
> understanding what each step of it does.

Well I feel a bit guilty now I look back at your
original post, because I've probably given
you a more complex solution than you really need. Your
initial approach is probably quite adequate. Python
dicts are highly tuned beasts so unless you're doing
something really big or bizarre, you can sensibly do:


d1 = {
   "00:00:00:00" : None,
   "11:11:11:11" : None,
   "22:22:22:22" : None,
   "44:44:44:44" : None,
   "55:55:55:55" : None
}

d2 = {
   "00:00:00:00" : None,
   "11:11:11:11" : None,
   "33:33:33:33" : None,
   "44:44:44:44" : None
}

for k in d1:
   if d1 not in d2:
 thisFunction (d1)

for k in d2
   if d2 not in d1:
thatFunction (k)



But even if this is adequate for your purposes,
it's always good to be aware of what's in your
programming toolbox and there's always the danger
you'll end up implementing sets in dicts (which
is what everyone did before Python 2.3).

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


Re: My Python annoyances

2007-04-30 Thread Isaac Rodriguez
> Hmm, on my PyCon mug there are words "Python: so easy...even your BOSS
> can use it!"

Oh man! I would've killed for a mug like that a year ago. I was
working for this guy, who had the entire build process automated
in .BAT scripts. We spent more time fixing the build process than
devoloping our product.

Anyway, I started to move the entire thing to Python. Using a real
programming language, allows creating a more robust process. It also
allows separating data and code, which comes very handy when the data
changes to not have to touch the code.

So a year ago, I moved to another department. I would not get into the
details of why, but I am just going to say that I'm much happier now.
One day, I walking down the hall, and I see a book in my old boss'
desk: "Learning Perl." I thought to my self, "You gotta be kiddin". So
I saw him in the coffee area, and I asked him about it. His answer
was, "Yeah, I'm re-writing the build scripts in Perl because you are
the only one that knew Python, and we need to maintain them."

Well, there is no-one in that team that knows Perl either, and if they
haven't been able to learn Python in the couple of years I tried to
push it, I really doubt they are going to learn Perl. Or maybe, the
problem was that I was trying to push Python, so they are doing this
just to prove me wrong.

Like I said, I'm much happier now, and so much glad to be out of that
team.

Thanks,

- Isaac.

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


Re: How do I parse a string to a tuple??

2007-04-30 Thread shakil ahmad


just do like this:




a="text1 \n text2 \n text3 \n text4"
g=a.split('\n')
g

['text1 ', ' text2 ', ' text3 ', ' text4']

d=tuple(g)
d

('text1 ', ' text2 ', ' text3 ', ' text4')


by

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

Re: I/O Operations .....

2007-04-30 Thread Daniel Nogradi
> > > I am parsing an XML file and sending the output to two files.The
> > > code asks the user to enter the input file,something like:
> >
> > > file_input = raw_input("Enter The ODX File Path:")
> > > input_xml = open(file_input,'r')
> >
> > >   Now suppose the user enters the path as :
> > > C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.odx.xml
> >
> > >  I have 2 output files to which i have to redirect the output.The
> > > output file name should be same as input file in the same path ( the
> > > extension has to change to a format "ini" which is basically text file
> > > opened using notepad).Eg..
> > > output files should be :
> > > C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.ini,   and,
> > > C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.xls
> >
> > If you only would like to know how to write files, this might help:
> >
> > content1 = ..
> > content2 = ...
> >
> > f = open( 'file1', 'w' )
> > f.write( content1 )
> > f.close( )
> >
> > f = open( 'file2', 'w' )
> > f.write( content2 )
> > f.close( )
> >
> > HTH,
> > Daniel- Hide quoted text -
> >
> > - Show quoted text -
>
>  Hi,
> File writing can be done in that way,but my query is
> something different.I have to rename the output file by default with
> input file name(only changing the extension.


Maybe something like this will help (on Linux, Windows is similar):

>>> from os import path
>>> f = '/tmp/hello.xls'
>>> path.splitext( f )
('/tmp/hello', '.xls')
>>> path.dirname( f )
'/tmp'
>>> path.basename( f )
'hello.xls'


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


RE: Dict Copy & Compare

2007-04-30 Thread Robert Rawlins - Think Blue
Thanks for that Tim,

Don't feel guilty mate, I've learned a little something from you anyway,
whether its applied here or not.

On quick question, how can I order a dict by the 'values' (not keys) before
looping? Is that possible?

Thanks,

Rob

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED]
On Behalf Of Tim Golden
Sent: 30 April 2007 11:27
Cc: python-list@python.org
Subject: Re: Dict Copy & Compare

Robert Rawlins - Think Blue wrote:
> Hello Tim,
> 
> Sorry, that 'value' was a slip up on my part, we're just dealing with keys
> here.
> 
> I get that a dict stores unique keys only but we're comparing the two
dicts,
> so when I say 'unique keys in dict 1' I basically mean all those keys that
> are in dict one but not in dict 2. So imagine my 2 dicts with the
following
> keys.
> 
> Dict 1Dict 2
> -----
> 00:00:00:00   00:00:00:00
> 11:11:11:11   11:11:11:11
> 22:22:22:22   33:33:33:33
> 44:44:44:44   44:44:44:44
> 55:55:55:55
> 
> Now, 22:22:22:22 and 55:55:55:55 is unique to dict one, and 33:33:33:33 is
> unique to dict 2, does that make sense? Sorry for not explaining this
stuff
> very well, being so new to dicts its easy to get confused with my terms.
> 
> I then want to pass those keys as a string value into my function as an
> argument, like.
> 
> thisFunction('22:22:22:22')
> thisFunction('55:55:55:55')
> 
> thatFunction('33:33:33:33')
> 
> I'm hoping that your method will work for me, I've just got to spend my
time
> understanding what each step of it does.

Well I feel a bit guilty now I look back at your
original post, because I've probably given
you a more complex solution than you really need. Your
initial approach is probably quite adequate. Python
dicts are highly tuned beasts so unless you're doing
something really big or bizarre, you can sensibly do:


d1 = {
   "00:00:00:00" : None,
   "11:11:11:11" : None,
   "22:22:22:22" : None,
   "44:44:44:44" : None,
   "55:55:55:55" : None
}

d2 = {
   "00:00:00:00" : None,
   "11:11:11:11" : None,
   "33:33:33:33" : None,
   "44:44:44:44" : None
}

for k in d1:
   if d1 not in d2:
 thisFunction (d1)

for k in d2
   if d2 not in d1:
thatFunction (k)



But even if this is adequate for your purposes,
it's always good to be aware of what's in your
programming toolbox and there's always the danger
you'll end up implementing sets in dicts (which
is what everyone did before Python 2.3).

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

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


Re: if __name__ == 'main': & passing an arg to a class object

2007-04-30 Thread Duncan Booth
Bart Willems <[EMAIL PROTECTED]> wrote:

> gtb wrote:
>> appear at the end of many examples I see. Is this to cause a .class
>> file to be generated?
> This might be obvious, but no one else mentioned it: the Python 
> interpreter cannot execute code that it hasn't compiled yet, which is 
> why the "if __name__ ..." code is always at the end of the module - to 
> guarantee that the entire file is scanned first.

This is somewhat misleading: the entire file is always compiled before any 
of it is executed (to see this try putting a syntax error on the last line: 
the syntax error will prevent any lines in the file being executed).

A more accurate statement would be to say that executing code cannot access 
any names which have not yet been defined. The code for functions and 
classes is compiled first with everything else, but the function or class 
objects are not created, and the relevant names are not bound until the 
appropriate 'def' or 'class' statement is executed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner Ping program

2007-04-30 Thread Duncan Booth
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:

> There is no (that I am aware of) ICMP module in the standard library.
> See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/409689 for
> an example of a Python implementation of ping.

Google also finds another implementation at:

 http://www.gnist.org/~lars/code/ping/ping.py
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regexp match string with word1 and not word2

2007-04-30 Thread James Stroud
Flyzone wrote:
> P.S: i can't have more re.search, so [clip]


This reminds me of a quote by the Great Researcher Roy Garcia:


 If it worked the first time, they'd just call it "search".


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


Re: Chart drawing tool in python

2007-04-30 Thread Laurent Pointal
[EMAIL PROTECTED] a écrit :
> Hi,
> 
> In Perl, there is a GD module to draw custom chart.
> 
> http://www-128.ibm.com/developerworks/opensource/library/os-perlgdchart/?ca=dgr-lnxw01Perl-GD-Charts
> 
> Can you please tell me if there is an equivalent library in python?
> 
> Thank you.
> 

You may look at DISLIN too.

http://www.mps.mpg.de/dislin/
http://www.mps.mpg.de/dislin/examples.html
http://www.mps.mpg.de/dislin/server.html


A+

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


Re: Importing a csv file

2007-04-30 Thread John Machin
On Apr 30, 7:21 pm, Tim Golden <[EMAIL PROTECTED]> wrote:
> sagar wrote:
> > Hi all ,
> >I want to read data in a csv file using the python scripts.
> > when i gave the following code :
> >  import csv
> > reader = csv.reader(open("some.csv", "rb"))
> > for row in reader:
> > print row
>
> > it is showing :
>
> > Traceback (most recent call last):
> >   File "csv.py", line 1, in 
> > import csv
> >   File "C:\Documents and Settings\meesa02\csv.py", line 2, in 

Only *almost* certainly, Tim? *Maybe*? You don't believe what the
above traceback lines are  telling you?

> > reader = csv.reader(open("some.csv", "rb"))
> > AttributeError: 'module' object has no attribute 'reader'
>
> You almost certainly have a file called "csv.py" in
> the current directory. (Maybe even the one that's
> running this script?). Rename it to "mycsv.py" or
> whatever and try again.
>



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


Re: I can't inherit from "compiled" classes ?

2007-04-30 Thread Diez B. Roggisch
> I understand what you are saying, and at the same time don't
> understand why it doesn't work. Isn't "everything an object" in
> python? And if something is an object does it not implies it's an
> instance of some class?

It means that, but it seems that you can't subclass everything, especially
functions:

>>> ft = type(lambda x: x)
>>> ft

>>> class FunctionSubclass(ft): pass
...
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: Error when calling the metaclass bases
type 'function' is not an acceptable base type
>>>

But even _if_ you could - what good does it do to you? select being an
_instance_ of function, it doesn't help you anything to subclass from it's
class. This doesn't affect select itself, in the same sense that instances
of some class Foo aren't affected by a subclass Bar(Foo).

Besides that, the semantics of "subclassing" a function type are unclear.
What would you expect?
 
> Does this mean I can't somehow make this work: """class
> PollingSocket(socket.socket, select):""" ?

As I point out above, this is a non-sensical thing to do anyway. Maybe you
should tell us what you want to accomplish here?

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


Restricting the alphabet of a string

2007-04-30 Thread Nathan Harmston
Hi,

I ve being thinking about playing around with bit strings but use in
some encoding problems I m considering and was trying to decide how to
implement a bit string class. Is there a library out there for doing
basic things with bit strings already is my first question?

I know that I can extend string to bit string, but is there anyway I
can force the alphabet to be restricted to 1's and 0's (or even 1, 0
and -1, as an extension to from trinary strings).

class Binary_String(String):
pass

Many Thanks

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


Re: Dict Copy & Compare

2007-04-30 Thread Tim Golden
Robert Rawlins - Think Blue wrote:
> On[e] quick question, how can I order a dict by 
 > the 'values' (not keys) before looping? Is that possible?

Depends on what you want to do. You can loop on
the sorted values very easily:


d1 = dict (a=2, b=1)
for value in sorted (d1.values):
   print value



but inferring the equivalent key is, in effect,
not possible since more than one key might correspond
to that value. Depending on what you're after, the
following technique might be of use:


import operator

d = dict (a=2, b=1, c=-1, d=4)
for k, v in sorted (
   d.items (),
   key=operator.itemgetter (1)
):
   print k, "=>", v



It may look a bit hairy, but break it down:

d.items () returns a list of 2-tuples, each one
corresponding to a key-value pair from the dict.
In our case, that'll be:

[('a', 2), ('b', 1), ('c', -1), ('d', 4)]

Although I've written them out like that,
the order they'll come in is undefined.

sorted () will return a sorted version of
whatever iterable you chuck at it. Under
normal Python semantics, sorted() on the
list above will return no change since I've
listed things out in alphanumeric order.

The extra key= parameter tells the sorted
routine to call the function you provide
against each of the items in the list (in
our case that means against each of the
2-tuples) and using the result of that
function as the sorting order.

The operation.itemgetter (1) bit is a touch
complicated unless you're already familiar with
partial functions, but it basically returns
*another* function which takes the item you
give it and returns the -- in this case --
1st item. Just believe me: it works.

So, in summary:

+ Get a list of key-value pairs
+ Sort them according to the 1st item (Python-style)
which in this case is the value.
+ Do something with the result

Before the key= param was introduced into
sort/sorted, people used to do the same thing
with what's often called DSU (short for
decorate-sort-undecorate), a technique which
here would look something like this:

items = d.items ()
sortable_items = [(i[1], i) for i in items]
sortable_items.sort ()
sorted_items = [i[-1] for i in sortable_items]

I mention this because (a) you still see it around
a fair bit and (b) there are occasions where it's
still useful, for example where a simple function
call can't really cope.

(Did I answer the question, or was I just rambling?)

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


Re: Importing a csv file

2007-04-30 Thread Tim Golden
John Machin wrote:
> On Apr 30, 7:21 pm, Tim Golden <[EMAIL PROTECTED]> wrote:
>> sagar wrote:
>>> Hi all ,
>>>I want to read data in a csv file using the python scripts.
>>> when i gave the following code :
>>>  import csv
>>> reader = csv.reader(open("some.csv", "rb"))
>>> for row in reader:
>>> print row
>>> it is showing :
>>> Traceback (most recent call last):
>>>   File "csv.py", line 1, in 
>>> import csv
>>>   File "C:\Documents and Settings\meesa02\csv.py", line 2, in 
> 
> Only *almost* certainly, Tim? *Maybe*? You don't believe what the
> above traceback lines are  telling you?

It's my natural British diffidence :) We almost never make
unqualified statements.

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


How to convert float to sortable integer in Python

2007-04-30 Thread ireyes

DEAR SIR,
I SAW YOUR INTERNET QUESTION AND I HAVE THE SAME TROUBLE.
CUOLD YOU HELP ME TO MAKE A FLOAT TO INTEGER CONVERTION?
DO YOU HAVE ANY EXEL FILE THAT CAN DO THAT?
REGARDS AND THANKS A LOT

IVAN REYES

___

AVISO LEGAL: El presente correo electronico no representa la opinion o el 
consentimiento oficial de la PONTIFICIA UNIVERSIDAD JAVERIANA. Este mensaje es 
confidencial y puede contener informacion privilegiada la cual no puede ser 
usada ni divulgada a personas distintas de su destinatario. Esta prohibida la 
retencion, grabacion, utilizacion, aprovechamiento o divulgacion con cualquier 
proposito. Si por error recibe este mensaje, por favor destruya su contenido y 
avise a su remitente.
En este aviso legal se omiten intencionalmente las tildes.

Este mensaje ha sido revisado por un sistema antivirus, por lo que su contenido 
esta libre de virus.
This e-mail has been scanned by an antivirus system, so its contents is free of 
viruses.
-- 
http://mail.python.org/mailman/listinfo/python-list


[ANN] Update to Python Quick Reference Card (for Python 2.4) (v0.67)

2007-04-30 Thread Laurent Pointal
PQRC (Python Quick Reference Card) is a condensed documentation for 
Python and its main libraries, targetting production of printed quick 
reference cards.
Its available as OpenDocument .odt files and as A4 and USLetter 
formatted PDF files ready to print.
Its distributed under a Creative Commons Attribution - NonCommercial - 
ShareAlike - 2.5 License, with allowing in-house print for curses.

Modifications since previous publication:
 Switching to DejaVu font.
 Rework styles.
 Get around bad index page numbers generation bug.
 Small corrections.


Its here:
http://www.limsi.fr/Individu/pointal/python/pqrc/


Note: Next version will target Python 2.5. I'll keep version for Python 
2.4 but should only make minor updates.


-- 
Laurent POINTAL
CNRS-LIMSI dépt. CHM, groupes AMI et PS
Courriel: [EMAIL PROTECTED](prof)
   [EMAIL PROTECTED] (perso)
Ouebe: http://www.limsi.fr/Individu/pointal/
Tél. 01 69 85 81 06 (prof)
Fax. 01 69 85 80 88
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Dict Copy & Compare

2007-04-30 Thread Robert Rawlins - Think Blue
No that makes sense Tim,

Thanks again for all your help on this one, it'll all prove invaluable I'm
sure. I managed to crack all the big troubles last week with my reoccurring
tasks, it's just a case of tidying up a few of these loose ends, then
that'll be python project no.1 over and done with :-D

Thanks,

Rob

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED]
On Behalf Of Tim Golden
Sent: 30 April 2007 12:54
Cc: python-list@python.org
Subject: Re: Dict Copy & Compare

Robert Rawlins - Think Blue wrote:
> On[e] quick question, how can I order a dict by 
 > the 'values' (not keys) before looping? Is that possible?

Depends on what you want to do. You can loop on
the sorted values very easily:


d1 = dict (a=2, b=1)
for value in sorted (d1.values):
   print value



but inferring the equivalent key is, in effect,
not possible since more than one key might correspond
to that value. Depending on what you're after, the
following technique might be of use:


import operator

d = dict (a=2, b=1, c=-1, d=4)
for k, v in sorted (
   d.items (),
   key=operator.itemgetter (1)
):
   print k, "=>", v



It may look a bit hairy, but break it down:

d.items () returns a list of 2-tuples, each one
corresponding to a key-value pair from the dict.
In our case, that'll be:

[('a', 2), ('b', 1), ('c', -1), ('d', 4)]

Although I've written them out like that,
the order they'll come in is undefined.

sorted () will return a sorted version of
whatever iterable you chuck at it. Under
normal Python semantics, sorted() on the
list above will return no change since I've
listed things out in alphanumeric order.

The extra key= parameter tells the sorted
routine to call the function you provide
against each of the items in the list (in
our case that means against each of the
2-tuples) and using the result of that
function as the sorting order.

The operation.itemgetter (1) bit is a touch
complicated unless you're already familiar with
partial functions, but it basically returns
*another* function which takes the item you
give it and returns the -- in this case --
1st item. Just believe me: it works.

So, in summary:

+ Get a list of key-value pairs
+ Sort them according to the 1st item (Python-style)
which in this case is the value.
+ Do something with the result

Before the key= param was introduced into
sort/sorted, people used to do the same thing
with what's often called DSU (short for
decorate-sort-undecorate), a technique which
here would look something like this:

items = d.items ()
sortable_items = [(i[1], i) for i in items]
sortable_items.sort ()
sorted_items = [i[-1] for i in sortable_items]

I mention this because (a) you still see it around
a fair bit and (b) there are occasions where it's
still useful, for example where a simple function
call can't really cope.

(Did I answer the question, or was I just rambling?)

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

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


Re: Reading Data From an Excel Sheet

2007-04-30 Thread garcia . marc
On Apr 30, 10:35 am, sagar <[EMAIL PROTECTED]> wrote:
> Hi all,
>I want a python script which takes in input an EXCEL sheet
> and then reads the data in it.
> Any code snippets will be fine and this i want this in windows
> XP .
>
>Thanks in Advance
>   Sagar Meesala

Here you have an example: http://
dataparser.cvs.sourceforge.net/dataparser/source/input_adapters/
excel.py?revision=1.1.1.1&view=markup

http://vaig.be";>Marc Garcia is the best expert in GNU/Linux
Debian, Apache, MySQL, and Python!

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


Python-URL! - weekly Python news and links (Apr 30)

2007-04-30 Thread Cameron Laird
QOTW:  "That is just as feasible as passing a cruise ship through a phone
line." - Carsten Haese, on transporting a COM object across a network.
Less vividly but more formally, as he notes, "A COM object represents a
connection to a service or executable that is running on one computer.
Transferring that connection to another computer is impossible."

"[D]on't burn bandwith by banal banter, post the examples!" - John Machin


See the great cities of Europe, learn Python, and play the "Where's
Alex (Guido/...)?" game:  attend a conference in Paris, Vilnius, 
Firenze, Birmingham, ...:
 
http://groups.google.com/group/comp.lang.python/browse_thread/thread/e12536c746c593a8/

Pygame is now having weekly (!) sprints to fix bugs on Wednesdays.
http://aspn.activestate.com/ASPN/Mail/Message/pygame-users/3441195
http://www.unixreview.com/documents/s=10116/ur0701j/

Exception-handling is important.  You need to learn 'most
everything about it you can.  See, for example, this thread
about disaggregating IOError:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/ed5b8e52d2642537/

Reasons to enjoy Python--but read the comments:

http://blog.cbcg.net/articles/2007/04/22/python-up-ruby-down-if-that-runtime-dont-work-then-its-bound-to-drizzown



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

For far, FAR more Python reading than any one mind should
absorb, much of it quite interesting, Planet Python indexes
much of the universe of Pybloggers.
http://www.planetpython.org/

The Python Papers aims to publish "the efforts of Python enthusiats".
http://pythonpapers.org/

Readers have recommended the "Planet" sites:
http://planetpython.org
http://planet.python.org

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Python411 indexes "podcasts ... to help people learn Python ..."
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

Steve Bethard continues the marvelous tradition early borne by
Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim
Lesher of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance.
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donate.html

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch

Although unmaintained since 2002, the Cetus collection of Python
hyperlinks retains a few gems.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://aspn.activestate.com/ASPN/Cookbook/Python

Many Python conferences around the world are in preparation.
Watch this space for links to them.

Among several Python-oriented RSS/RDF feeds available are
http://www.python.org/channews.rdf
http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi
http://python.de/backend.php
For more, see
http://ww

Re: How to convert float to sortable integer in Python

2007-04-30 Thread Larry Bates
[EMAIL PROTECTED] wrote:
> DEAR SIR,
> I SAW YOUR INTERNET QUESTION AND I HAVE THE SAME TROUBLE.
> CUOLD YOU HELP ME TO MAKE A FLOAT TO INTEGER CONVERTION?
> DO YOU HAVE ANY EXEL FILE THAT CAN DO THAT?
> REGARDS AND THANKS A LOT
> 
> IVAN REYES
> 
> ___
> 
> AVISO LEGAL: El presente correo electronico no representa la opinion o el 
> consentimiento oficial de la PONTIFICIA UNIVERSIDAD JAVERIANA. Este mensaje 
> es confidencial y puede contener informacion privilegiada la cual no puede 
> ser usada ni divulgada a personas distintas de su destinatario. Esta 
> prohibida la retencion, grabacion, utilizacion, aprovechamiento o divulgacion 
> con cualquier proposito. Si por error recibe este mensaje, por favor destruya 
> su contenido y avise a su remitente.
> En este aviso legal se omiten intencionalmente las tildes.
> 
> Este mensaje ha sido revisado por un sistema antivirus, por lo que su 
> contenido esta libre de virus.
> This e-mail has been scanned by an antivirus system, so its contents is free 
> of viruses.

You have given us an ill defined problem.

1) If you want to convert float to int just use int() function.
   s=int(f)

2) If you want to keep some fractional part of the float multiply
it by 10, 100, 1000, 1, ... depending on how many digits of
precision you wish to retain and then take int().

   s=int(f*1)

would retain 4 digits of precision and throw away the remainder.

3) You can sort on float just fine, so why do you need int()?

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


Re: Reading From an Excel Sheet

2007-04-30 Thread kyosohma
On Apr 30, 3:25 am, sagar <[EMAIL PROTECTED]> wrote:
> Hi all,
>   I want to write a python script which reads in data from the
> excel sheet .Can any one help out in this ...any help will be
> appreciated.
>
> Thanks in Advance
> Sagar Meesala

"Core Python Programming" by Chun and "Python Programming on Win32" by
Hammond & Robinson both have sections on interfacing with MS Office
and COM objects. Both are good references to boot.

Mike

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


Re: Cgi File Upload without Form

2007-04-30 Thread Karsten . G . Weinert
Thanks for your replies, however I think urlllib can not help me here.
I have control over the server side (I can write a cgi-script in
python), but I have very little control on the client side (I have to
use VBA).

Kind regards,
Karsten.

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


Re: Reading From an Excel Sheet

2007-04-30 Thread Dave Borne
>   I want to write a python script which reads in data from the
> excel sheet .Can any one help out in this ...any help will be
> appreciated.

Try here: http://cheeseshop.python.org/pypi/xlrd/0.5.2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cgi File Upload without Form

2007-04-30 Thread Dave Borne
> Since I want to upload the data programmatically, a form based
> solution is not good.

Karsten,
 Could you explain this statement? When I want to move data to a
server in a CGI environment, a form post is the easiest way I can
think of. What are the specific restrictions making forms a problem?

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


Re: My python annoyances so far

2007-04-30 Thread Sion Arrowsmith
7stud  <[EMAIL PROTECTED]> wrote:
>I know what you mean.  I always write:
>
>someStringVar.len
>
>and then I backspace and retype:
>
>len(someString).
>
>But then again, I can never remember whether length is a member or a
>method in other languages.

... or whether it's called length, size, count or len. Or even
whether the language is consistent from one container class to
the next.

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Launching an independent Python program in a cross-platform way (including mac)

2007-04-30 Thread Kevin Walzer
Prateek wrote:
> On Apr 30, 4:32 am, André <[EMAIL PROTECTED]> wrote:
>> I would like to find out how I can launch an independent Python
>> program from existing one in a cross-platform way.  The result I am
>> after is that a new terminal window should open (for io independent of
>> the original script).
>>
>> The following seems to work correctly under Ubuntu and Windows ... but
>> I haven't been able to find a way to make it work under Mac OS.
>>
>> def exec_external(code, path):
>> """execute code in an external process
>> currently works under:
>> * Windows NT (tested)
>> * GNOME (tested)  [January 2nd and 15th change untested]
>> This also needs to be implemented for OS X, KDE
>> and some form of linux fallback (xterm?)
>> """
>> if os.name == 'nt':
>> current_dir = os.getcwd()
>> target_dir, fname = os.path.split(path)
>>
>> filename = open(path, 'w')
>> filename.write(code)
>> filename.close()
>>
>> if os.name == 'nt':
>> os.chdir(target_dir) # change dir so as to deal with paths
>> that
>>  # include spaces
>> Popen(["cmd.exe", ('/c start python %s'%fname)])
>> os.chdir(current_dir)
>> elif os.name == 'posix':
>> try:
>> os.spawnlp(os.P_NOWAIT, 'gnome-terminal', 'gnome-
>> terminal',
>> '-x', 'python', '%s'%path)
>> except:
>> raise NotImplementedError
>> else:
>> raise NotImplementedError
>> ==
>> Any help would be greatly appreciated.
>>
>> André
> 
> Well,
> 
> You need to check sys.platform on the Mac instead of os.name.
> os.name returns 'posix' on all *nix based systems. sys.platform
> helpfully returns "darwin" on the Mac.
> 
> Not sure how to start Terminal. Here's what I got when I tried it:
> 
 if sys.platform == "darwin": os.spawnlp(os.P_NOWAIT, 
 '/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal')
> 9460
 2007-04-30 05:19:59.255 [9460] No Info.plist file in application bundle or 
 no NSPrincipalClass in the Info.plist file, exiting
> 

There are extension modules on the Mac for integrating Python and 
AppleScript (the best one is appscript). However, if you want to limit 
yourself to core Python, your best best is osascript, a system 
command-tool that lets you call AppleScript code with arguments from 
other programs. This can be called via os.system.

The basis syntax for doing this from Python might look something like this:

os.system('osascript -e \'tell app \"Terminal\" to activate\'')

This simply launches Terminal. Note that you have to deal with quoting 
issues. The equivalent syntax from AppleScript would be:

tell app "Terminal" to activate

If you want to Terminal to run a command-line program from AppleScript, 
you can do this with the "do script" command. Code to do this could look 
something like this:

myscript = "python -e foo.py"
os.system('osascript -e '\tell app \"Terminal"\ to do script %s\'', 
myscript)


I haven't tested this, but you get the basic idea--define the script and 
command-line paramaters in a string, then pass that to 
AppleScript/osascript as a variable.  This code should launch Terminal, 
then run the external Python script.

HTH,
Kevin

-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Restricting the alphabet of a string

2007-04-30 Thread 7stud
On Apr 30, 5:53 am, "Nathan Harmston" <[EMAIL PROTECTED]>
wrote:
> Hi,
>
> I ve being thinking about playing around with bit strings but use in
> some encoding problems I m considering and was trying to decide how to
> implement a bit string class. Is there a library out there for doing
> basic things with bit strings already is my first question?
>
> I know that I can extend string to bit string, but is there anyway I
> can force the alphabet to be restricted to 1's and 0's (or even 1, 0
> and -1, as an extension to from trinary strings).
>
> class Binary_String(String):
> pass
>
> Many Thanks
>
> Nathan

You could do something like this:

class Binary_String(str):
def __init__(self, val):
i = 0
for char in val:
if char not in "-101":
raise ValueError("illegal character at index " +
str(i)+ "\nOnly -1,0,1 allowed.")

i+=1
self.val = val


b = Binary_String("1a0101")

--output:--
Traceback (most recent call last):
  File "test1.py", line 13, in ?
b = Binary_String("1a100")
  File "test1.py", line 6, in __init__
raise ValueError("illegal character at index " + str(i)
ValueError: illegal character at index 1
Only -1,0,1 allowed.

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


Re: Python ODBC

2007-04-30 Thread kyosohma
On Apr 29, 11:34 am, Harlin Seritt <[EMAIL PROTECTED]> wrote:
> Is there a Python odbc module that will work on Linux? I have a jdbc
> connection to a DB2 server. I am looking hopefully for an open source
> solution and not a commercial one.
>
> Thanks,
>
> Harlin

I would think the odbc module would work. We've used SQLRelay here at
work too. Here's a link on the database modules for Python:

http://www.python.org/topics/database/modules.html

And here's a few links on db2 with Python:

http://www-128.ibm.com/developerworks/db2/library/tutorials/db2linux/db2proj/updated/python_db2_interface.htm
http://sourceforge.net/projects/pydb2/
http://www-128.ibm.com/developerworks/edu/i-dw-db2pylnx-i.html

Hope that helps.

Mike

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


Re: tkinter undo

2007-04-30 Thread kyosohma
On Apr 28, 8:50 am, Gigs_ <[EMAIL PROTECTED]> wrote:
> Hi
>
> I dont have idea how to write tkinter undo/redo function form my text editor 
> and
> my paint program.
> Could someone help? I'm not asking for code, just for some guidelines to get 
> me
> in the right way.
>
> thanks

>From what I've read, the Tkinter Text widget has an unlimited undo/
redo function built into it. If you use it for text editing, you
shouldn't need to worry about it. If you want to do it yourself, I
would recommend reading the code behind that widget or reading the
code behind IDLE itself.

Mike

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


Re: relative import broken?

2007-04-30 Thread Alan Isaac
"Alex Martelli" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> To me, it makes sense: if a module is top-level, and thus not part of a
> package (and __main__ in particular is always in that state), then
> saying "import from the current package" has no well defined meaning,
> because there IS no "current package".

Thanks for the explanations.
I do not have an opinion because I have not really thought this through.

One of the things I was hoping for, however, was for a less hackish way
for scripts bundled with a package to access the package modules.

That is, suppose I have directory ``mypackage`` with subdirectory
``scripts``.
What is the pretty way for the scripts to access ``mypackage`` without
assuming ``mypackage`` is in ``sys.path``?

Thanks,
Alan Isaac


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


socket module - recv() method

2007-04-30 Thread mirandacascade
Currently using the following technique in serveral client
applications to send a request message and receive a response:

import socket
bufferSize = 50
connectionHandle = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connectionHandle.connect(sa)
connectionHandle.sendall(requestMessage)
fullResponse = ''
# use while loop in case the entire response not sent in one chunk
while (1):
response = connectionHandle.recv(bufferSize)
fullResponse = fullResponse + response
if fullResponse.find(endOfMessageText) != -1:
break

where:
sa = 2-element tuple; 1st elem is string denoting ip address; 2nd elem
is int denoting port
requestMessage = string containing request message
endOfMessageText = string that unambiguously denotes the end of
response message

All of the client apps on which this technique is employed are very
predictable in the sense that  the client apps always know in advance
the value of endOfMessageText.

Questions:
1) is it theoretically possible that a client app will want to send a
request and receive a response where the response message does not
have something that unambigusously marks its end?
2) if so, are there any best-practices techniques for constructing the
code such that the client app knows that there is nothing else in the
response message?

Thank you.

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


Re: Cgi File Upload without Form

2007-04-30 Thread Karsten . G . Weinert
On 30 Apr., 15:51, "Dave Borne" <[EMAIL PROTECTED]> wrote:
> > Since I want to upload the data programmatically, a form based
> > solution is not good.
>
> Karsten,
>  Could you explain this statement? When I want to move data to a
> server in a CGI environment, a form post is the easiest way I can
> think of. What are the specific restrictions making forms a problem?
>
> -Dave

Hello Dave,
what I was thinking was: a form post is meant to be used manually. But
maybe I am wrong here and I can teach my VBA program to fill in forms
automatically. If I were using python as client, I could fill in forms
with urllib. However, I using python only server-side.

Kind regards,
Karsten.

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


Problem with PyQt4

2007-04-30 Thread [EMAIL PROTECTED]
Hi,

I am having some serious problems with PyQT4,
when i run pyqt script, I always get 'Segmentation fault'.

the script is simple:
==
%less qttest.py
from PyQt4 import QtGui, QtCore
import sys

if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
w = QtGui.QMainWindow()
w.show()
app.exec_()
==

When I run it , it crashes.
==
%python qttest.py
Segmentation fault (core dumped)
=

And the output with '-v' argument is :
=
%python -v qttest.py
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# /usr/local/lib/python2.4/site.pyc matches /usr/local/lib/python2.4/
site.py
import site # precompiled from /usr/local/lib/python2.4/site.pyc
# /usr/local/lib/python2.4/os.pyc matches /usr/local/lib/python2.4/
os.py
import os # precompiled from /usr/local/lib/python2.4/os.pyc
import posix # builtin
# /usr/local/lib/python2.4/posixpath.pyc matches /usr/local/lib/
python2.4/posixp
ath.py
import posixpath # precompiled from /usr/local/lib/python2.4/
posixpath.pyc
# /usr/local/lib/python2.4/stat.pyc matches /usr/local/lib/python2.4/
stat.py
import stat # precompiled from /usr/local/lib/python2.4/stat.pyc
# /usr/local/lib/python2.4/UserDict.pyc matches /usr/local/lib/
python2.4/UserDic
t.py
import UserDict # precompiled from /usr/local/lib/python2.4/
UserDict.pyc
# /usr/local/lib/python2.4/copy_reg.pyc matches /usr/local/lib/
python2.4/copy_re
g.py
import copy_reg # precompiled from /usr/local/lib/python2.4/
copy_reg.pyc
# /usr/local/lib/python2.4/types.pyc matches /usr/local/lib/python2.4/
types.py
import types # precompiled from /usr/local/lib/python2.4/types.pyc
# /usr/local/lib/python2.4/warnings.pyc matches /usr/local/lib/
python2.4/warning
s.py
import warnings # precompiled from /usr/local/lib/python2.4/
warnings.pyc
# /usr/local/lib/python2.4/linecache.pyc matches /usr/local/lib/
python2.4/lineca
che.py
import linecache # precompiled from /usr/local/lib/python2.4/
linecache.pyc
import encodings # directory /usr/local/lib/python2.4/encodings
# /usr/local/lib/python2.4/encodings/__init__.pyc matches /usr/local/
lib/python2
.4/encodings/__init__.py
import encodings # precompiled from /usr/local/lib/python2.4/encodings/
__init__.
pyc
# /usr/local/lib/python2.4/codecs.pyc matches /usr/local/lib/python2.4/
codecs.py
import codecs # precompiled from /usr/local/lib/python2.4/codecs.pyc
import _codecs # builtin
# /usr/local/lib/python2.4/encodings/aliases.pyc matches /usr/local/
lib/python2.
4/encodings/aliases.py
import encodings.aliases # precompiled from /usr/local/lib/python2.4/
encodings/a
liases.pyc
# /usr/local/lib/python2.4/encodings/gb2312.pyc matches /usr/local/lib/
python2.4
/encodings/gb2312.py
import encodings.gb2312 # precompiled from /usr/local/lib/python2.4/
encodings/gb
2312.pyc
dlopen("/usr/local/lib/python2.4/lib-dynload/_codecs_cn.so", 2);
import _codecs_cn # dynamically loaded from /usr/local/lib/python2.4/
lib-
dynload /
_codecs_cn.so
dlopen("/usr/local/lib/python2.4/lib-dynload/_multibytecodec.so", 2);
import _multibytecodec # dynamically loaded from /usr/local/lib/
python2.4/lib-
dy nload/
_multibytecodec.so
Python 2.4.3 (#2, Oct 15 2006, 05:32:11)
[GCC 3.4.6 [FreeBSD] 20060305] on freebsd6
Type "help", "copyright", "credits" or "license" for more information.
import PyQt4 # directory /usr/local/lib/python2.4/site-packages/PyQt4
# /usr/local/lib/python2.4/site-packages/PyQt4/__init__.pyc matches /
usr/local/
l ib/
python2.4/site-packages/PyQt4/__init__.py
import PyQt4 # precompiled from /usr/local/lib/python2.4/site-packages/
PyQt4/__i
nit__.pyc
dlopen("/usr/local/lib/python2.4/site-packages/PyQt4/QtGui.so", 2);
dlopen("/usr/local/lib/python2.4/site-packages/sip.so", 2);
import sip # dynamically loaded from /usr/local/lib/python2.4/site-
packages/
sip. so
dlopen("/usr/local/lib/python2.4/site-packages/PyQt4/QtCore.so", 2);
import PyQt4.QtCore # dynamically loaded from /usr/local/lib/python2.4/
site-pack
ages/PyQt4/QtCore.so
import PyQt4.QtGui # dynamically loaded from /usr/local/lib/python2.4/
site-packa
ges/PyQt4/QtGui.so
Segmentation fault (core dumped)
%python -v qttest.py
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# /usr/local/lib/python2.4/site.pyc matches /usr/local/lib/python2.4/
site.py
import site # precompiled from /usr/local/lib/python2.4/site.pyc
# /usr/local/lib/python2.4/os.pyc matches /usr/local/lib/python2.4/
os.py
import os # precompiled from /usr/local/lib/python2.4/os.pyc
import posix # builtin
# /usr/local/lib/python2.4/posixpath.pyc matches /usr/local/lib/
python2.4/posixpath.py
import posixpath # precompiled from /usr/local/lib/python

Re: Restricting the alphabet of a string

2007-04-30 Thread Paul McGuire
On Apr 30, 9:00 am, 7stud <[EMAIL PROTECTED]> wrote:
> On Apr 30, 5:53 am, "Nathan Harmston" <[EMAIL PROTECTED]>
> wrote:
>
>
>
>
>
> > Hi,
>
> > I ve being thinking about playing around with bit strings but use in
> > some encoding problems I m considering and was trying to decide how to
> > implement a bit string class. Is there a library out there for doing
> > basic things with bit strings already is my first question?
>
> > I know that I can extend string to bit string, but is there anyway I
> > can force the alphabet to be restricted to 1's and 0's (or even 1, 0
> > and -1, as an extension to from trinary strings).
>
> > class Binary_String(String):
> > pass
>
> > Many Thanks
>
> > Nathan
>
> You could do something like this:
>
> class Binary_String(str):
> def __init__(self, val):
> i = 0
> for char in val:
> if char not in "-101":
> raise ValueError("illegal character at index " +
> str(i)+ "\nOnly -1,0,1 allowed.")
>
> i+=1
> self.val = val
>
> b = Binary_String("1a0101")
>
> --output:--
> Traceback (most recent call last):
>   File "test1.py", line 13, in ?
> b = Binary_String("1a100")
>   File "test1.py", line 6, in __init__
> raise ValueError("illegal character at index " + str(i)
> ValueError: illegal character at index 1
> Only -1,0,1 allowed.- Hide quoted text -
>
> - Show quoted text -

Your character test only needs to check if the character is in "-10",
not "-101".  In fact, this is a little misleading, since it appears to
check for "-1" but is really only checking for "-"s and "1"s (and "0"s
too, of course).

This code accepts "1-0101" also, but what is -0?

-- Paul


-- Paul

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


Re: Launching an independent Python program in a cross-platform way (including mac)

2007-04-30 Thread André
On Apr 30, 10:59 am, Kevin Walzer <[EMAIL PROTECTED]> wrote:
[snip]
>
> There are extension modules on the Mac for integrating Python and
> AppleScript (the best one is appscript). However, if you want to limit
> yourself to core Python, your best best is osascript, a system
> command-tool that lets you call AppleScript code with arguments from
> other programs. This can be called via os.system.
>
> The basis syntax for doing this from Python might look something like this:
>
> os.system('osascript -e \'tell app \"Terminal\" to activate\'')
>
> This simply launches Terminal. Note that you have to deal with quoting
> issues. The equivalent syntax from AppleScript would be:
>
> tell app "Terminal" to activate
>
> If you want to Terminal to run a command-line program from AppleScript,
> you can do this with the "do script" command. Code to do this could look
> something like this:
>
> myscript = "python -e foo.py"
> os.system('osascript -e '\tell app \"Terminal"\ to do script %s\'',
> myscript)
>
> I haven't tested this, but you get the basic idea--define the script and
> command-line paramaters in a string, then pass that to
> AppleScript/osascript as a variable.  This code should launch Terminal,
> then run the external Python script.
>
> HTH,
Thanks.  I managed to get something like this to work.  Later, I'll
post it as an example to this thread so that other can use if for a
reference if needed.

André
> Kevin
>
> --
> Kevin Walzer
> Code by Kevinhttp://www.codebykevin.com


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


Re: Update to Python Quick Reference Card (for Python 2.4) (v0.67)

2007-04-30 Thread kyosohma
On Apr 30, 7:42 am, Laurent Pointal <[EMAIL PROTECTED]> wrote:
> PQRC (Python Quick Reference Card) is a condensed documentation for
> Python and its main libraries, targetting production of printed quick
> reference cards.
> Its available as OpenDocument .odt files and as A4 and USLetter
> formatted PDF files ready to print.
> Its distributed under a Creative Commons Attribution - NonCommercial -
> ShareAlike - 2.5 License, with allowing in-house print for curses.
>
> Modifications since previous publication:
>  Switching to DejaVu font.
>  Rework styles.
>  Get around bad index page numbers generation bug.
>  Small corrections.
>
> Its here:http://www.limsi.fr/Individu/pointal/python/pqrc/
>
> Note: Next version will target Python 2.5. I'll keep version for Python
> 2.4 but should only make minor updates.
>
> --
> Laurent POINTAL
> CNRS-LIMSI dépt. CHM, groupes AMI et PS
> Courriel: [EMAIL PROTECTED](prof)
>[EMAIL PROTECTED] (perso)
> Ouebe:http://www.limsi.fr/Individu/pointal/
> Tél. 01 69 85 81 06 (prof)
> Fax. 01 69 85 80 88

This is pretty cool. Kind of like the Python Phrasebook, but even more
succinct.

Thanks!

Mike

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


Re-running script from Tk shell

2007-04-30 Thread gtb

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

Perhaps I need to de-import the class, but I have not found a method
in the tutorial or the reference (yet).

Thanks

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


Re: While we're talking about annoyances

2007-04-30 Thread Alex Martelli
Michael Hoffman <[EMAIL PROTECTED]> wrote:
   ...
> >> Well, counting the index() function that is called in both cases, the
> >> original rank() had one sort, but my version has two sorts.
> > 
> > That doesn't affet the big-O behavior -- O(N log N) holds whether you
> > have one sort, or three, or twentyseven.
> 
> I've taught programming classes before, and I would have had to fail 
> anybody who misunderstood speed badly enough to claim that something 
> repeating an O(N log N) algorithm 27 times was no faster than doing it
> once. ;-)

As for me, I would fail somebody who thought they could compare speed
this way -- if the O(N log N) executed 27 times took (on a given
machine) 1 millisecond times N times log N, and the other one (on the
same machine) 1 second times N times log N (and in the big-O notation
you can NEVER infer what the multiplicative constant is), for example,
such a comparison would be totally of base.

> As Arnaud points out, asymptotic behavior is not the same as speed. His
> original statement that the more recently proposed definitions of rank()
> are slower than the OP's may be correct. And if it's not, it's not 
> because they're all O(N log N).

And if it is, it's not because of the "one sort" versus "two sorts": by
that sole criterion you just cannot guess (sensibly) at speed (measuring
is much better, though it has its own pitfalls).


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


import structures

2007-04-30 Thread spohle
hi,

i have written a small project for myself all in seperate classes and
each of the classes lives in a seperate file. now i am looking for an
import structure something like import wx, and then have access to all
my classes just like wx.Button or wx.BoxSizer etc.

as of now i have a __init__.py file in the directory with:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)

but i still have to import each class by it's own. im really looking
for something like import wx
and then get all my access right away under this new namespace.

thank you in advance

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


Re: import structures

2007-04-30 Thread Paul McGuire
On Apr 30, 9:56 am, spohle <[EMAIL PROTECTED]> wrote:
> hi,
>
> i have written a small project for myself all in seperate classes and
> each of the classes lives in a seperate file. now i am looking for an
> import structure something like import wx, and then have access to all
> my classes just like wx.Button or wx.BoxSizer etc.
>
> as of now i have a __init__.py file in the directory with:
> from pkgutil import extend_path
> __path__ = extend_path(__path__, __name__)
>
> but i still have to import each class by it's own. im really looking
> for something like import wx
> and then get all my access right away under this new namespace.
>
> thank you in advance

If it really is a small project, consider just putting all the classes
into a single module, say spohlePkg.py.  Then your users would import
this module using "import spohlePkg", and would access the classes as
"spohlePkg.ClassA", "spohlePkg.ClassB", etc.

-- Paul

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


Re: import structures

2007-04-30 Thread spohle
On Apr 30, 8:00 am, Paul McGuire <[EMAIL PROTECTED]> wrote:
> On Apr 30, 9:56 am, spohle <[EMAIL PROTECTED]> wrote:
>
>
>
> > hi,
>
> > i have written a small project for myself all in seperate classes and
> > each of the classes lives in a seperate file. now i am looking for an
> > import structure something like import wx, and then have access to all
> > my classes just like wx.Button or wx.BoxSizer etc.
>
> > as of now i have a __init__.py file in the directory with:
> > from pkgutil import extend_path
> > __path__ = extend_path(__path__, __name__)
>
> > but i still have to import each class by it's own. im really looking
> > for something like import wx
> > and then get all my access right away under this new namespace.
>
> > thank you in advance
>
> If it really is a small project, consider just putting all the classes
> into a single module, say spohlePkg.py.  Then your users would import
> this module using "import spohlePkg", and would access the classes as
> "spohlePkg.ClassA", "spohlePkg.ClassB", etc.
>
> -- Paul

yeah i had that, but my classes grew really fast and i decided to
split them up. but you're right that in one file that would solve my
problem. still hoping to find a way for the seperate files.

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


Re: regexp match string with word1 and not word2

2007-04-30 Thread Steven Bethard
Flyzone wrote:
> Hello,
> i have again problem with regexp :-P
> I need to match all lines that contain one word but not contain
> another.
> Like to do "grep one | grep -v two:"

You don't need a regexp:;

 if 'one' in line and 'two:' not in line:
 ... do something...

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


RE: import structures

2007-04-30 Thread Hamilton, William
> -Original Message-
> From: [EMAIL PROTECTED]
[mailto:python-
> [EMAIL PROTECTED] On Behalf Of spohle
> Sent: Monday, April 30, 2007 10:03 AM
> To: python-list@python.org
> Subject: Re: import structures
> 
> On Apr 30, 8:00 am, Paul McGuire <[EMAIL PROTECTED]> wrote:
> > On Apr 30, 9:56 am, spohle <[EMAIL PROTECTED]> wrote:
> >
> >
> >
> > > hi,
> >
> > > i have written a small project for myself all in seperate classes
and
> > > each of the classes lives in a seperate file. now i am looking for
an
> > > import structure something like import wx, and then have access to
all
> > > my classes just like wx.Button or wx.BoxSizer etc.
> >
> > > as of now i have a __init__.py file in the directory with:
> > > from pkgutil import extend_path
> > > __path__ = extend_path(__path__, __name__)
> >
> > > but i still have to import each class by it's own. im really
looking
> > > for something like import wx
> > > and then get all my access right away under this new namespace.
> >
> > > thank you in advance
> >
> > If it really is a small project, consider just putting all the
classes
> > into a single module, say spohlePkg.py.  Then your users would
import
> > this module using "import spohlePkg", and would access the classes
as
> > "spohlePkg.ClassA", "spohlePkg.ClassB", etc.
> >
> > -- Paul
> 
> yeah i had that, but my classes grew really fast and i decided to
> split them up. but you're right that in one file that would solve my
> problem. still hoping to find a way for the seperate files.
> 

If you've got modules a, b, and c, you can create a wrapper module d
that imports from each of those.

from a import *
from b import *
from c import *


Then, import d and use it as the module name.  So if a had a SomeThing
class, you could do this:

import d
x = d.SomeThing()



---
-Bill Hamilton

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


Re: regexp match string with word1 and not word2

2007-04-30 Thread Flyzone
James Stroud ha scritto:

> The P.S: suggests homework, but this can't be homework because python
> regex won't do this, so your teacher gets an F if its homework. You

Not a homework, but a "workwork" :-)
I'm writing a script to parse logfiles, and I have began to study
python for this (bash was too much slow).
When i'll finishi it, I'll post a link here if someone think that
could be helpful.

> require a negative look-behind assertion of variable length--not
> possible in python regex. You will have to use something else--or maybe
> you don't understand the homework problem.

I was asking that cause in the code i wrote this:
  for y in range(0, len(skip_lst) ):
 if (re.search(skip_lst[y], line)):
  skip=1
   break

In skip_lst there are the regexp and strings (on one line) to match
with "line".
But rarely the rules to be matched need to have also a logical And.
What could be the solution? Add another array with a "not" regexp?

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


Re: regexp match string with word1 and not word2

2007-04-30 Thread Flyzone
On 30 Apr, 17:11, Steven Bethard <[EMAIL PROTECTED]> wrote:

> You don't need a regexp:;

I need a regexp.i'm parsing a file with a rule-file that contains
also regexp and strings too
Read my post to James Stroud.

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


Re: import structures

2007-04-30 Thread spohle
On Apr 30, 8:16 am, "Hamilton, William " <[EMAIL PROTECTED]> wrote:
> > -Original Message-
> > From: [EMAIL PROTECTED]
> [mailto:python-
> > [EMAIL PROTECTED] On Behalf Of spohle
> > Sent: Monday, April 30, 2007 10:03 AM
> > To: [EMAIL PROTECTED]
> > Subject: Re: import structures
>
> > On Apr 30, 8:00 am, Paul McGuire <[EMAIL PROTECTED]> wrote:
> > > On Apr 30, 9:56 am, spohle <[EMAIL PROTECTED]> wrote:
>
> > > > hi,
>
> > > > i have written a small project for myself all in seperate classes
> and
> > > > each of the classes lives in a seperate file. now i am looking for
> an
> > > > import structure something like import wx, and then have access to
> all
> > > > my classes just like wx.Button or wx.BoxSizer etc.
>
> > > > as of now i have a __init__.py file in the directory with:
> > > > from pkgutil import extend_path
> > > > __path__ = extend_path(__path__, __name__)
>
> > > > but i still have to import each class by it's own. im really
> looking
> > > > for something like import wx
> > > > and then get all my access right away under this new namespace.
>
> > > > thank you in advance
>
> > > If it really is a small project, consider just putting all the
> classes
> > > into a single module, say spohlePkg.py.  Then your users would
> import
> > > this module using "import spohlePkg", and would access the classes
> as
> > > "spohlePkg.ClassA", "spohlePkg.ClassB", etc.
>
> > > -- Paul
>
> > yeah i had that, but my classes grew really fast and i decided to
> > split them up. but you're right that in one file that would solve my
> > problem. still hoping to find a way for the seperate files.
>
> If you've got modules a, b, and c, you can create a wrapper module d
> that imports from each of those.
>
> from a import *
> from b import *
> from c import *
>
> Then, import d and use it as the module name.  So if a had a SomeThing
> class, you could do this:
>
> import d
> x = d.SomeThing()
>
> ---
> -Bill Hamilton


that doesn't seem to work for me. the from a import * will only give
me a not d.a

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


Re: regexp match string with word1 and not word2

2007-04-30 Thread Carsten Haese
On Mon, 2007-04-30 at 08:22 -0700, Flyzone wrote:
> On 30 Apr, 17:11, Steven Bethard <[EMAIL PROTECTED]> wrote:
> 
> > You don't need a regexp:;
> 
> I need a regexp.i'm parsing a file with a rule-file that contains
> also regexp and strings too

That was not at all evident from your original description. The quality
of the advice you receive is directly influenced by the quality of your
description of the problem you're trying to solve.

-Carsten


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


Re: import structures

2007-04-30 Thread Duncan Booth
spohle <[EMAIL PROTECTED]> wrote:

> as of now i have a __init__.py file in the directory with:
> from pkgutil import extend_path
> __path__ = extend_path(__path__, __name__)
> 
> but i still have to import each class by it's own. im really looking
> for something like import wx
> and then get all my access right away under this new namespace.

You just need to make your __init__.py import anything you want to be 
available directly under the package.

So if the folder pkg contains __init__.py, class1.py, class2.py all you 
have to do is make pkg/__init__.py contain something like:

   from class1 import Class1
   from class2 import Class2
 
And then when using the package you can do:

  from pkg import Class1, Class2

or

  import pkg
  ...
  something = pkg.Class1()

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


RE: import structures

2007-04-30 Thread Hamilton, William
> -Original Message-
> From: [EMAIL PROTECTED]
[mailto:python-
> [EMAIL PROTECTED] On Behalf Of spohle
> Sent: Monday, April 30, 2007 10:25 AM
> To: python-list@python.org
> Subject: Re: import structures
> 
> On Apr 30, 8:16 am, "Hamilton, William " <[EMAIL PROTECTED]> wrote:

> >
> > If you've got modules a, b, and c, you can create a wrapper module d
> > that imports from each of those.
> >
> > from a import *
> > from b import *
> > from c import *
> >
> > Then, import d and use it as the module name.  So if a had a
SomeThing
> > class, you could do this:
> >
> > import d
> > x = d.SomeThing()
> >
> > ---
> > -Bill Hamilton
> 
> 
> that doesn't seem to work for me. the from a import * will only give
> me a not d.a
> 


"from blah import *" puts everything in blah into the current module's
namespace (or so I understand it).  This is different from "import
blah":  with the latter, you have to use "x = blah.SomeThing()".  With
the former, you can simply say "x = SomeThing()".

So, if a has a class SomeThing, and you import it into d using "from a
import *", in d you can use SomeThing's methods directly.  If you then
use "import d" in your main script, you can create a SomeThing instance
with 
"x = d.SomeThing()".

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


Can python find HW/SW installed on my PC - like Belarc?

2007-04-30 Thread walterbyrd
Lets suppose, I want a listing of what hardware and software is
installed on my
windows box. Can I do that with Python?

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


Re: Reading Data From an Excel Sheet

2007-04-30 Thread [EMAIL PROTECTED]
On Apr 30, 3:35 am, sagar <[EMAIL PROTECTED]> wrote:
> Hi all,
>I want a python script which takes in input an EXCEL sheet
> and then reads the data in it.
> Any code snippets will be fine and this i want this in windows
> XP .
>
>Thanks in Advance
>   Sagar Meesala

have you tried to output to csv (the comma output stuff) and then load
it..  (I don't know if that is an option for excel but I use the
reverse concept for dex tracker as many excel compatable sites allow
csv.)

https://sourceforge.net/projects/dex-tracker


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


Re: Can python find HW/SW installed on my PC - like Belarc?

2007-04-30 Thread kyosohma
On Apr 30, 10:47 am, walterbyrd <[EMAIL PROTECTED]> wrote:
> Lets suppose, I want a listing of what hardware and software is
> installed on my
> windows box. Can I do that with Python?

Yes, it is possible for Windows. I don't know how to grab the info for
other OS's though. There is a caveat that is annoying. If the software
doesn't put itself into the registry somehow, it is much harder to
discover if it is indeed installed.

For hardware, you'll need the WMI module and the win32 module. For the
computer memory and the name of the PC, see below:

c = wmi.WMI()
for i in c.Win32_ComputerSystem():
mem = int(i.TotalPhysicalMemory)
compname = i.Name

For the CPU:

for i in c.Win32_Processor ():
cputype = i.Name

For other cool WMI tricks: http://tgolden.sc.sabren.com/python/wmi_cookbook.html

For the majority of the software on your system, you'll want to
iterate over the following registry key (and its subkeys) using the
_winreg module and WMI's Registry() function:

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall

Some code that worked for me (may need modification for your setup):

from _winreg import HKEY_LOCAL_MACHINE, KEY_ALL_ACCESS, OpenKey,
EnumValue, QueryValueEx

r = wmi.Registry ()
result, names = r.EnumKey (hDefKey=HKEY_LOCAL_MACHINE,
sSubKeyName=r"Software\Microsoft\Windows\CurrentVersion\Uninstall")
for subkey in names:
try:
appFile.write('
+\n\n')
key = OpenKey(HKEY_LOCAL_MACHINE,
  r"Software\Microsoft\Windows\CurrentVersion
\Uninstall\%s" % subkey,0, KEY_ALL_ACCESS)
try:
temp = QueryValueEx(key, 'DisplayName')
display = str(temp[0])
appFile.write('Display Name: ' + display + '\nRegkey: ' +
subkey + '\n')
except:
appFile.write('Regkey: ' + subkey + '\n')
   except:
   print 'Error opening key'

# appFile is where I write the list to. You can just print to console.

That should get you going.

Mike

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


Re: Launching an independent Python program in a cross-platform way (including mac)

2007-04-30 Thread [EMAIL PROTECTED]
I would like to see this as a command along with something to open web
pages..  Just one command instead of trying to figure out all the
different op systems.  look forward to seeing your code

https://sourceforge.net/projects/dex-tracker


On Apr 30, 9:40 am, André <[EMAIL PROTECTED]> wrote:
> On Apr 30, 10:59 am, Kevin Walzer <[EMAIL PROTECTED]> wrote:
> [snip]
>
>
>
>
>
> > There are extension modules on the Mac for integrating Python and
> > AppleScript (the best one is appscript). However, if you want to limit
> > yourself to core Python, your best best is osascript, a system
> > command-tool that lets you call AppleScript code with arguments from
> > other programs. This can be called via os.system.
>
> > The basis syntax for doing this from Python might look something like this:
>
> > os.system('osascript -e \'tell app \"Terminal\" to activate\'')
>
> > This simply launches Terminal. Note that you have to deal with quoting
> > issues. The equivalent syntax from AppleScript would be:
>
> > tell app "Terminal" to activate
>
> > If you want to Terminal to run a command-line program from AppleScript,
> > you can do this with the "do script" command. Code to do this could look
> > something like this:
>
> > myscript = "python -e foo.py"
> > os.system('osascript -e '\tell app \"Terminal"\ to do script %s\'',
> > myscript)
>
> > I haven't tested this, but you get the basic idea--define the script and
> > command-line paramaters in a string, then pass that to
> > AppleScript/osascript as a variable.  This code should launch Terminal,
> > then run the external Python script.
>
> > HTH,
>
> Thanks.  I managed to get something like this to work.  Later, I'll
> post it as an example to this thread so that other can use if for a
> reference if needed.
>
> André
>
>
>
> > Kevin
>
> > --
> > Kevin Walzer
> > Code by Kevinhttp://www.codebykevin.com- Hide quoted text -
>
> - Show quoted text -- Hide quoted text -
>
> - Show quoted text -


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


fix an example of wxwindows listed on rentacoder.com

2007-04-30 Thread [EMAIL PROTECTED]
 The code in question is at https://sourceforge.net/projects/dex-tracker
I am trying to get rid of the part of the example where you have to
use run.py.  since I am stuck and it is driving me nuts I have put it
up for bid at 
http://www.rentacoder.com/RentACoder/misc/BidRequests/ShowBidRequest.asp?lngBidRequestId=676174
If I can get this to work well I have another small c project that
will allow me to compete with sep (stienburg) :)

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


OT somewhat: Do you telecommute? What do you wish the boss understood about it?

2007-04-30 Thread estherschindler
For a lot of IT people -- everyone from software developers to tech
writers to network support folks -- telecommuting is the best personal
option. They get a flexible schedule, they aren't bothered by noisy
cube-mates, they can code during whichever hours work for them (with
the help of IM and email), and so on. Many of us are lucky enough to
live this lifestyle; I include myself in this set, as I've been a full
time telecommuter for several years.

So I proposed to my boss that I write another in my "5 Things the CIO
Should Know..." series (along with "5 Things the CIO Should Know about
Fighting Spam" [http://www.cio.com/article/101475] and "...about
Software Requirements" [http://www.cio.com/article/29903]), this time
about telecommuting. He was enthusiastic about the idea, and I'm
anxious to get started.

My question has two parts:

* If you telecommute, full- or part-time, what *one* thing do you wish
the CIO or IT Management would understand that they don't currently
"get"?

* If you don't telecommute, the question is the same -- what do you
wish the CIO would understand about telecommuting -- but I expect the
answers will be different (such as "they should let me do it"). Or
perhaps you want to tell management something about the difficulty of
dealing with telecommuters ("I really hate that THEY always seem to do
email during teleconferences but nobody would let us get away with
that in person.") Note, though, that most of my attention will be
given to the people who DO telecommute because my context is "if
you're going to do this, we'll tell you how to do it right."

There is, of course, a manager's view to the same question. (I can
imagine a manager saying, "Telecommuting doesn't mean you can stay
home and play with your baby. You still need to get your work done.")
But mostly I'm trying to represent the concerns of the telecommuter
herself.

I realize that you may have more than one "...and THEN I'd say...!"
item. But I ask people to keep it to one answer to help me clarify
priorities.

As you can probably tell, I will collect opinions from a wide variety
of people who work in IT, over the next week or so. I'll collate the
results and then turn them into a  brilliant essay which
will be published on CIO.com. I promise to post the URL when the
article is posted, too.

I'm happiest when I can quote someone specifically ("Esther Schindler
is a programmer at the Groovy Corporation") but it's okay to have an
indirect reference too ("Esther is a programmer at a financial
services firm in the midwest"). I can even accept anonymity if
necessary ("a programmer named Esther said..."). You can write to me
privately if you like, but I suspect the question is of interest to
the larger community, so feel free to respond to the thread here. (It
does help if you cc me so that I see your message sooner.)

Esther Schindler
senior online editor, CIO.com
http://advice.cio.com/taxonomy/term/34

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


Re: Tracebacks for `exec`ed code?

2007-04-30 Thread brzrkr0
On Apr 29, 2:40 am, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> Adam Atlas schrieb:
>
> > Is it possible to make more traceback information available for
> > exceptions code dynamically run via `exec`? Normally it just says
> > things like "File '', line 3, in ?", which is not very
> > helpful. I'm looking for a way for it to show the line of source code
> > below it, like it would for an exception in a physical file. Is this
> > possible?
>
> Yes. You will need to print the traceback yourself; see
> traceback.print_tb for an example.
>
> Regards
> Martin

You could also write the code you want to execute to a temporary file,
then use execfile() on that file.

-Casey

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


Re: Cgi File Upload without Form

2007-04-30 Thread Karsten . G . Weinert
OK, I think I have a simple solution now. I am going to use FTP in my
VBA-Client (it's possible) and don't need to do any server-side
programming.

Kind regards,
Karsten.

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


Re: Launching an independent Python program in a cross-platform way (including mac)

2007-04-30 Thread kyosohma
On Apr 30, 11:29 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> I would like to see this as a command along with something to open web
> pages..  Just one command instead of trying to figure out all the
> different op systems.  look forward to seeing your code
>
> https://sourceforge.net/projects/dex-tracker
>
> On Apr 30, 9:40 am, André <[EMAIL PROTECTED]> wrote:
>
> > On Apr 30, 10:59 am, Kevin Walzer <[EMAIL PROTECTED]> wrote:
> > [snip]
>
> > > There are extension modules on the Mac for integrating Python and
> > > AppleScript (the best one is appscript). However, if you want to limit
> > > yourself to core Python, your best best is osascript, a system
> > > command-tool that lets you call AppleScript code with arguments from
> > > other programs. This can be called via os.system.
>
> > > The basis syntax for doing this from Python might look something like 
> > > this:
>
> > > os.system('osascript -e \'tell app \"Terminal\" to activate\'')
>
> > > This simply launches Terminal. Note that you have to deal with quoting
> > > issues. The equivalent syntax from AppleScript would be:
>
> > > tell app "Terminal" to activate
>
> > > If you want to Terminal to run a command-line program from AppleScript,
> > > you can do this with the "do script" command. Code to do this could look
> > > something like this:
>
> > > myscript = "python -e foo.py"
> > > os.system('osascript -e '\tell app \"Terminal"\ to do script %s\'',
> > > myscript)
>
> > > I haven't tested this, but you get the basic idea--define the script and
> > > command-line paramaters in a string, then pass that to
> > > AppleScript/osascript as a variable.  This code should launch Terminal,
> > > then run the external Python script.
>
> > > HTH,
>
> > Thanks.  I managed to get something like this to work.  Later, I'll
> > post it as an example to this thread so that other can use if for a
> > reference if needed.
>
> > André
>
> > > Kevin
>
> > > --
> > > Kevin Walzer
> > > Code by Kevinhttp://www.codebykevin.com-Hide quoted text -
>
> > - Show quoted text -- Hide quoted text -
>
> > - Show quoted text -

Opening web pages cross-platform can be done with the "webbrowser"
module: http://docs.python.org/lib/module-webbrowser.html

Mike

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


Re: Cgi File Upload without Form

2007-04-30 Thread Jarek Zgoda
[EMAIL PROTECTED] napisał(a):

>>  Could you explain this statement? When I want to move data to a
>> server in a CGI environment, a form post is the easiest way I can
>> think of. What are the specific restrictions making forms a problem?
> what I was thinking was: a form post is meant to be used manually. But
> maybe I am wrong here and I can teach my VBA program to fill in forms
> automatically. If I were using python as client, I could fill in forms
> with urllib. However, I using python only server-side.

"Form" usually means an action accessible for HTTP POST request with
content-type multipart/form-data. Uploading files is usually done in
this way, if you don't want/cann't use more sophisticated means like
WebDAV (which is HTTP extension, btw).

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


Re: Re-running script from Tk shell

2007-04-30 Thread kyosohma
On Apr 30, 9:51 am, gtb <[EMAIL PROTECTED]> wrote:
> I am testing a simple script by running it in the Tk shell. It imports
> a class from another module. I edit and save the file from which I
> import. When I want to re-run I delete the Tk window  and run the
> module from the Edit window (F5 - Run Module). The script that does
> the importing does not see the changes to the imported class, even if
> I delete the compiled files. For it to see the changes I must close
> all the edit windows and re-open an Idle edit.
>
> Perhaps I need to de-import the class, but I have not found a method
> in the tutorial or the reference (yet).
>
> Thanks

You probably need to reload() the imported module. Check out the
following thread: http://www.python.org/search/hypermail/python-1993/0342.html

Hopefully that's what you meant anyway.

Mike

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


Re: regexp match string with word1 and not word2

2007-04-30 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Flyzone wrote:

> for y in range(0, len(skip_lst) ):
>  if (re.search(skip_lst[y], line)):
>   skip=1
>break

Please try to avoid unnecessary indexes::

for regexp in skip_list:
if re.search(regexp, line):
skip = True
break

And if you don't intent to count the `skip`\s a `True` seems to be more
readable.

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


RE: Dict Copy & Compare

2007-04-30 Thread Hamilton, William
> -Original Message-
> From: [EMAIL PROTECTED]
[mailto:python-
> [EMAIL PROTECTED] On Behalf Of Robert
Rawlins -
> Think Blue
> Sent: Monday, April 30, 2007 6:09 AM
> To: 'Tim Golden'
> Cc: python-list@python.org
> Subject: RE: Dict Copy & Compare
> 
> On quick question, how can I order a dict by the 'values' (not keys)
> before
> looping? Is that possible?
> 

The easiest way I can think of is to create a new dict that's reversed.

reverseDict = {}
for key in dict1:
if dict1[key] not in reverseDict:
reverseDict[dict1[key]]=[key]
else:
reverseDict[dict1[key]].append(key)

This gives you a dictionary that has the old dict's values as keys, and
the old dict's keys as lists of values.  You can then sort the keys of
this dict and do what you want with it.  Of course, the values in dict1
have to be valid dictionary keys for this to work.  If they aren't, you
may be able to get away with converting them to strings.



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


  1   2   >