Re: how to remove multiple occurrences of a string within a list?

2007-04-04 Thread Hendrik van Rooyen
"bahoo" <[EMAIL PROTECTED]> wrote:


> On Apr 3, 2:31 pm, "Matimus" <[EMAIL PROTECTED]> wrote:
> > It depends on your application, but a 'set' might really be what you
> > want, as opposed to a list.
> >
> > >>> s = set(["0024","haha","0024"])
> > >>> s
> >
> > set(["0024","haha"])>>> s.remove("0024")
> > >>> s
> >
> > set(["haha"])
> 
> This sounds cool.
> But is there a command I can convert the "set" back to a "list"?
> 

Here is a general way to find the duplicates:

>>> duplist
[1, 2, 3, 4, 'haha', 1, 2, 3, 4, 5]
>>> copylist = duplist[:]
>>> for x in duplist:
 del(copylist[copylist.index(x)])
 if x in copylist:
  fullset.remove(x)
  
>>> fullset
set([5, 'haha'])
>>> list(fullset)
[5, 'haha']
>>> 

hth - Hendrik

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


Re: how to remove multiple occurrences of a string within a list?

2007-04-04 Thread Amit Khemka
On 3 Apr 2007 11:20:33 -0700, bahoo <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have a list like ['0024', 'haha', '0024']
> and as output I want ['haha']
>
> If I
> myList.remove('0024')
>
> then only the first instance of '0024' is removed.

To remove all items with multiple occurances in myList:

list(set(myList) - set([x for x in myList if myList.count(x)>1]))

cheers,
-- 

Amit Khemka -- onyomo.com
Home Page: www.cse.iitd.ernet.in/~csd00377
Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Math with unicode strings?

2007-04-04 Thread Tim Roberts
"erikcw" <[EMAIL PROTECTED]> wrote:
>
>What do I need to do to extract the intergers from these unicode
>strings (or better yet, parse them as intergers in the first place.).
>I'm using the SAX method attrs.get('cls1',"") to parse the xml.  Can I
>"cast" the string into an interger?

When I see a typo once, I figure it's a typo, but when I see it three
times, I figure it is a misunderstanding.  The word is "integer", not
"interger".
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: way to extract only the message from pop3

2007-04-04 Thread Tim Roberts
"flit" <[EMAIL PROTECTED]> wrote:
>
>Using poplib in python I can extract only the headers using the .top,
>there is a way to extract only the message text without the headers?

Only by using Python code.  The other responses gave you good pointers
toward that path, but I thought I would point out the reason why.

The POP3 protocol is surprisingly primitive.  There are only two commands
to fetch a message: RETR, which fetches the headers and the entire message,
and TOP, which fetches the headers and the first N lines of the message.
The key point is that both commands fetch the headers.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Requirements For A Visualization Software System For 2010

2007-04-04 Thread Vityok

