Re: Abelson and Python

2006-11-23 Thread Fredrik Lundh
markscottwright wrote:

 > If it were that easy, the PyPy guys would be done by now.

if the PyPy guys had focused on writing a Python interpreter in Python, 
they'd been done by now.



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


Re: utf - string translation

2006-11-23 Thread Fredrik Lundh
Klaas wrote:

> It's not too hard to imagine an accentual difference, eg:

especially in languages where certain combinations really are distinct 
letters, not just letters with accents or silly marks.

I have a Swedish children's book somewhere, in which some characters are 
harassed by a big ugly monster who carries a sign around his neck that 
says "Monster".

the protagonist ends up adding two dots to that sign, turning it into 
"Mönster" (meaning "model", in the "model citizen" sense), and all ends 
well.

just imagine that story in reverse.



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


Re: utf - string translation

2006-11-23 Thread Eric Brunel
On Wed, 22 Nov 2006 22:59:01 +0100, John Machin <[EMAIL PROTECTED]>  
wrote:
[snip]
> So why do you want to strip off accents? The history of communication
> has several examples of significant difference in meaning caused by
> minute differences in punctuation or accents including one of which you
> may have heard: a will that could be read (in part) as either "a chacun
> d'eux million francs" or "a chacun deux million francs" with the
> remainder to a 3rd party.

It may not be to store or even use the actual text. I stumbled on a  
problem like this some time ago: I had some code building an index for a  
document and wanted the entries starting with "e", "é", "è" or "ê" to be  
in the same section...
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


How do I find possible matches using regular expression?

2006-11-23 Thread Andy
Hi there,

I'm trying to do some predicting work over user input, here's my
question:

for pattern r'match me', the string 'no' will definitely fail to match,
but 'ma' still has a chance if user keep on inputting characters after
'ma', so how do I mark 'ma' as a possible match string?

Thanks a lot,

Andy

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

Re: How do I find possible matches using regular expression?

2006-11-23 Thread Paul McGuire
"Andy" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi there,
>
> I'm trying to do some predicting work over user input, here's my
> question:
>
> for pattern r'match me', the string 'no' will definitely fail to match,
> but 'ma' still has a chance if user keep on inputting characters after
> 'ma', so how do I mark 'ma' as a possible match string?
>
> Thanks a lot,
>
> Andy
>
Maybe .startsWith might be more useful than re.match, since you are 
predicting user input based on characters that have been typed so far.

-- Paul 


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


Re: The Python Papers Edition One

2006-11-23 Thread Tool69
I've recently tried the docutils's reST module with Pygments ( to
highlight Python sources), so you can have LaTeX + HTML + PDF output
(You can see what it renders here :
h**p://kib2.free.fr/geoPyX/geoPyX.html ). It worked fine, but needs a
little work to suit your needs (you'll have to write your own CSS, and
maybe your LaTeX preambule ).

For OpenOffice, a friend wrote a little Python script that colourize a
Python source inside a document. I think It will be possible to write
your own for HTML output, but the ooo API docs aren't well documented
for Python.

Chears,
6Tool9

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


Finding the carret position in a regular expression

2006-11-23 Thread Tool69
Hi,
supposed I've got the following text :

mytext = "for  in :"

with the following simple pattern : pattern = "<[a-z]+>"

I use re.findall(pattern, mytext) wich returns :
['','']

Now, I want my prog to return the positions of the returned list
elements, ie :
 was found at position 5 in mytext
 was found at position 16 in mytext

How can I implement this ? Sorry if it's trivial, that's the first time
I use regular expressions.
Thanks,
6Tool9

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


Using SimpleXMLRPCServer in a Windows Service

2006-11-23 Thread Rudy Schockaert
After some Googling I found a post of someone who wanted to do exactly
as what I want to do now.
There is however a problem in his code that makes the service fails
after the first connection. I slightly modified his code and now I can
run the service longer before I run into trouble.
I then tried making the SimpleXMLRPCServer multi-threaded, hoping the
problem would disappear, but no avail.
The code is as follows:
The commented part in the while loop is from the original code.



## XML-RPC Service
import sys
import win32serviceutil
import win32service
import win32event
import win32evtlogutil
import win32file
import servicemanager
import SimpleXMLRPCServer
import SocketServer
import select

class OBJECT:
def hello(self, text):
return "Hello World (%s)" % text

class ThreadedSimpleXMLRPCServer(SocketServer.ThreadingMixIn,
SimpleXMLRPCServer.SimpleXMLRPCServer): pass

class XMLRPCSERVICE(win32serviceutil.ServiceFramework):
_svc_name_ = "XMLRPCSERVICE"
_svc_display_name_ = "XMLRPCSERVICE"
_svc_description_ = "XMLRPCSERVICE"

def __init__(self, args):
win32evtlogutil.AddSourceToRegistry(self._svc_display_name_,
sys.executable, "Application")
win32serviceutil.ServiceFramework.__init__(self, args)

self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
self.hSockEvent = win32event.CreateEvent(None, 0, 0, None)
self.stop_requested = 0

def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
self.stop_requested = 1
win32event.SetEvent(self.hWaitStop)

def SvcDoRun(self):
## Write a started event
servicemanager.LogMsg(
servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ' (%s)' % self._svc_name_))

server = ThreadedSimpleXMLRPCServer(("", 8080))
object = OBJECT()
server.register_instance(object)
self.socket = server.socket

while 1:
r, w, x = select.select([self.socket],[],[],10)
if r == [self.socket]:
server.handle_request()
if self.stop_requested:
self.socket.close()
break


#win32file.WSAEventSelect(server,
self.hSockEvent,win32file.FD_ACCEPT)
#rc =
win32event.WaitForMultipleObjects((self.hWaitStop,self.hSockEvent), 0,
win32event.INFINITE)
#if rc == win32event.WAIT_OBJECT_0:
#break
#else:
#server.handle_request()
#win32file.WSAEventSelect(server,self.hSockEvent, 0)
##server.serve_forever()  ## Works, but breaks the

## Write a stopped event
win32evtlogutil.ReportEvent(self._svc_name_,
servicemanager.PYS_SERVICE_STOPPED,0,
servicemanager.EVENTLOG_INFORMATION_TYPE,
(self._svc_name_,""))

if __name__ == '__main__':
win32serviceutil.HandleCommandLine(XMLRPCSERVICE)




I tested with the following:



import xmlrpclib
import time

server = xmlrpclib.ServerProxy("http://localhost:8080";)
for i in range(100):
print server.hello("%d" % i)
time.sleep(1)



The loop ends with the following error:


Hello World (0)
...
Hello World (44)
Traceback (most recent call last):
  File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
line 310, in RunScript
exec codeObject in __main__.__dict__
  File "C:\DATA\TestSoap.py", line 6, in ?
print server.hello("%d" % i)
  File "C:\Python24\lib\xmlrpclib.py", line 1096, in __call__
return self.__send(self.__name, args)
  File "C:\Python24\lib\xmlrpclib.py", line 1383, in __request
verbose=self.__verbose
  File "C:\Python24\lib\xmlrpclib.py", line 1137, in request
headers
ProtocolError: 


Can someone help me in creating a windows service that allows me to
handle XMLRPC request?

Thanks in advance,

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


psyco-simplified idioms ?

2006-11-23 Thread Boris Borcic
I am curious about idioms instinctively avoided by experienced programmers 
because of inefficiencies that psyco eliminates. IOW, are there any 
identifiable 
ways in which the backing of psyco promotes simpler code by eliminating 
efficiency concerns ?

Best, BB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the carret position in a regular expression

2006-11-23 Thread Fredrik Lundh
Tool69 wrote:

> supposed I've got the following text :
> 
> mytext = "for  in :"
> 
> with the following simple pattern : pattern = "<[a-z]+>"
> 
> I use re.findall(pattern, mytext) wich returns :
> ['','']
> 
> Now, I want my prog to return the positions of the returned list
> elements, ie :
>  was found at position 5 in mytext
>  was found at position 16 in mytext

"findall" doesn't return that information; use "finditer" instead, and 
use the "span" or "start" method on the returned match object to get the 
position:

 for m in re.finditer(pattern, mytext):
 print m.span()



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


Re: How do I find possible matches using regular expression?

2006-11-23 Thread Andy
The problem is the input will be much more complex than the example, it
could be something like "30 minutes later" where any string starting
with a number is a possible match.


Paul McGuire 寫道:

> "Andy" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > Hi there,
> >
> > I'm trying to do some predicting work over user input, here's my
> > question:
> >
> > for pattern r'match me', the string 'no' will definitely fail to match,
> > but 'ma' still has a chance if user keep on inputting characters after
> > 'ma', so how do I mark 'ma' as a possible match string?
> >
> > Thanks a lot,
> >
> > Andy
> >
> Maybe .startsWith might be more useful than re.match, since you are
> predicting user input based on characters that have been typed so far.
> 
> -- Paul

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

Re: Finding the carret position in a regular expression

2006-11-23 Thread Tool69
Thanks Fredrik,
I was not aware of finditer. Iterators are very usefull !

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


Re: How do I find possible matches using regular expression?

2006-11-23 Thread Fredrik Lundh
Andy wrote:

> The problem is the input will be much more complex than the example, it
> could be something like "30 minutes later" where any string starting
> with a number is a possible match.

so if I type "1", are you going to suggest all possible numbers
that start with that digit?  doesn't strike me as very practical.

maybe you could post a more detailed example, where you clearly
explain what a pattern is and how it is defined, what prediction
means, and what you want to happen as new input arrives, so we
don't have to guess?



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


Re: How do I find possible matches using regular expression?

2006-11-23 Thread John Machin

Andy wrote:
> Hi there,
>
> I'm trying to do some predicting work over user input, here's my
> question:
>
> for pattern r'match me', the string 'no' will definitely fail to match,
> but 'ma' still has a chance if user keep on inputting characters after
> 'ma', so how do I mark 'ma' as a possible match string?
>

The answer is: Using regular expressions doesn't seem like a good idea.
If you want to match against only one target, then
target.startswith(user_input) is, as already mentioned, just fine.
However if you have multiple targets, like a list of computer-language
keywords, or the similar problem of an IME for a language like Chinese,
then you can set up a prefix-tree dictionary so that you can search the
multiple target keywords in parallel. All you need to do is keep a
"finger" pointed at the node you have reached along the path; after
each input character, either the finger gets pointed at the next
relevant node (if the input character is valid) or you return/raise a
failure indication.

HTH,
John

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


Re: X class missing in Python :-) - Re: What's going on here?

