Re: Problems with file IO in a thread, and shutil

2008-06-26 Thread Roopesh
Thanks for the reply. I did testing in a clean system, were anti virus/
spyware is not installed. It still gave this problem, in say 1 out of
1000 cases.

By any chance would it be possible that the Windows OS has not
completed writing to the file even after file.flush() and file.close()
is called?

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


Re: Threads, GIL and re.match() performance

2008-06-26 Thread Pau Freixes
But Python C-API[1] it's the main base for extent python with C/c++, and
this is not not threadsafe.? I dont understand

[1] http://docs.python.org/api/api.html

On Thu, Jun 26, 2008 at 4:49 AM, Benjamin <[EMAIL PROTECTED]>
wrote:

> On Jun 25, 9:05 am, Mirko Dziadzka <[EMAIL PROTECTED]> wrote:
> >
> > 1) Is there a reason for this?
>
> I think it is because the Python re library uses the Python C-API
> which is not threadsafe.
> > 2) Is the regex library not thread-safe?
> > 3) Is it possible, to release the GIL in re.match() to
> >get more performance?
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Pau Freixes
Linux GNU/User
--
http://mail.python.org/mailman/listinfo/python-list

Re: Accounting and financial system

2008-06-26 Thread Marcelo de Moraes Serpa
Btw, sorry it is [OT], I forgot to add the prefix, it is really not a post
tied to the language itself.

On Tue, Jun 24, 2008 at 1:24 PM, Marcelo de Moraes Serpa <
[EMAIL PROTECTED]> wrote:

> Hello list,
>
> In a next project of mine, I will need to implement some accounting and
> financial control. It is not a full ERP, only the basic functions for
> finances and accounting control. However, I have little to no experience in
> this business domain (accounting and finances) but I really do need to
> understand the basic machinery behind it, even if it will take a significant
> amount of time. What I would like to know is where I could look (besides
> getting a degree :P) for sample code and documentation for these subjects?
> Do you think I would need to read some books before I get into code? If so,
> which ones? For sample code, I was thinking about OpenERP, since I've heard
> it is a complete ERP solution and it is written in python ;)
>
> Really, I'm committed to understand the basiscs of the said business
> domains, I really need this project to succeed :)
>
> Thanks in advance!
>
> Marceo.
>
--
http://mail.python.org/mailman/listinfo/python-list

Accounting and financial system

2008-06-26 Thread Marcelo de Moraes Serpa
Hello list,

In a next project of mine, I will need to implement some accounting and
financial control. It is not a full ERP, only the basic functions for
finances and accounting control. However, I have little to no experience in
this business domain (accounting and finances) but I really do need to
understand the basic machinery behind it, even if it will take a significant
amount of time. What I would like to know is where I could look (besides
getting a degree :P) for sample code and documentation for these subjects?
Do you think I would need to read some books before I get into code? If so,
which ones? For sample code, I was thinking about OpenERP, since I've heard
it is a complete ERP solution and it is written in python ;)

Really, I'm committed to understand the basiscs of the said business
domains, I really need this project to succeed :)

Thanks in advance!

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

urllib tutorial or manual

2008-06-26 Thread Alex Bryan
I have never used the urllib class and I need to use it for an app I  
am working on. I am wondering if anyone has any good sites that will  
fill me in on it(especially the urllib.urlopen module). Or better yet,  
an example of how you would submit a search term into the search field  
on a site, such as google.

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


Question on time module

2008-06-26 Thread subhabrata . iisc
Dear Members of the group,
I have one function
def sum1(n):
  a1=5
  a2=6
  a3=a1+a2
  a4=a3+8
  print "The First sum is"
  print a3
  print "The Second sum is"
  print a4

Now, I want to do it in a way, a4 is calculated after a given time
interval of a3 -this is easy but if I want to check after how much
time a4 is calculated from a3 how can I do?
If any one can help it.
Best Regards,
Subhabrata.

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


Re: urllib tutorial or manual

2008-06-26 Thread Simon Brunning
2008/6/24 Alex Bryan <[EMAIL PROTECTED]>:
> I have never used the urllib class and I need to use it for an app I am
> working on. I am wondering if anyone has any good sites that will fill me in
> on it(especially the urllib.urlopen module). Or better yet, an example of
> how you would submit a search term into the search field on a site, such as
> google.

This is for urllib2:



If you must stick with urllib:



-- 
Cheers,
Simon B.
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question about tuples and list comprehensions

2008-06-26 Thread Peter Otten
idiolect wrote:

> On Jun 25, 7:26 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
>> idiolect wrote:
>> > Hi all - Sorry to plague you with another newbie question from a
>> > lurker.  Hopefully, this will be simple.
>>
>> > I have a list full of RGB pixel values read from an image.  I want to
>> > test each RGB band value per pixel, and set it to something else if it
>> > meets or falls below a certain threshold - i.e., a Red value of 0
>> > would be changed to 50.
>>
>> > I've built my list by using a Python Image Library statement akin to
>> > the following:
>>
>> > data = list(image.getdata())
>>
>> > Which produces a very long list that looks like [(0,150,175),
>> > (50,175,225),...].  I'm trying to figure out a fast and pythonic way
>> > to perform my operation.  The closest I've come so far to a succinct
>> > statement is a list comprehension along the syntax of:
>>
>> Why are you trying to do this with a list comprehension?  Learn the
>> basics first.  Perhaps you have read too many of the recent threads
>> presenting diverting challenges for bored experienced programmers.  Some
>> of these were definitely not Pythonic code for real use.
>>
>> First question: do you really want to create a new 'very long list' or
>> modify list 'data' in place.  Let's assume the latter.
>>
>> for i,tup in enumerate(data):
>>  data[i] = replace(tup)
>>
>> where replace(tup) is an expression or function that produces a tuple
>> meeting your criteria.  Simplest is
>> (max(tup[0],Rthresh), max(tup[1],Gthresh), max(tup[2],Bthresh)).
>>
>> If nearly all your pixels are ok, add the following before the
>> assignment so you only make replacements when actually needed:
>> if tup[0] < Rthresh or tup[1] < Gthresh or tup[2] < Bthresh:
>>
>> Terry Jan Reedy
> 
> A giant thank-you to all who've posted in response to my query - these
> are all much better approaches to my problem.  I think I got hooked on
> using a list comprehension as it seemed the most concise approach vs.
> other techniques after a bunch of Google searches, but all of you have
> pointed out more efficient methods.  I appreciate your willingness to
> indulge a n00b who hasn't thought his problem through, apparently.
> I'll try all of these approaches out over the next day and see what
> works best, although I suspect you've all posted sufficient solutions.
> 
> Can't wait to try these suggestions out - cheers, idiolect

I'd like to emphasize Roger Miller's point with a small example script:

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

def transform_image_getdata(old, new):
image = Image.open(old)

image.putdata([(max(50, r), min(g*2, 255), 0) for r, g, b in
image.getdata()])

image.save(new)

def transform_image_point(old, new):
image = Image.open(old)

transform_red = [max(50, i) for i in range(256)]
transform_green = [min(i*2, 255) for i in range(256)]
transform_blue = [0 for i in range(256)]

image.point(transform_red + transform_green + transform_blue).save(new)


if __name__ == "__main__":
import os, time
def measure(f):
def g(*args, **kw):
start = time.time()
try:
return f(*args, **kw)
finally:
print f.__name__, time.time() - start
return g

for name in sys.argv[1:]:
a, b = os.path.splitext(name)
measure(transform_image_getdata)(name, a + ".getdata" + b)
measure(transform_image_point)(name, a + ".point" + b)

Run it:

$ ./transform_image.py tmp.jpg
transform_image_getdata 27.5557489395
transform_image_point 0.458500862122

For the example Image.point() is about 60 times faster than getdata(). It's
the way to go if you can handle the color channels individually.

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


Re: Freeze problem with Regular Expression

2008-06-26 Thread John Machin
On Jun 26, 8:29 am, John Machin <[EMAIL PROTECTED]> wrote:
> (2) ALWAYS use a raw string for regexes; your \s* will match on lower-
> case 's', not on spaces
and should have written:
   (2) ALWAYS use a raw string for regexes. <<<=== Big fat full stop
aka period.
but he was at the time only half-way through the first cup of coffee
for the day :-)
--
http://mail.python.org/mailman/listinfo/python-list


python for driving the sound card

2008-06-26 Thread Rustom Mody
I am exploring the use of python to drive the sound card to experiment with
tunings.
How easy is it to write (or is it already available) to write a function
chord which takes a (list of) frequencies and plays them?
--
http://mail.python.org/mailman/listinfo/python-list

Re: recursion in Class-methods?

2008-06-26 Thread Bruno Desthuilliers

klant a écrit :

do i need to call Graph.find_path?

>



g = Graph({'A': ['B', 'C'],

 'B': ['C', 'D'],
 'C': ['D'],
 'D': ['C'],
 'E': ['F'],
 'F': ['C']})

g

<__main__.Graph instance at 0x01D74378>

g.find_all_paths('A', 'C')


Traceback (most recent call last):
  File "", line 1, in 
g.find_all_paths('A', 'C')
  File "C:/Python25/Progs/pygameProgs/visualgraph/graph.py", line 26,
in find_all_paths
newpaths = find_all_paths(self.dictionary, node, end, path)
NameError: global name 'find_all_paths' is not defined

g.find_path('A', 'C')


Traceback (most recent call last):
  File "", line 1, in 
g.find_path('A', 'C')
  File "C:/Python25/Progs/pygameProgs/visualgraph/graph.py", line 13,
in find_path
newpath = find_path(self.dictionary, node, end, path)
NameError: global name 'find_path' is not defined

>




class Graph:


Unless you need to ensure compat with ages-old Python versions, better 
to use newstyle classes:


class Graph(object):


def __init__(self, dictionary):
self.dictionary = dictionary

def find_path(self, start, end, path=[]):


http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm

Unless you exactly what you're doing (and given your current problem, I 
can tell it's not the case), *don't* use mutable containers as default 
function argument values.



 def find_path(self, start, end, path=None):
 if path is None:
 path = []


path = path + [start]


  path.append(start)


if start == end:
return path
if not self.dictionary.has_key(start):


  if start not in self.dictionnary:


return None




for node in self.dictionary[start]:
if node not in path:
newpath = find_path(self.dictionary, node, end, path)


  newpath = self.find_path(...)





(snip remaining code - same problems, same solutions...)
--
http://mail.python.org/mailman/listinfo/python-list


Re: struct.pack behavior

2008-06-26 Thread John Machin
On Jun 26, 12:38 pm, "Steven Clark" <[EMAIL PROTECTED]> wrote:
> On Wed, Jun 25, 2008 at 7:03 PM, John Machin <[EMAIL PROTECTED]> wrote:
> > On Jun 26, 9:00 am, "Steven Clark" <[EMAIL PROTECTED]> wrote:
> >> Can anyone explain to me why
> >> struct.pack('HB',1,2) gives 3 bytes, whereas struct.pack('BH',1,2)
> >> gives 4 bytes?
>
> > Alignment -- read the manual.
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> If "the manual" is the help files for the struct module, I've read it
> several times over. I understand endianness; I don't understand
> alignment. Could anyone give a less cryptic / terse answer?

google("struct alignment")
--
http://mail.python.org/mailman/listinfo/python-list


Komodo Edit newbie Q

