Re: Windows process ownership trouble

2008-06-26 Thread geoffbache

Tim,

I copied your code exactly from my browser and ran it, so I don't
think there was a typo.
I could upgrade to Python 2.5.2 I suppose to compare and contrast, but
I need to support older
Python versions anyway so it's a bit academic...

Your speculation about garbage collection did set me going, however,
and I discovered
that the following code does work on my system, so now I have a
functional workaround:

import os
import subprocess

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

runProcess()
os.remove ("filename")

So it seems that some things are only being garbage collected when the
function exits, but not when the
except clause exits or when the exception is thrown.

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


Re: Cyclic imports

2008-06-26 Thread Torsten Bronger
Hallöchen!

James writes:

>> # a.py
>> import b
>> # refer to b.b
>>
>> # b.py
>> import a
>> # refer to a.a
>
> Thanks Dan, but that still doesn't work for me I'm afraid...
>
> I renamed the modules avoid name overloading -- a.py is now:
> import b
>
> class A():
> print('b.b_mod:', b.b_mod)

Dan's hint is the way to go nevertheless.  However, it is still not
possible to actually use the module object on the top-level (i.e.,
while module a.py is read).  So, you must delay any access to module
b until everything is fully loaded -- for example, by wrapping the
access in a function which is called from the main program.

On the other hand, the above code was for debugging purposes I
assume.  So maybe there's no real problem anyway because all your
uses of module b are wrapped in functions/methods anyway.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
   Jabber ID: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cyclic imports

2008-06-26 Thread James
> # a.py
> import b
> # refer to b.b
>
> # b.py
> import a
> # refer to a.a

Thanks Dan, but that still doesn't work for me I'm afraid...

I renamed the modules avoid name overloading -- a.py is now:
import b

class A():
print('b.b_mod:', b.b_mod)

b is now defined, but b.b_mod isn't:
  File "main.py", line 1, in 
from a import a_mod
  File "/Users/james/tmp/python/a/a_mod.py", line 3, in 
class A():
  File "/Users/james/tmp/python/a/a_mod.py", line 4, in A
print('b.b_mod:', b.b_mod)
AttributeError: 'module' object has no attribute 'b_mod'

I must be missing something here - I've tried adding the modules to
__all__ in __init__.py but that didn't help either.

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


Re: Web Crawler - Python or Perl?

2008-06-26 Thread Chuck Rhode
On Sun, 22 Jun 2008 10:47:59 -0700, subeen wrote:

> You can avoid the problem using the following code:

> import socket

> timeout = 300 # seconds
> socket.setdefaulttimeout(timeout)

Yes, I tried that, too, but I forget what went wrong with it.
Perhaps, the socket kept up the handshake even though the download
stalled.

-- 
.. Chuck Rhode, Sheboygan, WI, USA
.. 1979 Honda Goldwing GL1000 (Geraldine)
.. Weather:  http://LacusVeris.com/WX
.. 73° — Wind Calm
--
http://mail.python.org/mailman/listinfo/python-list

Re: Cyclic imports

2008-06-26 Thread Dan Bishop
On Jun 26, 10:40 pm, James <[EMAIL PROTECTED]> wrote:
> Hi all,
> I'm looking for some advice dealing with cyclic, cross-package
> imports.
>
> I've created the following demo file structure:
> ./a/__init__.py
> ./a/a.py
> ./b/__init__.py
> ./b/b.py
> ./main.py
>
> a.py imports a class from b.py and vice versa, and main.py imports
> them both.
>
> However, because a.py has not been completely read by the time it gets
> to the:
> from b import b
> line, the
> from a import a
> line in b.py fails with an import error (stack trace at the end).
>
> I hope that's clear: basically, because of the cyclic import, I see
> incomplete modules which can't be imported.
>
> Can I have this module hierarchy in some other way?

# a.py
import b
# refer to b.b

# b.py
import a
# refer to a.a
--
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python in a group

2008-06-26 Thread Mr. Juju