2006-11-23 Thread robert
John Machin wrote:
> robert wrote:
>> Dale Strickland-Clark wrote:
>>> Python 2.4.2 (#1, Oct 13 2006, 17:11:24)
>>> [GCC 4.1.0 (SUSE Linux)] on linux2
>>> Type "help", "copyright", "credits" or "license" for more information.
>> a = object()
>> a
>>> 
>> a.spam = 1
>>> Traceback (most recent call last):
>>>   File "", line 1, in ?
>>> AttributeError: 'object' object has no attribute 'spam'
>> class b(object):
>>> ...pass
>>> ...
>> a = b()
>> a
>>> <__main__.b object at 0xb7b4dcac>
>> a.spam = 1
>>
>>> What is subclassing adding to the class here? Why can't I assign to
>>> attributes of an instance of object?
>>
>> Python so dynamic, but it lacks a (builtin) X-class ready for ad-hoc 
>> usage just like dict() :-)
>> I have in almost every app/toolcore-module this one:
>>
>> --
>>
>> class X(object):
>> def __init__(self,_d={},**kwargs):
>> kwargs.update(_d)
>> self.__dict__=kwargs
>> class Y(X):
>> def __repr__(self):
>> return ''%self.__dict__
>>
>> --
>>
>> x=X(spam=1)
>>
>> Maybe X should be renamed to __builtin__.Object ...
>>
>>
> 
> Have you considered putting it in one file and *importing* it into
> "almost every app/toolcore-module"?

(yes its in my core python "language extension" module, which I import 
frequently in apps)

> Have you considered that others may like to have something a little
> more elaborate, like maybe using the pprint module, or that the amount
> of data that would spew out might in some cases be so great that they
> wouldn't want that every time from repr(), preferring a dump-style
> method that wrote to a logfile?

(in X is no repr so far. of course one could make a default repr with short 
output. had no frequent needs so far)

> IMHO that's one of the enormous number of good points about Python; you
> can easily lash up something like that to suit yourself and inject it
> into any class you like; there's no central authority tying your hands
> behind your back.

its more about the general case, trying things out on the interactive etc. 
always - thus when I want speed not "suit"  :-)

very often I need a dummy object and find me always typing "class X:pass" or 
import above tools.
Think this trivial but needed Object() thing is possibly more than a private 
sitecustomize-thing. Thats why I wrote here upon seeing others trying object() 
which doesn't do what one expects at first.
It wouldn't really tie hands or ? but possibly converse

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


sys.stderr.write and sys.exit

2006-11-23 Thread GinTon
Is the same use _sys.stderr.write('error message'); sys.exit(1)_  than
_sys.exit('error message')_ ?

Note: help(sys.exit)
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is numeric, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system exit
status will be one (i.e., failure).

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


len(var) is [CONSTANT] equal to len(var) == [CONSTANT]?

2006-11-23 Thread Tor Erik Soenvisen
Hi,


(len(['']) is 1) == (len(['']) == 1) => True

Is this the case for all numbers? I've tried running the following:

for i in range(1):
for j in range(1):
if i != j:
assert id(i) != id(j), 'i=%d, j=%d, id=%d' % (i, j, id
(i))

which executes fine. Hence, 0- is okey... But this is a relatively 
small range, and sooner or later you probably get two numbers with the same 
id... Thoughts anyone?

Regards Tor Erik

PS: For those of you who don't know: keyword is compares object identities
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]?

2006-11-23 Thread Fredrik Lundh
Tor Erik Soenvisen wrote:

> (len(['']) is 1) == (len(['']) == 1) => True
> 
> Is this the case for all numbers?

I'm not sure what you're asking here, but if you digest the following 
facts, maybe you can answer it yourself:

1) all objects that exist at the same time have distinct identifies, and 
2) a Python implementation may or may not hand reuse existing immutable 
objects that have the same value when asked to create a new object,
3) identities are recycled when objects are deleted, and
4) [] and {} always create a new object every time they're evaluated.



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


How do I separate my parameters with spawnv

2006-11-23 Thread Fabio Chelly
Hi,

I have a command line that works fine when I execute it directly:

c:\\curl.exe -T c:\\upload.txt -u login:pwd ftp://ftp-myurl --ftp-ssl

But when I try to use os.spawnv to excute it from my python code, it 
doesn't work at all. Here is my code:

exe = "c:\\curl.exe"
f = "c:\\upload.txt"
logon = "login:pwd"
url = "ftp://ftp-myurl";
import os
os.spawnv(os.P_WAIT, exe, ["-T", f, "-u", logon, url, "--ftp-ssl"])

Does anyone know How I can execute my command line in python?

Thanks and best regards,
Fabio

-- 
Ceci est une signature automatique de MesNews.
Site : http://www.mesnews.net


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


Re: How do I find possible matches using regular expression?

2006-11-23 Thread Peter Otten
Andy wrote:

> I'm trying to do some predicting work over user input, here's my
> question:
> 
> for pattern r'match me', the string 'no' will definitely fail to match,
> but 'ma' still has a chance if user keep on inputting characters after
> 'ma', so how do I mark 'ma' as a possible match string?

The following may or may not work in the real world:

import re

def parts(regex, flags=0):
candidates = []
for stop in reversed(range(1, len(regex)+1)):
partial = regex[:stop]
try:
r = re.compile(partial + "$", flags)
except re.error:
pass
else:
candidates.append(r)
candidates.reverse()
return candidates

if __name__ == "__main__":
candidates = parts(r"[a-z]+\s*=\s*\d+", re.IGNORECASE)
def check(*args):
s = var.get()
for c in candidates:
m = c.match(s)
if m:
entry.configure(foreground="#008000")
break
else:
entry.configure(foreground="red")


import Tkinter as tk
root = tk.Tk()
var = tk.StringVar()
var.trace_variable("w", check)
entry = tk.Entry(textvariable=var)
entry.pack()
root.mainloop()

The example lets you write an assignment of a numerical value, e. g

meaning = 42

and colours the text in green or red for legal/illegal entries.

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


Re: PyQt app in seperate thread

2006-11-23 Thread Jeremy Sanders
anders wrote:

> OK I see that now. Thanks for pointing that out. So basically, I can't
> do what I want at all. That's a bit of a pain. Is there no way of
> tricking Qt into thinking I'm running it in the main thread?

I have an app which runs Qt in a separate thread and allows the user to send
it python commands from the main thread. Have a look at this code to see
how it works:

http://svn.gna.org/viewcvs/veusz/branches/qt4/embed.py?rev=530&view=markup

Jeremy

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


Re: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]?

2006-11-23 Thread Peter Otten
Tor Erik Soenvisen wrote:

> (len(['']) is 1) == (len(['']) == 1) => True
> 
> Is this the case for all numbers? I've tried running the following:
> 
> for i in range(1):
> for j in range(1):
> if i != j:
> assert id(i) != id(j), 'i=%d, j=%d, id=%d' % (i, 
> (i))

Shouldn't the test in the loop be

  if i == j:
  assert i is j


Of course it would fail...

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


Re: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]?

2006-11-23 Thread Fredrik Lundh
> distinct identifies

don't trust your spellchucker.



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


Re: How do I separate my parameters with spawnv

2006-11-23 Thread Fredrik Lundh
Fabio Chelly wrote:

> But when I try to use os.spawnv to excute it from my python code, it 
> doesn't work at all. Here is my code:
> 
> exe = "c:\\curl.exe"
> f = "c:\\upload.txt"
> logon = "login:pwd"
> url = "ftp://ftp-myurl";
> import os
> os.spawnv(os.P_WAIT, exe, ["-T", f, "-u", logon, url, "--ftp-ssl"])

iirc, spawnv expects an argv-style list, with the program name as the 
first argument.  try writing the above as

os.spawnv(os.P_WAIT, exe, [exe, "-T", f, "-u", logon, url, "--ftp-ssl"])

> Does anyone know How I can execute my command line in python?

the subprocess module is usually much nicer for things like this.



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


Re: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]?

2006-11-23 Thread Richard Brodie

"Tor Erik Soenvisen" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> which executes fine. Hence, 0- is okey... But this is a relatively
> small range, and sooner or later you probably get two numbers with the same
> id... Thoughts anyone?

I think you are confusing yourself unnecessarily. The obvious way to implement
unique ids is to return the address of the object. It's very unlikely that two
different objects share the same address. 


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


"10, 20, 30" to [10, 20, 30]

2006-11-23 Thread Daniel Austria
Sorry,

how can i convert a string like "10, 20, 30" to a list [10, 20, 30]

what i can do is:

s = "10, 20, 30"
tmp = '[' + s + ']'
l = eval(tmp)

but in my opinion this is not a nice solution


daniel

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


Re: "10, 20, 30" to [10, 20, 30]

2006-11-23 Thread Tim Williams
On 23 Nov 2006 03:13:10 -0800, Daniel Austria <[EMAIL PROTECTED]> wrote:
> Sorry,
>
> how can i convert a string like "10, 20, 30" to a list [10, 20, 30]
>
> what i can do is:
>
> s = "10, 20, 30"
> tmp = '[' + s + ']'
> l = eval(tmp)
>
> but in my opinion this is not a nice solution
>

Not nice, especially if you can't control what is in s :)

A simple solution if you know s will always contain string
representations of integers is:

>>> s = "10, 20, 30"
>>> [int(x) for x in s.split(',')]
[10, 20, 30]
>>>

Otherwise a good starting point might be:

>>> for i in s.split(','):

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


Re: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]?

2006-11-23 Thread Steven D'Aprano
On Thu, 23 Nov 2006 10:48:32 +, Tor Erik Soenvisen wrote:

> Hi,
> 
> 
> (len(['']) is 1) == (len(['']) == 1) => True

You shouldn't rely on this behaviour:

>>> x = 10
>>> len('a' * x) == x
True
>>> len('a' * x) is x
False

(Your results may vary -- this depends on the implementation.)



> Is this the case for all numbers? I've tried running the following:
> 
> for i in range(1):
>   for j in range(1):
>   if i != j:
>   assert id(i) != id(j), 'i=%d, j=%d, id=%d' % (i, j, id
> (i))
> 
> which executes fine. Hence, 0- is okey... 

This doesn't necessarily hold for all integers -- again, it depends on the
implementation, the precise version of Python, and other factors. Don't
rely on "is" giving the same results as "==".

>>> (1+2+3+4+5)**7 == 15**7
True
>>> (1+2+3+4+5)**7 is 15**7
False

> But this is a relatively 
> small range, and sooner or later you probably get two numbers with the same 
> id... Thoughts anyone?

No, you will never get two objects existing at the same time with the same
id. You will get two objects that exist at different times with the same
id, since ids may be reused when the object is deleted.

> PS: For those of you who don't know: keyword is compares object identities

Exactly. There is no guarantee that any specific integer object "1" must
be the same object as another integer object "1". It may be, but it isn't
guaranteed.

I think the only object that is guaranteed to hold for is None. None is a
singleton, so there is only ever one instance. Hence, you should test for
None with "obj is None" rather than ==, because some custom classes may do
silly things with __eq__:

class Blank(object):
"""Compares equal to anything false, including None."""
def __eq__(self, other):
return not other



-- 
Steven.

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


Re: "10, 20, 30" to [10, 20, 30]

2006-11-23 Thread Tech
Daniel Austria a écrit :
> Sorry,
> 
> how can i convert a string like "10, 20, 30" to a list [10, 20, 30]
> 
> what i can do is:
> 
> s = "10, 20, 30"
> tmp = '[' + s + ']'
> l = eval(tmp)
> 
> but in my opinion this is not a nice solution
> 
> 
> daniel
> 