2008-06-26 Thread John Dann
I'm learning Python using the Komodo Edit freeware code editor. One
thing I'm finding a little confusing is that the code completion lists
(what I would call Intellisense coming from a .Net background) are
often very incomplete, especially with imported classes like wx. It's
like KE can't look far enough into these classes to offer a
comprehensive list of method etc options.

I presume that I haven't possibly omitted some KE setup step that
would give more detail to the code completion?

If not then maybe this is just a limitation of the KE freeware
(because it's free?). Does anyone know if say Komodo IDE offers more
in the way of code completion (I know that it offers more things in
the way of debugging etc, but it's code completion specifically that
I'm asking about here). Or is one of the other Python IDEs maybe more
capable when it comes to code completion?
--
http://mail.python.org/mailman/listinfo/python-list


Looping-related Memory Leak

2008-06-26 Thread Tom Davis
I am having a problem where a long-running function will cause a
memory leak / balloon for reasons I cannot figure out.  Essentially, I
loop through a directory of pickled files, load them, and run some
other functions on them.  In every case, each function uses only local
variables and I even made sure to use `del` on each variable at the
end of the loop.  However, as the loop progresses the amount of memory
used steadily increases.

I had a related problem before where I would loop through a very large
data-set of files and cache objects that were used to parse or
otherwise operate on different files in the data-set.  Once again,
only local variables were used in the cached object's methods.  After
a while it got to the point where simply running these methods on the
data took so long that I had to terminate the process (think, first
iteration .01sec, 1000th iteration 10sec).   The solution I found was
to cause the cached objects to become "stale" after a certain number
of uses and be deleted and re-instantiated.

However, in the current case, there is no caching being done at all.
Only local variables are involved.  It would seem that over time
objects take up more memory even when there are no attributes being
added to them or altered.  Has anyone experienced similar anomalies?
Is this behavior to be expected for some other reason?  If not, is
there a common fix for it, i.e. manual GC or something?




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


Re: Working with the Windows Registry

2008-06-26 Thread teh_sAbEr
Great! It works properly now but I have one more question, would
anyone know how to get the changes to take effect immediately? Like
some sort of Python way to force the desktop to reload? AFAIK the only
way that'll happen is if I use the Display Properties dialog box. The
Registry value is changed properly, its just I don't think the changes
will take effect until I restart.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Looping-related Memory Leak

2008-06-26 Thread Carl Banks
On Jun 26, 5:19 am, Tom Davis <[EMAIL PROTECTED]> wrote:
> I am having a problem where a long-running function will cause a
> memory leak / balloon for reasons I cannot figure out.  Essentially, I
> loop through a directory of pickled files, load them, and run some
> other functions on them.  In every case, each function uses only local
> variables and I even made sure to use `del` on each variable at the
> end of the loop.  However, as the loop progresses the amount of memory
> used steadily increases.

Do you happen to be using a single Unpickler instance?  If so, change
it to use a different instance each time.  (If you just use the module-
level load function you are already using a different instance each
time.)

Unpicklers hold a reference to everything they've seen, which prevents
objects it unpickles from being garbage collected until it is
collected itself.


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


Re: Mobile Devices

2008-06-26 Thread rodmc
Thanks for your reply, I may dig out my really old Symbian phone and
try it out.

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


Re: Looping-related Memory Leak

2008-06-26 Thread Peter Otten
Tom Davis wrote:

> I am having a problem where a long-running function will cause a
> memory leak / balloon for reasons I cannot figure out.  Essentially, I
> loop through a directory of pickled files, load them, and run some
> other functions on them.  In every case, each function uses only local
> variables and I even made sure to use `del` on each variable at the
> end of the loop.  However, as the loop progresses the amount of memory
> used steadily increases.
> 
> I had a related problem before where I would loop through a very large
> data-set of files and cache objects that were used to parse or
> otherwise operate on different files in the data-set.  Once again,
> only local variables were used in the cached object's methods.  After
> a while it got to the point where simply running these methods on the
> data took so long that I had to terminate the process (think, first
> iteration .01sec, 1000th iteration 10sec).   The solution I found was
> to cause the cached objects to become "stale" after a certain number
> of uses and be deleted and re-instantiated.

Here the alleged "memory leak" is clearly the cache, and the slowdown is
caused by garbage collector. The solution is to turn it off with
gc.disable() during phases where your programm allocates huge amounts of
objects with the intent of keeping them for a longer time.

> However, in the current case, there is no caching being done at all.
> Only local variables are involved.  It would seem that over time
> objects take up more memory even when there are no attributes being
> added to them or altered.  Has anyone experienced similar anomalies?
> Is this behavior to be expected for some other reason?  If not, is
> there a common fix for it, i.e. manual GC or something?

Unless you post a script demonstrating the leak I will assume you are
overlooking a reference that keeps your data alive -- whether it's a true
global or within a long-running function doesn't really matter.

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


Re: Threads, GIL and re.match() performance

2008-06-26 Thread Matthieu Brucher
Hi,

The C-API uses references counts as well, so it is not threadsafe.

Matthieu

2008/6/26 Pau Freixes <[EMAIL PROTECTED]>:
> But Python C-API[1] it's the main base for extent python with C/c++, and
> this is not not threadsafe.? I dont understand
>
> [1] http://docs.python.org/api/api.html
>
> On Thu, Jun 26, 2008 at 4:49 AM, Benjamin <[EMAIL PROTECTED]>
> wrote:
>>
>> On Jun 25, 9:05 am, Mirko Dziadzka <[EMAIL PROTECTED]> wrote:
>> >
>> > 1) Is there a reason for this?
>>
>> I think it is because the Python re library uses the Python C-API
>> which is not threadsafe.
>> > 2) Is the regex library not thread-safe?
>> > 3) Is it possible, to release the GIL in re.match() to
>> >get more performance?
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>
>
>
> --
> Pau Freixes
> Linux GNU/User
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
French PhD student
Website : http://matthieu-brucher.developpez.com/
Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92
LinkedIn : http://www.linkedin.com/in/matthieubrucher
--
http://mail.python.org/mailman/listinfo/python-list


Re: poplib - retr() getting stuck

2008-06-26 Thread Roopesh
Thanks for the help.

At present I have modified the poplib code as follows (In POP3 and
POP3_SSL classes): Is it the correct way?

def __init__(self, host, port = POP3_PORT):
self.host = host
self.port = port
msg = "getaddrinfo returns an empty list"
self.sock = None

socket.setdefaulttimeout(30)