Taygun Kekec wrote:

hi guys.

I would be glad to join your group because i want to learn deeper
python but i am frustrated of isolation too. It would provide
stimulation and encourage to study and will boost our desire to learn.
So count me in!


hello all,
I just started studying python myself and was looking for a group. I 
would be happy to join. Count me in. Email me with the details of how 
you guys want to do this. Cheers

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


Cyclic imports

2008-06-26 Thread James
Hi all,
I'm looking for some advice dealing with cyclic, cross-package
imports.

I've created the following demo file structure:
./a/__init__.py
./a/a.py
./b/__init__.py
./b/b.py
./main.py

a.py imports a class from b.py and vice versa, and main.py imports
them both.

However, because a.py has not been completely read by the time it gets
to the:
from b import b
line, the
from a import a
line in b.py fails with an import error (stack trace at the end).

I hope that's clear: basically, because of the cyclic import, I see
incomplete modules which can't be imported.

Can I have this module hierarchy in some other way?

Thanks,
James

Stack trace from example:
  File "main.py", line 1, in 
from a import a
  File "/Users/james/tmp/python/a/a.py", line 1, in 
from b import b
  File "/Users/james/tmp/python/b/b.py", line 1, in 
from a import a
ImportError: cannot import name a
--
http://mail.python.org/mailman/listinfo/python-list


How to "rebind" py2.5.1 to run from comprompt after uninstalling py3.0?

2008-06-26 Thread defn noob
I installed python30 and so command prompt runs all pythonprograms
through that which i didnt want so i uninstalled it.

now i cant start any pythonprograms through the commandprompt.

how do I "rebind" python25 to luanch when claling .py-files from the
command prompt?
--
http://mail.python.org/mailman/listinfo/python-list


warning for unused packages/modules/objects

2008-06-26 Thread Daniel Fetchinson
How difficult would it be to implement a system in python that would
warn if there are unnecessarily imported packages/modules/objects in
the code? I mean that when developing some code one frequently imports
stuff, deletes the import, changes stuff here and there, imports other
stuff, later decides to change things and consequently delete the line
with the import, etc, etc. As a result there can stay
packages/modules/objects that are in the end not used. It would be
great if python would issue a warning once the program finishes.

Cheers,
Daniel
-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
--
http://mail.python.org/mailman/listinfo/python-list


Re: Working with the Windows Registry

2008-06-26 Thread s0suk3
On Jun 26, 4:24 am, teh_sAbEr <[EMAIL PROTECTED]> wrote:
> 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.

I haven't tried this, but I'd suggest to look at the Windows API.
There are several Python interface modules such as win32api.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python interface to Firefox and Thunderbird

2008-06-26 Thread Larry Bates

yardennis wrote:

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



The reason you haven't gotten any responses is that you didn't provide adequate 
information>


You didn't say what O/S, so I have to guess that since you said Outlook it must 
be windows.


- Auto download and install FF3/TB2.  Why?  Dowload the installers and put them 
somewhere (CD/ROM, Flash Drive, etc) , then write a batch file that installs them.


- Auto download and install Python.  Same as FF/TB.  Get setup.exe from 
ActiveState Python.


- Auto import from IE 6, 7 and OE 5,6 and Outlook.  Auto import what into what? 
Is OE Outlook Express?  What do you want to import and what are you importing into?


- Read contacts and emails from Thunderbird store.  Why?  Wouldn't it be easier 
to read them from the POP3/IMAP server?



- Read Firefox 3 bookmarks, history, cookies and password.  There are plug-ins 
that allow you to export these items (at least bookmarks and passwords). 
History/cookies can be easily cleared by the users.  If you want to monitor 
sites visited, there are better ways.


As you can see we will need to know more about what you are trying to accomplish 
to help more.


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


Design principles and architecture of an information transfer standard based on XML and SOAP

2008-06-26 Thread xkenneth
All,

   So i'm just about to undertake my first real open source project,