Xah Lee написав:
> REQUIREMENTS FOR A VISUALIZATION SOFTWARE SYSTEM FOR 2010
>
> Xah Lee, 2007-03-16
>
> In this essay, i give a list of requirements that i think is necessary
> for a software system for creating scientific visualization for the
> next decade (2007-2017).
>
> (for a HTML version with images, please see
> http://xahlee.org/3d/viz.html )
>

An interesting essay, of course it is much better to read the HTML
version (with illustrations).

With best regards,

Victor Anyakin
http://vityok.org.ua

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

how to build a forum?

2007-04-04 Thread kath
Hi everybody,

I am planning to build a web portal, which is mainly a discussion
forum for our corporate environment. I want to implement it with
Python. Because this project is very new to me and I have no idea
about how to go about this. I searched in google for getting some tuts/
guidelines about this but ended up in getting tuts for building
website.

I would like to know some useful links to learn or some usefull
guidelines.

I would appreciate your help,
Thanks in advance,
kath.

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


trying to check the creation date of a file

2007-04-04 Thread Geoff Bjorgan
Nice going…way to help!

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

Re: How can I time how much each thread takes?

2007-04-04 Thread 7stud
On Apr 3, 11:00 pm, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have the following code which spawn a number of thread and do
> something (in the run method of MyThread).
> how can I record how much time does EACH thread takes to complete the
> 'run'?
>
>   for j in range(threadCount):
> t = MyThread(testNo)
> threads.append(t)
> t.start()
> testNo += 1
>
>   for t in threads:
> print "len = %d", len(threads)
> t.join()
>
> I have read example of timeit.Timer() funcion, but I don' t know how
> can i use it in a multiple thread program?
> Thank you for any help.

How about this:

import time, threading

class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.begin = 0
self.end = 0

def run(self):
print "thread starting in background"
self.begin = time.time()
time.sleep(3)
self.end = time.time()
print "thread ending"

mt = MyThread()
mt.start()
print "main still running in foreground"

print "main going to wait for thread to end ."
mt.join()

diff = mt.end - mt.begin
print "Thread's run() time was: %.5f" % diff

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


how to build a forum in Python?

2007-04-04 Thread kath
Hi everybody,

I am planning to build a web portal, which is mainly a discussion
forum for our corporate environment. I want to implement it with
Python. Because this project is very new to me and I have no idea
about how to go about this. I searched in google for getting some tuts/
guidelines about this but ended up in getting tuts for building
website in PHP.

I would like to know some useful links to learn or some usefull
guidelines to build my fourm in Python.

Also is any forums which are built using Python?

I would appreciate your help,
Thanks in advance,
kath.

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


zip list with different length

2007-04-04 Thread s99999999s2003
hi
suppose i have 2 lists, a, b then have different number of elements,
say len(a) = 5, len(b) = 3
>>> a = range(5)
>>> b = range(3)
>>> zip(b,a)
[(0, 0), (1, 1), (2, 2)]
>>> zip(a,b)
[(0, 0), (1, 1), (2, 2)]

I want the results to be
[(0, 0), (1, 1), (2, 2) , (3) , (4) ]
can it be done?
thanks

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


Re: how to remove multiple occurrences of a string within a list?

2007-04-04 Thread 7stud
On Apr 3, 3:53 pm, "bahoo" <[EMAIL PROTECTED]> wrote:
> > target = "0024"
> > l = ["0024", "haha", "0024"]
>
>
> > for index, val in enumerate(l):
> > if val==target:
> > del l[index]
>
> > print l
>
> This latter suggestion (with the for loop) seems to be buggy: if there
> are multiple items in the list "l" equal to "target", then only the
> first one will be removed!
>
> Thanks anyways.

Prove it.


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


Re: Need help on reading line from file into list

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

> I don't see where the "str" came from, so perhaps the output of
> "open('source.txt').readlines()" is defaulted to "str?

Apart from Grant's explanation that str is the type of a string, what you 
perhaps haven't yet grasped is that if you have a type and an instance of 
that type there is an equivalence between calling a method on the instance, 
or calling the method directly on the type and passing the instance as the 
first parameter.

i.e. Given a type T and an instance I (so that type(I)==T) the following 
two are equivalent:

I.method(args)
T.method(I, args)

what that means in this particular case is that if you have a string 
'line' and want to strip leading and trailing whitespace you can call 
either:

   line.strip()
or:
   str.strip(line)

So str.strip is just another way to refer to the strip method of a str (but 
you do have to know that the line is a str rather than another type or it 
won't work).
-- 
http://mail.python.org/mailman/listinfo/python-list


Meetup in Amsterdam

2007-04-04 Thread [EMAIL PROTECTED]
I'm going to Amsterdam friday the 6. and would like to grab a beer
with anyone interested in Python and possible Django development.

My company is looking into building a CMS based on Django.

Mail me at martinskou [at] gmail [dot] com.

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


Re: Tkinter, how to get a button's bg color

2007-04-04 Thread James Stroud
John McMonagle wrote:
> [EMAIL PROTECTED] wrote:
>> I am new to Tkinter.  Following an example, I executed the following:
>>
>> window = Tk()
>> b = Button(window)
>> b.configure(bg = '#FF00FF')
>> b.grid(row = 0, column = 0)
>>
>> how can I later get the value of this button's background color?
>>
>> Thanks.
>>
> 
> b.cget('bg')
> 
> 

Even more fun is b['bg']

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


Re: how can I clear a dictionary in python

2007-04-04 Thread Antoon Pardon
On 2007-04-03, Aahz <[EMAIL PROTECTED]> wrote:
> In article <[EMAIL PROTECTED]>,
> Larry Bates  <[EMAIL PROTECTED]> wrote:
>>Aahz wrote:
>>> In article <[EMAIL PROTECTED]>,
>>> Larry Bates  <[EMAIL PROTECTED]> wrote:
 [EMAIL PROTECTED] wrote:
>
> I create a dictionary like this
> myDict = {}
>
> and I add entry like this:
> myDict['a'] = 1
> but how can I empty the whole dictionary?
 just point myDict to an empty dictionary again

 myDict={}
>>> 
>>> Go back and read Christian's post, then post a followup explaning why his
>>> solution is better than yours.  Your explanation should use id().
>>
>>I believe he (as many new to Python do) are mired in old programming
>>thinking that variables "contain" things.  As I'm sure you kno,
>>variables point to things in Python.  I don't believe that there are
>>lots of other objects pointing to this dictionary.  Perhaps the OP
>>can clarify for us.  If there aren't other objects pointing to this
>>dictionary it would make NO sense to iterate over a dictionary and
>>delete all the keys/values so I tried to read between the lines and
>>answer what I believe the OP thought he was asking.
>
> Then you should explain why you didn't answer the question that was
> asked.  Answering a different question without explanation makes your
> answer irrelevant at best, wrong at worst.

This is not true. If this different question was in fact the intended
question instead of the one actually asked. Anwering this different
question can be more usefull than answering the one actually asked.

People are often enough not very exact in their communication and
that goes double for people who are new in a particular subject.
So I think it is entirely appropiate to think about the real question
the person is strugling with that hides between the question
actually asked.

Yes sometimes those who try to guess the intentions of the OP
are going totally off in the wrong direction. But I have also
seen those people providing very helpfull information, while
those that would stick to the "actual" question didn'y provide
very usefull information.

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


Re: zip list with different length

2007-04-04 Thread ginstrom
On Apr 4, 4:53 pm, [EMAIL PROTECTED] wrote:
> elements, say len(a) = 5, len(b) = 3
> >>> a = range(5)
> >>> b = range(3)
...
> I want the results to be
> [(0, 0), (1, 1), (2, 2) , (3) , (4) ]
> can it be done?

A bit cumbersome, but at least shows it's possible:

>>> def superZip( a, b ):
common = min( len(a), len(b) )
results = zip( a[:common], b[:common] )
if len( a ) < len( b ):
a = b
return results + [ (x,) for x in a[common:] ]

>>> superZip( range( 5 ), range( 3 ) )
[(0, 0), (1, 1), (2, 2), (3,), (4,)]
>>> superZip( range( 3 ), range( 5 ) )
[(0, 0), (1, 1), (2, 2), (3,), (4,)]
>>> superZip( range( 0 ), range( 5 ) )
[(0,), (1,), (2,), (3,), (4,)]
>>> superZip( range( 3 ), range( 3 ) )
[(0, 0), (1, 1), (2, 2)]

Regards,
Ryan Ginstrom

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


Re: Requirements For A Visualization Software System For 2010

2007-04-04 Thread James Stroud
Check out pymol.

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


Re: zip list with different length

2007-04-04 Thread MC
Hi!

Brutal, not exact answer, but:

a = range(5)
b = range(3)
print zip(a+[None]*(len(b)-len(a)),b+[None]*(len(a)-len(b)))





-- 
@-salutations

Michel Claveau


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


Re: zip list with different length

2007-04-04 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> suppose i have 2 lists, a, b then have different number of elements,
> say len(a) = 5, len(b) = 3
 a = range(5)
 b = range(3)
 zip(b,a)
> [(0, 0), (1, 1), (2, 2)]
 zip(a,b)
> [(0, 0), (1, 1), (2, 2)]
> 
> I want the results to be
> [(0, 0), (1, 1), (2, 2) , (3) , (4) ]
> can it be done?
> thanks

from itertools import izip, chain, repeat, takewhile, starmap

def zip_longest(*seqs):
padded = [chain(izip(s), repeat(())) for s in seqs]
return takewhile(bool, starmap(sum, izip(izip(*padded), repeat(()

Just to bring itertools to your attention :-)

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


Re: heap doesn't appear to work as described

2007-04-04 Thread 7stud
On Apr 3, 10:30 pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
> |
> |>> My book says that in a heap, a value at position i will be smaller
> |>> than the values at positions 2*i and 2*i + 1.
>
> I am sure your book either uses 1-based arrays or a 0-based arrays with the
> first not used.  The need to keep these alternatives in mind is an
> unfortunate fact of programming  life.
>

My book uses lists.

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


optparse option prefix

2007-04-04 Thread Mathias Waack
We've integrated python into a legacy application. Everything works fine (of
course because its python;). There's only one small problem: the
application reads the commandline and consumes all arguments prefixed with
a '-' sign. Thus its not possible to call a python module from the
commandline with a parameter list containing options prefixed by '-'
or '--' signs. Thats not a major problem, but it prevents us from using th
optparse module. Is there a way to change to prefix, so one could use a '+'
(for instance) to mark command line options for optparse?

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


Re: Need help on reading line from file into list

2007-04-04 Thread bearophileHUGS
Bruno Desthuilliers:
> result = [line.strip() for line in f.readlines()]

Probably better, lazily:
result = [line.strip() for line in infile]

Bye,
bearophile

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


Re: File Object behavior

2007-04-04 Thread Bruno Desthuilliers
Michael Castleton a écrit :
> 
> 
> Bruno Desthuilliers wrote:
>> Michael Castleton a écrit :
>>> When I open a csv or txt file with:
>>>
>>> infile = open(sys.argv[1],'rb').readlines()
>>> or 
>>> infile = open(sys.argv[1],'rb').read()
>>>
>>> and then look at the first few lines of the file there is a carriage
>>> return
>>> + 
>>> line feed at the end of each line - \r\n
>> Is there any reason you open your text files in binary mode ?
>>
(snip)


> Bruno,
> No particular reason in this case. It was probably as a holdover from using
> the csv module in the past.  I'm wondering though if using binary on very
> large
> files (>100Mb) would save any processing time - no conversion to system
> newline?
> What do you think?

I think that premature optimization is the root of all evil.

You'll have to do the processing by yourself then, and I doubt it'll be 
as fast as the C-coded builtin newline processing.

Anyway, you can easily check it out by yourself - Python has timeit (for 
micro-benchmarks) and a profiler.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: zip list with different length

2007-04-04 Thread Alexander Schmolck
[EMAIL PROTECTED] writes:

C> hi
> suppose i have 2 lists, a, b then have different number of elements,
> say len(a) = 5, len(b) = 3
> >>> a = range(5)
> >>> b = range(3)
> >>> zip(b,a)
> [(0, 0), (1, 1), (2, 2)]
> >>> zip(a,b)
> [(0, 0), (1, 1), (2, 2)]
> 
> I want the results to be
> [(0, 0), (1, 1), (2, 2) , (3) , (4) ]
> can it be done?

map(lambda *t: filter(lambda x: x is not None,t),a,b)

'as

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


Re: how to remove multiple occurrences of a string within a list?

2007-04-04 Thread Steven D'Aprano
On Wed, 04 Apr 2007 00:59:23 -0700, 7stud wrote:

> On Apr 3, 3:53 pm, "bahoo" <[EMAIL PROTECTED]> wrote:
>> > target = "0024"
>> > l = ["0024", "haha", "0024"]
>>
>>
>> > for index, val in enumerate(l):
>> > if val==target:
>> > del l[index]
>>
>> > print l
>>
>> This latter suggestion (with the for loop) seems to be buggy: if there
>> are multiple items in the list "l" equal to "target", then only the
>> first one will be removed!
>>
>> Thanks anyways.
> 
> Prove it.

Try replacing l = ["0024", "haha", "0024"]
with 

l = ["0024", "0024", "haha"]

and re-running the code.


Actually, the description of the bug isn't quite right. The behaviour of
the for loop isn't defined -- sometimes it will work, sometimes it won't,
depending on how many items there are, and which of them are equal to the
target.

The reason it is buggy is that it is deleting items from the same list it
is trying to enumerate over. The only safe way to do that is to iterate
over the list backwards, only deleting items you've already seen and won't
go over again:

for i in range(len(my_list), -1, -1)):
if condition:
del my_list[i]


I don't think reversed() will help you here, but I can't check for sure
because I've only got Python 2.3 on this system.


-- 
Steven D'Aprano 


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


Re: zip list with different length

2007-04-04 Thread Alexander Schmolck
MC <[EMAIL PROTECTED]> writes:

> Hi!
> 
> Brutal, not exact answer, but:
> 
> a = range(5)
> b = range(3)
> print zip(a+[None]*(len(b)-len(a)),b+[None]*(len(a)-len(b)))

You reinvented map(None,a,b).

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


Re: how to remove multiple occurrences of a string within a list?

2007-04-04 Thread mik3l3374

7stud wrote:
> On Apr 3, 3:53 pm, "bahoo" <[EMAIL PROTECTED]> wrote:
> > > target = "0024"
> > > l = ["0024", "haha", "0024"]
> >
> >
> > > for index, val in enumerate(l):
> > > if val==target:
> > > del l[index]
> >
> > > print l
> >
> > This latter suggestion (with the for loop) seems to be buggy: if there
> > are multiple items in the list "l" equal to "target", then only the
> > first one will be removed!
> >
> > Thanks anyways.
>
> Prove it.
here's something:

>>> l = ["0024", "haha", "0024", "0024", "sfs"]
>>> target = "0024"
>>> for index, val in enumerate(l):
...  print "index: " , index , "value: " , val
...  del l[index]
...  print "after del: " , l
...
index:  0 value:  0024
after del:  ['haha', '0024', '0024', 'sfs']
index:  1 value:  0024
after del:  ['haha', '0024', 'sfs']
index:  2 value:  sfs
after del:  ['haha', '0024']
>>> l
['haha', '0024']

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


Re: how to remove multiple occurrences of a string within a list?

2007-04-04 Thread mik3l3374
On Apr 4, 2:20 am, "bahoo" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have a list like ['0024', 'haha', '0024']
> and as output I want ['haha']
>
> If I
> myList.remove('0024')
>
> then only the first instance of '0024' is removed.
>
> It seems like regular expressions is the rescue, but I couldn't find
> the right tool.
>
> Thanks!
> bahoo

how about this:
>>> target = "0024"
>>> l = ["0024", "haha", "0024", "0024", "sfs"]
>>> result = [ item for item in l if item != target]
>>> result
['haha', 'sfs']

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


Re: optparse option prefix

2007-04-04 Thread Steven D'Aprano
On Wed, 04 Apr 2007 08:52:48 +, Mathias Waack wrote:

> We've integrated python into a legacy application. Everything works fine (of
> course because its python;). There's only one small problem: the
> application reads the commandline and consumes all arguments prefixed with
> a '-' sign. Thus its not possible to call a python module from the
> commandline with a parameter list containing options prefixed by '-'
> or '--' signs. Thats not a major problem, but it prevents us from using th
> optparse module. Is there a way to change to prefix, so one could use a '+'
> (for instance) to mark command line options for optparse?

You have the source code. Does it look like the "-" is hard-coded in the
module?

Some solutions:

(1) Fork the code. It's open source, you should be able to copy the code
into a new module while still obeying the licence. (Note: open source does
not mean "I can do anything I want". There is still a licence, but it is a
very user-friendly licence. Read it and obey it.) Duplicate the file and
change all the relevant "-" signs to "+" signs.


(2) Are you sure you need to be using optparse? It sounds like an very
non-standard use of the module to me. Perhaps there is a simpler
alternative.


(3) Create a filter module that reads sys.argv, replaces leading "+" signs
with "-" signs, and then stuffs it back into sys.argv before optparse gets
to see it.


-- 
Steven D'Aprano 

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


operator overloading

2007-04-04 Thread looping
Hi,
for the fun I try operator overloading experiences and I didn't
exactly understand how it works.

Here is my try:
>>> class myint(int):
def __pow__(self, value):
return self.__add__(value)

>>> a = myint(3)
>>> a ** 3
6

OK, it works. Now I try different way to achieve the same result but
without much luck:

>>> class myint(int):
pass
>>> myint.__pow__ = myint.__add__

or:
>>> class myint(int):
__pow__ = int.__add__

or:
>>> class myint(int):
pass
>>> a.__pow__ = a.__add__

but for every try the result was the same:
>>> a = myint(3)
>>> a ** 3
27

Why it doesn't works ?

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


SNMP agent

2007-04-04 Thread alain
Hi,

I have a Python app and i would like to add some SNMP agent
functionality to it.
I know it's possible to write a sub-agent with netsnmp but it is in C
and quite complicated.
I know of YAPSNMP (a wrapper around NETSNMP) but it doesn't seem to
support agent writing.
Any suggestion ?

Thanks to all in advance

Alain

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


bool value 'False' no memory address?

2007-04-04 Thread autin
such as:
>>>b = False
>>>id(b)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: 'bool' object is not callable

---
how to desc it?

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


Re: bool value 'False' no memory address?

2007-04-04 Thread Jakub Stolarski
On Apr 4, 12:36 pm, "autin" <[EMAIL PROTECTED]> wrote:
> such as:>>>b = False
> >>>id(b)
>
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: 'bool' object is not callable
>
> ---
> how to desc it?

>>> b = False
>>> id(b)
135311308
>>>

python 2.4, FreeBSD 6.2

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


Re: bool value 'False' no memory address?

2007-04-04 Thread Tim Golden
Jakub Stolarski wrote:
> On Apr 4, 12:36 pm, "autin" <[EMAIL PROTECTED]> wrote:
>> such as:>>>b = False
> id(b)
>> Traceback (most recent call last):
>>   File "", line 1, in ?
>> TypeError: 'bool' object is not callable
>>
>> ---
>> how to desc it?
> 
 b = False
 id(b)
> 135311308
> 
> python 2.4, FreeBSD 6.2
> 

The OP's almost certainly accidentally used
"id" as a flag somewhere previously:


id = True
#
# .. do other stuff
#
b = False
id (b)


Also, I'm not quite sure what he wants to
do with the id, which is only the machine
address (if that's what it is) by implementation
detail.

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


Re: how to remove multiple occurrences of a string within a list?

2007-04-04 Thread Maël Benjamin Mettler
How about:

list(frozenset(['0024', 'haha', '0024']))

[EMAIL PROTECTED] schrieb:
> On Apr 4, 2:20 am, "bahoo" <[EMAIL PROTECTED]> wrote:
>> Hi,
>>
>> I have a list like ['0024', 'haha', '0024']
>> and as output I want ['haha']
>>
>> If I
>> myList.remove('0024')
>>
>> then only the first instance of '0024' is removed.
>>
>> It seems like regular expressions is the rescue, but I couldn't find
>> the right tool.
>>
>> Thanks!
>> bahoo
> 
> how about this:
 target = "0024"
 l = ["0024", "haha", "0024", "0024", "sfs"]
 result = [ item for item in l if item != target]
 result
> ['haha', 'sfs']
> 

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


Re: RSS feed parser

2007-04-04 Thread Florian Lindner
[EMAIL PROTECTED] wrote:

> On Apr 2, 10:20 pm, Florian Lindner <[EMAIL PROTECTED]> wrote:
>> Some of the question I have but found answered nowhere:
>>
>> I have a feedparser object that was created from a string. How can I
>> trigger a update (from a new string) but the feedparser should treat the
>> new string like the same feed (thus setting feed.updated etc.).
> 
> Hmm. Do you mean that the feed object should stay the same? Like the
> difference between "a = [1,2,3]; a = [1,2,3]+[4]" and "a = [1,2,3];
> a.append(4)"? I glanced at the parse function in the source code and
> it looks like it's not directly possible. You could modify it so that
> the "result" dictionary is optionally given as an argument, so when
> updating you'd do: feedparser.parse(string, oldFeed). You'd also have
> to clear the oldFeed object before update.
> 
> But you might also be able to solve the problem by using an additional
> layer of indirection. Instead of passing around the "feed" object,
> you'd pass around a proxy object like this:
> 
> class Empty: pass
> proxy = Empty()
> proxy.feed = feedparser.parse(string)
> storeProxyForLaterUse(proxy)
> proxy.feed = feedparser.parse(string2)
> useStoredProxy() #this would use the updated feed through the proxy
> 
> Then just use proxy.feed.updated everywhere instead of directly
> feed.updated. A smarter proxy would automatically translate
> proxy.updated into proxy.feed.updated so usage would stay as simple as
> without the proxy. Doing this is quite easy in Python (search for
> __getattr__ examples).

I already use something like that (with __getattr__). The problem is that
with this way there is still a new feed object created everytime a new
string needs to be passed to.
But since I want to use use the updated_parsed etc. function it's not
possible that each time the feed is parsed a new object is created (the
update times will always be the time of the last parsing).

Any idea?

Regards,

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


Re: bool value 'False' no memory address?

2007-04-04 Thread Bruno Desthuilliers
autin a écrit :
> such as:
 b = False
 id(b)
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: 'bool' object is not callable
> 

IMVHO, you shadowed the builtin id() function with a boolean somewhere 
else...

Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02)
[GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> b = False
 >>> id(b)
135506080
 >>>
 >>> id = False
 >>> id(b)
Traceback (most recent call last):
   File "", line 1, in ?
TypeError: 'bool' object is not callable
 >>>

My 2 cents...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bool value 'False' no memory address?

2007-04-04 Thread autin
Python 2.4.4 Linux debian 2.6.8-3-386
any wrong?
> > ---
> > how to desc it?
> >>> b = False
> >>> id(b)
> 135311308
>
> python 2.4, FreeBSD 6.2


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


Re: Need help on reading line from file into list

2007-04-04 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> Bruno Desthuilliers:
>> result = [line.strip() for line in f.readlines()]
> 
> Probably better, lazily:
> result = [line.strip() for line in infile]

This is of course better in the general case, but I wanted to stay 
consistant with the other examples...

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


Re: optparse option prefix

2007-04-04 Thread Diez B. Roggisch
> 
> (3) Create a filter module that reads sys.argv, replaces leading "+" signs
> with "-" signs, and then stuffs it back into sys.argv before optparse gets
> to see it.

That's not even necessary, the optparser will work on a passed argument
list. No need to alter sys.argv.

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


Re: how to build a forum in Python?

2007-04-04 Thread [EMAIL PROTECTED]
There are several different web frameworks in which a forum can be
implemented. Try to take a look at Django and Turbogear. You will need
to put some time into learning the framework.

But, if you want an easy "copy-paste" forum solution, I guess you will
be better of with one of the PHP open source forums.

/Martin

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


Re: bool value 'False' no memory address?

2007-04-04 Thread autin
and test on
Python 2.3.5
2.4.32 debian
is ok!maybe its bug for unstable debian version!

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


Re: bool value 'False' no memory address?

2007-04-04 Thread autin
My false!uh,i didnot understand it clearly.


On Apr 4, 6:46 am, Bruno Desthuilliers  wrote:
> autin a écrit :
>
> > such as:
>  b = False
>  id(b)
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> > TypeError: 'bool' object is not callable
>
> IMVHO, you shadowed the builtin id() function with a boolean somewhere
> else...
>
> Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02)
> [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> b = False
>  >>> id(b)
> 135506080
>  >>>
>  >>> id = False
>  >>> id(b)
> Traceback (most recent call last):
>File "", line 1, in ?
> TypeError: 'bool' object is not callable
>  >>>
>
> My 2 cents...


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


Re: how to remove multiple occurrences of a string within a list?

2007-04-04 Thread Bruno Desthuilliers
bahoo a écrit :
> Hi,
> 
> I have a list like ['0024', 'haha', '0024']
> and as output I want ['haha']
> 
> If I
> myList.remove('0024')
> 
> then only the first instance of '0024' is removed.
> 
> It seems like regular expressions is the rescue, 

Nope. re wouldn't help here - it works on strings, not on lists (you 
need to understand that in Python, strings are *not* 'lists of chars').

Use list comps:
   mylist = [item for item in mylist if item != '0024']

or filter() :
   mylist = filter(lambda item: item != '0024', mylist)


> but I couldn't find
> the right tool.

May I second Grant Edward's suggestion in previous thread ? You'd really 
do yourself a favor by following a couple Python tutorials. I'd say the 
one in the official doc, and Dive into Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling Fortran from Python

2007-04-04 Thread Mangabasi
Robert,

Thanks for your prompt response.  I think I got a lot closer but no
cigar yet.

This is the output

C:\fortrandll>f2py -c -m sample sample.pyf sample.for
numpy_info:
  FOUND:
define_macros = [('NUMERIC_VERSION', '"\\"24.2\\""')]
include_dirs = ['C:\\Python24\\include']

running build
running config_fc
running build_src
building extension "sample" sources
creating c:\docume~1\fb\locals~1\temp\tmpcosvgv
creating c:\docume~1\fb\locals~1\temp\tmpcosvgv\src
f2py: sample.pyf
Reading fortran codes...
Reading file 'sample.pyf'
Post-processing...
Block: sample
Block: sample
Post-processing (stage 2)...
Building modules...
Building module "sample"...
Constructing wrapper function "sample"...
  ierr1,ierr2,aout = sample(ain)
Wrote C/API module "sample" to file "c:\docume~1\fb
\locals~1\temp\tmpcos
vgv\src/samplemodule.c"
  adding 'c:\docume~1\fb\locals~1\temp\tmpcosvgv\src\fortranobject.c'
to sources
.
  adding 'c:\docume~1\fb\locals~1\temp\tmpcosvgv\src' to include_dirs.
copying C:\python24\lib\site-packages\f2py2e\src\fortranobject.c -> c:
\docume~1\
fb\locals~1\temp\tmpcosvgv\src
copying C:\python24\lib\site-packages\f2py2e\src\fortranobject.h -> c:
\docume~1\
fb\locals~1\temp\tmpcosvgv\src
running build_ext
No module named msvccompiler in scipy_distutils, trying from
distutils..
error: The .NET Framework SDK needs to be installed before building
extensions f
or Python.

I think I have a problem with distutils' msvccompiler.py.  It may be
the MacroExpander in distutils guessing the visual studio path
incorrectly or something related to the registry keys.  Is there a way
to specify the C compiler path to f2py so that it does not rely on the
distutils?  Or maybe I am totally off base here, I don't know.

Any thoughts?


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


Pexpect: SSH, Command and Password

2007-04-04 Thread Gil_H
Hi,

I'm trying to run a script over unix on a remote machine.
In order to automate it, the procedure requests the following:
1. Using SSH connection.
2. Operating a command on the remote machine.
3. Expecting password or (yes/no) request and authorize it.

I get an error (I thing that it occures at the last part (3) of the
password request).
I don't have any errors when trying to operate the script without the
last password.
Here is the script:

import pexpect
import sys
import re
import os
import getopt

PROMPT = "\$|\%|\>"


class SSH:
def __init__(self, user, password, host):
self.child = pexpect.spawn("ssh [EMAIL PROTECTED]"%(user, host))
i = self.child.expect(['assword:', r'yes/no'],
timeout=120)
if i==0:
self.child.sendline(password)
elif i==1:
self.child.sendline("yes")
self.child.expect("assword:", timeout=120)
self.child.sendline(password)
self.child.expect(PROMPT)

def command(self, command, password):
"""send a command and return the response"""
self.child.expect(PROMPT)
self.child.sendline(command)
j = self.child.expect(['assword:', r'yes/no'],
timeout=120)
if j==0:
self.child.sendline(password)
elif j==1:
self.child.sendline("yes")
self.child.expect("assword:", timeout=120)
self.child.sendline(password)
self.child.expect(PROMPT)

#   response = self.child.before
#   return response

def close(self):
"""close the connection"""
self.child.close()


if __name__=="__main__":

ssh = SSH(sys.argv[1], sys.argv[2], sys.argv[3])
command=sys.argv[4]
print command
print "Password: " + sys.argv[2]
responce=ssh.command(command, sys.argv[2])
ssh.close()
print responce


I'm waiting for your ideas.
Thanks,
Gil H.

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


Re: how to build a forum in Python?

2007-04-04 Thread olive
http://code.google.com/p/diamanda/

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


Re: SNMP agent

2007-04-04 Thread alf
alain wrote:
> Hi,
> 
> I have a Python app and i would like to add some SNMP agent
> functionality to it.
> I know it's possible to write a sub-agent with netsnmp but it is in C
> and quite complicated.
> I know of YAPSNMP (a wrapper around NETSNMP) but it doesn't seem to
> support agent writing.
> Any suggestion ?
> 
> Thanks to all in advance
> 
> Alain
> 

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


Re: SNMP agent

2007-04-04 Thread alain
On Apr 4, 1:30 pm, alf <[EMAIL PROTECTED]> wrote:

> twistedmatrix.org?

I already took a look at it but the agent functionality is somewhat
primitive. I need something production-ready.

Alain

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


Re: how to build a forum?

2007-04-04 Thread Steve Holden
kath wrote:
> Hi everybody,
> 
> I am planning to build a web portal, which is mainly a discussion
> forum for our corporate environment. I want to implement it with
> Python. Because this project is very new to me and I have no idea
> about how to go about this. I searched in google for getting some tuts/
> guidelines about this but ended up in getting tuts for building
> website.
> 
> I would like to know some useful links to learn or some usefull
> guidelines.
> 
> I would appreciate your help,
> Thanks in advance,

Without wishing to dampen your enthusiasm, it seems like you are putting 
the cart before the horse here if the goal is "build a web portal". 
Could it be that the real goal is to learn Python, and the web portal is 
a vehicle for that?

If not then you should use one of many already-extant web portals (you 
could surely find one written in Python if necessary) rather than 
developing one from scratch? Nuxeo comes to mind, but they've now 
switched from Python to Java ...

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings   http://holdenweb.blogspot.com

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


Re: Calling Fortran from Python

2007-04-04 Thread Mangabasi
There may be a way to finish this without having to deal with
distutils.
F2py created three files so far

samplemodule.c
fortranobject.h
fortranobject.c

Is there a way to create the sample.pyd from these files?

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


Re: Pexpect: SSH, Command and Password

2007-04-04 Thread Ganesan Rajagopal
> "Gil" == Gil H <[EMAIL PROTECTED]> writes:

> class SSH:
> def __init__(self, user, password, host):
> self.child = pexpect.spawn("ssh [EMAIL PROTECTED]"%(user, 
> host))

Try adding the following line here

self.child.logfile = sys.stdout

That should give you some clue.

Ganesan


-- 
Ganesan Rajagopal

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


Re: optparse option prefix

2007-04-04 Thread Mathias Waack
Diez B. Roggisch wrote:
>> (3) Create a filter module that reads sys.argv, replaces leading "+"
>> signs with "-" signs, and then stuffs it back into sys.argv before
>> optparse gets to see it.
> 
> That's not even necessary, the optparser will work on a passed argument
> list. No need to alter sys.argv.

Sounds nice, I'll do so. Thanks!

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


Re: heap doesn't appear to work as described

2007-04-04 Thread skip

skip> Check the heapq docs for the constraints the Python heapq module
skip> maintains:

s/constraints/invariants/

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


Re: Pexpect: SSH, Command and Password

2007-04-04 Thread Gil_H
On 4 Apr, 15:14, Ganesan Rajagopal <[EMAIL PROTECTED]> wrote:
> > "Gil" == Gil H <[EMAIL PROTECTED]> writes:
> > classSSH:
> > def __init__(self, user, password, host):
> > self.child =pexpect.spawn("[EMAIL PROTECTED]"%(user, host))
>
> Try adding the following line here
>
> self.child.logfile = sys.stdout
>
> That should give you some clue.
>
> Ganesan
>
> --
> Ganesan Rajagopal

Thanks,

That's all i needed!

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


Re: heap doesn't appear to work as described

2007-04-04 Thread skip

 My book says that in a heap, a value at position i will be than the
 values at positions 2*i and 2*i + 1.

>> I am sure your book either uses 1-based arrays or a 0-based arrays
>> with the first not used.  The need to keep these alternatives in mind
>> is an unfortunate fact of programming life.

> My book uses lists.

Yes, but is the first element of the list addressed as element 1 or element
0?  Terry was doing the transformation from 1-based to 0-based indexing to
demonstrate that the invariants you described were the same as those
maintained by Python's heapq module.

Skip

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


An error of matrix inversion using NumPy

2007-04-04 Thread lancered
Hi dear all,
I am using Python2.4.2+NumPy1.0.1 to deal with a parameter
estimation problem with the least square methods. During the
calculations, I use  NumPy package to deal with matrix operations,
mostly matrix inversion and trasposition. The dimentions of the
matrices used are about 29x19,19x19 and 29x29.

During the calculation, I noticed an apparent error of
inverion of a 19x19 matrix. Denote this matrix as KK, U=KK^ -1, I
found the product of U and KK is not equivalent to unit matrix! This
apparently violate the definition of inversion. The inversion is
through the function linalg.inv().

   I have checked that det(KK)=-1.2E+40. At first, I thought the
error may be caused by such a large determinant, so I scaled it as
LL=KK/100, then invert LL. Since det(LL)=11.5 and all its elements are
within -180.0 to 850.0, this seems easier. But the result is still not
correct, the product of LL^-1 thus obtained and LL still not unit
matrix ... At the same time, the inversion results of some 29x19
matrices are correct.

   So,  can you tell me what goes wrong?  Is this a bug in
Numpy.linalg? How to deal with this situation?  If you need, I can
post the matrix I used below, but it is so long,so not at the moment.

   Thanks in advance!

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


An error of matrix inversion using NumPy

2007-04-04 Thread lancered
Hi dear all,
I am using Python2.4.2+NumPy1.0.1 to deal with a parameter
estimation problem with the least square methods. During the
calculations, I use  NumPy package to deal with matrix operations,
mostly matrix inversion and trasposition. The dimentions of the
matrices used are about 29x19,19x19 and 29x29.

During the calculation, I noticed an apparent error of
inverion of a 19x19 matrix. Denote this matrix as KK, U=KK^ -1, I
found the product of U and KK is not equivalent to unit matrix! This
apparently violate the definition of inversion. The inversion is
through the function linalg.inv().

   I have checked that det(KK)=-1.2E+40. At first, I thought the
error may be caused by such a large determinant, so I scaled it as
LL=KK/100, then invert LL. Since det(LL)=11.5 and all its elements are
within -180.0 to 850.0, this seems easier. But the result is still not
correct, the product of LL^-1 thus obtained and LL still not unit
matrix ... At the same time, the inversion results of some 29x19
matrices are correct.

   So,  can you tell me what goes wrong?  Is this a bug in
Numpy.linalg? How to deal with this situation?  If you need, I can
post the matrix I used below, but it is so long,so not at the moment.

   Thanks in advance!

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


Re: An error of matrix inversion using NumPy

2007-04-04 Thread BJörn Lindqvist
On 4 Apr 2007 06:15:18 -0700, lancered <[EMAIL PROTECTED]> wrote:
> During the calculation, I noticed an apparent error of
> inverion of a 19x19 matrix. Denote this matrix as KK, U=KK^ -1, I
> found the product of U and KK is not equivalent to unit matrix! This
> apparently violate the definition of inversion. The inversion is
> through the function linalg.inv().

Could it have something to do with floating point accuracy?

>>> r = matrix([[random.random() *  for x in range(19)] for y in range(19)])
>>> allclose(linalg.inv(r) * r, identity(19))
True

>So,  can you tell me what goes wrong?  Is this a bug in
> Numpy.linalg? How to deal with this situation?  If you need, I can
> post the matrix I used below, but it is so long,so not at the moment.

Please post it.

-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An error of matrix inversion using NumPy

2007-04-04 Thread Dayong Wang
Here below is the matrix KK I used:

[[  1939.33617572   -146.94170404  0.  0.  0.
   0.  0.  0.  0.
-1172.61032101
   0.  0.   -193.69962687   -426.08452381  0.
   0.  0.  0.   1792.39447168]
 [  -146.94170404   5175.33392519   -442.4308390.  0.
   0.  0.  0.  0.  0.
   -3409.58801135  0.  0.  0.
-767.46969697
-408.90367384  0.  0.   4585.96138215]
 [ 0.   -442.430839 4373.33685159  0.  0.
   0.  0.  0.  0.  0.
   0.  -2354.70959362  0.  0.  0.
   0.   -855.36922061   -720.82719836   3930.90601259]
 [ 0.  0.  0.  17064.73017917
-949.49987581  0.  0.  0.  0.
   0.  0.  0. -16115.23030336  0.
   0.  0.  0.  0.
16115.23030336]
 [ 0.  0.  0.   -949.49987581
   11005.53604312  -1358.01000599  0.  0.  0.
   0.  0.  0.  0.
-8698.02616132
   0.  0.  0.  0.
8698.02616132]
 [ 0.  0.  0.  0.
-1358.01000599
   18322.57142994  -1495.29428718  0.  0.  0.
   0.  0.  0.  0.
-15469.26713677
   0.  0.  0.  15469.26713677]
 [ 0.  0.  0.  0.  0.
   -1495.29428718  12497.65812936  -1858.81899672  0.  0.
   0.  0.  0.  0.  0.
   -9143.54484546  0.  0.   9143.54484546]
 [ 0.  0.  0.  0.  0.
   0.  -1858.81899672  20170.17739075  -1249.5298217   0.
   0.  0.  0.  0.  0.
   0. -17061.82857234  0.  17061.82857234]
 [ 0.  0.  0.  0.  0.
   0.  0.  -1249.52982179476.04289846  0.
   0.  0.  0.  0.  0.
   0.  0.  -8226.51307677   8226.51307677]
 [ -1172.61032101  0.  0.  0.  0.
   0.  0.  0.  0.   1500.8055591
-328.1952381   0.  0.  0.  0.
   0.  0.  0.  -1172.61032101]
 [ 0.  -3409.58801135  0.  0.  0.
   0.  0.  0.  0.   -328.1952381
4112.15248021   -374.36923077  0.  0.  0.
   0.  0.  0.  -3409.58801135]
 [ 0.  0.  -2354.70959362  0.  0.
   0.  0.  0.  0.  0.
-374.36923077   2729.07882439  0.  0.  0.
   0.  0.  0.  -2354.70959362]
 [  -193.69962687  0.  0. -16115.23030336  0.
   0.  0.  0.  0.  0.
   0.  0.  17726.91399397  -1417.98406375  0.
   0.  0.  0. -16308.92993023]
 [  -426.08452381  0.  0.  0.
-8698.02616132
   0.  0.  0.  0.  0.
   0.  0.  -1417.98406375  12320.46305747
   -1778.36830859  0.  0.  0.
-9124.11068513]
 [ 0.   -767.46969697  0.  0.  0.
  -15469.26713677  0.  0.  0.  0.
   0.  0.  0.  -1778.36830859
   19552.18019195  -1537.07504962  0.  0.
-16236.73683374]
 [ 0.   -408.90367384  0.  0.  0.
   0.  -9143.54484546  0.  0.  0.
   0.  0.  0.  0.
-1537.07504962
   12983.70625768  -1894.18268877  0.  -9552.44851929]
 [ 0.  0.   -855.36922061  0.  0.
   0.  0. -17061.82857234  0.  0.
   0.  0.  0.  0.  0.
   -1894.18268877  21039.17951514  -1227.79903343 -17917.19779295]
 [ 0.  0.   -720.82719

Re: Question about using urllib2 to load a url

2007-04-04 Thread John J. Lee
"Kushal Kumaran" <[EMAIL PROTECTED]> writes:
[...]
> If, at any time, an error response fails to reach your machine, the
> code will have to wait for a timeout.  It should not have to wait
> forever.
[...]

...but it might have to wait a long time.  Even if you use
socket.setdefaulttimeout(), DNS lookups can block for a long time.
The way around that is to use Python threads (no need to try to "kill"
the thread that's doing the urlopen() -- just ignore that thread if it
takes too long to finish).

Looks like 2.6 will have socket timeouts exposed at the urllib2 level
(so no need to call socket.setdefaulttimeout() any more), but the need
to use threads with urllib2 to get timeouts will remain in many cases,
due to the DNS thing (the same applies to urllib, or any other module
that ends up doing DNS lookups).


John

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


Re: An error of matrix inversion using NumPy

2007-04-04 Thread Lou Pecora
In article <[EMAIL PROTECTED]>,
 "lancered" <[EMAIL PROTECTED]> wrote:

> Hi dear all,
> I am using Python2.4.2+NumPy1.0.1 to deal with a parameter
> estimation problem with the least square methods. During the
> calculations, I use  NumPy package to deal with matrix operations,
> mostly matrix inversion and trasposition. The dimentions of the
> matrices used are about 29x19,19x19 and 29x29.
> 
> During the calculation, I noticed an apparent error of
> inverion of a 19x19 matrix. Denote this matrix as KK, U=KK^ -1, I
> found the product of U and KK is not equivalent to unit matrix! This
> apparently violate the definition of inversion. The inversion is
> through the function linalg.inv().
> 
>I have checked that det(KK)=-1.2E+40. At first, I thought the
> error may be caused by such a large determinant, so I scaled it as
> LL=KK/100, then invert LL. Since det(LL)=11.5 and all its elements are
> within -180.0 to 850.0, this seems easier. But the result is still not
> correct, the product of LL^-1 thus obtained and LL still not unit
> matrix ... At the same time, the inversion results of some 29x19
> matrices are correct.
> 
>So,  can you tell me what goes wrong?  Is this a bug in
> Numpy.linalg? How to deal with this situation?  If you need, I can
> post the matrix I used below, but it is so long,so not at the moment.
> 
>Thanks in advance!
> 

Changing the overall scaling won't help unless the numbers themselves 
are near the double floating point boundary (perhaps).  The real number 
you want to calculate is the condition number of the matrix. Roughly the 
ratio of the largest to the smallest eigenvalue.  If that's large, then 
you're attempt at inversion is dealing with differences between very 
large and very small numbers and/or very small differences between two 
large numbers which probably goes beyond the number of digits (bits) the 
machine can provide to represent floating point numbers.  No rescaling 
of the original matrix will change that.  Do a google on "condition 
number".

-- Lou Pecora  (my views are my own) REMOVE THIS to email me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An error of matrix inversion using NumPy

2007-04-04 Thread Robin Becker
lancered wrote:
> Hi dear all,
..
> matrices are correct.
> 
>So,  can you tell me what goes wrong?  Is this a bug in
> Numpy.linalg? How to deal with this situation?  If you need, I can
> post the matrix I used below, but it is so long,so not at the moment.
...

presumably the matrix KK is actually some kind of normal matrix obtained from 
the data. So you have say n variables and m observations the data matrix is 
than 
an n x m real valued thing say D then you want the inverse of something like 
D'D 
ie an n by n thing. Typically the data D is de-meaned and normalized by the 
column norms so that you end up with a fairly well scaled problem.

A long time ago I used Numeric+python to do exactly this sort of calculation 
with excellent results and the matrices were as large or larger eg 100 x 100 
and 
above. I don't think the underlying numeric routines have changed that much. If 
your matrix is symmetric then you should certainly be using

Even if you can't post the matrix, perhaps you should indicate how you proceed 
from data to matrix. Another problem is that a large determinant is no 
guarantee 
of stability for the inversion. If the largest eigenvalue is 10**100 and the 
smallest 10**-200 I probably have an ill determined problem; surprisingly easy 
to achieve :(
-- 
Robin Becker

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


Re: Refactoring question

2007-04-04 Thread kyosohma
On Apr 3, 11:41 pm, "ginstrom" <[EMAIL PROTECTED]> wrote:
> > On Behalf Of Kevin Walzer
> > What's the best way to do this? Can anyone point me in the
> > right direction? How could, for instance, the top snippet be
> > rewritten to separate the Tkinter parts from the generic stuff?
>
> I like to use the broadcaster/broker recipe 
> athttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81983
>
> I added a few features (such as decorators for listener functions --
> see below sig).
> There are other recipes out there, such as PyDispatcher.
>
> Basically, I have GUI events translated into broadcaster events (by
> passing lambdas that call broadcaster.Broadcast() to the event
> binders), which are received by controller functions/classes.
>
> Feedback (status/progress) is also communicated via broadcaster
> events.
>
> Something I tried on my current project, which is going fairly well,
> is first writing a command-line version, then writing a GUI version,
> with the same controller back-end used in each case, and the
> controller communicating progress/results via the same interface. This
> approach has made me keep presentation and logic very loosely
> coupled.
>
> So for instance, the view class would send request for processing,
> which the controller gets.
> The controller performs the requested action, sending broadcasts of
> progress (note that the controller can start a worker thread for the
> processing, but the broadcasts should be made on the GUI thread...)
>
> broadcaster.Broadcast( "progress", "start", (100, "Doing your
> bidding now..." ) ) # number of items we will process
>
> # ...
> broadcaster.Broadcast( "progress", "progress", (i, "Working on
> item %i" % i ) ) # current item
> # ...
>
> broadcaster.Broadcast( "progress", "end", (100, "Done!") )
>
> Depending on who is showing the progress, this might go onto a status
> bar, progress dialog, the console, a log file, and so on, or some
> combination thereof -- the controller doesn't know or care.
>
> When the controller is finished, it asks the broker for a view, and
> calls show results on the view
>
> view = broker.Request( "view" )
> view.ShowResults( results )
>
> That could have been done equally with the broadcaster, but for some
> reason I like the broker here (it makes the view "dumber").
>
> Regards,
> Ryan
>
> --
> Ryan Ginstrom
>
> ==
> # listener decorators
>
> def BrokerRequestHandler( title ):
> """A decorator for broker listeners
>
> @param title: the title to provide
>
> The decorated function must take no arguments
> (it can retrieve them using CurrentData())
> """
>
> def decorator(func):
> broker.Register( title, func )
> return func
> return decorator
>
> def BroadcasterEventHandler( source, title ):
> """A decorator for broadcaster event handlers
>
> @param source: the broadcast source
> @param title: the title of the broadcast
>
> The decorated function must take no arguments
> (it can retrieve them using CurrentData())
> """
>
> def decorator(func):
> broadcaster.Register( func, source, title )
> return func
> return decorator
>
> # example ...
> @BrokerRequestHandler( "meaning of life" )
> def getMeaningOfLife():
> return 42
>
> ## A little more complicated for class methods. I stole this technique
> from WCK
>
> # Lifted shamelessly from WCK (effbot)'s wckTkinter.bind
> def EventHandler( source, title ):
> """Dectorator for event-handling methods"""
>
> def decorator(func):
> func.BroadcasterEvent = (source, title)
> return func
> return decorator
>
> class FrameController:
> """Controller for the main frame window"""
>
> def __init__( self ):
>
> for key in dir(self):
> method = getattr(self, key)
> if hasattr(method, "BroadcasterEvent") and
> callable(method):
> source, title = method.BroadcasterEvent
> broadcaster.Register( method,
>  source=source,
>  title=title )
>
> @EventHandler( "event", "onExport" )
> def onExport( self ):
> """Handles the onExport broadcast by exporting the database to
> the requested format"""
>
> format = broadcaster.CurrentData()
> # Perform export...

I usually put all my GUI code into their own methods(s) and call those
methods from the __init__(). I do the same with the logic (where
applicable). This makes the code easier to manipulate and/or import.

In wxPython, you can also use XRC to define most of the common
elements of you GUI. I've found this method to be very helpful in
keeping my code short and easy to read, for GUI code.

Mike

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


Re: An error of matrix inversion using NumPy

2007-04-04 Thread Robin Becker
Robin Becker wrote:
> lancered wrote:
h. If
> your matrix is symmetric then you should certainly be using


a qr decomposition I meant to say :)
-- 
Robin Becker

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


Symposium "Computational Methods in Image Analysis" within the USNCCM IX Congress - Announce & Call for Papers

2007-04-04 Thread [EMAIL PROTECTED]

-

(Apologies for cross-posting)

Symposium "Computational Methods in Image Analysis"
National Congress on Computational Mechanics (USNCCM IX)
San Francisco, CA, USA, July 22 - 26 2007
http://www.me.berkeley.edu/compmat/USACM/main.html

We would appreciate if you could distribute this information by your
colleagues and co-workers.

-


Dear Colleague,

Within the National Congress on Computational Mechanics (USNCCM IX),
to be held in San Francisco, CA, USA, July 22 - 26 2007, we are
organizing the Symposium "Computational Methods in Image Analysis".
Examples of some topics that will be considered in that symposium are:
Image acquisition, Image processing and analysis, Image segmentation,
3D Vision, Motion analysis, Pattern recognition, Objects recognition,
Medical imaging and Tools and applications.
Due to your research activities in those fields, we would like to
invite you to submit an abstract and participate in the symposium
"Computational Methods in Image Analysis".

For instructions and submission, please access to the congress website
at: http://www.me.berkeley.edu/compmat/USACM/main.html.
Please note, when submitting your abstract you should select
"Computational Methods in Image Analysis".

Important dates:

- Deadline for abstract submissions: May 1, 2007
- Final selection of abstracts: May 15, 2007
- Deadline for early registration: May 22, 2007
- Deadline for CD-ready abstracts: June 1, 2007
- Deadline for regular registration: July 15, 2007

We would appreciate if you could distribute this information by your
colleagues and co-workers.

Kind regards,

João Manuel R. S. Tavares
Renato Natal Jorge
Yongjie Zhang
Dinggang Shen
(Symposium organizers)

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


Re: Refactoring question

2007-04-04 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> On Apr 3, 11:41 pm, "ginstrom" <[EMAIL PROTECTED]> wrote:
>>> On Behalf Of Kevin Walzer
>>> What's the best way to do this? Can anyone point me in the
>>> right direction? How could, for instance, the top snippet be
>>> rewritten to separate the Tkinter parts from the generic stuff?
>> I like to use the broadcaster/broker recipe 
>> athttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81983

[lots of code that was pretty irrelevant to the reply]

> 
> I usually put all my GUI code into their own methods(s) and call those
> methods from the __init__(). I do the same with the logic (where
> applicable). This makes the code easier to manipulate and/or import.
> 
> In wxPython, you can also use XRC to define most of the common
> elements of you GUI. I've found this method to be very helpful in
> keeping my code short and easy to read, for GUI code.
> 
While talking about keeping things short and easy to read, maybe you 
could be a bit more considerate in your quoting practices. We really 
didn't need to see all the code quoted to hear what you had to say ...

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings   http://holdenweb.blogspot.com

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


Re: An error of matrix inversion using NumPy

2007-04-04 Thread lancered
Here is the eigenvalues of KK  I obtained:

 >>> linalg.eigvals(KK)
array([  1.11748411e+05,   3.67154458e+04,   3.41580846e+04,
 2.75272440e+04,   2.09790868e+04,   1.86242332e+04,
 8.68628325e+03,   6.66127732e+03,   6.15547187e+03,
 4.68626197e+03,   3.17838339e+03,   2.84888045e+03,
 1.88279736e+03,   1.32427574e+03,   1.04946287e+03,
 5.79303171e+02,   3.83111876e+02,   4.93826556e-12,
 1.50263232e-12])

You are right. The ratio of max/min eigenvalues is 7.4368432669e+016
Maybe this exceed the of precision of my machine?

Is there any tricks for me to be able to deal with this matrix
correctly with
NumPy?




On Apr 4, 3:58 pm, Robin Becker <[EMAIL PROTECTED]> wrote:
> lancered wrote:
> > Hi dear all,
> ..
> > matrices are correct.
>
> >So,  can you tell me what goes wrong?  Is this a bug in
> > Numpy.linalg? How to deal with this situation?  If you need, I can
> > post the matrix I used below, but it is so long,so not at the moment.
>
> ...
>
> presumably the matrix KK is actually some kind of normal matrix obtained from
> the data. So you have say n variables and m observations the data matrix is 
> than
> an n x m real valued thing say D then you want the inverse of something like 
> D'D
> ie an n by n thing. Typically the data D is de-meaned and normalized by the
> column norms so that you end up with a fairly well scaled problem.
>
> A long time ago I used Numeric+python to do exactly this sort of calculation
> with excellent results and the matrices were as large or larger eg 100 x 100 
> and
> above. I don't think the underlying numeric routines have changed that much. 
> If
> your matrix is symmetric then you should certainly be using
>
> Even if you can't post the matrix, perhaps you should indicate how you proceed
> from data to matrix. Another problem is that a large determinant is no 
> guarantee
> of stability for the inversion. If the largest eigenvalue is 10**100 and the
> smallest 10**-200 I probably have an ill determined problem; surprisingly easy
> to achieve :(
> --
> Robin Becker


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


String manipulation

2007-04-04 Thread marco . minerva
Hi all!

I have a file in which there are some expressions such as "kindest
regard" and "yours sincerely". I must create a phyton script that
checks if a text contains one or more of these expressions and, in
this case, replaces the spaces in the expression with the character
"_". For example, the text

Yours sincerely, Marco.

Must be transformated in:

Yours_sincerely, Marco.

Now I have written this code:

filemw = codecs.open(sys.argv[1], "r", "iso-8859-1").readlines()
filein = codecs.open(sys.argv[2], "r", "iso-8859-1").readlines()

mw = ""
for line in filemw:
mw = mw + line.strip() + "|"

mwfind_re = re.compile(r"^(" + mw + ")",re.IGNORECASE|re.VERBOSE)
mwfind_subst = r"_"

for line in filein:
line = line.strip()
if (line != ""):
line = mwfind_re.sub(mwfind_subst, line)
print line

It correctly identifies the expressions, but doesn't replace the
character in the right way. How can I do what I want?

Thanks in advance.
--
Marco Minerva, [EMAIL PROTECTED]
http://blogs.ugidotnet.org/marcom

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


Re: String manipulation

2007-04-04 Thread Alexander Schmolck

All the code is untested, but should give you the idea. 

[EMAIL PROTECTED] writes:

> Hi all!
> 
> I have a file in which there are some expressions such as "kindest
> regard" and "yours sincerely". I must create a phyton script that
> checks if a text contains one or more of these expressions and, in
> this case, replaces the spaces in the expression with the character
> "_". For example, the text
> 
> Yours sincerely, Marco.
> 
> Must be transformated in:
> 
> Yours_sincerely, Marco.
> 
> Now I have written this code:
> 
> filemw = codecs.open(sys.argv[1], "r", "iso-8859-1").readlines()
> filein = codecs.open(sys.argv[2], "r", "iso-8859-1").readlines()
> 
> mw = ""
> for line in filemw:
>   mw = mw + line.strip() + "|"

One "|" too many. Generally, use join instead of many individual string +s.

mwfind_re_string = "(%s)" % "|".join(line.strip() for line in filemw)

> mwfind_re = re.compile(r"^(" + mw + ")",re.IGNORECASE|re.VERBOSE)


mwfind_re = re.compile(mwfind_re_string),re.IGNORECASE)
 
> mwfind_subst = r"_"
> 
> for line in filein:

That doesn't work. What about "kindest\nregard"? I think you're best of
reading the whole file in (don't forget to close the files, BTW).


>   line = line.strip()
>   if (line != ""):
>   line = mwfind_re.sub(mwfind_subst, line)
>   print line
> 
> It correctly identifies the expressions, but doesn't replace the
> character in the right way. How can I do what I want?

Use the fact that you can also use a function as a substitution.

print mwfind_re.sub(lambda match: match.group().replace(' ','_'), 
"".join(line.strip() for line in filein))

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


Re: optparse option prefix

2007-04-04 Thread Steven Bethard
Mathias Waack wrote:
> We've integrated python into a legacy application. Everything works fine (of
> course because its python;). There's only one small problem: the
> application reads the commandline and consumes all arguments prefixed with
> a '-' sign. Thus its not possible to call a python module from the
> commandline with a parameter list containing options prefixed by '-'
> or '--' signs. Thats not a major problem, but it prevents us from using th
> optparse module. Is there a way to change to prefix, so one could use a '+'
> (for instance) to mark command line options for optparse?

If your arguments come in a particular order, you could use argparse 
(http://argparse.python-hosting.com/) to parse them as positional 
arguments::

 >>> parser = argparse.ArgumentParser()
 >>> parser.add_argument('foo')
 >>> parser.add_argument('bar', nargs='+')
 >>> parser.add_argument('baz')
 >>> parser.parse_args('FOO BAR1 BAR2 BAR3 BAZ'.split())
 Namespace(bar=['BAR1', 'BAR2', 'BAR3'], baz='BAZ', foo='FOO')

I've also filed a feature request for you asking for options with '+' as 
a prefix:

 http://argparse.python-hosting.com/ticket/30

I'll see if I can make some time to implement it, but if you'd like to 
take a look yourself, I can see '-' being hard-coded in at least:

 add_argument()
 _get_optional_kwargs()
 consume_optional() within _parse_args()
 _parse_optional()
 _get_option_prefix_tuples()

I guess there ought to be an easy way to customize the prefix 
characters...  Maybe something like::

 parser = argparse.ArgumentParser(prefix_chars='+')

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


Windows service and pyc files

2007-04-04 Thread Laszlo Nagy

 Hello,

I have a win32 service written in Python that starts a plain 
application, written in Python.

The win32 service tries to launch the application in a while loop and 
logs the return value of the os.system call. That's all.

The application is a simple Python program that connects to an https 
xml/rpc server, and works with the data retrieved from that server. It 
is written as an application because it must be able to download updates 
for itself. Here is how it works:

a.) connect to server
b.) compare current version with the latest
c.) if there is a difference, then download all sources from the server, 
delete all pyc files and exit; otherwise start processing

I could not write a self-restarting server, and I did not want to 
write/install two services for one problem. The win32 service is very 
small and primitive so probably I will not need to update it. I think 
the basic idea is good, but...

When there is a client update available, my application updates itself 
cleanly and exists. Then the service tries to restart the application, 
but it cannot. os.system returns with OS error code -1. The pyc files 
are NOT generated for the application. However, if I start the 
application from the command line, then pyc files are created, and then 
the service will also start the application immediatelly. The win32 
service is running as "Localsystem" so it is sure that it has write 
permission on all files.

I cannot log out the error from the application since it is not started. 
The only error message I have is OSError -1, but it tells me nothing 
about the nature of the error.

Thanks,

   Laszlo

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


Re: An error of matrix inversion using NumPy

2007-04-04 Thread Robin Becker
lancered wrote:
> Here is the eigenvalues of KK  I obtained:
> 
>  >>> linalg.eigvals(KK)
> array([  1.11748411e+05,   3.67154458e+04,   3.41580846e+04,
>  2.75272440e+04,   2.09790868e+04,   1.86242332e+04,
>  8.68628325e+03,   6.66127732e+03,   6.15547187e+03,
>  4.68626197e+03,   3.17838339e+03,   2.84888045e+03,
>  1.88279736e+03,   1.32427574e+03,   1.04946287e+03,
>  5.79303171e+02,   3.83111876e+02,   4.93826556e-12,
>  1.50263232e-12])
> 
> You are right. The ratio of max/min eigenvalues is 7.4368432669e+016
> Maybe this exceed the of precision of my machine?
> 
> Is there any tricks for me to be able to deal with this matrix
> correctly with
> NumPy?
> 
...

You have to be very careful with a set of eigenvalues like the above. The 
implication is that you have a rank deficiency of two ie either you have to 
small a number of observations or there's something fishy about the model (two 
of the data matrix columns can be written as linear combinations of the others 
or  two of the columns are structurally zero). If you really believe the data 
to 
be good then normalize to unit column length first ie try using

[d(1)/||d(1)||.d(n)/||d(n)||]

and see if the eigenvalues are still zero (this will only be of benefit if the 
data is vastly different in scale).

I often got bad results, but that was mostly bad programming and or measuring 
the voltage of the earth wire by mistake :). Some problems naturally have a 
zero 
at the origin.
-- 
Robin Becker

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


Re: String manipulation

2007-04-04 Thread Alexander Schmolck
Alexander Schmolck <[EMAIL PROTECTED]> writes:

> That doesn't work. What about "kindest\nregard"? I think you're best of
> reading the whole file in (don't forget to close the files, BTW).

I should have written "that may not always work, depending of whether the set
phrases you're interested in can also span lines". If in doubt, it's better
to assume they can.

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


Indentifying the LAST occurrence of an item in a list

2007-04-04 Thread tkpmep
For any list x, x.index(item) returns the index of the FIRST
occurrence of the item in x. Is there a simple way to identify the
LAST occurrence of an item in a list? My solution feels complex -
reverse the list, look for the first occurence of the item in the
reversed list, and then subtract its index from the length of the list
- 1, i.e.

LastOcc = len(x) - 1 - x[::-1].index(item)

Is there a simpler solution?

Thanks in advance

Thomas Philips

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


Re: String manipulation

2007-04-04 Thread marco . minerva
On 4 Apr, 17:39, Alexander Schmolck <[EMAIL PROTECTED]> wrote:
> All the code is untested, but should give you the idea.
>
>
>
>
>
> [EMAIL PROTECTED] writes:
> > Hi all!
>
> > I have a file in which there are some expressions such as "kindest
> > regard" and "yours sincerely". I must create a phyton script that
> > checks if a text contains one or more of these expressions and, in
> > this case, replaces the spaces in the expression with the character
> > "_". For example, the text
>
> > Yours sincerely, Marco.
>
> > Must be transformated in:
>
> > Yours_sincerely, Marco.
>
> > Now I have written this code:
>
> > filemw = codecs.open(sys.argv[1], "r", "iso-8859-1").readlines()
> > filein = codecs.open(sys.argv[2], "r", "iso-8859-1").readlines()
>
> > mw = ""
> > for line in filemw:
> >mw = mw + line.strip() + "|"
>
> One "|" too many. Generally, use join instead of many individual string +s.
>
> mwfind_re_string = "(%s)" % "|".join(line.strip() for line in filemw)
>
> > mwfind_re = re.compile(r"^(" + mw + ")",re.IGNORECASE|re.VERBOSE)
>
> mwfind_re = re.compile(mwfind_re_string),re.IGNORECASE)
>
> > mwfind_subst = r"_"
>
> > for line in filein:
>
> That doesn't work. What about "kindest\nregard"? I think you're best of
> reading the whole file in (don't forget to close the files, BTW).
>
> >line = line.strip()
> >if (line != ""):
> >line = mwfind_re.sub(mwfind_subst, line)
> >print line
>
> > It correctly identifies the expressions, but doesn't replace the
> > character in the right way. How can I do what I want?
>
> Use the fact that you can also use a function as a substitution.
>
> print mwfind_re.sub(lambda match: match.group().replace(' ','_'),
> "".join(line.strip() for line in filein))
>
> 'as- Nascondi testo tra virgolette -
>
> - Mostra testo tra virgolette -

Hi Alexander!

Thank you very much, your code works perfectly!

--
Marco Minerva, [EMAIL PROTECTED]
http://blogs.ugidotnet.org/marcom

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


How to process the nested String for sybase sql statement?

2007-04-04 Thread boyeestudio

now,I want to insert some data to the sybase database,
some variable such as i,j,k,name,k,j I have defined before.
I write the sql statement here But I meet some errors,How to write this
nested String for sql query?
For example:


import Sybase
db = Sybase.connect('boyee','sa','',"test'')
c = db.cursor()

..

>>> values = "%d,%d,%d,%s,%d,%d" % (i,j,k,name,k,j)
>>> c.execute("'insert into
productinfo(productid,spid,corpid,productname,type1,
type2) value(@value)',{'@value':values}")

Traceback (most recent call last):
 File "", line 1, in ?
 File "C:\Python24\lib\site-packages\Sybase.py", line 774, in execute
   self.description = fetcher.start(self.arraysize)
 File "C:\Python24\lib\site-packages\Sybase.py", line 517, in start
   return self._start_results()
 File "C:\Python24\lib\site-packages\Sybase.py", line 645, in
_start_results
   self._raise_error(Error, 'ct_results')
 File "C:\Python24\lib\site-packages\Sybase.py", line 506, in _raise_error
   raise exc(text)
Sybase.Error: ct_results

Any reply is enjoyable,Thank a lot!
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: os.popen--which one to use?

2007-04-04 Thread Kevin Walzer
[EMAIL PROTECTED] wrote:
> Check out subprocess. It's meant to be a replacement for all of the
> above.

OK, I've done this. What is the benefit of subprocess? Improved 
performance? It doesn't seem that way--in fact, os.popen has a 
non-blocking mode, which subprocess seems to lack.

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


Re: how to build a forum in Python?

2007-04-04 Thread Goldfish
Sounds like phpBB (http://www.phpbb.com/) would do great. I'm not sure
why you want to go write another forum management tool when others are
already out there for usage. I know its not in python, but not
everything has to be in python.

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


Re: How to process the nested String for sybase sql statement?

2007-04-04 Thread Steve Holden
boyeestudio wrote:
> now,I want to insert some data to the sybase database,
> some variable such as i,j,k,name,k,j I have defined before.
> I write the sql statement here But I meet some errors,How to write this 
> nested String for sql query?
> For example:
> 
>  >>>import Sybase
>  >>> db = Sybase.connect('boyee','sa','',"test'')
>  >>> c = db.cursor()
> ..
> 
>  >>> values = "%d,%d,%d,%s,%d,%d" % (i,j,k,name,k,j)
>  >>> c.execute("'insert into 
> productinfo(productid,spid,corpid,productname,type1,
> type2) value(@value)',{'@value':values}")
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "C:\Python24\lib\site-packages\Sybase.py", line 774, in execute
> self.description = fetcher.start(self.arraysize)
>   File "C:\Python24\lib\site-packages\Sybase.py", line 517, in start
> return self._start_results()
>   File "C:\Python24\lib\site-packages\Sybase.py", line 645, in 
> _start_results
> self._raise_error(Error, 'ct_results')
>   File "C:\Python24\lib\site-packages\Sybase.py", line 506, in _raise_error
> raise exc(text)
> Sybase.Error: ct_results
> 
> Any reply is enjoyable,Thank a lot!
> 
Try instead:

 values = (i,j,k,name,k,j)
 c.execute("""insert into  productinfo
 (productid, spid, corpid, productname, type1, type2)
 values (%d,%d,%d,%s,%d,%d)""",
 values)

I haven't used the Sybase module - you may find you need to use

%s,%s,%s,%s,%s,%s

to represent the parameterized values in the query rather than

%d,%d,%d,%s,%d,%d

Don't forget to call

   db.commit()

to make the changes permanent.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings   http://holdenweb.blogspot.com

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


Re: Newbie - needs help

2007-04-04 Thread Goldfish
Nothing beats http://diveintopython.org/toc/index.html for getting
into the basics of Python. This guy's writing is great!

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


Re: low level networking in python

2007-04-04 Thread Irmen de Jong
Maxim Veksler wrote:

> I'm trying to bind a non-blocking socket, here is my code:
> """
> #!/usr/bin/env python
> 
> import socket, select
> from time import sleep
> 
> s_nb1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s_nb1.setblocking(0)
> 
> s_nb1.bind(('192.168.2.106', 10002))
> s_nb1.listen(5)
> 
> while 1:
>   conn, addr = s_nb1.accept()
>   ready_to_read, ready_to_write, in_error = select.select([conn], [], 
> [], 0)
>   print (ready_to_read, ready_to_write, in_error)
>   sleep(100)
> 
> s_nb1.close()
> """
> 
> And this is the exception I'm getting:
> """
> python non_blocking_socket.py
> Traceback (most recent call last):
>  File "non_blocking_socket.py", line 13, in ?
>conn, addr = s_nb1.accept()
>  File "/usr/lib/python2.4/socket.py", line 161, in accept
>sock, addr = self._sock.accept()
> socket.error: (11, 'Resource temporarily unavailable')
> """
> 
> What am I doing wrong here?

Nothing.
Any operation on a non-blocking socket that is usually blocking
(this includes accept(), bind(), connect(), recv with MSG_WAITALL)
can possibly return a socket.error with errno set to EAGAIN.
('resource temporarily unavailable').
If this happens you should use a select() on the socket to
wait until it's done with the requested operation.

--Irmen

> 
> p.s.
> I've looked at twisted before posting this post. I've seen they
> impelement alot of application level protocols but I didn't see much
> treatment for low level "raw" network data, not to mention that it's a
> way way over kill for what I'm asking to achieve. Twisted does have a
> subproject called "Twisted Pair: Low-level networking" but sadly it's
> unmaintained and undocumented.
> 
>> Mike
>>
> 
> Maxim.
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Indentifying the LAST occurrence of an item in a list

2007-04-04 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| For any list x, x.index(item) returns the index of the FIRST
| occurrence of the item in x. Is there a simple way to identify the
| LAST occurrence of an item in a list? My solution feels complex -
| reverse the list, look for the first occurence of the item in the
| reversed list, and then subtract its index from the length of the list
| - 1, i.e.
|
| LastOcc = len(x) - 1 - x[::-1].index(item)
|
| Is there a simpler solution?

Unless I wanted the list reversed, I would simply iterate backwards, 
parhaps in a utility function.

def rindex(lis, item):
for i in range(len(lis)-1, -1, -1):
if item == lis[i]:
return i
else:
raise ValueError("rindex(lis, item): item not in lis")

t=[0,1,2,3,0]
print rindex(t,3)
print rindex(t,0)
print rindex(t,4)
# prints 3, 4, and traceback

Terry Jan Reedy



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


Re: how to remove multiple occurrences of a string within a list?

2007-04-04 Thread Goldfish
I don't think I would use sets at all. They change the semantic
meaning of the original list. What if you have duplicate entries that
you want to keep? Converting to a set and back will strip out the
duplicates of that.

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


Re: heap doesn't appear to work as described

2007-04-04 Thread 7stud
On Apr 4, 7:05 am, [EMAIL PROTECTED] wrote:
>  My book says that in a heap, a value at position i will be than the
>  values at positions 2*i and 2*i + 1.
>
> >> I am sure your book either uses 1-based arrays or a 0-based arrays
> >> with the first not used.  The need to keep these alternatives in mind
> >> is an unfortunate fact of programming life.
>
> > My book uses lists.
>
> Yes, but is the first element of the list addressed as element 1 or element
> 0?

Here is the example:
-
from heapq import *
from random import shuffle

data = range(10)
shuffle(data)
heap = []
for n in data:
heappush(heap, n)
print heap
heappush(heap, 0.5)
print heap

#my test:
print heap[0]  #output: 0
---

It's from Beginning Python: Novice to Professional, which I think is a
really poorly written book chock full of mistakes and ambiguous
example code.




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


Write to a binary file

2007-04-04 Thread Thomi Aurel RUAG A
Hy
I'm using Python 2.4.2 on an ARM (PXA-270) platform (linux-2.6.17).
My Goal is to write a list of bytes down to a file (opened in binary
mode) in one cycle. The crux is that a '0x0a' (line feed) will break the
cycle of one writing into several pieces. Writing to a "simple" file,
this wouldn't cause any problem.

Assuming - without questioning ;-) - that a device file (/dev/*) has to
be written in one cycle because one write call will be interpreted as
one "transaction". The write behaviour on line feed's isn't really
usefull because such "transactions" would be broken up into serveral
pieces and therefore for the device into several "transactions".

Is there a possibility to write a list of bytes "en bloc" to a binary
file? (without the interpreting of the line feed's)
Opening a file i binary mode (i.e "wb") seems not to be enough.

Thank you for any help
Aurel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to remove multiple occurrences of a string within a list?

2007-04-04 Thread 7stud
On Apr 4, 3:08 am, Steven D'Aprano <[EMAIL PROTECTED]>
wrote:
> On Wed, 04 Apr 2007 00:59:23 -0700, 7stud wrote:
> > On Apr 3, 3:53 pm, "bahoo" <[EMAIL PROTECTED]> wrote:
> >> > target = "0024"
> >> > l = ["0024", "haha", "0024"]
>
> >> > for index, val in enumerate(l):
> >> > if val==target:
> >> > del l[index]
>
> >> > print l
>
> >> This latter suggestion (with the for loop) seems to be buggy: if there
> >> are multiple items in the list "l" equal to "target", then only the
> >> first one will be removed!
>
> >> Thanks anyways.
>
> > Prove it.
>
> Try replacing l = ["0024", "haha", "0024"]
> with
>
> l = ["0024", "0024", "haha"]
>
> and re-running the code.
>
> Actually, the description of the bug isn't quite right. The behaviour of
> the for loop isn't defined -- sometimes it will work, sometimes it won't,
> depending on how many items there are, and which of them are equal to the
> target.
>

Thank you for the explanation.

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


Re: An error of matrix inversion using NumPy

2007-04-04 Thread Lou Pecora
In article <[EMAIL PROTECTED]>,
 "lancered" <[EMAIL PROTECTED]> wrote:

> Here is the eigenvalues of KK  I obtained:
> 
>  >>> linalg.eigvals(KK)
> array([  1.11748411e+05,   3.67154458e+04,   3.41580846e+04,
>  2.75272440e+04,   2.09790868e+04,   1.86242332e+04,
>  8.68628325e+03,   6.66127732e+03,   6.15547187e+03,
>  4.68626197e+03,   3.17838339e+03,   2.84888045e+03,
>  1.88279736e+03,   1.32427574e+03,   1.04946287e+03,
>  5.79303171e+02,   3.83111876e+02,   4.93826556e-12,
>  1.50263232e-12])
> 
> You are right. The ratio of max/min eigenvalues is 7.4368432669e+016
> Maybe this exceed the of precision of my machine?
> 
> Is there any tricks for me to be able to deal with this matrix
> correctly with
> NumPy?

That sounds large to me, too.  Close to the floating point accuracy.  
The problem is not with NumPy,but with double precision numbers. No 
routine can save you if the condition number is large.  However, several 
people here have noted that you might be able to solve your problem by 
avoiding inverting the matrix in the first place.  In other words, 
depending on your particular problem, there may be other ways to solve 
it beside brute force inversion.  Can you Use a QR or SVD approach?

-- Lou Pecora  (my views are my own) REMOVE THIS to email me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.popen--which one to use?

2007-04-04 Thread Robert Kern
Kevin Walzer wrote:
> [EMAIL PROTECTED] wrote:
>> Check out subprocess. It's meant to be a replacement for all of the
>> above.
> 
> OK, I've done this. What is the benefit of subprocess?

Code that will work on most platforms and into the Python 3.0, when the popen*
zoo will disappear in favor of subprocess.

-- 
Robert Kern

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

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


Re: Indentifying the LAST occurrence of an item in a list

2007-04-04 Thread 7stud
On Apr 4, 10:55 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
> | For any list x, x.index(item) returns the index of the FIRST
> | occurrence of the item in x. Is there a simple way to identify the
> | LAST occurrence of an item in a list? My solution feels complex -
> | reverse the list, look for the first occurence of the item in the
> | reversed list, and then subtract its index from the length of the list
> | - 1, i.e.
> |
> | LastOcc = len(x) - 1 - x[::-1].index(item)
> |
> | Is there a simpler solution?
>

How about:

l = [1, 2, 1, 3, 1, 5]
target = 1
for index, val in enumerate(l):
if val==1:
lastIndexOf = index

print lastIndexOf

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


Re: Calling Fortran from Python

2007-04-04 Thread Robert Kern
Mangabasi wrote:
> Robert,
> 
> Thanks for your prompt response.  I think I got a lot closer but no
> cigar yet.
> 
> This is the output
> 
> C:\fortrandll>f2py -c -m sample sample.pyf sample.for
> numpy_info:
>   FOUND:
> define_macros = [('NUMERIC_VERSION', '"\\"24.2\\""')]
> include_dirs = ['C:\\Python24\\include']
> 
> running build
> running config_fc
> running build_src
> building extension "sample" sources
> creating c:\docume~1\fb\locals~1\temp\tmpcosvgv
> creating c:\docume~1\fb\locals~1\temp\tmpcosvgv\src
> f2py: sample.pyf
> Reading fortran codes...
> Reading file 'sample.pyf'
> Post-processing...
> Block: sample
> Block: sample
> Post-processing (stage 2)...
> Building modules...
> Building module "sample"...
> Constructing wrapper function "sample"...
>   ierr1,ierr2,aout = sample(ain)
> Wrote C/API module "sample" to file "c:\docume~1\fb
> \locals~1\temp\tmpcos
> vgv\src/samplemodule.c"
>   adding 'c:\docume~1\fb\locals~1\temp\tmpcosvgv\src\fortranobject.c'
> to sources
> .
>   adding 'c:\docume~1\fb\locals~1\temp\tmpcosvgv\src' to include_dirs.
> copying C:\python24\lib\site-packages\f2py2e\src\fortranobject.c -> c:
> \docume~1\
> fb\locals~1\temp\tmpcosvgv\src
> copying C:\python24\lib\site-packages\f2py2e\src\fortranobject.h -> c:
> \docume~1\
> fb\locals~1\temp\tmpcosvgv\src
> running build_ext
> No module named msvccompiler in scipy_distutils, trying from
> distutils..
> error: The .NET Framework SDK needs to be installed before building
> extensions f
> or Python.
> 
> I think I have a problem with distutils' msvccompiler.py.  It may be
> the MacroExpander in distutils guessing the visual studio path
> incorrectly or something related to the registry keys.  Is there a way
> to specify the C compiler path to f2py so that it does not rely on the
> distutils?  Or maybe I am totally off base here, I don't know.

What C and Fortran compilers are you trying to use? You can look at f2py's help
for flags that you can use to help control where the compilers get picked up,
but you can't avoid distutils.

-- 
Robert Kern

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

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


Re: Indentifying the LAST occurrence of an item in a list

2007-04-04 Thread 7stud
On Apr 4, 11:20 am, "7stud" <[EMAIL PROTECTED]> wrote:
> On Apr 4, 10:55 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
>
> > <[EMAIL PROTECTED]> wrote in message
>
> >news:[EMAIL PROTECTED]
> > | For any list x, x.index(item) returns the index of the FIRST
> > | occurrence of the item in x. Is there a simple way to identify the
> > | LAST occurrence of an item in a list? My solution feels complex -
> > | reverse the list, look for the first occurence of the item in the
> > | reversed list, and then subtract its index from the length of the list
> > | - 1, i.e.
> > |
> > | LastOcc = len(x) - 1 - x[::-1].index(item)
> > |
> > | Is there a simpler solution?
>
> How about:
>
> l = [1, 2, 1, 3, 1, 5]
> target = 1
> for index, val in enumerate(l):
> if val==1:
> lastIndexOf = index
>
> print lastIndexOf

Nahh.  Horrible solution.  You should start at the end of the list.

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


Re: only loading a language installed on system

2007-04-04 Thread kyosohma
On Apr 4, 1:27 am, "ianaré" <[EMAIL PROTECTED]> wrote:
> i'm doing this:
>
> mylocale = wx.Locale(wx.LANGUAGE_POLISH, wx.LOCALE_LOAD_DEFAULT)
> if not wx.Locale.IsOk(mylocale):
> mylocale = wx.Locale(wx.LANGUAGE_DEFAULT, wx.LOCALE_LOAD_DEFAULT)
>
> and getting this:
> Segmentation fault (core dumped)
>
> I'm trying to see if I can properly load a language. If the system
> will not load it, then use system default. What am I doing wrong?
>
> TIA

You would probably be better off to post this question to the wxPython
users group: http://wxpython.org/maillist.php

Here's some related links about Internationalization with wxPython
though:

http://wiki.wxpython.org/index.cgi/Internationalization
http://wiki.wxpython.org/index.cgi/RecipesI18n

Mike

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


Re: Requirements For A Visualization Software System For 2010

2007-04-04 Thread jon
Go for it!  I can see immediate application in displaying and
exploring multivariate projections. e.g., factor analyses and
components analysis, multivariate groupings superimposed on projected
hyperspaces... This is stuff some of us have been dreaming about for a
couple of decades, and getting there from primitives has been (ahem)
"fun."  To be able to express this and see results using a higher
level language would be really important to a lot of research
exploration.

--
jondr

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


Re: Indentifying the LAST occurrence of an item in a list

2007-04-04 Thread Terry Reedy

"7stud" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| How about:
|
| l = [1, 2, 1, 3, 1, 5]
| target = 1
| for index, val in enumerate(l):
|if val==1:
|lastIndexOf = index
|
| print lastIndexOf

You might want to initialize lastIndexOf (to None, for instance).
If len(l) = 100, you might prefer to start from the end, as I 
suggested.

tjr



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


try... except SyntaxError: unexpected EOF while parsing

2007-04-04 Thread oscartheduck
I have a small script for doing some ssh stuff for me. I could have
written it as shell script, but wanted to improve my python skills
some.

RIght now, I'm not catching a syntax error as I'd like to.

Here's my code:

#!/usr/bin/env python
import sys
import os

port = input("Please enter a port to connect on. If you're unsure or
just want the default of port 2024 just hit enter  --  ")


try:
  if port > 65535:
print "That's not a valid port number, sorry. Between 0 and 65535
is cool."
sys.exit()
  else:
cmd = 'su root -c "/usr/sbin/sshd -p %s"' % port
except SyntaxError:
  cmd = 'su root -c "/usr/sbin/sshd -p 2024;exit"'

os.system(cmd)


I'm under the impression that the except should catch the syntax error
and execute the "default" command, but hitting enter at the input
value doesn't lead to that. Any ideas what's going wrong?

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


Re: Write to a binary file

2007-04-04 Thread kyosohma
On Apr 4, 11:40 am, "Thomi Aurel RUAG A" <[EMAIL PROTECTED]> wrote:
> Hy
> I'm using Python 2.4.2 on an ARM (PXA-270) platform (linux-2.6.17).
> My Goal is to write a list of bytes down to a file (opened in binary
> mode) in one cycle. The crux is that a '0x0a' (line feed) will break the
> cycle of one writing into several pieces. Writing to a "simple" file,
> this wouldn't cause any problem.
>
> Assuming - without questioning ;-) - that a device file (/dev/*) has to
> be written in one cycle because one write call will be interpreted as
> one "transaction". The write behaviour on line feed's isn't really
> usefull because such "transactions" would be broken up into serveral
> pieces and therefore for the device into several "transactions".
>
> Is there a possibility to write a list of bytes "en bloc" to a binary
> file? (without the interpreting of the line feed's)
> Opening a file i binary mode (i.e "wb") seems not to be enough.
>
> Thank you for any help
> Aurel

I don't know if these will help or not, but they all have info on
binary file writing:

http://mail.python.org/pipermail/python-list/2001-September/105529.html
http://docs.python.org/tut/node9.html
http://www-128.ibm.com/developerworks/opensource/library/os-python8/

If your data is a bunch of strings, have to tried just concatenating
them into one variable and writing that? If Python is the only program
you will use to read the data, you should be able to pickle it.

Mike

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


Re: try... except SyntaxError: unexpected EOF while parsing

2007-04-04 Thread kyosohma
On Apr 4, 12:38 pm, "oscartheduck" <[EMAIL PROTECTED]> wrote:
> I have a small script for doing some ssh stuff for me. I could have
> written it as shell script, but wanted to improve my python skills
> some.
>
> RIght now, I'm not catching a syntax error as I'd like to.
>
> Here's my code:
>
> #!/usr/bin/env python
> import sys
> import os
>
> port = input("Please enter a port to connect on. If you're unsure or
> just want the default of port 2024 just hit enter  --  ")
>
> try:
>   if port > 65535:
> print "That's not a valid port number, sorry. Between 0 and 65535
> is cool."
> sys.exit()
>   else:
> cmd = 'su root -c "/usr/sbin/sshd -p %s"' % port
> except SyntaxError:
>   cmd = 'su root -c "/usr/sbin/sshd -p 2024;exit"'
>
> os.system(cmd)
>
> I'm under the impression that the except should catch the syntax error
> and execute the "default" command, but hitting enter at the input
> value doesn't lead to that. Any ideas what's going wrong?

Try sticking your

port = input("Please enter a port to connect on. If you're unsure or
just want the default of port 2024 just hit enter  --  ")

inside your "try" block instead. Or switch to using the "raw_input"
builtin instead of "input".

Mike

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


Re: Write to a binary file

2007-04-04 Thread Grant Edwards
On 2007-04-04, Thomi Aurel RUAG A <[EMAIL PROTECTED]> wrote:

> I'm using Python 2.4.2 on an ARM (PXA-270) platform (linux-2.6.17).
> My Goal is to write a list of bytes down to a file (opened in binary
> mode) in one cycle. The crux is that a '0x0a' (line feed) will break the
> cycle of one writing into several pieces.

Says who?  I've never experienced this...

> Writing to a "simple" file, this wouldn't cause any problem.
>
> Assuming - without questioning ;-) - that a device file (/dev/*) has to
> be written in one cycle because one write call will be interpreted as
> one "transaction".

I've never seen a write() on a file descriptor broken up by
Python.  What makes you think this is an issue?

> The write behaviour on line feed's isn't really usefull

What write behavior?

> because such "transactions" would be broken up into serveral
> pieces and therefore for the device into several
> "transactions".
>
> Is there a possibility to write a list of bytes "en bloc" to a
> binary file? (without the interpreting of the line feed's)
> Opening a file i binary mode (i.e "wb") seems not to be
> enough.

It sounds like you're using open() and Python file objects.
You probably ought to use os.open() an os.write().

-- 
Grant Edwards   grante Yow!  I want DUSTIN
  at   HOFFMAN!! ... I want
   visi.comLIBRACE!! YOW!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: try... except SyntaxError: unexpected EOF while parsing

2007-04-04 Thread Terry Reedy

"oscartheduck" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
|I have a small script for doing some ssh stuff for me. I could have
| written it as shell script, but wanted to improve my python skills
| some.
|
| RIght now, I'm not catching a syntax error as I'd like to.
|
| Here's my code:
|
| #!/usr/bin/env python
| import sys
| import os
|
| port = input("Please enter a port to connect on. If you're unsure or
| just want the default of port 2024 just hit enter  --  ")
|
|
| try:
|  if port > 65535:
|print "That's not a valid port number, sorry. Between 0 and 65535
| is cool."
|sys.exit()
|  else:
|cmd = 'su root -c "/usr/sbin/sshd -p %s"' % port
| except SyntaxError:
|  cmd = 'su root -c "/usr/sbin/sshd -p 2024;exit"'
|
| os.system(cmd)
|
|
| I'm under the impression that the except should catch the syntax error
| and execute the "default" command, but hitting enter at the input
| value doesn't lead to that. Any ideas what's going wrong?

Try putting the input statement after the try statement.



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


  1   2   3   >