If you're sure that there's only ints
l = [int(item) for item in s.split(', ')]

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


Re: "10, 20, 30" to [10, 20, 30]

2006-11-23 Thread Steven D'Aprano
On Thu, 23 Nov 2006 03:13:10 -0800, Daniel Austria wrote:

> Sorry,
> 
> how can i convert a string like "10, 20, 30" to a list [10, 20, 30]
> 
> what i can do is:
> 
> s = "10, 20, 30"
> tmp = '[' + s + ']'
> l = eval(tmp)
> 
> but in my opinion this is not a nice solution


It is a dangerous solution if your data is coming from an untrusted source.

>>> s = "10, 20, 30"
>>> L = [x.strip() for x in s.split(',')]
>>> L
['10', '20', '30']
>>> L = [int(x) for x in L]
>>> L
[10, 20, 30]

Or, as a one liner:  [int(x.strip()) for x in s.split(',')]


-- 
Steven.

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


Re: "10, 20, 30" to [10, 20, 30]

2006-11-23 Thread John Machin

Daniel Austria wrote:
> Sorry,
>
> how can i convert a string like "10, 20, 30" to a list [10, 20, 30]
>
> what i can do is:
>
> s = "10, 20, 30"
> tmp = '[' + s + ']'
> l = eval(tmp)
>
> but in my opinion this is not a nice solution

Most people share your opinion. Try this:

| >>> strg = "10, 20, 30"
| >>> [int(x) for x in strg.split(',')]
| [10, 20, 30]

Cheers,
John

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


Re: Abelson and Python

2006-11-23 Thread markscottwright
Fredrik Lundh wrote:
> markscottwright wrote:
>
>  > If it were that easy, the PyPy guys would be done by now.
>
> if the PyPy guys had focused on writing a Python interpreter in Python,
> they'd been done by now.
>
> 

Isn't that the point of PyPy?  It's what their mission statement says
(http://codespeak.net/pypy/dist/pypy/doc/architecture.html#mission-statement):

"PyPy is an implementation of the Python programming language written
in Python itself, flexible and easy to experiment with."

This is something that is amazingly easy to do in scheme, since the
language is so simple, but is typically pretty difficult to do in other
languages.  I remember being blown away by how much I knew after
reaching the end of SICP - I wanted to go out and write my own scheme
compiler (and given the proliferation of scheme implementations, a lot
of other people must have felt the same way).  I don't remember getting
to the end of a book on python and thinking, "that's easy.  I could do
that!"

That said, I see now that the course we're talking about isn't the same
as the old 6.001 course, and presumably has different pedagogical goals.

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


Re: "10, 20, 30" to [10, 20, 30]

2006-11-23 Thread Tim Williams
On 23/11/06, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> On Thu, 23 Nov 2006 03:13:10 -0800, Daniel Austria wrote:
>
> > Sorry,
> >
> > how can i convert a string like "10, 20, 30" to a list [10, 20, 30]
> >
> > what i can do is:
> >
> > s = "10, 20, 30"
> > tmp = '[' + s + ']'
> > l = eval(tmp)
> >
> > but in my opinion this is not a nice solution
>
>
> It is a dangerous solution if your data is coming from an untrusted source.
>
> >>> s = "10, 20, 30"
> >>> L = [x.strip() for x in s.split(',')]
> >>> L
> ['10', '20', '30']
> >>> L = [int(x) for x in L]
> >>> L
> [10, 20, 30]
>
> Or, as a one liner:  [int(x.strip()) for x in s.split(',')]

You don't need the strip()

>>> int('10 ')
10
>>>

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


Re: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]?

2006-11-23 Thread Tor Erik Soenvisen
Steven D'Aprano <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> On Thu, 23 Nov 2006 10:48:32 +, Tor Erik Soenvisen wrote:
> 
>> Hi,
>> 
>> 
>> (len(['']) is 1) == (len(['']) == 1) => True
> 
> You shouldn't rely on this behaviour:
> 
 x = 10
 len('a' * x) == x
> True
 len('a' * x) is x
> False
> 
> (Your results may vary -- this depends on the implementation.)
> 
> 
> 
>> Is this the case for all numbers? I've tried running the following:
>> 
>> for i in range(1):
>>  for j in range(1):
>>   if i != j:
>>assert id(i) != id(j), 'i=%d, j=%d, id=%d' % (i, j, id
>> (i))
>> 
>> which executes fine. Hence, 0- is okey... 
> 
> This doesn't necessarily hold for all integers -- again, it depends on
> the implementation, the precise version of Python, and other factors.
> Don't rely on "is" giving the same results as "==".
> 
 (1+2+3+4+5)**7 == 15**7
> True
 (1+2+3+4+5)**7 is 15**7
> False
> 
>> But this is a relatively 
>> small range, and sooner or later you probably get two numbers with
>> the same id... Thoughts anyone?
> 
> No, you will never get two objects existing at the same time with the
> same id. You will get two objects that exist at different times with
> the same id, since ids may be reused when the object is deleted.
> 
>> PS: For those of you who don't know: keyword is compares object
>> identities 
> 
> Exactly. There is no guarantee that any specific integer object "1"
> must be the same object as another integer object "1". It may be, but
> it isn't guaranteed.
> 
> I think the only object that is guaranteed to hold for is None. None
> is a singleton, so there is only ever one instance. Hence, you should
> test for None with "obj is None" rather than ==, because some custom
> classes may do silly things with __eq__:
> 
> class Blank(object):
> """Compares equal to anything false, including None."""
> def __eq__(self, other):
> return not other
> 
> 
I've seen code like this:

if type([]) is list:
print 'Is list'

which seem to work. And also I've seen "var is None", as you mention.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]?

2006-11-23 Thread Duncan Booth
Steven D'Aprano wrote:

> No, you will never get two objects existing at the same time with the
> same id. You will get two objects that exist at different times with
> the same id, since ids may be reused when the object is deleted.
> 
I think it is worth pointing out that this is an area where people get 
confused quite often; it is very easily to get misleading results when you 
call the id() function. e.g.

>>> class C:
def f(self): pass
def g(self): pass


>>> c = C()
>>> id(c.f)==id(c.g)
True
>>> c.f is c.g
False

The ids are the same here only because the objects do not exist at the same 
time. In the first comparison c.f is an expression which creates a 
temporary object that is destroyed before the expression involving c.g is 
evaluated, so it is possible for the different objects to have the same id. 
In the second comparison the objects exist at the same time so they are 
forced to have different ids.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyParsing and Headaches

2006-11-23 Thread Bytter
(This message has already been sent to the mailing-list, but I don't
have sure this is arriving well since it doesn't come up in the usenet,
so I'm posting it through here now.)

Chris,

Thanks for your quick answer. That changes a lot of stuff, and now I'm
able to do my parsing as I intended to.

Still, there's a remaining problem. By using Combine(), everything is
interpreted as a single token. Though what I need is that
'include_bool' and 'literal' be parsed as separated tokens, though
without a space in the middle...

Paul,

Thanks for your detailed explanation. One of the things I think is
missing from the documentation (or that I couldn't find easy) is the
kind of explanation you give about 'The Way of PyParsing'. For example,
It took me a while to understand that I could easily implement simple
recursions using OneOrMany(Group()). Or maybe things were out there and
I didn't searched enough...

Still, fwiw, congratulations for the library. PyParsing allowed me to
do in just a couple of hours, including learning about it's API (minus
this little inconvenient) what would have taken me a couple of days
with, for example,  ANTLR (in fact, I've already put aside ANTLR more
than once in the past for a built-from-scratch parser).

Cheers,

Hugo Ferreira

On Nov 22, 7:50 pm, Chris Lambacher <[EMAIL PROTECTED]> wrote:
> On Wed, Nov 22, 2006 at 11:17:52AM -0800, Bytter wrote:
> > Hi,
>
> > I'm trying to construct a parser, but I'm stuck with some basic
> > stuff... For example, I want to match the following:
>
> > letter = "A"..."Z" | "a"..."z"
> > literal = letter+
> > include_bool := "+" | "-"
> > term = [include_bool] literal
>
> > So I defined this as:
>
> > literal = Word(alphas)
> > include_bool = Optional(oneOf("+ -"))
> > term = include_bool + literal+ here means that you allow a space.  You need 
> > to explicitly override this.
> Try:
>
> term = Combine(include_bool + literal)
>
>
>
> > The problem is that:
>
> > term.parseString("+a") -> (['+', 'a'], {}) # OK
> > term.parseString("+ a") -> (['+', 'a'], {}) # KO. It shouldn't
> > recognize any token since I didn't said the SPACE was allowed between
> > include_bool and literal.
>
> > Can anyone give me an hand here?
>
> > Cheers!
>
> > Hugo Ferreira
>
> > BTW, the following is the complete grammar I'm trying to implement with
> > pyparsing:
>
> > ## L ::= expr | expr L
> > ## expr ::= term | binary_expr
> > ## binary_expr ::= term " " binary_op " " term
> > ## binary_op ::= "*" | "OR" | "AND"
> > ## include_bool ::= "+" | "-"
> > ## term ::= ([include_bool] [modifier ":"] (literal | range)) | ("~"
> > literal)
> > ## modifier ::= (letter | "_")+
> > ## literal ::= word | quoted_words
> > ## quoted_words ::= '"' word (" " word)* '"'
> > ## word ::= (letter | digit | "_")+
> > ## number ::= digit+
> > ## range ::= number (".." | "...") number
> > ## letter ::= "A"..."Z" | "a"..."z"
> > ## digit ::= "0"..."9"
>
> > And this is where I got so far:
>
> > word = Word(nums + alphas + "_")
> > binary_op = oneOf("* and or", caseless=True).setResultsName("operator")
> > include_bool = oneOf("+ -")
> > literal = (word | quotedString).setResultsName("literal")
> > modifier = Word(alphas + "_")
> > rng = Word(nums) + (Literal("..") | Literal("...")) + Word(nums)
> > term = ((Optional(include_bool) + Optional(modifier + ":") + (literal |
> > rng)) | ("~" + literal)).setResultsName("Term")
> > binary_expr = (term + binary_op + term).setResultsName("binary")
> > expr = (binary_expr | term).setResultsName("Expr")
> > L = OneOrMore(expr)
>
> > --
> > GPG Fingerprint: B0D7 1249 447D F5BB 22C5  5B9B 078C 2615 504B 7B85
> 
> > --
> >http://mail.python.org/mailman/listinfo/python-list

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


socket.error connection refused

2006-11-23 Thread Vania
Hi, I'm not sure this is the proper forum but I try nevertheless.
The problem I'am facing is that the socket library always fail to
connect to an URL. The net effect is that I can not use setuptools.
I'm using Python2.4 on a windows XPPRO Sp2 machine.
The firewall is disabled.
There is no NLTM proxy.
I connect to the internet through a NAT server (and it works).
Other than with easy_install I tried to connect to a number of external
urls
(all of them running) and even to localhost,
directly in script using urllib
and the error is always the same errno:  10061 connection refused.
Any ideas?

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