and I'm looking for a bit of advice. There's an oilfield standard
called WITSML (Wellsite Information Transfer Standard Markup Language
- witsml.org), it's basically a collection of XML schemas and a spec
for an client-server based communication standard based on SOAP and
WSDL. I'm looking for advice and past experience on how to architect
this project and implement it properly. I'm fairly new with concepts
such as threading, ORM, etc in a server/client context. If anyone has
any past experience they'd like to contribute, architecture theory,
documentation, anything at all, I'd be very grateful.

You can find our project here:
(also feel more than welcome to join and help!)
http://www.openplans.org/projects/openwitsml/summary

Regards,
Kenneth Miller
[EMAIL PROTECTED]

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


Re: recursion in Class-methods?

2008-06-26 Thread Saul Spatz

defn noob wrote:

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


I modified your code as shown below, and it seems to work fine.  (I 
didn't test the shortest path part, just the example you gave.)


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

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

def find_all_paths(self, start, end, path=None):
if not path:
path = []
path = path + [start]
if start == end:
return [path]
if not self.dictionary.has_key(start):
return []
paths = []
for node in self.dictionary[start]:
if node not in path:
newpaths = self.find_all_paths(node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths

def find_shortest_path(self, start, end, path=None):
if not path:
path = []
path = path + [start]
if start == end:
return path
if not self.dictionary.has_key(start):
return None
shortest = None
for node in self.dictionary[start]:
if node not in path:
newpath = self.find_shortest_path(node, end, path)
if newpath:
if not shortest or len(newpath) < len(shortest):
shortest = newpath
return shortest

g = Graph({'A': ['B', 'C'],
 'B': ['C', 'D'],
 'C': ['D'],
 'D': ['C'],
 'E': ['F'],
 'F': ['C']})
print g.find_all_paths('A', 'C')

Output:
[['A', 'B', 'C'], ['A', 'B', 'D', 'C'], ['A', 'C']]

Here are the changes I made.
1) Inherit from object.  (Anticipation of 3.0)

2) Changed calls such as find_path(self.dictionary, node, end, path) to 
self.find_path(node, end, path).  In python, an objects methods have no

special privileges in calling its other methods.  They call it like
self.otherMethod(...).  Also, the first parameter is supposed to be a
Graph object.  I'm not sure what the effect of calling it with a 
dictionary would be.  BTW, "dictionary" seems like an uninformative

name. Why not call it "adjacent" or "neighbor", or "successor"?

3) Changed the default value of path to None, as suggested by Bruno 
Desthuilliers. What he's telling you is that the default object is 
created only once; when the method is defined.  If it's an int or a 
string, that doesn't matter.  You can't change it, and so you will 
always have the same default value if you need it.  If it's a mutable 
object, like a list, when your method changes it, as with

path = path + [start]
it changes the global default object; the next time you need it, it 
won't be [] but whatever you last changed it to.


This last is a tricky point.  I hope I've been clear.

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


Re: sqlite3 alternative option

2008-06-26 Thread Gandalf
you where right!

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


Re: Need help capturing output of re.search

2008-06-26 Thread John Machin
On Jun 27, 10:45 am, [EMAIL PROTECTED] wrote:
> On Jun 26, 5:12 pm, John Machin <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Jun 27, 10:01 am, [EMAIL PROTECTED] wrote:
>
> > > >You may like to read this:http://www.amk.ca/python/howto/regex/
>
> > > This is a good resource.  Thank you.
> > > Someone else pointed out that I needed to change the
>
> > > if reCheck == "None":
>
> > > to
>
> > > if reCheck == None:   # removed the "s
>
> > "Somebody else" should indeed remain anonymous if they told you that.
> > Use
> >if reCheck is None:
> > or even better:
> >if not reCheck:
>
> > It's not obvious from your response if you got these points:
> > (1) re.match, not re.search
> > (2) filename.startswith does your job simply and more understandably
>
> Understood.  I replaced re.search with re.match (although both work)