for res in socket.getaddrinfo(self.host, self.port, 0,
socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
self.sock.connect(sa)
except socket.error, msg:

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


Urllib(1/2) how to open multiple client sockets?

2008-06-26 Thread ShashiGowda
Hey there i made a script to download all images from a web site but
it runs damn slow though I have a lot of bandwidth waiting to be used
please tell me a way to use urllib to open many connections to the
server to download many pics simultaneously Any off question
suggestions are also ok...
--
http://mail.python.org/mailman/listinfo/python-list


instructions on adding external Tcl/Tk widget into Tkinter?

2008-06-26 Thread oyster
It is so funny that the official GUI lib for python is Tkinter, but I
cannot find an articles which explains indetail how can we use
thounsands of Tcl/Tk widget in Tkinter.


For example, I have download the dll at
http://www.hwaci.com/sw/tkhtml/index.html, renamed it to tkhtml12.dll
and put it in
H:\python25\bin\tcl\Tkhtml1.2\
then I edited a h:\python25\bin\tcl\Tkhtml1.2\pkgIndex.tcl file:
[**pkgIndex.tcl]
if {![package vsatisfies [package provide Tcl] 8]} {return}
if {[string compare $::tcl_platform(platform) windows]} {return}
if {[info exists ::tcl_platform(debug)]} {
package ifneeded Tkhtml 1.2.3 [list load [file join $dir
Tkhtml12g.dll] Tkhtml]
} else {
package ifneeded Tkhtml 1.2.3 [list load [file join $dir
Tkhtml12.dll] Tkhtml]
}
[/**pkgIndex.tcl]

but http://tix.sourceforge.net/Tixapps/src/Python/TkHtml.py says
[*says*]
attempt to provide package Tkhtml 1.2.3 failed: package Tkhtml 0.0
provided instead
[/*says*]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Threads, GIL and re.match() performance

2008-06-26 Thread Pau Freixes
Hi

Ok, if I understand between Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS
is not possible use a C/Python api functions ?

Sorry, but when thread enter another time with Py_END_ALLOW_THREADS this
thread enter to competition to lock GIL ?

Thks

Thks


On Thu, Jun 26, 2008 at 12:16 PM, Matthieu Brucher <
[EMAIL PROTECTED]> wrote:

> Hi,
>
> The C-API uses references counts as well, so it is not threadsafe.
>
> Matthieu
>
> 2008/6/26 Pau Freixes <[EMAIL PROTECTED]>:
> > But Python C-API[1] it's the main base for extent python with C/c++, and
> > this is not not threadsafe.? I dont understand
> >
> > [1] http://docs.python.org/api/api.html
> >
> > On Thu, Jun 26, 2008 at 4:49 AM, Benjamin <[EMAIL PROTECTED]>
> > wrote:
> >>
> >> On Jun 25, 9:05 am, Mirko Dziadzka <[EMAIL PROTECTED]> wrote:
> >> >
> >> > 1) Is there a reason for this?
> >>
> >> I think it is because the Python re library uses the Python C-API
> >> which is not threadsafe.
> >> > 2) Is the regex library not thread-safe?
> >> > 3) Is it possible, to release the GIL in re.match() to
> >> >get more performance?
> >>
> >> --
> >> http://mail.python.org/mailman/listinfo/python-list
> >
> >
> >
> > --
> > Pau Freixes
> > Linux GNU/User
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
>
>
>
> --
> French PhD student
> Website : http://matthieu-brucher.developpez.com/
> Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92
> LinkedIn : http://www.linkedin.com/in/matthieubrucher
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Pau Freixes
Linux GNU/User
--
http://mail.python.org/mailman/listinfo/python-list

Re: Urllib(1/2) how to open multiple client sockets?

2008-06-26 Thread Gerhard Häring

ShashiGowda wrote:

Hey there i made a script to download all images from a web site but
it runs damn slow though I have a lot of bandwidth waiting to be used
please tell me a way to use urllib to open many connections to the
server to download many pics simultaneously Any off question
suggestions are also ok...


"Simultaneously" means using multiple threads (or processes).

You could create worker threads that do the downloading (use the 
threading module for this) and communicate with them via a queue (use 
the Queue module for this).


For example the main thread would then do the HTML parsing and push the 
image URLs to the worker threads via the queue.


Each worker thread then polls the queue and downloads the images it gets.

One issue is how to terminate the multithreaded application. A simple 
approach is to use a sentinel value to push to the queue to signal the 
worker threads to quit. Something like "QUIT" will do. Be sure to push 
at least as many sentinel values as you have worker threads, then.


-- Gerhard

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


extend getattr()

2008-06-26 Thread Rotlaus
Hello,

lets assume i have some classes:

class A(object):
def __init__(self):
b = B()

class B(object):
def __init__(self):
c = C()

class C(object):
def __init__(self):
pass

and now i wanna do something like this:

a=A()
c=getattr(a, 'b.c')

I know this doesn't work, but what can i do to get this or a similar
functionality to get it work for this sample and for even more nested
classes?

Kind regards,

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


Re: extend getattr()

2008-06-26 Thread Gerhard Häring

Rotlaus wrote:

Hello,

lets assume i have some classes:
[...]

a=A()
c=getattr(a, 'b.c')

I know this doesn't work, but what can i do to get this or a similar
functionality to get it work for this sample and for even more nested
classes?


Just recursively apply the getattr(), like this:

class A(object):
def __init__(self):
self.b = B()

class B(object):
def __init__(self):
self.c = C()

class C(object):
def __init__(self):
pass

def ext_getattr(obj, attr):
for subattr in attr.split("."):
obj = getattr(obj, subattr)
return obj

a=A()
c = ext_getattr(a, 'b.c')

-- Gerhard

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


Re: Threads, GIL and re.match() performance

2008-06-26 Thread Jeff
> However, I assumed that calls to (thread safe) C Library functions
> release the global interpreter lock.

This is mainly applicable to external C libraries.  The interface to
them may not be thread-safe; anything that uses the Python API to
create/manage Python objects will require use of the GIL.  So the
actual regex search may release the GIL, but the storing of results
(and possibly intermediate results) would not.

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


Re: extend getattr()

2008-06-26 Thread Cédric Lucantis
Le Thursday 26 June 2008 13:06:53 Rotlaus, vous avez écrit :
> Hello,
>
> lets assume i have some classes:
>
> class A(object):
> def __init__(self):
> b = B()
>
> class B(object):
> def __init__(self):
> c = C()
>

note you're just defining some local variables here, should be self.b = B() 
and self.c = C().

> class C(object):
> def __init__(self):
> pass
>
> and now i wanna do something like this:
>
> a=A()
> c=getattr(a, 'b.c')
>
> I know this doesn't work, but what can i do to get this or a similar
> functionality to get it work for this sample and for even more nested
> classes?
>

You could do it manually:

c = getattr(getattr(a, 'b'), 'c')

or make it automatic:

def get_dotted_attr (obj, dotted_attr) :
for attr in dotted_attr.split('.') :
obj = getattr(obj, attr)
return obj

a = A()
print 'a.b.c = %s' % get_dotted_attr(a, 'b.c')

-- 
Cédric Lucantis
--
http://mail.python.org/mailman/listinfo/python-list


Re: the problem about the DLL file generate by py2exe

2008-06-26 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> Dear All,
> 
> I have try to use the py2exe to compile the DLL file
> 
> first i write the simple python script "test01.py":
> def test001():
> return 1
> 
> then write the setup.py:
> # setup.py
> from distutils.core import setup
> import py2exe
> import sys
> 
> if len(sys.argv) == 1:
> sys.argv.append("py2exe")
> sys.argv.append("-q")
> 
> class Target:
> def __init__(self, **kw):
> self.__dict__.update(kw)
> # for the version info resources (Properties -- Version)
> self.version = "0.0.1"
> self.company_name = "Nil"
> self.copyright = "Nil"
> self.name = "test"
> 
> testTK = Target(
> # used for the versioninfo resource
> description = "test app",
> # what to build
> modules = ["test01"],
> script = "test01.py",
> # specify which type of com server you want (exe and/or dll)
> create_exe = False,
> create_dll = True)
> 
> #setup(windows=["hkcity_ide_main.py"])
> setup(
> name='Test',
> options={"py2exe": {"bundle_files": 1, }},
> zipfile=None,
> version='1.0',
> description='Test',
> author='',
> author_email='',
> url='',
> ctypes_com_server=[testTK],
> )
> 
> 
> and compile the it by the command:
> 
> C:\Python25\python setup.py py2exe
> 
> 
> I use the script try to call the function "test001" in the "test01.py"
> from ctypes import *
> test01 = cdll.LoadLibrary("test01.dll")
> test001 = test01.test001
> print test01()
> 
> However, this is out the error:
> AttributeError: function 'test001' not found
> 
> Is it any problem when i define the function?

I guess you should define a python-function, inside which you call your
dll-function.

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


Re: very large graph

2008-06-26 Thread boggom
Drawing a large graph like this is not
very insightful by itself, and doing this well
is still an art form.
Many cool visualizations, and all
very domain and question dependent,
can be found at
http://www.visualcomplexity.com/vc/

You can also search on flickr for network
and graph drawing.

Much of it is eyecandy though. What do you
really want to know?

Your graph is not overly huge for python, provided
you do not want to compute nonlocal statistics
such as betweenness metrics. (If you have
a laptop running windows and with
less than 1GB RAM, then you have a really large graph.)

Given that you do not know much about graph theory,
I would suggest that networkx applied to a
subset of your large website --- one of the
representative branches --- will allow
for the fastest way to figure out what you
want to do. Python provides access to many other
libraries for html mangling or even webpage
analysis. Imagine writing C code to ask questions
like: how many pdfs and images? how big are they?
when were these pages last updated? etc.
You can come up with 10 questions faster
than you can write C code, and this where
python has its great advantage.

You can learn graph theory while using these libraries,
on one of the smaller branches of your website tree.
Even interactively by using ipython.
This provides at least a feeling of great power while
stumbling in the dark.

Many of your edges are probably repetitions
associated with navigation menus to provide
a standard look-and-feel. See how much of that
you can strip out and find the cross-links that took
effort to insert an manage. (I suggest
doing the analyis on a digraph rather than a graph,
even if you want to draw it as graph.)


For visualization, the new ubigraph is quite
fast compared to graphviz.
See the cool networkx + ubigraph
video at http://ubietylab.net/blog/


Ask on the networkx mailinglist when stuck.

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


Making code more efficient and effective

2008-06-26 Thread cokofreedom
I've written up a little piece of code that isn't that foolproof to
scan through a file (java presently) to find functions and then look
for them throughout the document and output the name of the function,
followed by how many times it appears and the lines it appears on.

What I was looking for was ways to improve, simplfy and beautify the
code. More to aid my learning of Python than produce a perfect way to
scan for this (netbeans was annoying me...which is why I did this)

Anyway, the source code:

from __future__ import with_statement

functions = dict()
func_words = ("private", "public", "protected")
ignore_class = " class "

def get_func_name(line):
for word in func_words:
if word in line: break
else: return None
# set it to ignore the func_word and the space after
line = line[len(word) + 1:]
index = line.find("(")
if index != -1:
func_name = ""
for letter in reversed(line[:index]):
if letter == " ": break
func_name += letter
return ''.join(reversed(func_name))
else: return None

with open(r"C:\example.java", "r") as test_file:
for number, line in enumerate(test_file):
line = line.strip()
if line.startswith(func_words) and line.find(ignore_class ) ==
-1:
func_name = get_func_name(line);
if func_name is not None:
functions.setdefault(func_name, []).append(number)

test_file.seek(0)
for number, line in enumerate(test_file):
for key in functions.iterkeys():
if line.find(key) != -1:
functions[key].append(number)

print "\n".join("Function: %s, found on %d line(s); these being
%s"
% (k, len(v), v) for k, v in
functions.iteritems())
--
http://mail.python.org/mailman/listinfo/python-list


where is the error?

2008-06-26 Thread lajam
Hello,

I'm trying to assign data into an array with the nonzero function.
There is my code.

from numarray import *
diff_temp=(logical_and(values[:,5] > -2,values[:,5] < 2)).nonzero()

This command works fine but when I apply the following,

values_matchup=values_Stumpf[diff_temp_Stumpf,:]

I have this error message:
IndexError: each subindex must be either a slice, an integer,
Ellipsis, or NewAxis

Does someone know what it is the problem? I'm using python2.4.3 on
Ubuntu.

Using this command with python on windows xp worked fine.

Thank you for the help,
Cedric
--
http://mail.python.org/mailman/listinfo/python-list


Re: Making code more efficient and effective

2008-06-26 Thread Cédric Lucantis
Le Thursday 26 June 2008 14:11:35 [EMAIL PROTECTED], vous avez écrit :
> I've written up a little piece of code that isn't that foolproof to
> scan through a file (java presently) to find functions and then look
> for them throughout the document and output the name of the function,
> followed by how many times it appears and the lines it appears on.
>
> What I was looking for was ways to improve, simplfy and beautify the
> code. More to aid my learning of Python than produce a perfect way to
> scan for this (netbeans was annoying me...which is why I did this)
>
> Anyway, the source code:

I would use some regexp instead (assuming that the function prototype is on a 
single line and that the return type of the function is a single identifier, 
I don't remember if it's always the case in Java)

PAT = re.compile('^[ ]*(public|protected|private)[ ]+([a-zA-Z0-9_]+)
[ ]+([a-zA-Z0-9_]+)[ ]+\((.*)\).*$')

for line in source_file :
if PAT.match(line) :
func_vis = PAT.sub(r'\1', line)
func_type = PAT.sub(r'\2', line)
func_name = PAT.sub(r'\3', line)
func_args = PAT.sub(r'\4', line)
print "'%s' -> '%s' '%s' '%s' '%s'" % (line, func_vis, func_type, 
func_name, func_args)

It might be hard to read but will avoid a lot of obscure parsing code. I can't 
tell if it makes the code more efficient but you don't care about that unless 
you're parsing several million lines of code.

-- 
Cédric Lucantis
--
http://mail.python.org/mailman/listinfo/python-list


ask for a RE pattern to match TABLE in html

2008-06-26 Thread oyster
that is, there is no TABLE tag between a TABLE, for example
something with out table tag
what is the RE pattern? thanks

the following is not right
[^table]*?
--
http://mail.python.org/mailman/listinfo/python-list


Re: ask for a RE pattern to match TABLE in html

2008-06-26 Thread Cédric Lucantis
Le Thursday 26 June 2008 15:53:06 oyster, vous avez écrit :
> that is, there is no TABLE tag between a TABLE, for example
> something with out table tag
> what is the RE pattern? thanks
>
> the following is not right
> [^table]*?

The construct [abc] does not match a whole word but only one char, so  
[^table] means "any char which is not t, a, b, l or e".

Anyway the inside table word won't match your pattern, as there are '<' 
and '>' in it, and these chars have to be escaped when used as simple text.
So this should work:

re.compile(r'.*')
^ this is to avoid matching a tag name starting with table 
(like )

-- 
Cédric Lucantis
--
http://mail.python.org/mailman/listinfo/python-list


python, acpi and hid code howto

2008-06-26 Thread Oguz Yarimtepe
Hi all,

Is it possible to get the hid code of any pressed key via python?
If anyone used such a thing before, i will be happy to get some clues.

-- 
Oğuz Yarımtepe
--
http://mail.python.org/mailman/listinfo/python-list


ConfigParser: Can I read(ConfigParser.get()) a configuration file and use it to call a funciton?

2008-06-26 Thread jamitwidme
Hello. I am a novice programmer and have a question

I have a configuration file(configuration.cfg)
I read this from reading.py using ConfigParser
When I use ConfigParser.get() function, it returns a string.
I want to call a function that has the same name as the string from
the configuration file.


configuration.cfg
---
[1234]
title: abcd
function: efgh
---


reading.py

import ConfigParser

def efgh():
   print 'blah'

config = ConfigParser.ConfigParser()
config.read('configuration.cfg')

fcn = config.get('1234','function')
type(fcn)
print fcn



efgh


Is there any way to call efgh() ?
One way I know is using if statement
if fcn == 'efgh':
   efgh()

But I am going to have many functions to call, so I want to avoid
this.


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


Re: ConfigParser: Can I read(ConfigParser.get()) a configuration file and use it to call a funciton?

2008-06-26 Thread Cédric Lucantis
Le Thursday 26 June 2008 16:41:27 [EMAIL PROTECTED], vous avez écrit :
> Hello. I am a novice programmer and have a question
>
> I have a configuration file(configuration.cfg)
> I read this from reading.py using ConfigParser
> When I use ConfigParser.get() function, it returns a string.
> I want to call a function that has the same name as the string from
> the configuration file.
>
>

You can find the function in the global dictionary (returned by globals()):

globs = globals()
func_name = config.read('1234', 'function')
func = globs[func_name]

# and then call it
func()

But a safer way would be to use a class with some static methods:

class Functions (object) :

@staticmethod
def efgh () :
blah blah...

and then find the function in the class dict:

func = getattr(Functions, func_name)
func()

this way you can restrict the set of functions the user can give, excluding 
those which are not supposed to be called this way.

-- 
Cédric Lucantis
--
http://mail.python.org/mailman/listinfo/python-list


Adding functions to an existing instance

2008-06-26 Thread Allen
I need a way to add a method to an existing instance, but be as close as 
possible to normal instance methods.  Using 'new' module or such code as 
'def addfunc(...): def helper(...) .. setattr(...)' causes a cyclic 
reference which requires using 'gc.collect' to release the object.  Also 
'new' is deprecated.  I also made a helper that uses weakref, but the 
problem is when the object is gone, existing instance method object 
would not work:



f = myobject.function
myobject = None
f() <--- would not work if it holds weak ref to myobject


The best I can come up with is to create a parent class and try to 
simulate as best as possible.  The code below works with no cyclic 
references that would be cause by 'new.instancemethod' etc, and without 
the weakref as well.  Is there a simpler way of achieving the same 
without cyclic references?  I know this is 'monkey patching' but for a 
small project I'm working on it is useful to be able to add functions 
dynamically to one instance without adding it to another instance of the 
same class, etc.



class InstanceFunctionHelper(object):
class FunctionCaller(object):
def __init__(self, instance, func):
self.__instance = instance
self.__func = func

def __call__(self, *args, **kwargs):
return self.__func(self.__instance, *args, **kwargs)

def add_instance_function(self, func, name = None):
if name is None:
name = func.__name__

if hasattr(self, name):
delattr(self, name)

try:
self._instance_funcs[name] = func
except AttributeError:
self._instance_funcs = {name: func}

def __setattr__(self, name, value):
funcs = getattr(self, '_instance_funcs', None)
if funcs and name in funcs:
del funcs[name]

object.__setattr__(self, name, value)

def __delattr__(self, name):
funcs = getattr(self, '_instance_funcs', None)
if funcs and name in funcs:
del funcs[name]
else:
object.__delattr__(self, name)

def __getattr__(self, name):
if name == '_instance_funcs':
raise AttributeError

funcs = object.__getattribute__(self, '_instance_funcs')

if name in funcs:
return InstanceFunctionHelper.FunctionCaller(self, funcs[name])

raise AttributeError



x = 0
class Blah(InstanceFunctionHelper):
def __init__(self):
global x
x += 1
def __del__(self):
global x
x -= 1

def Action(self, value):
print self
print value

a = Blah()
a.add_instance_function(Action)
a.Action(5)
a = None
print x

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


Re: ConfigParser: Can I read(ConfigParser.get()) a configuration file and use it to call a funciton?

2008-06-26 Thread Matimus
On Jun 26, 7:41 am, [EMAIL PROTECTED] wrote:
> Hello. I am a novice programmer and have a question
>
> I have a configuration file(configuration.cfg)
> I read this from reading.py using ConfigParser
> When I use ConfigParser.get() function, it returns a string.
> I want to call a function that has the same name as the string from
> the configuration file.
>
> configuration.cfg
> ---
> [1234]
> title: abcd
> function: efgh
> ---
>
> reading.py
> 
> import ConfigParser
>
> def efgh():
>    print 'blah'
>
> config = ConfigParser.ConfigParser()
> config.read('configuration.cfg')
>
> fcn = config.get('1234','function')
> type(fcn)
> print fcn
> 
>
> 
> efgh
>
> Is there any way to call efgh() ?
> One way I know is using if statement
> if fcn == 'efgh':
>    efgh()
>
> But I am going to have many functions to call, so I want to avoid
> this.
>
> Thank you for your help

Something like this:
globals()[fcn]()
--
http://mail.python.org/mailman/listinfo/python-list


Re: where is the error?

2008-06-26 Thread Gary Herron

[EMAIL PROTECTED] wrote:

Hello,

I'm trying to assign data into an array with the nonzero function.
There is my code.

from numarray import *
diff_temp=(logical_and(values[:,5] > -2,values[:,5] < 2)).nonzero()
  


Does that have something to do with the question below?


This command works fine but when I apply the following,

values_matchup=values_Stumpf[diff_temp_Stumpf,:]
  


Clearly, from the error message, the index  diff_temp_Stumpf is not one 
of the allowed types.   Have you examined its value?   Printed it?   Set 
it equal to a known legal value and tried that line again?


First thing:  Find out what value that index has, then if it's necessary 
to ask your question again, include that information and we'll have 
something to go on in forming an answer.


Gary Herron


I have this error message:
IndexError: each subindex must be either a slice, an integer,
Ellipsis, or NewAxis

Does someone know what it is the problem? I'm using python2.4.3 on
Ubuntu.

Using this command with python on windows xp worked fine.

Thank you for the help,
Cedric
--
http://mail.python.org/mailman/listinfo/python-list
  


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


Re: Windows process ownership trouble

2008-06-26 Thread geoffbache
Thanks Tim, very helpful again.

I've now reported this as http://bugs.python.org/issue3210
and implemented your suggested workaround.

Regards,
Geoff

On Jun 25, 9:19 pm, Tim Golden <[EMAIL PROTECTED]> wrote:
> geoffbache wrote:
> > Am currently being very confused over the following code on Windows
>
> > import subprocess, os
>
> > file = open("filename", "w")
> > try:
> > proc = subprocess.Popen("nosuchprogram", stdout=file)
> > except OSError:
> > file.close()
> > os.remove("filename")
>
> Forgot to say: slightly awkward, but you can work around
> it like this:
>
> 
> import os
> import subprocess
>
> f = open ("filename", "w")
> try:
>proc = subprocess.Popen ("blah", stdout=f)
> except OSError:
>os.close (f.fileno ())
>
> os.remove ("filename")
>
> 
>
> TJG

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


Re: Making code more efficient and effective

2008-06-26 Thread bearophileHUGS
Cédric Lucantis:
> PAT = re.compile('^[ ]*(public|protected|private)[ ]+([a-zA-Z0-9_]+)
> [ ]+([a-zA-Z0-9_]+)[ ]+\((.*)\).*$')
> ...
> It might be hard to read but will avoid a lot of obscure parsing code.

You can use the VERBOSE mode, to add comments and split that RE into
some lines.

I think the RE module of Python 3.0 can be modified in some way to
encourage people to write more readable REs, but I don't know how.
Maybe the VERBOSE can be on by default...

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: automatically import modules upon interpreter invocation

2008-06-26 Thread Jeffrey Froman
Daniel Fetchinson wrote:

> Is there a way of making python execute the above whenever it starts
> up so that I don't have to type it all the time?

Create a script containing these statements, and specify its location with
the PYTHONSTARTUP environment variable. Your script will run whenever
python starts.


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


Re: Windows process ownership trouble

2008-06-26 Thread geoffbache

Tim,

Unfortunately my previous message was premature, it seems your
workaround doesn't work
either on my system (Windows XP, Python 2.5.1) I get the following
printed out

Traceback (most recent call last):
  File "C:\TextTest\processown.py", line 12, in 
os.remove ("filename")
WindowsError: [Error 32] The process cannot access the file because it
is being used by another process: 'filename'
close failed: [Errno 9] Bad file descriptor

Any ideas?

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


Re: Making code more efficient and effective

2008-06-26 Thread cokofreedom
On Jun 26, 5:42 pm, [EMAIL PROTECTED] wrote:
> Cédric Lucantis:
>
> > PAT = re.compile('^[ ]*(public|protected|private)[ ]+([a-zA-Z0-9_]+)
> > [ ]+([a-zA-Z0-9_]+)[ ]+\((.*)\).*$')
> > ...
> > It might be hard to read but will avoid a lot of obscure parsing code.
>
> You can use the VERBOSE mode, to add comments and split that RE into
> some lines.
>
> I think the RE module of Python 3.0 can be modified in some way to
> encourage people to write more readable REs, but I don't know how.
> Maybe the VERBOSE can be on by default...
>
> Bye,
> bearophile

Thank you to everyone that replied in the thread and privately, been
looking into the different techniques. Presently found the RE to be
readable once I put it into VERBOSE format. I had looked it at earlier
but struck a dead wall, till Cédric gave such clear code!

I've been doing Java code the last few weeks and it is hard to jump
between them sometimes, Java has to be so organised and checked over
and over, I forget Python doesn't need such defensive programming.

I currently have it finding functions, constructors and classes, and
looking for them within the code, which is exactly what I was hoping
for! It also reads a lot clearer, which was what I was aiming for. So
thanks to everyone that helped!
--
http://mail.python.org/mailman/listinfo/python-list


url.encore/quote

2008-06-26 Thread zowtar
urlencode({'page': i, 'order': 'desc', 'style': 'flex power'})
return:
page=1&order=desc&style=flex+power

but I want:
page=1&order=desc&style=flex%20power

and url.quote don't put the &'s and ='s
any idea guys?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Windows process ownership trouble

2008-06-26 Thread Tim Golden

geoffbache wrote:

Tim,

Unfortunately my previous message was premature, it seems your
workaround doesn't work
either on my system (Windows XP, Python 2.5.1) I get the following
printed out

Traceback (most recent call last):
  File "C:\TextTest\processown.py", line 12, in 
os.remove ("filename")
WindowsError: [Error 32] The process cannot access the file because it
is being used by another process: 'filename'
close failed: [Errno 9] Bad file descriptor


Strange. I've just double-checked and it works perfectly
well for me, although I haven't traced all the way through
the code paths of the subprocess module: it was a bit of
an educated guess. Just to confirm, I'm talking about this
code running on Python 2.5.2 on Win XP SP2.


import os
import subprocess

f = open ("filename", "w")
try:
 proc = subprocess.Popen ("blah", stdout=f)
except OSError:
 os.close (f.fileno ())

os.remove ("filename")


If I get a chance I'll try to look more closely at the subprocess
code. Could you dump out the code (or the interpreter session
in its entirety) just to make sure there's not a typo or a thinko
getting in the way?

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


Re: Mako vs. Cheetah?

2008-06-26 Thread John Salerno
"John Salerno" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I always have the desire to learn one thing well instead of split my 
>attention between several options, so I'm trying to decide which of these 
>two to start learning. Are there any particular things I should look at 
>when deciding between them, in terms of features, for example? Do they do 
>all the same things?

Is it correct to say that Mako allows you to embed Python code within HTML, 
whereas Cheetah requires a certain amount of "tweaking" of Python code so 
that it isn't really code you could just run independently in the 
interpreter?

I'm getting that impression from what I see so far. 


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


Re: url.encore/quote

2008-06-26 Thread ianitux
On 26 jun, 12:53, zowtar <[EMAIL PROTECTED]> wrote:
> urlencode({'page': i, 'order': 'desc', 'style': 'flex power'})
> return:
> page=1&order=desc&style=flex+power
>
> but I want:
> page=1&order=desc&style=flex%20power
>
> and url.quote don't put the &'s and ='s
> any idea guys?

Hi, a quick solution can be this one, or maybe you can do something
similar

>>> import string, urllib
>>> a = urllib.urlencode({'page': 'i', 'order': 'desc', 'style': 'flex power'})
>>> a.replace('+','%20')
'style=flex%20power&page=i&order=desc'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Freeze problem with Regular Expression

2008-06-26 Thread Peter Pearson
On 25 Jun 2008 15:20:04 GMT, Kirk <[EMAIL PROTECTED]> wrote:
> Hi All,
> the following regular expression matching seems to enter in a infinite 
> loop:
>
> 
> import re
> text = ' MSX INTERNATIONAL HOLDINGS ITALIA srl (di seguito MSX ITALIA) 
> una '
> re.findall('[^A-Z|0-9]*((?:[0-9]*[A-Z]+[0-9|a-z|\-]*)+\s*[a-z]*\s*(?:[0-9]
> *[A-Z]+[0-9|a-z|\-]*\s*)*)([^A-Z]*)$', text)
> #
>
> No problem with perl with the same expression:
>
> #
> $s = ' MSX INTERNATIONAL HOLDINGS ITALIA srl (di seguito MSX ITALIA) una 
> ';
> $s =~ /[^A-Z|0-9]*((?:[0-9]*[A-Z]+[0-9|a-z|\-]*)+\s*[a-z]*\s*(?:[0-9]*[A-
> Z]+[0-9|a-z|\-]*\s*)*)([^A-Z]*)$/;
> print $1;
> #
>
> I've python 2.5.2 on Ubuntu 8.04.
> any idea?

If it will help some smarter person identify the problem, it can
be simplified to this:

re.findall('[^X]*((?:0*X+0*)+\s*a*\s*(?:0*X+0*\s*)*)([^X]*)$',
   "X (X" )

This doesn't actually hang, it just takes a long time.  The
time taken increases quickly as the chain of X's gets longer.

HTH

-- 
To email me, substitute nowhere->spamcop, invalid->net.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Storing value with limits in object

2008-06-26 Thread Josip
Thanks alot. I'm going to use this with few modifications to tailor it to my 
needs.
Thumbs up!

> #!/usr/bin/env python
>
> ## VERSION 2
> ##
> ## changelog:
> ## - Uses inheritance from _Limited
> ## - Added _LimitedLong and llong
> ## - limit choose between int, long, and float
>
> class _Limited(object):
>def setlimits(self, lim):
>''' Set the limits and if value is not within limit,
>raise ValueError
>
>The lim argument accepts:
>- An instance of _Limited, from which to copy the limits
>- A two-tuple, which specifies the limits i.e. (min, max)
>
>If lim isn't those or lim[0] > lim[1], raise
> InvalidLimitsError
>
>Accepting _Limited instance is just for convenience
>'''
>
>if isinstance(lim, _Limited):
>self.min, self.max = lim.limits
>else:
>try:
>self.min, self.max = lim
>if self.min > self.max: raise ValueError
>except (ValueError, TypeError):
>raise self.InvalidLimitsError, ('limit = %s' %
> str(lim))
>
>if not (self.min < self < self.max):
>raise ValueError, \
>  ('val = %s, min = %s, max = %s' % \
>  (self, self.min, self.max))
>
>def getlimits(self):
>return (self.min, self.max)
>
>limits = property(getlimits, setlimits)
>
> class _LimitedInt(int, _Limited):
>def __init__(self, value, base = 10):
>int.__init__(value, base)
>
> class _LimitedLong(long, _Limited):
>def __init__(self, value, base = 10):
>long.__init__(value, base)
>
> class _LimitedFloat(float, _Limited):
>def __init__(self, value):
>float.__init__(value)
>
>
> def lint(value, limits, base = None):
>''' Always Creates _LimitedInt instance, allows the use of base
>'''
>if base:
>ret = _LimitedInt(value, base)
>else:
>ret = _LimitedInt(value)
>
>ret.limits = limits
>return ret
>
> def llong(value, limits, base = None):
>''' Always Creates _LimitedLong instance, allows the use of base
>'''
>if base:
>ret = _LimitedLong(value, base)
>else:
>ret = _LimitedLong(value)
>
>ret.limits = limits
>return ret
>
> def lfloat(value, limits):
>''' Always Creates _LimitedFloat instance
>'''
>ret = _LimitedFloat(value)
>
>ret.limits = limits
>return ret
>
> def limit(value, limits):
>''' Automatically choose between _LimitedInt, _LimitedLong,
>or _LimitedFloat. Cannot use _LimitedInt's/Long's base
>'''
>if isinstance(value, (int, long)):
>try:
>ret = _LimitedInt(value)
>except OverflowError:
>ret = _LimitedLong(value)
>elif isinstance(value, float):
>ret = _LimitedFloat(value)
>
>ret.limits = limits
>return ret 


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


Re: Mako vs. Cheetah?

2008-06-26 Thread Michael Mabin
Cheetah also allows you to embed Python code in the HTML.

On Thu, Jun 26, 2008 at 11:10 AM, John Salerno <[EMAIL PROTECTED]>
wrote:

> "John Salerno" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> >I always have the desire to learn one thing well instead of split my
> >attention between several options, so I'm trying to decide which of these
> >two to start learning. Are there any particular things I should look at
> >when deciding between them, in terms of features, for example? Do they do
> >all the same things?
>
> Is it correct to say that Mako allows you to embed Python code within HTML,
> whereas Cheetah requires a certain amount of "tweaking" of Python code so
> that it isn't really code you could just run independently in the
> interpreter?
>
> I'm getting that impression from what I see so far.
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
| _ | * | _ |
| _ | _ | * |
| * | * | * |
--
http://mail.python.org/mailman/listinfo/python-list

Re: extend getattr()

2008-06-26 Thread George Sakkis
On Jun 26, 7:39 am, Cédric Lucantis <[EMAIL PROTECTED]> wrote:

> Le Thursday 26 June 2008 13:06:53 Rotlaus, vous avez écrit :
>
> > Hello,
>
> > lets assume i have some classes:
>
> > class A(object):
> > def __init__(self):
> > b = B()
>
> > class B(object):
> > def __init__(self):
> > c = C()
>
> note you're just defining some local variables here, should be self.b = B()
> and self.c = C().
>
> > class C(object):
> > def __init__(self):
> > pass
>
> > and now i wanna do something like this:
>
> > a=A()
> > c=getattr(a, 'b.c')
>
> > I know this doesn't work, but what can i do to get this or a similar
> > functionality to get it work for this sample and for even more nested
> > classes?
>
> You could do it manually:
>
> c = getattr(getattr(a, 'b'), 'c')
>
> or make it automatic:
>
> def get_dotted_attr (obj, dotted_attr) :
> for attr in dotted_attr.split('.') :
> obj = getattr(obj, attr)
> return obj
>
> a = A()
> print 'a.b.c = %s' % get_dotted_attr(a, 'b.c')

FYI, this feature will exist in operator.attrgetter from Python 2.6,
i.e. you'll be able to say attrgetter('b.c')(a).

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


Re: Bind compiled code to name?

2008-06-26 Thread Martin v. Löwis
>> d = {}
>> exec source_code in d
>> some_name = d['some_name']
> 
> This works quite well! I can't believe after googling for half on hour I 
> didn't notice this "exec ... in ..." syntax.
> One more thing though, is there a way to access "some_name" as a 
> attribute, instead as a dictionary:
> 
> some_name = d.some_name

Sure:

class D:pass
d = D()
exec source_code in d.__dict__
print d.some_name

Notice that this will also give you d.__builtins__, which you might
want to del afterwards.

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


Re: Bind compiled code to name?

2008-06-26 Thread Martin v. Löwis
>> d = {}
>> exec source_code in d
>> some_name = d['some_name']
> 
> This works quite well! I can't believe after googling for half on hour I 
> didn't notice this "exec ... in ..." syntax.
> One more thing though, is there a way to access "some_name" as a 
> attribute, instead as a dictionary:
> 
> some_name = d.some_name

Sure:

class D:pass
d = D()
exec source_code in d.__dict__
print d.some_name

Notice that this will also give you d.__builtins__, which you might
want to del afterwards.

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


Re: Is there any way to find out sizeof an object

2008-06-26 Thread zooko
Here are a few little tools that I developed to do this kind of thing:

http://allmydata.org/trac/pyutil/browser/pyutil/pyutil/memutil.py

Regards,

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


I Need A Placeholder

2008-06-26 Thread Ampedesign
I'm trying to build a try/except case, and I want to have the except
function like such:

try:
  # Do some code here
  var = 1 # For example
except:
  #Do nothing here

The only problem is if I leave a comment only in the except block, I
get an error back saying that the except block is not properly
formatted, since it has no content other than a comment.

So if anyone could suggest some code to put there as a placeholder
that would be wonderful.
--
http://mail.python.org/mailman/listinfo/python-list


Re: I Need A Placeholder

2008-06-26 Thread Gary Herron

Ampedesign wrote:

I'm trying to build a try/except case, and I want to have the except
function like such:

try:
  # Do some code here
  var = 1 # For example
except:
  #Do nothing here

  


try:
 # Do some code here
 var = 1 # For example
except:
 pass



Gary Herron





The only problem is if I leave a comment only in the except block, I
get an error back saying that the except block is not properly
formatted, since it has no content other than a comment.

So if anyone could suggest some code to put there as a placeholder
that would be wonderful.
--
http://mail.python.org/mailman/listinfo/python-list
  


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


Re: I Need A Placeholder

2008-06-26 Thread Daniel Mahoney
On Thu, 26 Jun 2008 10:03:47 -0700, Ampedesign wrote:

> I'm trying to build a try/except case, and I want to have the except
> function like such:
> 
> try:
>   # Do some code here
>   var = 1 # For example
> except:
>   #Do nothing here
> 
> The only problem is if I leave a comment only in the except block, I
> get an error back saying that the except block is not properly
> formatted, since it has no content other than a comment.
> 
> So if anyone could suggest some code to put there as a placeholder
> that would be wonderful.

"pass" would work fine.

try:
 # Do something that can throw an exception
except:
 pass



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


Re: I Need A Placeholder

2008-06-26 Thread Ampedesign
On Jun 26, 10:06 am, Daniel Mahoney <[EMAIL PROTECTED]> wrote:
> On Thu, 26 Jun 2008 10:03:47 -0700, Ampedesign wrote:
> > I'm trying to build a try/except case, and I want to have the except
> > function like such:
>
> > try:
> >       # Do some code here
> >       var = 1         # For example
> > except:
> >       #Do nothing here
>
> > The only problem is if I leave a comment only in the except block, I
> > get an error back saying that the except block is not properly
> > formatted, since it has no content other than a comment.
>
> > So if anyone could suggest some code to put there as a placeholder
> > that would be wonderful.
>
> "pass" would work fine.
>
> try:
>      # Do something that can throw an exception
> except:
>      pass

Thanks. That will work perfectly.
--
http://mail.python.org/mailman/listinfo/python-list


Re: I Need A Placeholder

2008-06-26 Thread Duncan Booth
Ampedesign <[EMAIL PROTECTED]> wrote:

> I'm trying to build a try/except case, and I want to have the except
> function like such:
> 
> try:
>   # Do some code here
>   var = 1 # For example
> except:
>   #Do nothing here
> 
> The only problem is if I leave a comment only in the except block, I
> get an error back saying that the except block is not properly
> formatted, since it has no content other than a comment.
> 
> So if anyone could suggest some code to put there as a placeholder
> that would be wonderful.
> 

Use the 'pass' statement.

But really, you should not have a bare except: if you are going to ignore a 
specific exception that's fine, but don't ignore all exceptions. You'll 
regret it.
--
http://mail.python.org/mailman/listinfo/python-list


How to get a multicast to wait for all nodes?

2008-06-26 Thread Ryuke
I have a code that receives gps information from nodes and gives off
its own coordinates via radios connected by Ethernet.  but the code
continues to run after receiving only 1 set of coordinates, how do i
get it to wait for multiple nodes to send before continuing
--
http://mail.python.org/mailman/listinfo/python-list


Re: I Need A Placeholder

2008-06-26 Thread Joshua Kugler
Ampedesign wrote:

> I'm trying to build a try/except case, and I want to have the except
> function like such:
> 
> try:
>   # Do some code here
>   var = 1 # For example
> except:
>   #Do nothing here
> 
> The only problem is if I leave a comment only in the except block, I
> get an error back saying that the except block is not properly
> formatted, since it has no content other than a comment.
> 
> So if anyone could suggest some code to put there as a placeholder
> that would be wonderful.

except:
pass

is the usual technique there.

j

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


Re: url.encore/quote

2008-06-26 Thread Duncan Booth
zowtar <[EMAIL PROTECTED]> wrote:

> urlencode({'page': i, 'order': 'desc', 'style': 'flex power'})
> return:
> page=1&order=desc&style=flex+power
> 
> but I want:
> page=1&order=desc&style=flex%20power
> 
> and url.quote don't put the &'s and ='s
> any idea guys?

Why does it matter to you? The + means exactly the same as %20. When the 
server decodes the parameter it will get the space back whichever form you 
use.

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


Re: I Need A Placeholder

2008-06-26 Thread Ampedesign
On Jun 26, 10:08 am, Duncan Booth <[EMAIL PROTECTED]>
wrote:
> Ampedesign <[EMAIL PROTECTED]> wrote:
> > I'm trying to build a try/except case, and I want to have the except
> > function like such:
>
> > try:
> >       # Do some code here
> >       var = 1         # For example
> > except:
> >       #Do nothing here
>
> > The only problem is if I leave a comment only in the except block, I
> > get an error back saying that the except block is not properly
> > formatted, since it has no content other than a comment.
>
> > So if anyone could suggest some code to put there as a placeholder
> > that would be wonderful.
>
> Use the 'pass' statement.
>
> But really, you should not have a bare except: if you are going to ignore a
> specific exception that's fine, but don't ignore all exceptions. You'll
> regret it.

This is true. Though I get a wide range of exceptions since I'm
downloading and parsing a file. I will get everything from a socket
error to an empty xml element.

In the future however, I will make separate exceptions.
--
http://mail.python.org/mailman/listinfo/python-list


RE: I Need A Placeholder

2008-06-26 Thread Deverter,Mark
I typically use pass for a place holder.

try:
  # Do some code here
  var = 1 # For example
except:
  pass

HTH,
Mark

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On
Behalf Of Ampedesign
Sent: Thursday, June 26, 2008 12:04 PM
To: python-list@python.org
Subject: I Need A Placeholder

I'm trying to build a try/except case, and I want to have the except
function like such:

try:
  # Do some code here
  var = 1 # For example
except:
  #Do nothing here

The only problem is if I leave a comment only in the except block, I
get an error back saying that the except block is not properly
formatted, since it has no content other than a comment.

So if anyone could suggest some code to put there as a placeholder
that would be wonderful.
--
http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list


Re: Windows process ownership trouble

2008-06-26 Thread Tim Golden

geoffbache wrote:

Tim,

Unfortunately my previous message was premature, it seems your
workaround doesn't work
either on my system (Windows XP, Python 2.5.1) I get the following
printed out

Traceback (most recent call last):
  File "C:\TextTest\processown.py", line 12, in 
os.remove ("filename")
WindowsError: [Error 32] The process cannot access the file because it
is being used by another process: 'filename'
close failed: [Errno 9] Bad file descriptor


(Assuming you have the pywin32 extensions installed...)

If you tweak your copy of subprocess.py by switching on
the use of the pywin32 extensions in preference to the
_subprocess module, the problem goes away, I think
because the PyHANDLE object auto-closes. I'm not saying
it won't ever fail -- the interactions of objects, scope,
frames, exceptions and garbage collection are things I've
never looked at too closely. But if you change line 378 from
if 0: to if 1:, then the following works fine:


import os
import subprocess

f = open ("filename", "w")
try:
 p = subprocess.Popen ("blah", stdout=f)
except WindowsError:
 f.close ()

os.remove ("filename")



Note that the os.remove is *outside* the except handler.
This is, I think, because the underlying handle object
is still active until the try/except block closes. At which
point it is, probably, gc-ed and closes. And you can
remove the file.

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


Re: I Need A Placeholder

2008-06-26 Thread John Salerno
"Joshua Kugler" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> except:
>pass
>
> is the usual technique there.

Is there any other? 


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


Re: Windows process ownership trouble

2008-06-26 Thread Tim Golden

Tim Golden wrote:

geoffbache wrote:

Tim,

Unfortunately my previous message was premature, it seems your
workaround doesn't work
either on my system (Windows XP, Python 2.5.1) I get the following
printed out

Traceback (most recent call last):
  File "C:\TextTest\processown.py", line 12, in 
os.remove ("filename")
WindowsError: [Error 32] The process cannot access the file because it
is being used by another process: 'filename'
close failed: [Errno 9] Bad file descriptor


[... snip purported solution using pywin32 ...]

 or maybe I should just stop talking rubbish and go home 
since that solution works even *without* the tweak to 
subprocess.py.


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


Re: I Need A Placeholder

2008-06-26 Thread Carsten Haese

John Salerno wrote:
"Joshua Kugler" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

except:
   pass

is the usual technique there.


Is there any other? 


Sure. Evaluating any side-effect free expression and ignoring the result 
will work:


try:
# do somthing
except:
None

try:
# do something
except:
"I don't care about the exception."

Of course, using pass *is* the preferred method.

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: ask for a RE pattern to match TABLE in html

2008-06-26 Thread Stefan Behnel
oyster wrote:
> that is, there is no TABLE tag between a TABLE, for example
> something with out table tag
> what is the RE pattern? thanks
> 
> the following is not right
> [^table]*?

Why not use an HTML parser instead? Try lxml.html.

http://codespeak.net/lxml/

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


Re: I Need A Placeholder

2008-06-26 Thread Peter Otten
John Salerno wrote:

> "Joshua Kugler" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>> except:
>>pass
>>
>> is the usual technique there.
> 
> Is there any other?

if 0: 42

Proof:

>>> def cp(pass_):
... return compile("try: 1/0\nexcept:\n %s" % pass_, "", "exec")
...
>>> cp("pass") == cp("if 0: 42")
True

:-)

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


Re: ask for a RE pattern to match TABLE in html

2008-06-26 Thread Grant Edwards
On 2008-06-26, Stefan Behnel <[EMAIL PROTECTED]> wrote:
> oyster wrote:
>> that is, there is no TABLE tag between a TABLE, for example
>> something with out table tag
>> what is the RE pattern? thanks
>> 
>> the following is not right
>> [^table]*?
>
> Why not use an HTML parser instead?

Stating it differently: in order to correctly recognize HTML
tags, you must use an HTML parser.  Trying to write an HTML
parser in a single RE is probably not practical.

-- 
Grant Edwards   grante Yow! I want another
  at   RE-WRITE on my CEASAR
   visi.comSALAD!!
--
http://mail.python.org/mailman/listinfo/python-list


python interface to Firefox and Thunderbird

2008-06-26 Thread yardennis
Hi,

I need python moudles that can

auto install python 2.5 (web install or a EXE file)

auto download and install Firefox3 and Thunderbird 2
auto import from IE 6, 7 and OE 5,6 and Outlook

read contacts and emails from Thunderbird store
read Firefox 3 bookmarks, history, cookies and password

Can anyone point to a open source solution ?

If you know of any freelancer that can help me develop the module
please let me know.

Thanks

Dennis
yardennis at gmail dot com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Komodo Edit newbie Q

2008-06-26 Thread Todd Whiteman

John Dann wrote:

I'm learning Python using the Komodo Edit freeware code editor. One
thing I'm finding a little confusing is that the code completion lists
(what I would call Intellisense coming from a .Net background) are
often very incomplete, especially with imported classes like wx. It's
like KE can't look far enough into these classes to offer a
comprehensive list of method etc options.

I presume that I haven't possibly omitted some KE setup step that
would give more detail to the code completion?


Hi John,

There are some Komodo forum posts that help out when dealing with wx 
completions in Komodo, this link below may be particularly helpful:





If not then maybe this is just a limitation of the KE freeware
(because it's free?). Does anyone know if say Komodo IDE offers more
in the way of code completion (I know that it offers more things in
the way of debugging etc, but it's code completion specifically that
I'm asking about here). Or is one of the other Python IDEs maybe more
capable when it comes to code completion?


Komodo Edit and Komodo IDE both use the exact same code intelligence 
system, so what occurs in Edit occurs in the IDE version.



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


Re: Adding functions to an existing instance

2008-06-26 Thread [EMAIL PROTECTED]
On 26 juin, 17:18, Allen <[EMAIL PROTECTED]> wrote:
> I need a way to add a method to an existing instance, but be as close as
> possible to normal instance methods.

def set_method(obj, func, name=None):
  if not name:
name = func.__name__
  setattr(obj, name, func.__get__(obj, type(obj)))

class Toto(object):
  pass

toto = Toto()

def titi(self):
  print self

set_method(toto, titi)

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


Re: ask for a RE pattern to match TABLE in html

2008-06-26 Thread David C. Ullrich
In article <[EMAIL PROTECTED]>,
 Cédric Lucantis <[EMAIL PROTECTED]> wrote:

> Le Thursday 26 June 2008 15:53:06 oyster, vous avez écrit :
> > that is, there is no TABLE tag between a TABLE, for example
> > something with out table tag
> > what is the RE pattern? thanks
> >
> > the following is not right
> > [^table]*?
> 
> The construct [abc] does not match a whole word but only one char, so  
> [^table] means "any char which is not t, a, b, l or e".
> 
> Anyway the inside table word won't match your pattern, as there are '<' 
> and '>' in it, and these chars have to be escaped when used as simple text.
> So this should work:
> 
> re.compile(r'.*')
> ^ this is to avoid matching a tag name starting with 
> table 
> (like )

Doesn't work - for example it matches ''
(and in fact if the html contains any number of tables it's going
to match the string starting at the start of the first table and
ending at the end of the last one.)

-- 
David C. Ullrich
--
http://mail.python.org/mailman/listinfo/python-list

Re: Freeze problem with Regular Expression

2008-06-26 Thread Peter Pearson
On Thu, 26 Jun 2008 11:20:01 -0500, Peter Pearson wrote:
> On 25 Jun 2008 15:20:04 GMT, Kirk <[EMAIL PROTECTED]> wrote:
[snip]
>> the following regular expression matching seems to enter in a infinite 
>> loop:
[snip]
>> import re
>> text = ' MSX INTERNATIONAL HOLDINGS ITALIA srl (di seguito MSX ITALIA) 
>> una '
>> re.findall('[^A-Z|0-9]*((?:[0-9]*[A-Z]+[0-9|a-z|\-]*)+\s*[a-z]*\s*(?:[0-9]
>> *[A-Z]+[0-9|a-z|\-]*\s*)*)([^A-Z]*)$', text)
[snip]
>
> If it will help some smarter person identify the problem, it can
> be simplified to this:
>
> re.findall('[^X]*((?:0*X+0*)+\s*a*\s*(?:0*X+0*\s*)*)([^X]*)$',
>"X (X" )
>
> This doesn't actually hang, it just takes a long time.  The
> time taken increases quickly as the chain of X's gets longer.

... and can be further reduced to this:

re.findall('(X+)+(X+)*$', "XXXy" )

which bears considerable resemblance to a regexp that was called
to my attention inconjunction with this report on pathological
regular expressions:

  http://www.cs.rice.edu/~scrosby/hash/

that resulted in my measuring the following data for the
regular expression '(x+x+)+y' in strings consisting of many
x's and maybe a terminal y:

   seconds to scan ...
   ---
 # x's xxx...xyxxx...x
 - ---
   10  0.00.0
   11  0.00.0
   12  0.00.0
   13  0.00.01
   14  0.00.0
   15  0.00.01
   16  0.00.03
   17  0.00.04
   18  0.00.09
   19  0.00.16
   20  0.00.33
   21  0.00.65
   22  0.01.3
   23  0.02.58
   24  0.05.18
   25  0.010.27
   26  0.020.41

Bottom line: given any regular-expression matcher, you can
find a regular expression and a family of strings such that
the matching time increases exponentially in the length of
the string.

-- 
To email me, substitute nowhere->spamcop, invalid->net.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with file IO in a thread, and shutil

2008-06-26 Thread MRAB
On Jun 26, 8:06 am, Roopesh <[EMAIL PROTECTED]> wrote:
> Thanks for the reply. I did testing in a clean system, were anti virus/
> spyware is not installed. It still gave this problem, in say 1 out of
> 1000 cases.
>
> By any chance would it be possible that the Windows OS has not
> completed writing to the file even after file.flush() and file.close()
> is called?
>
> Thanks
> Roopesh

Maybe it's a Windows service, eg the indexing service or generating
thumbnails. Anyway, retrying after a delay would still be worth it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: url.encore/quote

2008-06-26 Thread John Salerno
"zowtar" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> urlencode({'page': i, 'order': 'desc', 'style': 'flex power'})
> return:
> page=1&order=desc&style=flex+power
>
> but I want:
> page=1&order=desc&style=flex%20power
>
> and url.quote don't put the &'s and ='s
> any idea guys?

urlencode() uses quote_plus() when it creates a URL, which is why you are 
getting the plus signs. Unfortunately I don't have Python at work, so I 
can't try this, but maybe do:

quote(urlencode({'page': i, 'order': 'desc', 'style': 'flex power'}))

and see if that works? I'm not sure if quote() will convert the %20 into +, 
though, but it may. 


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


Re: Urllib(1/2) how to open multiple client sockets?

2008-06-26 Thread MRAB
On Jun 26, 11:48 am, ShashiGowda <[EMAIL PROTECTED]> wrote:
> Hey there i made a script to download all images from a web site but
> it runs damn slow though I have a lot of bandwidth waiting to be used
> please tell me a way to use urllib to open many connections to the
> server to download many pics simultaneously Any off question
> suggestions are also ok...

You also need to remember the bandwidth of the website itself, which
is being shared with other users.
--
http://mail.python.org/mailman/listinfo/python-list


Re: I Need A Placeholder

2008-06-26 Thread John Salerno
"Peter Otten" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> if 0: 42

How Pythonic. ;-) 


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


Re: python-dbus example request

2008-06-26 Thread Casey McGinty
You will need this page to figure out the name of the device, and details on
how to access it. However it is not python specific.

http://people.freedesktop.org/~david/hal-spec/hal-spec.html
--
http://mail.python.org/mailman/listinfo/python-list

simplest c python api callback example

2008-06-26 Thread Tim Spens
The following is a simple complete example using the c python api to generate 
callbacks from c to python.  But when I run the c code I get a segfault in 
PyInt_FromLong () (see below).  Most of this example code was taken from pg 
1478 of the 3rd edition python o'reilly book.  I cannot see what I'm doing 
wrong here to get this segfault?  Please help.

//---python-code-//
#! /usr/bin/env python
###
# register for and handle event callbacks from C;
# compile C code, and run with 'python register.py'
###

import time

#
# C calls these Python functions;
# handle an event, return a result
#
def callback1(label, count):
return 'callback1 called with args: label-%s and count-%i' % (label, count)
#
# Python calls a C extension module
# to register handlers, trigger events
#

import cregister
cregister.setpythonHandler(callback1)

print '\nwaiting for callback pythonHandler to be called:'
while 1:
time.sleep(1)

//---compiler commands--//
gcc -Wall -fno-strict-aliasing -g -I /usr/include/python2.5 -c cregister.c;gcc 
-g -Wall -I /usr/include/python2.5 -L /usr/local/lib -lpython2.5 cregister.c -o 
cregister;gcc -shared -fPIC -g -Wall -I /usr/include/python2.5 -L /usr/lib 
-lpython2.5 -o cregister.so cregister.o

//---c-code-//
#include 
#include 

/***/
/* 1) code to route events to Python object*/
/* note that we could run strings here instead */
/***/

//python handlers
//keep Python object in C
static PyObject *pythonHandler = NULL;

void Route_Event(){
PyObject *args;
// call Python handler
args = Py_BuildValue("(si)", "c code", 5);
PyEval_CallObject(pythonHandler, args);
}

/*/
/* 2) python extension module to register handlers   */
/* python imports this module to set handler objects */
/*/
static PyObject *
Register_pythonHandler(PyObject *self, PyObject *args){
// save Python callable object
Py_XDECREF(pythonHandler); //called before?
PyArg_Parse(args, "O", &pythonHandler);//one argument?
Py_XINCREF(pythonHandler); //add a reference
Py_INCREF(Py_None);//return 'None': success
return Py_None;
}

//makes these functions available by importing cregister in python
static struct PyMethodDef cregister_methods[] = {
{"setpythonHandler",Register_pythonHandler},
{NULL, NULL}
};

// this is called by Python on first "import cregister"
void initcregister(){
(void) Py_InitModule("cregister", cregister_methods);
}

int main(){
while (1){
PyObject *arglist;
arglist = Py_BuildValue("(si)", "c code", 5);
Py_XINCREF(pythonHandler);
Py_XINCREF(arglist);
PyEval_CallObject(pythonHandler, arglist);
Py_XDECREF(pythonHandler);
Py_XDECREF(arglist);
sleep(1);
}
}

Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0xb7c1c6b0 (LWP 13699)]
0xb7e0bcfb in PyInt_FromLong () from /usr/lib/libpython2.5.so.1.0
(gdb) bt
#0  0xb7e0bcfb in PyInt_FromLong () from /usr/lib/libpython2.5.so.1.0
#1  0xb7e8cae6 in ?? () from /usr/lib/libpython2.5.so.1.0
#2  0x0005 in ?? ()
#3  0x0006 in ?? ()
#4  0xbf89a378 in ?? ()
#5  0xb7e9d095 in _PyObject_GC_Malloc () from /usr/lib/libpython2.5.so.1.0
#6  0xb7e8d1dd in ?? () from /usr/lib/libpython2.5.so.1.0
#7  0x0002 in ?? ()
#8  0x08048320 in ?? ()
#9  0x72d6dafa in ?? ()
#10 0x0029 in ?? ()
#11 0xbf89a474 in ?? ()
#12 0xbf89a478 in ?? ()
#13 0x in ?? ()



  

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


Help me optimize my feed script.

2008-06-26 Thread bsagert
I wrote my own feed reader using feedparser.py but it takes about 14
seconds to process 7 feeds (on a windows box), which seems slow on my
DSL line. Does anyone see how I can optimize the script below? Thanks
in advance, Bill

# UTF-8
import feedparser

rss = [
'http://feeds.feedburner.com/typepad/alleyinsider/
silicon_alley_insider',
'http://www.techmeme.com/index.xml',
'http://feeds.feedburner.com/slate-97504',
'http://rss.cnn.com/rss/money_mostpopular.rss',
'http://rss.news.yahoo.com/rss/tech',
'http://www.aldaily.com/rss/rss.xml',
'http://ezralevant.com/atom.xml'
]
s = '\n\nC:/x/test.htm\n'

s += '\n'\
 'h3{margin:10px 0 0 0;padding:0}\n'\
 'a.x{color:black}'\
 'p{margin:5px 0 0 0;padding:0}'\
 '\n'

s += '\n\n\n'

for url in rss:
d = feedparser.parse(url)
title = d.feed.title
link = d.feed.link
s += '\n'+ title +'\n'
# aldaily.com has weird feed
if link.find('aldaily.com') != -1:
description = d.entries[0].description
s += description + '\n'
for x in range(0,3):
if link.find('aldaily.com') != -1:
continue
title = d.entries[x].title
link = d.entries[x].link
s += ''+ title +'\n'

s += '\n\n'

f = open('c:/scripts/myFeeds.htm', 'w')
f.write(s)
f.close

print
print 'myFeeds.htm written'
--
http://mail.python.org/mailman/listinfo/python-list


Re: ConfigParser: Can I read(ConfigParser.get()) a configuration file and use it to call a funciton?

2008-06-26 Thread jamitwidme
Thank you for the answers.
Now I understood how to call a function, let me ask you another
question.

configuration.cfg
---
[1234]
title: abcd
function: efgh
---

reading.py

import ConfigParser

class Functions:
   def efgh(self):
  print 'blah'

fcn = Functions()

config = ConfigParser.ConfigParser()
config.read('configuration.cfg')
title = config.get('1234','title') # number 1
function_name = config.get('1234','function')

title = getattr(fcn, function_name)
title()


instead of assigning string value('abcd') to title at number 1

I want to assign this function(fcn.efgh()) to abcd and make abcd a
FunctionType.
so later on, I want to call it by abcd(), not title().
The reason is I will have a loop reading from configuration file, so I
need to have different names for each function.
abcd is a string I read got it from config.get('1234','title')

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


Re: url.encore/quote

2008-06-26 Thread ianitux
On 26 jun, 15:53, "John Salerno" <[EMAIL PROTECTED]> wrote:
> "zowtar" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
>
> > urlencode({'page': i, 'order': 'desc', 'style': 'flex power'})
> > return:
> > page=1&order=desc&style=flex+power
>
> > but I want:
> > page=1&order=desc&style=flex%20power
>
> > and url.quote don't put the &'s and ='s
> > any idea guys?
>
> urlencode() uses quote_plus() when it creates a URL, which is why you are
> getting the plus signs. Unfortunately I don't have Python at work, so I
> can't try this, but maybe do:
>
> quote(urlencode({'page': i, 'order': 'desc', 'style': 'flex power'}))
>
> and see if that works? I'm not sure if quote() will convert the %20 into +,
> though, but it may.

This is what quot do.

>>> import urllib
>>> u = urllib
>>> u.quote(u.urlencode({'page': 'i', 'order': 'desc', 'style': 'flex power'}))
'style%3Dflex%2Bpower%26page%3Di%26order%3Ddesc'
--
http://mail.python.org/mailman/listinfo/python-list


Re: url.encore/quote

2008-06-26 Thread John Salerno
"ianitux" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>> and see if that works? I'm not sure if quote() will convert the %20 into 
>> +,
>> though, but it may.
>
> This is what quot do.
>
 import urllib
 u = urllib
 u.quote(u.urlencode({'page': 'i', 'order': 'desc', 'style': 'flex 
 power'}))
> 'style%3Dflex%2Bpower%26page%3Di%26order%3Ddesc'

I know quote will convert spaces to %20, just wasn't sure if it would 
explicitly convert + to %20.

But it seems the output isn't what the OP wants anyway, because he wanted 
the & and = symbols. 


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


Help me on Backspace please

2008-06-26 Thread cakomo
Hi
I am a beginner on Python and have a problem..

I have text file and reading it line by line and there are backspace
characters in it like '\b' or anything you want like "#".  I want to
replace these chars. with Backspace action. I mean deleting the
previous char. and the \b char also. and writing all cleaned text to a
file again.

How can I do that.

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


sqlite3 alternative option

2008-06-26 Thread Gandalf
Hi every one I'm looking for a good alternative db to replace sqlite

I'm using pySQlite3, And I tried to translate very big database from
Mysql to sqlite.
I generated through  PHP a python script that insert 200,000 records
to my sqlite db and took me more then 5 hours and managed to insert
only  100,000 records.
I have almost million records so I need a better solution.


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


Re: recursion in Class-methods?

2008-06-26 Thread defn noob
class Graph(object):

where does anyone write like that? I've seen only examples like i have
written.

is the object then passed to init?


class Graph(object):
def __init__(self, dictionary):
self.structure = dictionary

or

class Graph(object):
def __init__(self, object):
self.structure = object


i dont get it.




and "mutable containers", do you refer to "path=[]" as a parameter.
--
http://mail.python.org/mailman/listinfo/python-list


Re: recursion in Class-methods?

2008-06-26 Thread defn noob
>
> > if start == end:
> > return path
> > if not self.dictionary.has_key(start):
>
>if start not in self.dictionnary:
>
> > return None
> > for node in self.dictionary[start]:
> > if node not in path:
> > newpath = find_path(self.dictionary, node, end, path)
>
>newpath = self.find_path(...)
>
> (snip remaining code - same problems, same solutions...)

it is to incoherent fo follow what you mean here(not meaning to sound
rude i appreciate the help).
--
http://mail.python.org/mailman/listinfo/python-list



Re: Help me optimize my feed script.

2008-06-26 Thread Carl Banks
On Jun 26, 3:30 pm, [EMAIL PROTECTED] wrote:
> I wrote my own feed reader using feedparser.py but it takes about 14
> seconds to process 7 feeds (on a windows box), which seems slow on my
> DSL line. Does anyone see how I can optimize the script below? Thanks
> in advance, Bill
>
> # UTF-8
> import feedparser
>
> rss = [
> 'http://feeds.feedburner.com/typepad/alleyinsider/
> silicon_alley_insider',
> 'http://www.techmeme.com/index.xml',
> 'http://feeds.feedburner.com/slate-97504',
> 'http://rss.cnn.com/rss/money_mostpopular.rss',
> 'http://rss.news.yahoo.com/rss/tech',
> 'http://www.aldaily.com/rss/rss.xml',
> 'http://ezralevant.com/atom.xml'
> ]
> s = '\n\nC:/x/test.htm\n'
>
> s += '\n'\
>  'h3{margin:10px 0 0 0;padding:0}\n'\
>  'a.x{color:black}'\
>  'p{margin:5px 0 0 0;padding:0}'\
>  '\n'
>
> s += '\n\n\n'
>
> for url in rss:
> d = feedparser.parse(url)
> title = d.feed.title
> link = d.feed.link
> s += '\n'+ title +'\n'
> # aldaily.com has weird feed
> if link.find('aldaily.com') != -1:
> description = d.entries[0].description
> s += description + '\n'
> for x in range(0,3):
> if link.find('aldaily.com') != -1:
> continue
> title = d.entries[x].title
> link = d.entries[x].link
> s += ''+ title +'\n'
>
> s += '\n\n'
>
> f = open('c:/scripts/myFeeds.htm', 'w')
> f.write(s)
> f.close
>
> print
> print 'myFeeds.htm written'

Using the += operator on strings is a common bottleneck in programs.
First thing you should try is to get rid of that.  (Recent versions of
Python have taken steps to optimize it, but still it sometimes doesn't
work, such as if you have more than one reference to the string
alive.)

Instead, create a list like this:

s = []

And append substrings to the list, like this:

s.append('\n\n\n')

Then, when writing the string out (or otherwise using it), join all
the substrings with the str.join method:

f.write(''.join(s))


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


list previous or following list elements

2008-06-26 Thread antar2
Hello


Suppose I have a textfile (text1.txt) with following four words:

Apple
balcony
cartridge
damned
paper
bold
typewriter

and I want to have a python script that prints the words following the
word starting with the letter b (which would be cartridge) or
differently put, a script that prints the element following a
specified element:

I am more experienced in Perl, and a beginner in python

I wrote a script that - of course - does not work, that should print
the element in a list following the element that starts with a b

import re
f = open('text1.txt', 'r')
list1 = []
list2 = []
for line in f:
list1.append(line)
a = re.compile("^b")
int = 0
while(int <= list1[-1]):
int = int + 1
a_match = a.search(list1[int])
if(a_match):
list2.append(list1[int + 1])
print list2

I did not find information about addressing previous or following list
elements. So some help would be magnificent

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


Re: Help me on Backspace please

2008-06-26 Thread Craig Radcliffe
Something like this might do the trick:

import re
f  = open("file.txt")
old_text = f.readlines()
f.close()
new_text = [re.sub(r'.\b', '', i) for i in old_text]
f = open("file_modified.txt", "w")
f.writelines(new_text)

I don't know how necessary the separate read and writes are, but it'll be
good for a start. At any rate, you'll want to look at the
remodule.

On Thu, Jun 26, 2008 at 16:32, <[EMAIL PROTECTED]> wrote:

> Hi
> I am a beginner on Python and have a problem..
>
> I have text file and reading it line by line and there are backspace
> characters in it like '\b' or anything you want like "#".  I want to
> replace these chars. with Backspace action. I mean deleting the
> previous char. and the \b char also. and writing all cleaned text to a
> file again.
>
> How can I do that.
>
> Thanks..
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: Help me optimize my feed script.

2008-06-26 Thread Jason Scheirer
On Jun 26, 12:30 pm, [EMAIL PROTECTED] wrote:
> I wrote my own feed reader using feedparser.py but it takes about 14
> seconds to process 7 feeds (on a windows box), which seems slow on my
> DSL line. Does anyone see how I can optimize the script below? Thanks
> in advance, Bill
>
> # UTF-8
> import feedparser
>
> rss = [
> 'http://feeds.feedburner.com/typepad/alleyinsider/
> silicon_alley_insider',
> 'http://www.techmeme.com/index.xml',
> 'http://feeds.feedburner.com/slate-97504',
> 'http://rss.cnn.com/rss/money_mostpopular.rss',
> 'http://rss.news.yahoo.com/rss/tech',
> 'http://www.aldaily.com/rss/rss.xml',
> 'http://ezralevant.com/atom.xml'
> ]
> s = '\n\nC:/x/test.htm\n'
>
> s += '\n'\
>      'h3{margin:10px 0 0 0;padding:0}\n'\
>      'a.x{color:black}'\
>      'p{margin:5px 0 0 0;padding:0}'\
>      '\n'
>
> s += '\n\n\n'
>
> for url in rss:
>         d = feedparser.parse(url)
>         title = d.feed.title
>         link = d.feed.link
>         s += '\n'+ title +'\n'
>         # aldaily.com has weird feed
>         if link.find('aldaily.com') != -1:
>                 description = d.entries[0].description
>                 s += description + '\n'
>         for x in range(0,3):
>                 if link.find('aldaily.com') != -1:
>                         continue
>                 title = d.entries[x].title
>                 link = d.entries[x].link
>                 s += ''+ title +'\n'
>
> s += '\n\n'
>
> f = open('c:/scripts/myFeeds.htm', 'w')
> f.write(s)
> f.close
>
> print
> print 'myFeeds.htm written'

I can 100% guarantee you that the extended run time is network I/O
bound. Investigate using a thread pool to load the feeds in parallel.
Some code you might be able to shim in:

# Extra imports
import threading
import Queue

# Function that fetches and pushes
def parse_and_put(url, queue_):
  parsed_feed = feedparser.parse(url)
  queue_.put(parsed_feed)

# Set up some variables
my_queue = Queue.Queue()
threads = []

# Set up a thread for fetching each URL
for url in rss:
  url_thread = threading.Thread(target=parse_and_put, name=url,
args=(url, my_queue))
  threads.append(url_thread)
  url_thread.setDaemonic(False)
  url_thread.start()

# Wait for threads to finish
for thread in threads:
  thread.join()

# Push the results into a list
feeds_list = []
while not my_queue.empty():
  feeds_list.append(my_queue.get())

# Do what you were doing before, replacing the for url in rss with for
d in feedS_list
for d in feeds_list:
title = d.feed.title
link = d.feed.link

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


Re: Error when interfacing with TCP/IP

2008-06-26 Thread Terry Reedy



Devarajulu, Baskar (D.) wrote:

Hi,

  I'm using Python and working for automation of testing ,I face error 
when the script accessed  TCP/IP Interface


COMM_TYPE = 1# Choose 1 - TCP IP Communication or 0 - 
RS232 communication.

TCP_ip = '136.18.201.53' #   the TCP IP address of the  PC.
port = 8080 
BAUD_RATE   = 115200


if (COMM_TYPE == 1):
asap3.TcpOpen(TCP_ip,port)

Error:

C:/Apps/dSPACE51/Common/Python22/Modules/InterfaceLibs/asap3lib.py", 
line 320, in TcpOpen

asap3libError: Error connect TCP/IP
Thanks if you can help.


asap3lib.py is not part of the stdlib, and the error message is not very 
informative.  Look at line 320 and see what might trigger the error.


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


Strange urllib.unquote() behavior

2008-06-26 Thread Jonas Galvez
To me, at least.

>>> urllib.unquote("content%28type%3D%2527Car%2527%29")
'content(type=%27Car%27)'
>>> urllib.unquote('content(type=%27Car%27)')
"content(type='Car')"

The quoted string is coming from a URL parameter parsed in a Google App
Engine request handler.

So right now I have to apply unquote() twice in order to get the correct
result.

Any clue much appreciated.

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

Re: list previous or following list elements

2008-06-26 Thread Terry Reedy



antar2 wrote:

Hello


Suppose I have a textfile (text1.txt) with following four words:


I see seven.  Just say 'list of words'


Apple
balcony
cartridge
damned
paper
bold
typewriter

and I want to have a python script that prints the words following the
word starting with the letter b (which would be cartridge) or
differently put, a script that prints the element following a
specified element:

I am more experienced in Perl, and a beginner in python

I wrote a script that - of course - does not work, that should print
the element in a list following the element that starts with a b


I believe
wordlist = open('words.txt','r').read().split('\n')
should give you the list in Python.  In any case,

wordlist = ['Apple','balcony', 'cartridge',
'damned', 'paper', 'bold', 'typewriter']
for i, word in enumerate(wordlist):
if word[0] == 'b':
print(wordlist[i+1]) # 3.0
break

#prints cartridge (in 3.0)

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


  1   2   >