Re: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]?

2006-11-23 Thread Duncan Booth
Tor Erik Soenvisen <[EMAIL PROTECTED]> wrote:

> I've seen code like this:
> 
> if type([]) is list:
>  print 'Is list'
> 
> which seem to work.

'seem to work' is correct. Occasionally 'type(x) is list' is exactly what 
is needed, but much more likely it is a potential bug.

It is more likely that what was intended was: isinstance(x, list)

It is even more likely that the intention was that the object should have 
some list-like behaviour, in which case not doing a test at all is the 
correct behaviour; or quite often that the object should be list-like but 
not a string in which case testing the type against basestring would be 
correct. e.g.:

if isinstance(x, basestring):
   x = [x]
# ... now just assume x is a suitable sequence ...
for element in x:
   ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket.error connection refused

2006-11-23 Thread Tim Williams
On 23 Nov 2006 04:09:18 -0800, Vania <[EMAIL PROTECTED]> wrote:
> Hi, I'm not sure this is the proper forum but I try nevertheless.
> The problem I'am facing is that the socket library always fail to
> connect to an URL. The net effect is that I can not use setuptools.
> I'm using Python2.4 on a windows XPPRO Sp2 machine.
> The firewall is disabled.
> There is no NLTM proxy.
> I connect to the internet through a NAT server (and it works).
> Other than with easy_install I tried to connect to a number of external
> urls
> (all of them running) and even to localhost,
> directly in script using urllib
> and the error is always the same errno:  10061 connection refused.
> Any ideas?

A socket can't connect to a URL, a URL is an absolute location of an
internet resource, eg hostname + (virtual) location on a server + page
name.  A socket can connect to an IP address or hostname - which is
the first part of the URL after the "http://";  (or ftp:// etc)

You need to post a code snippet and the errors you are getting.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket.error connection refused

2006-11-23 Thread Vania
Hi, the reason I mentioned the socket is because that is
where the error eventually occurs.

the code I tried manually (with different urls including a local one)
is the following:

import urllib
fo=urllib.urlopen("http://www.google.com";)

the error I get is:

  File "", line 1, in ?
  File "C:\Python24\lib\urllib.py", line 82, in urlopen
return opener.open(url)
  File "C:\Python24\lib\urllib.py", line 190, in open
return getattr(self, name)(url)
  File "C:\Python24\lib\urllib.py", line 313, in open_http
h.endheaders()
  File "C:\Python24\lib\httplib.py", line 798, in endheaders
self._send_output()
  File "C:\Python24\lib\httplib.py", line 679, in _send_outp
self.send(msg)
  File "C:\Python24\lib\httplib.py", line 646, in send
self.connect()
  File "C:\Python24\lib\httplib.py", line 630, in connect
raise socket.error, msg
IOError: [Errno socket error] (10061, 'Connection refused')


Tim Williams ha scritto:

> On 23 Nov 2006 04:09:18 -0800, Vania <[EMAIL PROTECTED]> wrote:
> > Hi, I'm not sure this is the proper forum but I try nevertheless.
> > The problem I'am facing is that the socket library always fail to
> > connect to an URL. The net effect is that I can not use setuptools.
> > I'm using Python2.4 on a windows XPPRO Sp2 machine.
> > The firewall is disabled.
> > There is no NLTM proxy.
> > I connect to the internet through a NAT server (and it works).
> > Other than with easy_install I tried to connect to a number of external
> > urls
> > (all of them running) and even to localhost,
> > directly in script using urllib
> > and the error is always the same errno:  10061 connection refused.
> > Any ideas?
>
> A socket can't connect to a URL, a URL is an absolute location of an
> internet resource, eg hostname + (virtual) location on a server + page
> name.  A socket can connect to an IP address or hostname - which is
> the first part of the URL after the "http://";  (or ftp:// etc)
> 
> You need to post a code snippet and the errors you are getting.

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


Re: WSGI with mod_python (was: Python, WSGI, legacy web application)

2006-11-23 Thread Rob De Almeida
Ben Finney wrote:
> I was under the impression that WSGI in mod_python was a rather kludgy
> way to do WSGI, but I don't know what the alternatives are. CGI?
> Python http server (e.g. CherryPy)? Something else?

You can use FastCGI or SCGI too, with Apache, lighttpd or Cherokee. I
have a short description of different ways to run a WSGI app here:

http://pydap.org/docs/server.html

Though it's focused on a specific WSGI app I wrote it uses Paste
Deploy, so you can generalize it easily.

--Rob

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


Re: The Python Papers Edition One

2006-11-23 Thread kilnhead
I for one like the pdf format. Nothing irks me more than help files in
multipage HTML. I want a document I can easily download and save.
Thanks for your efforts.


[EMAIL PROTECTED] wrote:
> Greetings all,
>
> Some of you may have noticed the launch of the Python Journal a while
> back. Due to artistic differences, the journal has now been re-launched
> as The Python Papers. It is available under a Creative Commons License,
> something we felt was appropriate given its nature. Many here commented
> that this was important to them, and it is important to us also.
>
> For a fuller description of what we hope the journal to be, I re-create
> my inaugural blog posting at the end of this email, or it can be found
> online here: http://pythonpapers.cgpublisher.com/diary
>
> Some of you had a number of specific points to raise, which I can now
> answer properly since launching under our own banner.
>
> 1.) It takes too many clicks to download.
> A) We know, but it's like that to save our server. We will be
> publishing to a number of online archives, back-issues may be
> back-linkable from those.
>
> 2.) Is it free?
> A) Yes, as in beer and as in freedom. Creative Commons 2.5
> Noncommercial, attribution, share-alike.
>
> 3.) Can I have an HTML version?
> A) No, we like it pretty.
>
> 4.) Why not try (insert favourite thing here)
> A) We will. Thanks for the fish.
>
> " Volume 1, Edition 1 makes history
>
> Welcome to The Python Papers. This journal, small though it is,
> represents the careful efforts of a small group of Python enthusiasts
> who are keen to form a better community in which developers may work.
>
> As Editor-In-Chief, my role is manifold, but my goals are to improve
> the level of connectedness of Python developers, and in so doing
> improve my own developer experience.
>
> The entire editorial board has put time into making this publication
> something which will hopefully lead to a buildup of momentum, fuelled
> by the enthusiastic involvement of others who find Python as exciting
> as we do.
>
> The current issue contains one academic, peer-reviewed article, one
> industry article, and a list of events coming up in Melbourne,
> Australia. We would like to expand this list significantly. We offer
> our services in organising, collating and reviewing submitted content
> such that Python developers around the world may participate in the
> creation of something bigger than all of us, for the benefit of all of
> us. It may be a small journal, a little thing really, but all are
> welcome, and we look forward to getting to know our readers through the
> written word.
>
> Please download the first edition, and consider both what it is and
> what it might be.
>
> For those of you looking to publish an academic paper as a part of
> coursework or for interest's sake alone, we can offer a formal review
> process which will meet those guidelines while preserving the goals of
> freedom of information and community spirit.
>
> Those who are using Python in their work may like to consider using the
> journal as a means of expressing successes or frustrations with either
> the language itself or specific applications. We may be able to offer
> code reviews and style guides, and would be happy to hear about and
> help propagate news of what is happening so that everyone can take an
> interest.
>
> For those who would like a reliable source of information, The Python
> Papers presents a unique and current view into the state of Python at
> large.
> 
> To all of you, welcome!
> Cheers,
> -Tennessee (Editor-In-Chief)"

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


Re: WSGI with mod_python (was: Python, WSGI, legacy web application)

2006-11-23 Thread Paul Boddie
Rob De Almeida wrote:
> Ben Finney wrote:
> > I was under the impression that WSGI in mod_python was a rather kludgy
> > way to do WSGI, but I don't know what the alternatives are. CGI?
> > Python http server (e.g. CherryPy)? Something else?
>
> You can use FastCGI or SCGI too, with Apache, lighttpd or Cherokee.

I think the motivation behind suggesting an Apache solution was that
you'd be able to migrate the PHP resources you already have running in
Apache (I assume, since PHP can run in other places these days) to
mod_python whilst staying within the Apache environment, rather than
having to maintain a number of different environments at the same time.
In other words, you'd write your replacement resources using WSGI (or
whatever) on mod_python (for performance), CGI (for relative
simplicity), or some other connection technology, and then it'd just be
a matter of changing the various directives and having Apache figure it
out.

I know some people advocate proxying to a variety of backend servers,
and the Web obviously lends itself to flexible architectures in this
respect, but there are fairly good reasons for keeping the component
count low.

Paul

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


Re: How do I find possible matches using regular expression?

2006-11-23 Thread Andy
OK, here's what I want...

I'm doing a auto-tasking tool in which user can specify the execution
rule by inputting English instead of a complex GUI interface(Normally a
combination of many controls). This way is way better user interaction.

So the problem comes down to "understanding" user input and
"suggesting" possible inputs when user is writing a rule.

Rules will be like "30 minutes later", "Next Monday", "Every 3 hours",
"3pm"...Sure this is an infinite collection, but it doesn't have to be
perfect , it might make mistakes given inputs like "10 minutes after
Every Monday noon".

The "suggesting" feature is even harder, I'm still investigating
possibilities.

Tried NLTK_Lite, I'm sure it can understands well a good user input,
but it is not doing good with some bad inputs("2 hours later here"),
bad inputs makes the toolkit fails to parse it. And NLTK also does not
help on the suggesting part.

Now I'm thinking manipulating regular expressions. I think it's
possible to come up with a collection of REs to understand basic
execution rules. And the question is again how to do suggestions with
the RE collection.

Any thoughts on this subject?

I'm not a native English speaker so...please, be mistake tolerant with
my post here:-)




"Fredrik Lundh 写道:
"
> Andy wrote:
>
> > The problem is the input will be much more complex than the example, it
> > could be something like "30 minutes later" where any string starting
> > with a number is a possible match.
>
> so if I type "1", are you going to suggest all possible numbers
> that start with that digit?  doesn't strike me as very practical.
>
> maybe you could post a more detailed example, where you clearly
> explain what a pattern is and how it is defined, what prediction
> means, and what you want to happen as new input arrives, so we
> don't have to guess?
> 
> 

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

Re: How do I find possible matches using regular expression?

2006-11-23 Thread Andy
The seems good to me, I'll try it out, thanks for the posting.