Not so. Consider a filename that starts with some non-alphanumeric
characters followed by CC_ e.g. "---CC_foo". re.search will score a
hit but re.match won't. It's quite simple: if you want hits only at
the beginning of the string, use re.match. Please don't say "I don't
have any filenames like that, so it doesn't matter" ... it's like
saying "They couldn't hit an elephant at this distance".

> can filename.startswith be used in a conditional?  ala:
>
> if filename.startswith('CC_'):
> processtheFile()

Of course. *Any* expression can be used in a condition. This one
returns True or False -- a prime candidate for such use. Why are you
asking?
--
http://mail.python.org/mailman/listinfo/python-list


What happened to _tkinter.so?

2008-06-26 Thread akineko
Hello Python developers,

I have noticed something curious while I was investigating a problem
with the PyInstaller.

In my environment, the PyInstaller couldn't find TCL/TK installation
path even I have it.
I found the PyInstaller uses output from ldd  to
find the a path to TCL/TK libraries.
But no dynamic libraries under my Python 5 lib-dynload directoty
contain a path to TCL/TK libraries.

When I posted this problem to the PyInstaller newsgroup, a guy
responded that he didn't have such problem.
After several exchanges, what we found was his lib-dynload directory
contains _tkinter.so (even he has the same Python2.5.2) while my lib-
dynload directory doesn't have it.

He installed the Python using package tool (no fresh compile) while I
installed my Python from src (clean compile).

I recompiled Python 2.4 and confirmed that Python 2.4 creates
_tkinter.so.
After browsing the Makefile under Python 2.5, I had an impression that
Python 2.5 no longer uses _tkinter.so.

Am I correct?
If that is the case, I need to warn the PyInstaller developers that
the scheme to find TCL/TK path is no longer valid.

Any comments will be highly appreciated.

Thank you for your attention.
Aki Niimura
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need help capturing output of re.search

2008-06-26 Thread joemacbusiness
On Jun 26, 5:12 pm, John Machin <[EMAIL PROTECTED]> wrote:
> On Jun 27, 10:01 am, [EMAIL PROTECTED] wrote:
>
> > >You may like to read this:http://www.amk.ca/python/howto/regex/
>
> > This is a good resource.  Thank you.
> > Someone else pointed out that I needed to change the
>
> > if reCheck == "None":
>
> > to
>
> > if reCheck == None:   # removed the "s
>
> "Somebody else" should indeed remain anonymous if they told you that.
> Use
>    if reCheck is None:
> or even better:
>    if not reCheck:
>
> It's not obvious from your response if you got these points:
> (1) re.match, not re.search
> (2) filename.startswith does your job simply and more understandably

Understood.  I replaced re.search with re.match (although both work)
can filename.startswith be used in a conditional?  ala:

if filename.startswith('CC_'):
processtheFile()

Thanks for the great help!
--
http://mail.python.org/mailman/listinfo/python-list


Re: list previous or following list elements

2008-06-26 Thread bearophileHUGS
Terry Reedy:
> I believe
> wordlist = open('words.txt','r').read().split('\n')
> should give you the list in Python.

This looks better (but it keeps the newlines too. Untested. Python
2.x):

words = open("words.txt").readlines()
for i, word in enumerate(words):
if word.startswith("b"):
print words[i+1]
break

Another possibility (untested, lazy, uses less memory, probably
better):

fin = open("words.txt")
last_word = fin.next()
for word in fin:
if last_word.startswith("b"):
print word
break
else:
last_word = word
fin.close()

A note for the original poster: I suggest you to try to learn string
methods (not the string module), they are designed to avoid you to use
regular expressions most of the times, and they are faster and more
readable too. I have seen that people that learn Python coming from
Perl are often 'blind' to their existence.

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


Re: sqlite3 alternative option