"Peter Otten 写道:
"
> Andy wrote:
>
> > I'm trying to do some predicting work over user input, here's my
> > question:
> >
> > for pattern r'match me', the string 'no' will definitely fail to match,
> > but 'ma' still has a chance if user keep on inputting characters after
> > 'ma', so how do I mark 'ma' as a possible match string?
>
> The following may or may not work in the real world:
>
> import re
>
> def parts(regex, flags=0):
> candidates = []
> for stop in reversed(range(1, len(regex)+1)):
> partial = regex[:stop]
> try:
> r = re.compile(partial + "$", flags)
> except re.error:
> pass
> else:
> candidates.append(r)
> candidates.reverse()
> return candidates
>
> if __name__ == "__main__":
> candidates = parts(r"[a-z]+\s*=\s*\d+", re.IGNORECASE)
> def check(*args):
> s = var.get()
> for c in candidates:
> m = c.match(s)
> if m:
> entry.configure(foreground="#008000")
> break
> else:
> entry.configure(foreground="red")
>
>
> import Tkinter as tk
> root = tk.Tk()
> var = tk.StringVar()
> var.trace_variable("w", check)
> entry = tk.Entry(textvariable=var)
> entry.pack()
> root.mainloop()
>
> The example lets you write an assignment of a numerical value, e. g
>
> meaning = 42
>
> and colours the text in green or red for legal/illegal entries.
> 
> Peter

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

Re: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]?

2006-11-23 Thread Fredrik Lundh
Tor Erik Soenvisen wrote:

> I've seen code like this:
>
> if type([]) is list:
>print 'Is list'
>
> which seem to work. And also I've seen "var is None", as you mention.

None is guaranteed to be a singleton:

http://effbot.org/pyref/type-none.htm

Why "is" works for type objects should be pretty obvious, of course.

 



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


Re: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]?

2006-11-23 Thread Stefan Behnel
Tor Erik Soenvisen wrote:
> (len(['']) is 1) == (len(['']) == 1) => True

   >>> len([''])
   1
   >>> len(['']) is 1
   True
   >>> len(['']) == 1
   True
   >>> True == True
   True
   >>> (len(['']) is 1) == (len(['']) == 1)
   True


What did you expect?

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


Re: Porting Tkinter application to JYthon

2006-11-23 Thread Tim N. van der Leeuw
Hi,

sandip desale wrote:
> Dear All,
>
> We have a Tcl/Tk application written using Python 2.2. Using this application 
> we want to call some customizable Java APIs. I tried porting Tcl/Tk 
> application to Jython but not able to do the same as TKinter library is not 
> available with JYthon.
>
> Can you please help me in porting Tkinter application to Jython? Also kindly 
> let me know how to do the same.

Not having Tkinter in Jython, you can either rewrite your app to be a
Java Swing app, or you can embed the Java JVM into the Python
interpreter as an importable library. I believe some projects exist to
enable the latter, although I don't know of a URL.

Cheers,

--Tim
>
>
> Thanks & Regards,
> Sandip Desale
>
>
> --
> 
> Search for products and services at: 
> http://search.mail.com

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


Re: socket.error connection refused

2006-11-23 Thread Bjoern Schliessmann
Vania wrote:

> IOError: [Errno socket error] (10061, 'Connection refused')

What does "telnet www.google.com 80" in some cmd.exe window say? The
same?

Regards,


Björn

-- 
BOFH excuse #36:

dynamic software linking table corrupted

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


Re: Tkinter, main loop question.

2006-11-23 Thread Bjoern Schliessmann
Exod wrote:

> Don't know if its possible in this light-weight GUI toolset, but
> can i somehow hook up into the mainloop in it, for example if i
> were to create an internet application, i would need to keep
> recieving data from within it?

That's something where you could try the Twisted framework
(http://twistedmatrix.com). Its event loop integrates with many GUI
toolkits', also Tk's.

Regards,


Björn

-- 
BOFH excuse #394:

Jupiter is aligned with Mars.

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


Re: Porting Tkinter application to JYthon

2006-11-23 Thread Andre Burgaud

Hi Sandip,

JPype could be a solution to implement the second option mentioned by Tim:
http://jpype.sourceforge.net/

Thanks,

Andre
http://www.burgaud.com/




On 23 Nov 2006 05:36:46 -0800, Tim N. van der Leeuw <[EMAIL PROTECTED]>
wrote:


Hi,

sandip desale wrote:
> Dear All,
>
> We have a Tcl/Tk application written using Python 2.2. Using this
application we want to call some customizable Java APIs. I tried porting
Tcl/Tk application to Jython but not able to do the same as TKinter library
is not available with JYthon.
>
> Can you please help me in porting Tkinter application to Jython? Also
kindly let me know how to do the same.

Not having Tkinter in Jython, you can either rewrite your app to be a
Java Swing app, or you can embed the Java JVM into the Python
interpreter as an importable library. I believe some projects exist to
enable the latter, although I don't know of a URL.

Cheers,

--Tim
>
>
> Thanks & Regards,
> Sandip Desale
>
>
> --
>
> Search for products and services at:
> http://search.mail.com

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

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

ldapsearch example in python-ldap?

2006-11-23 Thread Nico Grubert
Hi there,

on a linux machine I am running this ldapsearch from the command line:

ldapsearch -x -h myldaphost.mydomain.com \
   -D "CN=ldapuser,CN=Users,DC=mydomain,DC=com" -w "secret" \
   -b "CN=ANYCOMPUTER,CN=Computers,DC=mydomain,DC=com"

How can I do this with python-ldap?

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


Re: How do I separate my parameters with spawnv

2006-11-23 Thread Fabio Chelly
Thank you very much

-- 
Ceci est une signature automatique de MesNews.
Site : http://www.mesnews.net


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


Email headers and non-ASCII characters

2006-11-23 Thread Christoph Haas
Hello, everyone...

I'm trying to send an email to people with non-ASCII characters in their 
names. A recpient's address may look like:

"Jörg Nørgens" <[EMAIL PROTECTED]>

My example code:

=
def sendmail(sender, recipient, body, subject):
   message = MIMEText(body)
   message['Subject'] = Header(subject, 'iso-8859-1')
   message['From'] = Header(sender, 'iso-8859-1')
   message['To'] = Header(recipient, 'iso-8859-1')

   s = smtplib.SMTP()
   s.connect()
   s.sendmail(sender, recipient, message.as_string())
   s.close()
=

However the Header() method encodes the whole expression in ISO-8859-1:

=?iso-8859-1?q?=22J=C3=B6rg_N=C3=B8rgens=22_=3Cjoerg=40nowhere=3E?=

However I had expected something like:

"=?utf-8?q?J=C3=B6rg?= =?utf-8?q?_N=C3=B8rgens?=" <[EMAIL PROTECTED]>

Of course my mail transfer agent is not happy with the first string 
although I see that Header() is just doing its job. I'm looking for a way 
though to encode just the non-ASCII parts like any mail client does. Does 
anyone have a recipe on how to do that? Or is there a method in 
the "email" module of the standard library that does what I need? Or 
should I split by regular expression to extract the email address 
beforehand? Or a list comprehension to just look for non-ASCII character 
and Header() them? Sounds dirty.

Hints welcome.

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

Re: combining the path and fileinput modules

2006-11-23 Thread Rob Wolfe

wo_shi_big_stomach wrote:
> Newbie to python writing a script to recurse a directory tree and delete
> the first line of a file if it contains a given string. I get the same
> error on a Mac running OS X 10.4.8 and FreeBSD 6.1.
>
> Here's the script:
>
> # start of program
>
> # p.pl - fix broken SMTP headers in email files
> #
> # recurses from dir and searches all subdirs
> # for each file, evaluates whether 1st line starts with "From "
> # for each match, program deletes line
>
> import fileinput
> import os
> import re
> import string
> import sys
> from path import path
>
> # recurse dirs
> dir = path(/home/wsbs/Maildir)
> for f in dir.walkfiles('*'):
>   #
>   # test:
>   # print f

Are you absolutely sure that f list doesn't contain
any path to directory, not file?
Add this:

f = filter(os.path.isfile, f)

and try one more time.

>   #
>   # open file, search, change if necessary, write backup
>   for line in fileinput.input(f, inplace=1, backup='.bak'):
>   # check first line only
>   if fileinput.isfirstline():
>   if not re.search('^From ',line):
>   print line.rstrip('\n')
>   # just print all other lines
>   if not fileinput.isfirstline():
>   print line.rstrip('\n')
>   fileinput.close()
> # end of program

-- 
HTH,
Rob

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


non blocking "i o", The deep freeze.

2006-11-23 Thread guy . flowers
Hi

Have a problem, Ill give some history to the problem and add a little
example code to start with
to see if anybody can help or if I am correct in what the problem is.

I have been looking on the newsgroups and have found lots of stuff on
the problem
but no solutions as of yet, will keep looking here to see if I can find
one that fits.

I created a script which runs a whole suite of regression tests, the
test exe which is
built daily, is created from c code, this changes from day to day as
stuff is added, and fixed, the exe is then used to run text files which
have lots of commands and data in, which produce lots of pretty
pictures on the screen, errors and warning output is also produced from
this, which I collect and create logs with. Up until recently I havn't
had any problems with my script, the main tests were run on a local
win32 machine with all the logs and test files all local, with
occasional runs on various different unix's and win64 platforms. We
have just recently had installed a big test and build rack full of
win32 (winxp) machines 3 of these are automated test machines which run
my script in a loop (it also builds the test exe and does one or two
other things), the test files are now held on a big central disk, which
was ment to save me coping data down from the network. The whole thing
works pretty well, a part from every so offen completely randomly the 3
machines seem to freeze (or to put in the terms of our sys admin it
trashes them).
The machines needs to be reset and the connection between the machines
and the big central disk is lost and needs to be reset as well.

According to the sys admin I need to be using, non blocking "i o" for
my file control, the code below shows what Im doing at the moment. Has
any one got any suggestions on what to do here, I kept everything
really simple so it would work across all platform and I thought I was
there,
but like with most things, its not and the code will probably get
really complex.
The code below is only a small snipet and I've made it simple for this
example but its the part I think where the freeze is happening.


output, input = popen2("cmd.exe")

input.write("set LI_DIR=" + MW_OPTS.GetOption("MainOpts","LI_DIR") +
"\n")
input.write("set LI\n")

# Writes commands to it.
input.write(mwtest_exe + mwtest_args +  os.path.dirname(f_testlwc_str)
+  testlwc + "\n")
input.write("exit\n")

while 1:
  text = output.readline()
  if text:
OutputCount += 1
# Searches the line for errors, when found stops doing this.
f_Error_Code = FileLineQuickStat(text , f_Possible_Errs_dict ,
f_Error_Code)
# Records the line in a log.

LW_FLOG.WriteLogEntry("TEST_LOG",str(OutputCount),string.replace(text,"\n",""),1)
  else:
LW_FLOG.FinishLog("TEST_LOG","")
# Returns the error code.
return f_Error_Code
break

TIA
Guy

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


Re: "10, 20, 30" to [10, 20, 30]

2006-11-23 Thread Fredrik Lundh
Tim Williams wrote:

>> It is a dangerous solution if your data is coming from an untrusted source.
>>
>> >>> s = "10, 20, 30"
>> >>> L = [x.strip() for x in s.split(',')]
>> >>> L
>> ['10', '20', '30']
>> >>> L = [int(x) for x in L]
>> >>> L
>> [10, 20, 30]
>>
>> Or, as a one liner:  [int(x.strip()) for x in s.split(',')]
>
> You don't need the strip()
>
 int('10 ')
> 10


and the use of a list comprehension is pretty silly to, given that you want
to apply the same *function* to all items, and don't really need to look
it up for every item:

map(int,  s.split(','))

 



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


Re: Email headers and non-ASCII characters

2006-11-23 Thread Christoph Haas
On Thursday 23 November 2006 15:12, I wrote:
> My example code:
>
> =
> def sendmail(sender, recipient, body, subject):
>message = MIMEText(body)
>message['Subject'] = Header(subject, 'iso-8859-1')
>message['From'] = Header(sender, 'iso-8859-1')
>message['To'] = Header(recipient, 'iso-8859-1')
>
>s = smtplib.SMTP()
>s.connect()
>s.sendmail(sender, recipient, message.as_string())
>s.close()
> =

Just for completeness - of course I imported the Header methods from here:

from email.MIMEText import MIMEText
from email.Header import Header

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


Re: socket.error connection refused

2006-11-23 Thread Vania
Hi,

the telnet call succeed

Vania

Bjoern Schliessmann ha scritto:

> Vania wrote:
>
> > IOError: [Errno socket error] (10061, 'Connection refused')
>
> What does "telnet www.google.com 80" in some cmd.exe window say? The
> same?
>
> Regards,
>
>
> Björn
>
> -- 
> BOFH excuse #36:
> 
> dynamic software linking table corrupted

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


Re: non blocking "i o", The deep freeze.

2006-11-23 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> The whole thing works pretty well, a part from every so offen completely
> randomly the 3 machines seem to freeze (or to put in the terms of our sys
> admin it trashes them).

thrashing?

that usually means that a process uses too much memory, thus causing the
system to spend too much time swapping to be able to do anything useful.

have you checked the process size during normal operations?  is it stable, or
does it grow a little all the time?

> According to the sys admin I need to be using, non blocking "i o" for
> my file control

if the problem is thrashing, I'm not sure I see how that would help.

 



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


Re: "10, 20, 30" to [10, 20, 30]

2006-11-23 Thread Tim Williams
On 23/11/06, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Tim Williams wrote:
> 
>
> and the use of a list comprehension is pretty silly to, given that you want
> to apply the same *function* to all items, and don't really need to look
> it up for every item:
>
> map(int,  s.split(','))

Haha, thanks Frederic,  I wondered how long it would take for a reply
from you :)