2008-06-26 Thread jay graves
On Jun 26, 6:30 pm, Allen <[EMAIL PROTECTED]> wrote:
> Gandalf wrote:
> > 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
>
> I don't know if this will help, but using transactions dramatically
> speed things up.  I've only played around with inserting records from
> large CVS files in C++, but outside of a transaction it creates an
> automatic transaction every time an update is made and takes forever,
> but if all the updates are inserted into one transaction and committed
> as one, it is  substantially faster.

In addition, if this is a one time conversion, look into using the
bulk import functions.   (.import FILE TABLE)
Since you are coming from another database you know your constraints
are satisfied, I would wait until all the data is loaded before
building your indexes.

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


Re: Need help capturing output of re.search

2008-06-26 Thread John Machin
On Jun 27, 10:01 am, [EMAIL PROTECTED] wrote:
> >You may like to read this:http://www.amk.ca/python/howto/regex/
>
> This is a good resource.  Thank you.
> Someone else pointed out that I needed to change the
>
> if reCheck == "None":
>
> to
>
> if reCheck == None:   # removed the "s

"Somebody else" should indeed remain anonymous if they told you that.
Use
   if reCheck is None:
or even better:
   if not reCheck:

It's not obvious from your response if you got these points:
(1) re.match, not re.search
(2) filename.startswith does your job simply and more understandably

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


Re: list previous or following list elements

2008-06-26 Thread norseman


Terry Reedy wrote:




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


using copy/paste: yes it does


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)



using copy/paste: same (correct) result in python 2.5.2
  for wordlist = open...   AND for wordlist = [

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


Re: Help me on Backspace please

2008-06-26 Thread John Machin
On Jun 27, 6:32 am, [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.
>

I haven't seen anything like that for ... ummm, a very long time. Used
for bolding and making up your own characters on a daisy-wheel
printer. Where did you get the file from?

If there are no cases of multiple adjacent backspaces (e.g. "blahfoo\b
\b\bblah") you can do:
   new_line = re.sub(r'.\x08', old_line, '')

Note: using \x08 for backspace instead of \b to avoid having to worry
about how many \ to use in the regex :-)

Otherwise you would need to do something like
   while True:
  new_line = re.sub(r'[^\x08]\x08', '', old_line)
  if new_line == old_line: break
  old_line = new_line

And if you were paranoid, you might test for any remaining stray
backspaces, just in case the line contains "illegal" things like
"\bfoo" or "foo\b\b\b\b" etc.

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


Re: Need help capturing output of re.search

2008-06-26 Thread joemacbusiness
>You may like to read this: http://www.amk.ca/python/howto/regex/

This is a good resource.  Thank you.
Someone else pointed out that I needed to change the

if reCheck == "None":

to

if reCheck == None:   # removed the "s

This worked great!  Thanks!

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


Re: sqlite3 alternative option

2008-06-26 Thread Allen

Gandalf wrote:

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


I don't know if this will help, but using transactions dramatically 
speed things up.  I've only played around with inserting records from 
large CVS files in C++, but outside of a transaction it creates an 
automatic transaction every time an update is made and takes forever, 
but if all the updates are inserted into one transaction and committed 
as one, it is  substantially faster.



Brian Vanderburg II
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need help capturing output of re.search

2008-06-26 Thread John Machin
On Jun 27, 8:31 am, [EMAIL PROTECTED] wrote:
> Hi -
>
> I need help capturing the output of a RegEx search.
> I dont understand why this conditional fails.
>
> Here is the code:
>
> #= start snip
> ==
> #!/usr/local/bin/python
>
> import os
> import re
>
> dirName = '/home/user/bin/logs'
> os.chdir(dirName)
> files = os.listdir(dirName)
> for myFile in files:
> #print 'checking ...', myFile
> reCheck = ''
> reCheck = re.search(r'\bCC_',  myFile)
> #print 'reCheck = ', '=', reCheck, '='
>
> if reCheck == "None":
> print myFile, '   . does not qualify'
> else:
> print '  ', myFile, 'qualifies...', reCheck
>
> #= end snip
> ==
>
> The problem is that reCheck never == None.
> So all of the files "qualify".  My understanding of the
> re.search (re.search(r'\bCC_',  myFile)) is ...
> 1) give me  only files that start with a word boundary (\b)
> 2) followed by a (CC_)
> 3) in myFile
>
> Why doesn't the output of the re.search load reCheck with valid data?
> (like "None")