"Silly" though ??

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


ImportError: No module named getopt

2006-11-23 Thread prashant
I am running a python script which has the line

import getopt, sys, os, re, string

And i get the error

ImportError: No module named getopt

Could you please point out a possible solution for this?

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


Re: Trying to understand Python objects

2006-11-23 Thread Aahz
In article <[EMAIL PROTECTED]>,
Ben Finney  <[EMAIL PROTECTED]> wrote:
>
>Typically, classes are created as a subclass of another class. The
>top-level basic type in Python is 'object', so if your class doesn't
>make sense deriving from anything else, derive from 'object'.
>
>class Point(object):
>pass
>
>Defining a class with *no* superclass is not recommended. If you don't
>yet understand the difference between the above style (called a
>"new-style" class) and the style you presented, you should always
>derive from a superclass ('object' or something more specific) until
>you encounter a situation where that causes a problem.

Side note: I disagree with the above advice, but it's Thanksgiving and I
don't have enough room on the margin for the proof.  I think classic
classes are just fine.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"In many ways, it's a dull language, borrowing solid old concepts from
many other languages & styles:  boring syntax, unsurprising semantics,
few automatic coercions, etc etc.  But that's one of the things I like
about it."  --Tim Peters on Python, 16 Sep 1993
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: combining the path and fileinput modules

2006-11-23 Thread wo_shi_big_stomach
On 11/23/06 6:15 AM, Rob Wolfe wrote:
> wo_shi_big_stomach wrote:
>> Newbie to python writing a script to recurse a directory tree and delete
>> the first line of a file if it contains a given string. I get the same
>> error on a Mac running OS X 10.4.8 and FreeBSD 6.1.
>>
>> Here's the script:
>>
>> # start of program
>>
>> # p.pl - fix broken SMTP headers in email files
>> #
>> # recurses from dir and searches all subdirs
>> # for each file, evaluates whether 1st line starts with "From "
>> # for each match, program deletes line
>>
>> import fileinput
>> import os
>> import re
>> import string
>> import sys
>> from path import path
>>
>> # recurse dirs
>> dir = path(/home/wsbs/Maildir)
>> for f in dir.walkfiles('*'):
>>  #
>>  # test:
>>  # print f
> 
> Are you absolutely sure that f list doesn't contain
> any path to directory, not file?
> Add this:
> 
> f = filter(os.path.isfile, f)
> 
> and try one more time.

Sorry, no joy. Printing f then produces:

rppp
rp
rp
rpppr
rp
rpppP
rp
rp

which I assure you are not the filenames in this directory.

I've tried this with f and f.name. The former prints the full pathname
and filename; the latter prints just the filename. But neither works
with the fileinput.input() call below.

I get the same error with the filtered mod as before:

  File "./p", line 23, in ?
for line in fileinput.input(f, inplace=1, backup='.bak'):

Thanks again for info on what to feed fileinput.input()



> 
>>  #
>>  # open file, search, change if necessary, write backup
>>  for line in fileinput.input(f, inplace=1, backup='.bak'):
>>  # check first line only
>>  if fileinput.isfirstline():
>>  if not re.search('^From ',line):
>>  print line.rstrip('\n')
>>  # just print all other lines
>>  if not fileinput.isfirstline():
>>  print line.rstrip('\n')
>>  fileinput.close()
>> # end of program
> 

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


Re: ImportError: No module named getopt

2006-11-23 Thread Fredrik Lundh
"prashant" wrote:

>I am running a python script which has the line
>
> import getopt, sys, os, re, string
>
> And i get the error
>
> ImportError: No module named getopt
>
> Could you please point out a possible solution for this?

looks like a broken installation.  try running the script as

python -vv script.py

and see where it looks for the getopt module.

is the ImportError all you get, btw ?  it doesn't complain about site.py before
that ?

 



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


Re: Trying to understand Python objects

2006-11-23 Thread Aahz
In article <[EMAIL PROTECTED]>,
walterbyrd <[EMAIL PROTECTED]> wrote:
>
>Is there some book, or other reference, that explains of this? I was
>thinking about "Python for Dummies." The "Think like a Computer
>Scientist" book, and "Dive into Python" book don't seem to explain
>Python's object model clearly enough for me.

Speaking as the co-author of _Python for Dummies_, we certainly tried to
make much of this clear, but I haven't seen any reviews yet (partly our
fault for not getting out review copies).
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"In many ways, it's a dull language, borrowing solid old concepts from
many other languages & styles:  boring syntax, unsurprising semantics,
few automatic coercions, etc etc.  But that's one of the things I like
about it."  --Tim Peters on Python, 16 Sep 1993
-- 
http://mail.python.org/mailman/listinfo/python-list


Simple threading

2006-11-23 Thread jrpfinch
I'm just getting started on threading and was wondering why the
following code does not work (i know globals is bad style - I'll
eliminate them eventually).  All I get is a blank cursor flashing.

Many thanks

Jon

import threading
import sys
import time
global g_datum
global g_rawfile
global g_rawtext
global g_overs
global g_currentover
global g_secondspertick


g_secondspertick=5
g_datum=time.time()
g_currenttick=1
g_rawfile=open('inputashes.txt','r')
g_rawtext=g_rawfile.read()
g_overs=g_rawtext.split('')
g_currentover=0


class ImapThread(threading.Thread):
def run(self):
global g_currenttick
if time.time() > (g_datum + (g_secondspertick *
g_currenttick)):
print "Ticked %s" % g_currenttick
g_currenttick=g_currenttick+1
print g_currenttick
sys.stdout.flush()
time.sleep(0.01)

def main():
ImapThread().start()
while 1:
pass

if __name__ == "__main__":
main()

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


Re: PyParsing and Headaches

2006-11-23 Thread Bytter
Heya there,

Ok, found the solution. I just needed to use leaveWhiteSpace() in the
places I want pyparsing to take into consideration the spaces.
Thx for the help.

Cheers!

Hugo Ferreira

On Nov 23, 11:57 am, "Bytter" <[EMAIL PROTECTED]> wrote:
> (This message has already been sent to the mailing-list, but I don't
> have sure this is arriving well since it doesn't come up in the usenet,
> so I'm posting it through here now.)
>
> Chris,
>
> Thanks for your quick answer. That changes a lot of stuff, and now I'm
> able to do my parsing as I intended to.
>
> Still, there's a remaining problem. By using Combine(), everything is
> interpreted as a single token. Though what I need is that
> 'include_bool' and 'literal' be parsed as separated tokens, though
> without a space in the middle...
>
> Paul,
>
> Thanks for your detailed explanation. One of the things I think is
> missing from the documentation (or that I couldn't find easy) is the
> kind of explanation you give about 'The Way of PyParsing'. For example,
> It took me a while to understand that I could easily implement simple
> recursions using OneOrMany(Group()). Or maybe things were out there and
> I didn't searched enough...
>
> Still, fwiw, congratulations for the library. PyParsing allowed me to
> do in just a couple of hours, including learning about it's API (minus
> this little inconvenient) what would have taken me a couple of days
> with, for example,  ANTLR (in fact, I've already put aside ANTLR more
> than once in the past for a built-from-scratch parser).
>
> Cheers,
>
> Hugo Ferreira
>
> On Nov 22, 7:50 pm, Chris Lambacher <[EMAIL PROTECTED]> wrote:
>
> > On Wed, Nov 22, 2006 at 11:17:52AM -0800, Bytter wrote:
> > > Hi,
>
> > > I'm trying to construct a parser, but I'm stuck with some basic
> > > stuff... For example, I want to match the following:
>
> > > letter = "A"..."Z" | "a"..."z"
> > > literal = letter+
> > > include_bool := "+" | "-"
> > > term = [include_bool] literal
>
> > > So I defined this as:
>
> > > literal = Word(alphas)
> > > include_bool = Optional(oneOf("+ -"))
> > > term = include_bool + literal+ here means that you allow a space.  You 
> > > need to explicitly override this.
> > Try:
>
> > term = Combine(include_bool + literal)
>
> > > The problem is that:
>
> > > term.parseString("+a") -> (['+', 'a'], {}) # OK
> > > term.parseString("+ a") -> (['+', 'a'], {}) # KO. It shouldn't
> > > recognize any token since I didn't said the SPACE was allowed between
> > > include_bool and literal.
>
> > > Can anyone give me an hand here?
>
> > > Cheers!
>
> > > Hugo Ferreira
>
> > > BTW, the following is the complete grammar I'm trying to implement with
> > > pyparsing:
>
> > > ## L ::= expr | expr L
> > > ## expr ::= term | binary_expr
> > > ## binary_expr ::= term " " binary_op " " term
> > > ## binary_op ::= "*" | "OR" | "AND"
> > > ## include_bool ::= "+" | "-"
> > > ## term ::= ([include_bool] [modifier ":"] (literal | range)) | ("~"
> > > literal)
> > > ## modifier ::= (letter | "_")+
> > > ## literal ::= word | quoted_words
> > > ## quoted_words ::= '"' word (" " word)* '"'
> > > ## word ::= (letter | digit | "_")+
> > > ## number ::= digit+
> > > ## range ::= number (".." | "...") number
> > > ## letter ::= "A"..."Z" | "a"..."z"
> > > ## digit ::= "0"..."9"
>
> > > And this is where I got so far:
>
> > > word = Word(nums + alphas + "_")
> > > binary_op = oneOf("* and or", caseless=True).setResultsName("operator")
> > > include_bool = oneOf("+ -")
> > > literal = (word | quotedString).setResultsName("literal")
> > > modifier = Word(alphas + "_")
> > > rng = Word(nums) + (Literal("..") | Literal("...")) + Word(nums)
> > > term = ((Optional(include_bool) + Optional(modifier + ":") + (literal |
> > > rng)) | ("~" + literal)).setResultsName("Term")
> > > binary_expr = (term + binary_op + term).setResultsName("binary")
> > > expr = (binary_expr | term).setResultsName("Expr")
> > > L = OneOrMore(expr)
>
> > > --
> > > GPG Fingerprint: B0D7 1249 447D F5BB 22C5  5B9B 078C 2615 504B 7B85
> 
> > > --
> > >http://mail.python.org/mailman/listinfo/python-list

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