Because "None" is not "valid data" in this case. re.search returns
None or a MatchObject instance.

>>> type(None)

>>> type("None")

>>> None == "None"
False
>>>

You may like to read this: http://www.amk.ca/python/howto/regex/

If you want to check for strings that start with some condition, you
need re.match, not re.search.

You don't need the '\b'; re.match(r'CC_', filename) would do the job.

But then so would filename.startswith('CC_')

HTH,
John

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


Re: Adding functions to an existing instance

2008-06-26 Thread Allen

[EMAIL PROTECTED] wrote:

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)



I tried that.  func.__get__(obj, type(obj)) creates a bound method and 
then sets an attribute to that, creating a cyclic reference.  toto 
contains a reference to the bound method, the bound method contains a 
reference to the instance toto.


However it does eliminate the need for FunctionCaller.  Instead of:

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

__getattr__(...) can just do:

return funcs[name].__get__(self, type(self))

to get the same behavior.

All of the extra __setattr__ and __delattr__ exist so that if the 
attribute is set after a function is set, it will delete the function so 
that later deleting the attribute will not make the function visible again.



Brian Vanderburg II
--
http://mail.python.org/mailman/listinfo/python-list


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

2008-06-26 Thread Jonathan Gardner
On Jun 26, 3:22 pm, MRAB <[EMAIL PROTECTED]> wrote:
> Try something like:
>
> re.compile(r'.*?', re.DOTALL)

So you would pick up strings like "foo"? I doubt that is what oyster wants.
--
http://mail.python.org/mailman/listinfo/python-list


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

2008-06-26 Thread Jonathan Gardner
On Jun 26, 11:07 am, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2008-06-26, Stefan Behnel <[EMAIL PROTECTED]> wrote:
> >
> > 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.
>

s/practical/possible

It isn't *possible* to grok HTML with regular expressions. Individual
tags--yes. But not a full element where nesting is possible. At least
not properly.

Maybe we need some notes on the limits of regular expressions in the
re documentation for people who haven't taken the computer science
courses on parsing and grammars. Then we could explain the necessity
of real parsers and grammars, at least in layman's terms.
--
http://mail.python.org/mailman/listinfo/python-list


Need help capturing output of re.search

2008-06-26 Thread joemacbusiness
Hi -

I need help capturing the output of a RegEx search.
I dont understand why this conditional fails.

Here is the code:

#= start snip
==
#!/usr/local/bin/python

import os
import re

dirName = '/home/user/bin/logs'
os.chdir(dirName)
files = os.listdir(dirName)
for myFile in files:
#print 'checking ...', myFile
reCheck = ''
reCheck = re.search(r'\bCC_',  myFile)
#print 'reCheck = ', '=', reCheck, '='

if reCheck == "None":
print myFile, '   . does not qualify'
else:
print '  ', myFile, 'qualifies...', reCheck

#= end snip
==

The problem is that reCheck never == None.
So all of the files "qualify".  My understanding of the
re.search (re.search(r'\bCC_',  myFile)) is ...
1) give me  only files that start with a word boundary (\b)
2) followed by a (CC_)
3) in myFile

Why doesn't the output of the re.search load reCheck with valid data?
(like "None")

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


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

2008-06-26 Thread MRAB
On Jun 26, 7:26 pm, "David C. Ullrich" <[EMAIL PROTECTED]> wrote:
> 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.)
>
Try something like:

re.compile(r'.*?', re.DOTALL)
--
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


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


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

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


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


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


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


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


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


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


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


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

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


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


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

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


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


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


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


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


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


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


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


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


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


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


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


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


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


  1   2   >