Re: Email headers and non-ASCII characters

2006-11-23 Thread Max M
Christoph Haas skrev:
> Hello, everyone...
> 
> I'm trying to send an email to people with non-ASCII characters in their 
> names. A recpient's address may look like:
> 
> "Jörg Nørgens" <[EMAIL PROTECTED]>
> 
> My example code:
> 
> =
> def sendmail(sender, recipient, body, subject):
>message = MIMEText(body)
>message['Subject'] = Header(subject, 'iso-8859-1')
>message['From'] = Header(sender, 'iso-8859-1')
>message['To'] = Header(recipient, 'iso-8859-1')
> 
>s = smtplib.SMTP()
>s.connect()
>s.sendmail(sender, recipient, message.as_string())
>s.close()
> =
> 
> However the Header() method encodes the whole expression in ISO-8859-1:
> 
> =?iso-8859-1?q?=22J=C3=B6rg_N=C3=B8rgens=22_=3Cjoerg=40nowhere=3E?=
> 
> However I had expected something like:
> 
> "=?utf-8?q?J=C3=B6rg?= =?utf-8?q?_N=C3=B8rgens?=" <[EMAIL PROTECTED]>
> 
> Of course my mail transfer agent is not happy with the first string 


Why offcourse? But it seems that you are passing the Header object a 
utf-8 encoded string, not a latin-1 encoded.

You are telling the header the encoding. Not asking it to encode.

-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: The Python Papers Edition One

2006-11-23 Thread jdunck

[EMAIL PROTECTED] wrote:
> 1.) It takes too many clicks to download.
> A) We know, but it's like that to save our server. We will be
> publishing to a number of online archives, back-issues may be
> back-linkable from those.

Please consider using S3, coral cache, or similar to distribute, if the
server limitations are a cause of fewer people reading.

I'd be happy to help you get going with S3 if you like, otherwise,
coral CDN couldn't be simpler to use (if a bit unstable).

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


Re: Simple threading

2006-11-23 Thread hg
jrpfinch wrote:
> I'm just getting started on threading and was wondering why the
> following code does not work (i know globals is bad style - I'll
> eliminate them eventually).  All I get is a blank cursor flashing.
> 
> Many thanks
> 
> Jon
> 
> import threading
> import sys
> import time
> global g_datum
> global g_rawfile
> global g_rawtext
> global g_overs
> global g_currentover
> global g_secondspertick
> 
> 
> g_secondspertick=5
> g_datum=time.time()
> g_currenttick=1
> g_rawfile=open('inputashes.txt','r')
> g_rawtext=g_rawfile.read()
> g_overs=g_rawtext.split('')
> g_currentover=0
> 
> 
> class ImapThread(threading.Thread):
> def run(self):
> global g_currenttick
> if time.time() > (g_datum + (g_secondspertick *
> g_currenttick)):
> print "Ticked %s" % g_currenttick
> g_currenttick=g_currenttick+1
> print g_currenttick
> sys.stdout.flush()
> time.sleep(0.01)
> 
> def main():
> ImapThread().start()
> while 1:
> pass
> 
> if __name__ == "__main__":
> main()
> 
Run gets called only once: you need to put your logic in a "while True"
or something equivalent/define some escape clause.

Right now you just get into the implicit "else" and get out.

hg

import time
global g_datum
global g_rawfile
global g_rawtext
global g_overs
global g_currentover
global g_secondspertick


g_secondspertick=5
g_datum=time.time()
g_currenttick=1
#g_rawfile=open('inputashes.txt','r')
#g_rawtext=g_rawfile.read()
#g_overs=g_rawtext.split('')
g_currentover=0


class ImapThread(threading.Thread):
def run(self):
while True:
global g_currenttick
if time.time() > (g_datum + (g_secondspertick *
g_currenttick)):
print "Ticked %s" % g_currenttick
g_currenttick=g_currenttick+1
print g_currenttick
sys.stdout.flush()
else:
print 'HERE'
time.sleep(0.01)

def main():
ImapThread().start()
while 1:
pass

if __name__ == "__main__":
main()

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


Re: Pyparsing Question.

2006-11-23 Thread Ant

> Welcome to pyparsing!  The simplest way to implement a markup processor in
> pyparsing is to define the grammar of the markup, attach a parse action to
> each markup type to convert the original markup to the actual results, and
> then use transformString to run through the input and do the conversion.
> This discussion topic has some examples:
> http://pyparsing.wikispaces.com/message/view/home/31853.

Thanks for the pointers - I had a look through the examples on the
pyparsing website, but none seemed to show a simple example of this
kind of thing. The discussion topic you noted above is exactly the sort
of thing I was after!

Cheers,

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


select() on WinXP

2006-11-23 Thread [EMAIL PROTECTED]
I'm running Python 2.5 on Windows XP. When I try to do this:

[code]
import select
select.select([], [], [])
[/code]

I get this:

[output]
Traceback (most recent call last):
  File "C:/Documents and Settings/Grebekel/Desktop/s.py", line 2, in

select.select([],[],[])
error: (10022, 'An invalid argument was supplied')
[/output]

Is there anything I should be aware of to get select() working under
Windows?

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


Re: ImportError: No module named getopt

2006-11-23 Thread prashant
Thanks for the reply,
I am actually using Cygwin to run a python script.
I have python 2.5 installed. But when i ran the command mentioned by
you... I see that it is looking in the wrong directories... how can i
change these look up directories?


Fredrik Lundh wrote:
> "prashant" wrote:
>
> >I am running a python script which has the line
> >
> > import getopt, sys, os, re, string
> >
> > And i get the error
> >
> > ImportError: No module named getopt
> >
> > Could you please point out a possible solution for this?
>
> looks like a broken installation.  try running the script as
>
> python -vv script.py
>
> and see where it looks for the getopt module.
>
> is the ImportError all you get, btw ?  it doesn't complain about site.py 
> before
> that ?
> 
> 

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


Re: select() on WinXP

2006-11-23 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> I'm running Python 2.5 on Windows XP. When I try to do this:
>
> [code]
> import select
> select.select([], [], [])
> [/code]
>
> I get this:
>
> [output]
> Traceback (most recent call last):
>  File "C:/Documents and Settings/Grebekel/Desktop/s.py", line 2, in
> 
>select.select([],[],[])
> error: (10022, 'An invalid argument was supplied')
> [/output]
>
> Is there anything I should be aware of to get select() working under
> Windows?

like, say, only calling select if you actually have something you want to 
select on?

(if you want to sleep, use time.sleep())

 



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


Does only emacs and idle support symbolic debugging?

2006-11-23 Thread Victor Ng
Subject line pretty much says it all - are those the only two editors
that support running the symbolic debugger from inside the editor?

vic

-- 
"Never attribute to malice that which can be adequately explained by
stupidity."  - Hanlon's Razor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ImportError: No module named getopt

2006-11-23 Thread Fredrik Lundh
"prashant" wrote:

> I am actually using Cygwin to run a python script.
> I have python 2.5 installed. But when i ran the command mentioned by
> you... I see that it is looking in the wrong directories... how can i
> change these look up directories?

is PYTHONHOME perhaps set to the wrong thing?

if not, you can point it to the root of your Python installation.  use "python 
-h"
for more alternatives.

 



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


[ANN] pylint 0.12.2 / astng 0.16.3

2006-11-23 Thread Sylvain Thénault
Hi there !

I'm pleased to announce new bugs fix releases of pylint and astng. Most
bug discussed more or less recently on the python-projects mailing list
should be fixed by those releases, and astng inference capability has
been enhanced for some construction, so upgrade is recommended.

Visit the respective projects'page of our fresh new .org site to get the
latest source distribution :o)
http://www.logilab.org/project/name/pylint
http://www.logilab.org/project/name/logilab-astng

Enjoy !
-- 
Sylvain Thénault   LOGILAB, Paris (France)
Formations Python, Zope, Plone, Debian:  http://www.logilab.fr/formations
Développement logiciel sur mesure:   http://www.logilab.fr/services
Python et calcul scientifique:   http://www.logilab.fr/science

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


Re: Does only emacs and idle support symbolic debugging?

2006-11-23 Thread Diez B. Roggisch
Victor Ng wrote:

> Subject line pretty much says it all - are those the only two editors
> that support running the symbolic debugger from inside the editor?

Nope, eric for example does as well. And I presume komodo will do that also.

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


Re: What's going on here?

2006-11-23 Thread Dale Strickland-Clark
Thanks for the answers. I am informed but I don't feel enlightened. 

It does strike me as odd that an apparently empty subclass should add extra
function to the base class. 

Not at all obvious.
-- 
Dale Strickland-Clark
We are recruiting Python programmers. Please see the web site.
Riverhall Systems www.riverhall.co.uk

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


Re: ldapsearch example in python-ldap?

2006-11-23 Thread Michael Ströder
Nico Grubert wrote:
> 
> on a linux machine I am running this ldapsearch from the command line:
> 
> ldapsearch -x -h myldaphost.mydomain.com \
>   -D "CN=ldapuser,CN=Users,DC=mydomain,DC=com" -w "secret" \
>   -b "CN=ANYCOMPUTER,CN=Computers,DC=mydomain,DC=com"
> 
> How can I do this with python-ldap?

http://python-ldap.sourceforge.net/docs.shtml contains some links to
introductions.

This command above boils down to:

l=ldap.initialize("ldap://myldaphost.mydomain.com";)
l.simple_bind_s("CN=ldapuser,CN=Users,DC=mydomain,DC=com","secret")
r = l.search_s(
  "CN=ANYCOMPUTER,CN=Computers,DC=mydomain,DC=com",
  ldap.SCOPE_SUBTREE, # this is the default of ldapsearch
  "(objectClass=*)"
)

But you really should learn more about it by diving into:

http://python-ldap.sourceforge.net/doc/python-ldap/ldap-objects.html

Ciao, Michael.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: select() on WinXP

2006-11-23 Thread [EMAIL PROTECTED]
I'm using it for sockets, it works on linux but not on Windows. The
actual code is something like (server side):

r, w, e = select.select(self.clients, [], self.clients, 5)

where self.clients is a list of accepted sockets.

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


Re: select() on WinXP

2006-11-23 Thread Thomas Heller
[EMAIL PROTECTED] schrieb:
> I'm using it for sockets, it works on linux but not on Windows. The
> actual code is something like (server side):
> 
> r, w, e = select.select(self.clients, [], self.clients, 5)
> 
> where self.clients is a list of accepted sockets.
> 
The docs for select.select say:

Empty sequences are allowed, but acceptance of three empty sequences is 
platform-dependent.
(It is known to work on Unix but not on Windows.) 

Thomas

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


Re: ImportError: No module named getopt

2006-11-23 Thread prashant
thanks a lot that helped...


Fredrik Lundh wrote:
> "prashant" wrote:
>
> > I am actually using Cygwin to run a python script.
> > I have python 2.5 installed. But when i ran the command mentioned by
> > you... I see that it is looking in the wrong directories... how can i
> > change these look up directories?
>
> is PYTHONHOME perhaps set to the wrong thing?
>
> if not, you can point it to the root of your Python installation.  use 
> "python -h"
> for more alternatives.
> 
> 

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


Re: Abelson and Python

2006-11-23 Thread Scott David Daniels
markscottwright wrote:
> Fredrik Lundh wrote:
>> markscottwright wrote:
>>
>>  > If it were that easy, the PyPy guys would be done by now.
>>
>> if the PyPy guys had focused on writing a Python interpreter in Python,
>> they'd been done by now.
>>
>> 
> 
> Isn't that the point of PyPy?  It's what their mission statement says
> (http://codespeak.net/pypy/dist/pypy/doc/architecture.html#mission-statement):
> 
> "PyPy is an implementation of the Python programming language written
> in Python itself, flexible and easy to experiment with."
> 
> This is something that is amazingly easy to do in scheme, since the
> language is so simple, but is typically pretty difficult to do in other
> languages
> 
> That said, I see now that the course we're talking about isn't the same
> as the old 6.001 course, and presumably has different pedagogical goals.
> 
There are a more than a few library functions in the Python code that
are written in C in CPython.  Not only is PyPy trying to get the
_entire_ Python system into Python, it is trying to do so in a
friendly-to-translation-in-a-statically-typed-language way.

Besides, if you can freely use "eval" and "exec", how hard is a pure
python language interpreter?

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


Re: select() on WinXP

2006-11-23 Thread [EMAIL PROTECTED]
I patched the code to:

if self.clients:
r, w, e = select.select(self.clients, [], self.clients, 5)

It works now, thank you Thomas :)

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


Re: What's going on here?

2006-11-23 Thread robert
Dale Strickland-Clark wrote:
> Thanks for the answers. I am informed but I don't feel enlightened. 
> 
> It does strike me as odd that an apparently empty subclass should add extra
> function to the base class. 
> 
> Not at all obvious.

Yes. As said, there is missing a __builtin__.Object

object is not an "empty class", but the base builtin-type:

>>> isinstance(int,object)
True

built-in type instances are basically read-only because if ...


>>> (1).spam=1
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'int' object has no attribute 'spam'
>>> 


..would work, that would be very strange. 
Maybe in a mud place language like Ruby, where you can jam and scribble 
everywhere in the system and in builtins, such things are possible.  


I'd propose to add something trivial like


class Object(object):
   def __init__(self,_d={},**kwargs):
   kwargs.update(_d)
   self.__dict__=kwargs 
   ...

to Python. I use such empty (common) class since all time I can think of - and 
frequently. 
If there would be a common such Empty class in Python you'd have a lot of 
advantanges. From ad-hoc instances, "OO-dicts" to reliable pickling of bunches 
of variables etc.


Robert


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


Re: Does only emacs and idle support symbolic debugging?

2006-11-23 Thread Bytter
PyScripter (windows only) here:
http://mmm-experts.com/Products.aspx?ProductId=4

On Nov 23, 4:00 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Victor Ng wrote:
> > Subject line pretty much says it all - are those the only two editors
> > that support running the symbolic debugger from inside the editor?Nope, 
> > eric for example does as well. And I presume komodo will do that also.
> 
> Diez

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


Re: Simple threading

2006-11-23 Thread jrpfinch
many thanks - works perfectly now

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


Re: How to sort list

2006-11-23 Thread Michael J. Fromberger
In article <[EMAIL PROTECTED]>,
 "Lad" <[EMAIL PROTECTED]> wrote:

> I have a list of emails and I would like to sorted that list by domains
> E.g.
> If the list is
> 
> Emails=['[EMAIL PROTECTED]','[EMAIL PROTECTED]','[EMAIL PROTECTED]','[EMAIL 
> PROTECTED]',]
> 
> after sorting I would like to have
> Emails=['[EMAIL PROTECTED]','[EMAIL PROTECTED]','[EMAIL PROTECTED]','[EMAIL 
> PROTECTED]',]
> 
> What is the best/easiest way?

One reasonable option is to use the .sort() method of a list:

  Emails.sort(key = lambda s: list(reversed(s.split('@'

The "key" parameter specifies how to obtain a sort key from each element 
in the source list.

Cheers,
-M

-- 
Michael J. Fromberger | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/  | Dartmouth College, Hanover, NH, USA
-- 
http://mail.python.org/mailman/listinfo/python-list


Python business software?

2006-11-23 Thread Greg Lindstrom

Hello-

My wife runs a sewing/embroidery business and has asked me to write a system
to help her with her client database, inventory, and accounts
receivable/payable.  I've looked into using either PythonCard or Dabo (I
like both packages) but thought I ask the list if there is anything like
this out there already.  Tasks such as tracking clients are fairly routine
in business, so maybe there's something close that I could hack in order to
add details specific to our business.  We only have one computer right now,
so we don't *need* a web-based system but we plan on growing so it would be
an option.

Thanks for you help,
--greg
-- 
http://mail.python.org/mailman/listinfo/python-list

python gaining popularity according to a study

2006-11-23 Thread [EMAIL PROTECTED]
http://www.tiobe.com/index.htm?tiobe_index

Python is the 7th most commonly used language, up from 8th.
The only one gaining ground besides VB in the top 10.

We're glad, our app is written in python.
It's free at http://pnk.com and it is a web timesheet for project
accounting

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


Re: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]?

2006-11-23 Thread Brian Quinlan
Fredrik Lundh wrote:
> 4) [] and {} always create a new object every time they're evaluated.

Not quite. The empty tuple is cached:

 >>> a = ()
 >>> b = ()
 >>> a is b
True

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


Re: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]?

2006-11-23 Thread Fredrik Lundh
Brian Quinlan wrote:

>> 4) [] and {} always create a new object every time they're evaluated.
> 
> Not quite. The empty tuple is cached:
> 
>  >>> a = ()
>  >>> b = ()
>  >>> a is b
> True

() isn't [] or {}, though.  time to switch to a bigger font? ;-)



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


Re: The Python Papers Edition One

2006-11-23 Thread Klaas
Tennessee writes:
>* If you say LaTex, I'll eat your brain. Or my hat. Unless I'm
> seriously underrating it, but I don't think so.

Why?  It is a suitable solution to this problem.  You can produce
unformatted content, then produce pdf and html pages from it.

-Mike

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


Python work in UK

2006-11-23 Thread Will McGugan
Hi,

I'd love to work in Python, for the sake of my blood pressure, but there 
doesnt seem to be that many jobs that look for Python as the main skill. 
I use Python at work from time to time, and occasionaly get to spend 
several days on a Python project but the majority of the time I use C++. 
How can I make that leap to working with Python? There doesn't seem to 
be many UK positions on the jobs section of Python.org or the usual jobs 
sites. Any recommended jobs sites or tips? (I have googled)

In the off chance that a potential empolyer is reading this, I'm looking 
for something in web development, applications, graphics or other 
interesting field. Here is a copy of my CV.

http://www.willmcgugan.com/cvwillmcgugan.pdf

Regards,

Will McGugan
-- 
http://www.willmcgugan.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Python 2.5 idle and print command How do I suppress a line feed?

2006-11-23 Thread notejam
Hi,
I am having a problem with print statements always cause a line feed.
I need to print a line of text, then the next print statement will
start printing where the last one stopped rather than drop down a line.

In basic we can do this with print "texst";   followed by next command
print "text2"
So how do I do that in python?

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


Re: Trying to understand Python objects

2006-11-23 Thread Bruno Desthuilliers
Aahz a écrit :
> In article <[EMAIL PROTECTED]>,
> Ben Finney  <[EMAIL PROTECTED]> wrote:
> 
>>Typically, classes are created as a subclass of another class. The
>>top-level basic type in Python is 'object', so if your class doesn't
>>make sense deriving from anything else, derive from 'object'.
>>
>>   class Point(object):
>>   pass
>>
>>Defining a class with *no* superclass is not recommended. If you don't
>>yet understand the difference between the above style (called a
>>"new-style" class) and the style you presented, you should always
>>derive from a superclass ('object' or something more specific) until
>>you encounter a situation where that causes a problem.
> 
> 
> Side note: I disagree with the above advice, but it's Thanksgiving and I
> don't have enough room on the margin for the proof.  I think classic
> classes are just fine.

Don't see it as a religious point please, but I fail to understand why 
you seem so in love with old-style classes ? new-style classes are the 
"official" Python object model since 2.2 (which is a few years ago now), 
and the last mandatory use of them (exceptions...) disappeared with the 
2.5. AFAIK, everything you do with old-style classes can be done with 
new-style ones. FWIW, old-style classes support is now only for backward 
compat. So *why* insisting on using them ?

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


Re: Python 2.5 idle and print command How do I suppress a line feed?

2006-11-23 Thread Will McGugan
notejam wrote:
> Hi,
> I am having a problem with print statements always cause a line feed.
> I need to print a line of text, then the next print statement will
> start printing where the last one stopped rather than drop down a line.
> 
> In basic we can do this with print "texst";   followed by next command
> print "text2"
> So how do I do that in python?
> 

Thusly...

print "texst",
print "text2"

--
work: http://www.kelpiesoft.com
blog: http://www.willmcgugan.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 idle and print command How do I suppress a line feed?

2006-11-23 Thread Will McGugan
notejam wrote:
> Hi,
> I am having a problem with print statements always cause a line feed.
> I need to print a line of text, then the next print statement will
> start printing where the last one stopped rather than drop down a line.
> 
> In basic we can do this with print "texst";   followed by next command
> print "text2"
> So how do I do that in python?
> 

Or if you want to get rid of the space...

import sys
sys.stdout.write("texst")
sys.stdout.write("text2")

-- 
--
work: http://www.kelpiesoft.com
blog: http://www.willmcgugan.com
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >