scrolledtext widget error?

2009-05-07 Thread shstein2002
I wrote a twitter client which writes the statuses into a ScrolledText
widget, but it rarely gives a error that I can't nail down. The code
is:

twitwin.scrolled.config(state=NORMAL)
twitwin.scrolled.delete("1.0", END)
evens = True
_.links = []
for x in _.parser.tweets:
start = _.scrolled.index(INSERT)
print "start = ",start
_.scrolled.insert(END, x['screen_name']+" ", ("bold",))
txt = _.whitere.sub(" ",x['text'])  #the text with whitespace
compressed
islink = False
for y in _.urlre.split(txt):  #handle urls
if y != "":
if islink:
a = _.scrolled.index(INSERT)
_.scrolled.insert(END, y)#, ("link",))
b = _.scrolled.index(INSERT)
_.scrolled.tag_add("link", a, b)
_.scrolled.tag_add("href%d"%len(_.links), a, b)
_.links.append((a,b,y))  #save url info and position
in the widget
else:
_.scrolled.insert(END, y)
islink = not islink
_.scrolled.insert(END, "\n")
if evens:
_.scrolled.tag_add("light", start, END)  #alternating
background colors
else:
_.scrolled.tag_add("dark", start, END)
evens = not evens
twitwin.scrolled.config(state=DISABLED)

The print statement usually prints a valid index, but rarely prints
"start=None" and it crashes. Should I be using something other than
INSERT or another method here?

Thanks in advance,
-- Rick
--
http://mail.python.org/mailman/listinfo/python-list


Re: update python version

2009-05-07 Thread Gerhard Häring
km wrote:
> Hi all,
> 
> Is there a way to update python 2.6.1 to 2.6.2  using easy_install ?

No, easy_install installs Python packages. It doesn't upgrade Python
itself. If this is Windows, just install the newer Python version. No
need to uninstall the 2.6.1 first.

If this is some Unix variant, hopefully they will provide updated Python
 packages soon.

-- Gerhard

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


Re: configuring python with disable-thread in Ubuntu

2009-05-07 Thread Gerhard Häring
Deepak Chandran wrote:
> Hello, 
> 
> I am embedding python inside a C++ program. For some reason (I think
> libxml2), I am getting Segmentation fault at PyThread_release_lock. 
> 
> The solution I found online was to configure python with --disable-thread.

That doesn't sound like a solution, but like a kludge.

> I used "apt-get install python-dev" to install python. 
> How do I re-configure it using the --disable-thread option?

You don't want your system Python to be built with "--disable-thread".
Other utilities might depend on threads being available in Python.

If you really want to go this route, download Python from python.org and
build it from source with the required options to "./configure".

-- Gerhard

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


Simple programme - Just want to know whether this is correct way of coding

2009-05-07 Thread guptha
Hi group,
This is my first programme in python ,I need to know whether my code
is in the right path of performance

I wrote a code using multithreading to send mails

FROM = 'com'

SUBJECT = 'This is the subject'
MSGBODY = 'This the body of the message '
MAILSERVER = 'mailcom'
port = 25
username = 'username'
password = 'pass'

# trim the strings of any leading or trailing spaces
FROM = FROM.strip()
SUBJECT = SUBJECT.strip()
MSGBODY = MSGBODY.strip()
MAILSERVER = MAILSERVER.strip()
username = username.strip()
password = password.strip()


# set up email parameters
msg = MIMEMultipart()
msg['From'] = FROM
msg['Subject'] = SUBJECT

#--
print "Starting Multi Thread Method"

class MyThread(Thread):

def __init__(self, site,  FROM, MSGBODY):
Thread.__init__(self)
self.site = site
self.FROM=FROM
self.MSGBODY=MSGBODY

def run(self):
#Connect to server
print 'Connecting to mail server ', MAILSERVER
try:
s = smtplib.SMTP(MAILSERVER,port)
print 'connected'
#s.set_debuglevel(1)
except:
print 'ERROR: Unable to connect to mail server', sys.exc_info   
()[0]
sys.exit(1)

#login to server
if password <> '':
print 'Logging into mail server'
try:
s.login(username,password)
except:
print 'ERROR: Unable to login to mail server', 
MAILSERVER
print 'Please recheck your password'
sys.exit(1)
print "running for %s " %self.site
print s
s.sendmail(self.FROM, self.site, self.MSGBODY)
print "from %s" %self.FROM
print "msg %s" %self.MSGBODY
print "Emailed for  site %s" %self.site
s.quit()
s.close()


a= time.time()
threads = []

for site in listTo:
T = MyThread(site,FROM,MSGBODY)
threads.append(T)
T.start()


for i in threads:
i.join()

print "Took %s seconds" %str(time.time()-a)

#-

The code Works fine ,but I doubt about the performance issue ,My
intention is to send mails concurrently to large number of mail.
1.For every mail id i send It creates a new SMTP object,in case, if i
send to 1000 or more ids
  a) It obliviously creates that much SMPT connections ,is this a
right approach .
Thanks in Advance
--
http://mail.python.org/mailman/listinfo/python-list


Public attributes with really private data

2009-05-07 Thread Mark Summerfield
Hi,

I had a quick search & didn't find anything _nice_ that produced
attributes with really private data, so I came up with a possible
solution---for Python 3.
(For Python 2 there does seem to be an approach although I'm not
keen on it:
http://www.builderau.com.au/blogs/byteclub/viewblogpost.htm?p=339270875
)

Here's a standard class with one read-only and one writable
property that has a tiny bit of validation.

class P:
def __init__(self, w):
self.w = w
@property
def r(self): return 5
@property
def w(self): return self.__w
@w.setter
def w(self, value):
if value > 0: # Only +ve values allowed
self.__w = value
else:
raise ValueError("'{0}' is not valid for w".format(value))

The read-only property is completely private because it isn't
actually stored as such.

But if we do dir() on an instance, in addition to 'r' and 'w', we
also have '_P__w'. So the writable property's data is easily
accessible, and the validation can be got around:

>>> p = P(9)
>>> p.r, p.w
(5, 9)
>>> p.w = 43
>>> p.r, p.w
(5, 43)
>>> p.w = -7
Traceback (most recent call last):
...
ValueError: '-7' is not valid for w
>>> p._P__w = -7
>>> p.r, p.w
(5, -7)

Here's a class where I can't think of a way to access the private
data and set invalid values.

class A:
r = Attribute("r", 5)
w = Attribute("w", None, lambda self, value: value > 0)
def __init__(self, w):
self.w = w

The Attribute class is a descriptor that takes three arguments:
name of attribute, initial value (essential for read-only
attributes!), and a validator function (which could be "lambda
*a: True" if any value is accepatble).

>>> a = A(9)
>>> a.r, a.w
(5, 9)
>>> a.w = 43
>>> a.r, a.w
(5, 43)
>>> a.w = -7
Traceback (most recent call last):
...
ValueError: '-7' is not valid for w

If we do a dir(a) the only attributes we get (beyond those from
object) are 'r' and 'w', so it shouldn't be possible to get
around the validation---at least not easily.

Here's a rough & ready implementation of the Attribute class:

class Attribute:
def __init__(self, name, first_value=None, validator=None):
self.__name__ = name
hidden_value = first_value
self.__getter = lambda self: hidden_value
if validator is not None:
def set(self, value):
if validator(self, value):
nonlocal hidden_value
hidden_value = value
else:
raise ValueError("'{0}' is not valid for
{1}".format(value, name))
self.__setter = set
else:
self.__setter = None
def __get__(self, instance, owner=None):
if instance is None:
return self
return self.__getter(instance)
def __set__(self, instance, value):
if self.__setter is None:
raise AttributeError("'{0}' is read-only".format(
 self.__name__))
return self.__setter(instance, value)

The key to making the attribute data private is that it is held
as part of a closure's state. Notice that nonlocal is needed,
so you need Python 3.

--
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
C++, Python, Qt, PyQt - training and consultancy
"Programming in Python 3" - ISBN 0137129297
--
http://mail.python.org/mailman/listinfo/python-list


configuring python with disable-thread in Ubuntu

2009-05-07 Thread Deepak Chandran
Hello, 

I am embedding python inside a C++ program. For some reason (I think libxml2), 
I am getting Segmentation fault at PyThread_release_lock. 

The solution I found online was to configure python with --disable-thread.

I used "apt-get install python-dev" to install python. 
How do I re-configure it using the --disable-thread option?

Thanks.


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


Re: Python 2.6, File read() problems in Windows Xp

2009-05-07 Thread Chris Rebert
On Thu, May 7, 2009 at 10:04 PM, Li Wang  wrote:
> Hi all:
>
> I am trying to read a non-text file as a string by using Python
> read(), however, it seems there is some thing wrong with it. I can use
> read() on text file correctly, but unable to read .xls file correctly.
> (The program can read any file correctly in Fedora 10)
>
> Any idea how to solve this problem?

You need to add a "b" to the `flags` argument to open() when you open
the file, e.g. open("the_file.xls", "rb")
Unlike *nix, Windows differentiates between binary and text files,
hence the need for the "b" flag to specify which you're dealing with.

Further info: http://docs.python.org/library/functions.html#open

Cheers,
Chris
-- 
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Python 2.6, File read() problems in Windows Xp

2009-05-07 Thread Li Wang
Hi all:

I am trying to read a non-text file as a string by using Python
read(), however, it seems there is some thing wrong with it. I can use
read() on text file correctly, but unable to read .xls file correctly.
(The program can read any file correctly in Fedora 10)

Any idea how to solve this problem?

Thank you very much!

-- 
Li
--
Time is all we have
and you may find one day
you have less than you think
--
http://mail.python.org/mailman/listinfo/python-list


Re: heapq.merge with key=

2009-05-07 Thread Chris Rebert
On Thu, May 7, 2009 at 2:23 PM, Kevin D. Smith  wrote:
> I need the behavior of heapq.merge to merge a bunch of results from a
> database.  I was doing this with sorted(itertools.chain(...), key=...), but
> I would prefer to do this with generators.  My issue is that I need the key=
> argument to sort on the correct field in the database.  heapq.merge doesn't
> have this argument and I don't understand the code enough to know if it's
> possible to add it.  Is this enhancement possible without drastically
> changing the current code?

I think so. Completely untested code:

def key(ob):
#code here

class Keyed(object):
def __init__(self, obj):
self.obj = obj
def __cmp__(self, other):
return cmp(key(self.obj), key(other.obj))

def keyify(gen):
for item in gen:
yield Keyed(item)

def stripify(gen):
for keyed in gen:
yield keyed.obj

merged = stripify(merge(keyify(A), keyify(B), keyify(C))) #A,B,C being
the iterables


Cheers,
Chris
-- 
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


heapq.merge with key=

2009-05-07 Thread Kevin D . Smith
I need the behavior of heapq.merge to merge a bunch of results from a 
database.  I was doing this with sorted(itertools.chain(...), key=...), 
but I would prefer to do this with generators.  My issue is that I need 
the key= argument to sort on the correct field in the database.  
heapq.merge doesn't have this argument and I don't understand the code 
enough to know if it's possible to add it.  Is this enhancement 
possible without drastically changing the current code?


--
Kevin D. Smith

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


Re: free chart lib for Python?

2009-05-07 Thread alex23
On May 8, 12:27 pm, oyster  wrote:
> is there such a thing with many kinds of chart, i.e. pie-chart,
> line-chart, ..?

The best place to look is PyPI, there are several possible candidates
there:
http://pypi.python.org/pypi?%3Aaction=search&term=charts&submit=search

I've had a lot of success with the Python Google Chart module:
http://pygooglechart.slowchop.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Which one is best Python or Java for developing GUI applications?

2009-05-07 Thread David Cook
On 2009-05-05, srinivasan srinivas  wrote:
 
> Could you tell me does Python have any advantages over Java for the
> development of GUI applications?

You don't have to choose between them.  You can program Swing applications
in Jython.  And Jython is just a jar that you can bundle in another jar for
distribution just like any other Java jar.  You will have to understand Java
code to learn Swing, though.  I suggest also looking into the
Swing Application Framework and Netbeans.

However, I would look at PyQt first (if the license requirements are OK).
PyQT is well thought out, consistent, and featureful.  And then maybe try
wxPython if you need a more liberal license.  wxPython is clunky and
inconsistent, but gets the job done.

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


Re: SQL and CSV

2009-05-07 Thread John Machin
On May 8, 1:45 am, Nick  wrote:
> On May 5, 8:27 pm, Tim Golden  wrote:
>
>
>
> > Nick wrote:
> > > Part of the problem is that the 'selection' needs to be in a config
> > > file. I can put the if row['status'] != 'Cancelled': return True into
> > > a config, read it and eval it, but its not quite as clean as ansql
> > > route.
>
> > Still not clear what the restriction is. If you were writingSQLyou'd have 
> > to read *something* from your config file,
> > unless you're suggesting that the "config file" is in fact
> > aSQLfile. Which is one way of doing it, but then you might
> > just as well have your config file as a Python file and
> > import it.
>
> > Have I missed the point somewhere here? Can you give an
> > example -- even a fictional one -- of what you couldn't
> > do using, say, the example I gave earlier?
>
> > TJG
>
> Solution found. In the end I used SQLite to read from a csv file, and
> now I can query the CSV file. The file is read using the csv module
>
> First create a function
>
> def fraction(p, denom):
>     num, frac = p.split ('-')
>     return float (num) + float (frac) / denom
>
> for use within queries.
>
> Now build the class.
>
>         self.filename  = filename
>         self.dialect   = dialect
>         self.query     = query
>         reader = csv.reader (open (filename, 'r'))
>         self.connection = sqlite.connect(":memory:")
>         self.connection.create_function("fraction", 2, fraction) #
> Adds in function
>         self.cursor = self.connection.cursor()
>         first = True
>         for row in reader:
>             if first:
>                 headers = []
>                 for r in row:
>                     n = r.strip().replace (' ', '_').replace ('-','_')
>                     headers.append (n)
>                 command = 'create table csv (%s)' % ','.join (headers)
>                 self.cursor.execute (command)
>                 first = False
>             else:
>                 command = 'insert into csv values ("%s")' % '","'.join
> (row)
>                 self.cursor.execute (command)
>
> and then I can use this
>
>         self.cursor.execute (self.query)
>         rows = self.cursor.fetchall()
>         headers = []
>         for r in self.cursor.description:
>             headers.append (r[0])
>         results = Results.Results (headers, self.name, {})
>         i = 0
>         for row in rows:
>             results.add (row, i)
>             i = i + 1
>         return results
>
> to query the results.
>
> Results.Results is one of my classes that's reused in lots of places.
>
> The query then looks somethign like this
>
>                 select
>                     Client_Reference_Number as TrdNbr,
>                     Asset_Number as ISIN,
>                     Quantity as Qty,
>                     status
>                 from
>                     csv

The remaining lines of your SELECT statement are incredibly redundant
AFAICT. It seems you have pushed the contents of your csv file into a
data base and pulled them ALL out again ... not what I'd call a
"query". What's the point?


>                 where status in ("CANCELLED")
>
>                 union
>
>                 select
>                     Client_Reference_Number as TrdNbr,
>                     Asset_Number as ISIN,
>                     Quantity as Qty,
>                     status
>                 from
>                     csv
>                 where status not in ("CANCELLED")
>
> All incredibly neat and the first time I've used SQLite.
>
> nick

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


free chart lib for Python?

2009-05-07 Thread oyster
I mean chart, not plot. If you don't know the difference, you can
check www.advsofteng.com, which is a commercial program

is there such a thing with many kinds of chart, i.e. pie-chart,
line-chart, ..?

A long time ago, I programmed a rmchart interface, however rmchart is
windows only, and www.rmchart.com disappeared now

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


update python version

2009-05-07 Thread km
Hi all,

Is there a way to update python 2.6.1 to 2.6.2  using easy_install ?

thanks,
regards,
KM
--
http://mail.python.org/mailman/listinfo/python-list


Re: Code works fine except...

2009-05-07 Thread John Yeung
On May 7, 8:32 pm, Ross  wrote:
> I've managed to solve the problem. If you go in
> order, the discrepancy between the player with the
> least amount of byes and the greatest amount of byes
> is only 1.

I don't mean to rain on your parade, but that's not the case for all
values.  For example, with 7 players and only 1 or 2 courts, there
will be weeks in the middle where the bye-difference is 2.

This behavior is present in both your shuffle and the standard one in
Wikipedia.

Ultimately, as it pertains to your physical tennis scheduling with
actual courts and actual players, you may never encounter the
imbalance.  But as a math problem, it's still not solved.  (Someone
may have solved it or proved it insoluble, but obviously I am not
aware of such a proof, because otherwise I would have presented it
already.)

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


Web Based Front End?

2009-05-07 Thread baseelinger
I have been using Python for several years now and although my main
occupation is not directly related to writing code I have been able to
use Python to accomplish writing complex configuration files and
analyzing data against standards, etc.  I now have a requirement to
provide a web based interface rather than say using the IDLE GUI for
several reasons, (allowing others to use a server based Python script
and to provide a slicker user interface via the users web browser).

As I wade into very new territory I see articles on PHP, mod_python,
Python Server Pages, CGI, Zope, Python in PHP, CherryPy, Pylons, etc.,
etc.  It's all pretty confusing and while one method may work to
accomplish the task at hand someone with far greater experience may
look at the situation and say, "um, yeah, it will work that way but it
would have been a whole lot easier if you had done it this way...".

So, my question is what is the best method to be able to have a user
enter specific data on a web page, have that data be passed to the
Python script and then have the output returned to the web page?
Essentially, I want to use a web based front end to accomplish the
same thing that the IDLE GUI does, (asks me a few questions, I answer
them, it builds a configuration file and prints it to the screen).

A basic example can be found at 
http://webpython.codepoint.net/wsgi_request_parsing_post
using httpd in Python but its seems very basic.

Can anyone point me in the right direction?  Thanks in advance for any
assistance you may be able to provide.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Call a function when a thread exits

2009-05-07 Thread Carl Banks
On May 7, 6:12 pm, "Giampaolo Rodola'"  wrote:
> Hi,
> I'm searching for a smooth way to call a certain function when a
> thread has finished its job.
> I guess I can keep calling isAlive() in a loop and call my function
> when it returns False but it's not very elegant.
> Actually I'm a bit surprised it doesn't exists an "atexit" function.
> Something like:
>
> import threading, time
>
> def myfun():
>     time.sleep(1)
>     print "hello"
>
> def cleanup():
>     print "thread finished, starting cleanup operations..."
>
> t = threading.Thread(target=myfun)
> t.atexit(target=cleanup)
> t.start()
>
> Is there a reason why there's no such thing in the threading module?

You can define your target function to clean up on exit.  Using your
definitions of myfun and cleanup,

def mycleanfun():
try:
myfun()
finally:
cleanup()

t = threading.Thread(target=mycleanfun)
t.start()


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


Re: regular expression for getting content between parentheses

2009-05-07 Thread Rajanikanth Jammalamadaka
Thanks for your replies.

I changed the file to look like this:


{ testName : {"someParam": "value1", "anotherParam": (value2, value3)},
}

to make it look like a hash to Python.

Thanks,

Raj

On Thu, May 7, 2009 at 5:19 PM, Rhodri James
 wrote:
> On Fri, 08 May 2009 00:51:14 +0100, Rajanikanth Jammalamadaka
>  wrote:
>
>> Hi
>>
>> I have a text file as follows:
>>
>> testName = (
>>  someParam = value1
>>  anotherParam = (value2, value3)
>> )
>>
>> how do I write a regular expression to get all the contents of the
>> file which are between the first and last parentheses.
>
> You don't, or at least you don't without some cast-iron guarantees
> that your file will look *exactly* like this.  If you can guarantee
> that, then this should work:
>
> import re
>
> f = open(filename)
> data = f.read()
> m = re.match(r"""[^(]*\(     # Find the first open parenthesis
>                 (.*)        # Gobble up everything...
>                 \)[^)]*$    # ...to the last close paren""",
>             data, re.X)
> if m:
>  print m.group(1)
>
>
> Notice that this will do *exactly* what you asked; pick up
> everything between the first and the last parentheses.  In
> particular, if your text looks like this:
>
> testName1 = (
>  someParam1 = value1
>  anotherParam1 = (value2, value3)
> )
> testName2 = (
>  sameParam2 = value4
> )
>
> ...then what you'll get out is:
>
>  someParam1 = value1
>  anotherParam1 = (value2, value3)
> )
> testName2 = (
>  sameParam2 = value4
>
>
> You can't get around that with regular expressions, you'll
> have to parse your way through the input string counting
> open and close parentheses as you go.
>
> --
> Rhodri James *-* Wildebeeste Herder to the Masses
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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


Call a function when a thread exits

2009-05-07 Thread Giampaolo Rodola'
Hi,
I'm searching for a smooth way to call a certain function when a
thread has finished its job.
I guess I can keep calling isAlive() in a loop and call my function
when it returns False but it's not very elegant.
Actually I'm a bit surprised it doesn't exists an "atexit" function.
Something like:

import threading, time

def myfun():
time.sleep(1)
print "hello"

def cleanup():
print "thread finished, starting cleanup operations..."

t = threading.Thread(target=myfun)
t.atexit(target=cleanup)
t.start()


Is there a reason why there's no such thing in the threading module?


--- Giampaolo
http://code.google.com/p/pyftpdlib/
--
http://mail.python.org/mailman/listinfo/python-list


Re: IIR filter conversion routines for Python?

2009-05-07 Thread Aahz
In article ,
wzab   wrote:
>
>I'm looking for procedures converting the IIR filters into cascade and/
>or parallel forms. Something like dir2cas.m or dir2par.m known in the
>Matlab/Octave world.
>Unfortunately SciPy does not contain such functions.
>If they are not available, I would be grateful for any hints helping
>me to implement them myself.

Even though they're not in SciPy, the mailing lists for NumPy/SciPY are
probably good places to get advice.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Code works fine except...

2009-05-07 Thread Ross
On May 7, 1:11 am, John Yeung  wrote:
> On May 7, 12:30 am, Ross  wrote:
>
>
>
> > If I were to set up a dictionary that counted players used in the bye
> > list and only allowed players to be added to the bye list if they were
> > within 2 of the least used player, would this be a good approach for
> > managing bye selection or would using a dictionary in this manner be
> > unnecessary/redundant?
>
> I certainly have not proved it, but I think you don't need to resort
> to anything fancy if you are OK with the maximum byes being within two
> of the minimum byes.  (Maybe this needs to be larger with larger
> numbers of players.)  Try using your original shuffle but instead of
> selecting matches to "throw away" each week, just use the matches you
> need (to fill up the courts) and pick up where you left off the next
> week.  For example, with 10 players, each "round" ideally consists of
> five matches.  If you only have four courts, don't throw away the
> fifth match; save it as the first match next week.
>
> To be honest, I didn't look too carefully at your original shuffle.
> It may be good enough.  It's a little different than the "standard"
> rotation as presented on Wikipedia:
>
>  http://en.wikipedia.org/wiki/Round-robin_tournament#Scheduling_algorithm
>
> The one on Wikipedia happened to pass my casual tests with no more
> than a 2-bye difference between the most-played and least-played
> players, and didn't run into the problem of scheduling the same player
> for two matches the same week.  But I have to stress I only tried a
> few starting values, which all worked; I didn't try to break it, or
> run an extensive battery of tests.
>
> John

John,
   I really appreciate your help with this problem. Thanks to your
suggestions, I've managed to solve the problem. Here's what I did: I
used my original round_robin generator to generate each week. I then
took every week and chained them all together end to end. Then,
depending on how many courts are available, I can select that many
tuples at a time from the list. If you go in order, the discrepancy
between the player with the least amount of byes and the greatest
amount of byes is only 1. If you can make it exactly all the way
through a cycle, there will be no discrepancy. Anyways, I've done all
this by hand and it works so now I'm going to go ahead and code it up.
Again, thanks for your help.

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


Re: Pygame

2009-05-07 Thread Dave Angel

cripplem...@gmail.com wrote:

I am following this tutorial on python, and it has instructed me to
download pygame. I am not sure it works with the new version of python
I am using,
and what version would that be?  What release, and what platform?  print 
sys.version and include the output in your next message.

 as the last version it states on the tutorial is 2.6.

It is telling me the module 


what module?  Copy & paste the error message into your query, and you're 
likely to get useful response.  Also copy & paste the command you're 
issuing to cause this error message.
does not exist after I download, 


Then your download manager is complaining about a missing module?

and I
even tried placing it in the python folder, 
which "python folder".   Be specific.  Do you mean the folder that 
contains Python.exe? And just what are you "placing" there?

but it still came up with
a problem.
  

A new problem?  Be specific.

Any way to fix it, or do I try something else?

  
Wild guess - maybe it's complaining about a missing SDL module.  PyGame 
is dependent on SDL, as far as I can tell.


Also, see http://www.pygame.org/download.shtmlIf you're on Windows, 
PyGame has different versions for different versions of Python.  This 
page recommends Python 2.5.4.  And there isn't a version for Python 3.0


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


Re: regular expression for getting content between parentheses

2009-05-07 Thread Rhodri James
On Fri, 08 May 2009 00:51:14 +0100, Rajanikanth Jammalamadaka  
 wrote:



Hi

I have a text file as follows:

testName = (
 someParam = value1
 anotherParam = (value2, value3)
)

how do I write a regular expression to get all the contents of the
file which are between the first and last parentheses.


You don't, or at least you don't without some cast-iron guarantees
that your file will look *exactly* like this.  If you can guarantee
that, then this should work:

import re

f = open(filename)
data = f.read()
m = re.match(r"""[^(]*\( # Find the first open parenthesis
 (.*)# Gobble up everything...
 \)[^)]*$# ...to the last close paren""",
 data, re.X)
if m:
  print m.group(1)


Notice that this will do *exactly* what you asked; pick up
everything between the first and the last parentheses.  In
particular, if your text looks like this:

testName1 = (
  someParam1 = value1
  anotherParam1 = (value2, value3)
)
testName2 = (
  sameParam2 = value4
)

...then what you'll get out is:

  someParam1 = value1
  anotherParam1 = (value2, value3)
)
testName2 = (
  sameParam2 = value4


You can't get around that with regular expressions, you'll
have to parse your way through the input string counting
open and close parentheses as you go.

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: regular expression for getting content between parentheses

2009-05-07 Thread Emile van Sebille

On 5/7/2009 4:51 PM Rajanikanth Jammalamadaka said...

Hi

I have a text file as follows:

testName = (
 someParam = value1
 anotherParam = (value2, value3)
)

how do I write a regular expression to get all the contents of the
file which are between the first and last parentheses.

In this case,  I want:

 someParam = value1
 anotherParam = (value2, value3)

Thanks,


It's not a regex nor probably what you want, but I'd start with...


>>> filetext = '''testName = (
...  someParam = value1
...  anotherParam = (value2, value3)
... )'''
>>>
>>> print filetext.split("(",1)[-1].rsplit(")",1)[0]

 someParam = value1
 anotherParam = (value2, value3)

>>>

Emile

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


Re: Pygame

2009-05-07 Thread Mensanator
On May 7, 6:52 pm, cripplem...@gmail.com wrote:
> I am following this tutorial on python, and it has instructed me to
> download pygame. I am not sure it works with the new version of python
> I am using, as the last version it states on the tutorial is 2.6.

If the module says 2.6, then that's the version you must use.

There's not much point in using 3.x until the 3rd party modules
catch up. Unless said modules are not important to you.

And even that's no guarantee. The sympy module writers just assumed
their code would work in 2.6 without testing it. Turns out they were
seriously wrong and had to scramble to make a bug fix.

>
> It is telling me the module does not exist after I download, and I
> even tried placing it in the python folder, but it still came up with
> a problem.
>
> Any way to fix it, or do I try something else?

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


Re: Pygame

2009-05-07 Thread Chris Rebert
On Thu, May 7, 2009 at 4:52 PM,   wrote:
> I am following this tutorial on python, and it has instructed me to
> download pygame. I am not sure it works with the new version of python
> I am using, as the last version it states on the tutorial is 2.6.
>
> It is telling me the module does not exist after I download, and I
> even tried placing it in the python folder, but it still came up with
> a problem.

Please give the actual full text of the error message (and traceback
if possible).
Please explain precisely which folder you mean by "the python folder".

Cheers,
Chris
-- 
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Pygame

2009-05-07 Thread cripplemeal
I am following this tutorial on python, and it has instructed me to
download pygame. I am not sure it works with the new version of python
I am using, as the last version it states on the tutorial is 2.6.

It is telling me the module does not exist after I download, and I
even tried placing it in the python folder, but it still came up with
a problem.

Any way to fix it, or do I try something else?
--
http://mail.python.org/mailman/listinfo/python-list


regular expression for getting content between parentheses

2009-05-07 Thread Rajanikanth Jammalamadaka
Hi

I have a text file as follows:

testName = (
 someParam = value1
 anotherParam = (value2, value3)
)

how do I write a regular expression to get all the contents of the
file which are between the first and last parentheses.

In this case,  I want:

 someParam = value1
 anotherParam = (value2, value3)

Thanks,

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


Re: subprocess.Popen howto?

2009-05-07 Thread Carl Banks
On May 7, 2:58 pm, norseman  wrote:
> If you don't like a lot of typing that obscures the process,
> take a look at os.Popen2  Pg.39 or so in Lib.pdf for 2.5.2
> In this case - the popen3 is probably your best bet.
>
> I took a test run on "subprocess" a few months ago. My review:
> excessive typing to accomplish the simple.


Hmm, I won't argue that it can be excessive typing, but I think its
purpose isn't to accomplish the simple but to hit all the corners of
subprocesses.

What if you want os.system without the shell?  What if you want popen
with the shell?  On Windows what if I want a subprocess without a
console from a Python program in a console.  Stuff like that.

I still use os.system for Q&D stuff, but now use subprocess for
everything else since I prefer thorough to short and sweet.


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


Re: Python 2.4.3 array memory leak

2009-05-07 Thread Robert Kern

On 2009-05-07 16:31, danmcle...@yahoo.com wrote:

I am using the array module to instantiate many arrays in my
application. It seems like there is a memory leak in there somewhere.
Can anyone confim this and let me know what, if anything, I can do
about it? I am using Fedora Core 5 Linux:

import commands
import array
import itertools
import sys

from itertools import repeat

print '*** before ***'
print commands.getoutput('cat /proc/meminfo').split('\n')[1]
for i in range(100):
 a = array.array('I', repeat(0, int(2E6)))
 del a
print '*** after ***'
print commands.getoutput('cat /proc/meminfo').split('\n')[1]

Output:
*** before ***
MemFree:   1459772 kB
*** after ***
MemFree:   1457688 kB


This is not necessarily indicative of a memory leak, per se. Python sometimes 
does not release memory back to the OS. The memory isn't leaked; it will be 
reused by Python for later allocations. Now, if you saw Python's memory usage 
*grow* with increasing iterations, then that would be evidence of a leak.


Try measuring the "before" memory, then do one iteration, measure the memory 
again (let's call it "intermediate"), then do your loop, and then measure the 
"after" memory. The "intermediate" measurement should be about your "after" 
measurement.


Also, try to measure the process's own memory usage, not the system's free 
memory.

--
Robert Kern

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

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


Re: subprocess.Popen howto?

2009-05-07 Thread Chris Rebert
2009/5/7 Øystein Johansen (OJOHANS) :
> Hi,
>
> I have problems understanding the subprocess.Popen object. I have a
> iterative calculation in a process running and I want to pipe the output
> (stdout) from this calculation to a Python script.
>
> Let me include a simple code that simulates the calculating process:
> /* This code simulates a big iterative calculation */
> #include 
> #include 
>
> int main()
> {
>  float val[2] = { M_PI, M_E };
>  int i;
>
>  for ( i = 0; i < 2 i++) {
>   sleep( 15 );   /* It's a hard calculation. It take 15 seconds */
>   printf("Value: %5.6f\n", val[i] );
>   fflush( stdout );
>  }
>  return 0;
> }
>
> let's compile this to mycalc: gcc -o mycalc calc.c ... (untested code)
>
> In C I have this code which starts the mycalc process and handles the output
> from it:
>
> #include 
> #include 
> #define BUF_SIZE 256
>
> int main()
> {
>  FILE *pip;
>  char line[BUF_SIZE];
>
>  pip = popen("mycalc", "r");
>  assert( pip != NULL );
>
>  while ( fgets( line, BUF_SIZE, pip )) {
>   printf( "Hello; I got: %s \n", line );
>   fflush( stdout );
>  }
>  pclose( pip );
>  return 0;
> }
> How can I make such while-loop in Python? I assume I should use
> subprocess.Popen(), but I can't figure out how?

import subprocess
subprocess.call(["./mycalc"]) # add `bufsize=-1` as argument to have
output be buffered
#process inherits our filehandles and writes directly to them
#.call() only returns once the process has exited

Cheers,
Chris
-- 
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.4.3 array memory leak

2009-05-07 Thread danmcle...@yahoo.com
On May 7, 4:41 pm, Terry Reedy  wrote:
> danmcle...@yahoo.com wrote:
> > I am using the array module to instantiate many arrays in my
> > application. It seems like there is a memory leak in there somewhere.
> > Can anyone confim this and let me know what, if anything, I can do
> > about it? I am using Fedora Core 5 Linux:
>
> > import commands
> > import array
> > import itertools
> > import sys
>
> > from itertools import repeat
>
> > print '*** before ***'
> > print commands.getoutput('cat /proc/meminfo').split('\n')[1]
> > for i in range(100):
> >     a = array.array('I', repeat(0, int(2E6)))
> >     del a
> > print '*** after ***'
> > print commands.getoutput('cat /proc/meminfo').split('\n')[1]
>
> > Output:
> > *** before ***
> > MemFree:       1459772 kB
> > *** after ***
> > MemFree:       1457688 kB
>
> What happens if you remove the loop?  I would not be surprised if Python
> grabs the memory once, reuses it, and does not let go.  That is not a
> leak.  What happens if you put the after inside the loop?  Does mem
> usage steadily increase, and continue if you increase range to 1000,
> 1?  That would be a leak.
>
> If there actually is a problem, try a later version of Python.

I'm not convinced there is a problem anymore. In my latest code, I
record the virtual mem allocated to my specific process and I do not
see it increasing. I would think that if I was leaking memory, I
should see a steady increase in virtual memory consumed by my process,
which I do not.

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


Re: Python 2.4.3 array memory leak

2009-05-07 Thread Terry Reedy

danmcle...@yahoo.com wrote:

I am using the array module to instantiate many arrays in my
application. It seems like there is a memory leak in there somewhere.
Can anyone confim this and let me know what, if anything, I can do
about it? I am using Fedora Core 5 Linux:

import commands
import array
import itertools
import sys

from itertools import repeat

print '*** before ***'
print commands.getoutput('cat /proc/meminfo').split('\n')[1]
for i in range(100):
a = array.array('I', repeat(0, int(2E6)))
del a
print '*** after ***'
print commands.getoutput('cat /proc/meminfo').split('\n')[1]

Output:
*** before ***
MemFree:   1459772 kB
*** after ***
MemFree:   1457688 kB


What happens if you remove the loop?  I would not be surprised if Python 
grabs the memory once, reuses it, and does not let go.  That is not a 
leak.  What happens if you put the after inside the loop?  Does mem 
usage steadily increase, and continue if you increase range to 1000, 
1?  That would be a leak.


If there actually is a problem, try a later version of Python.

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


Re: Python 3.1 beta 1

2009-05-07 Thread Benjamin Peterson
  lycos.com> writes:
> 
> collections.Counter and collections.OrderedDict: very nice and useful.
> Is the order inside OrderedDict kept with a double linked list of the
> items?
 
There's a doubly-linked list containing the values. Another dictionary maps keys
to the list.



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


Re: Python 3.1 beta 1

2009-05-07 Thread Benjamin Peterson
  latinmail.com> writes:
> Congratulations!

Thanks!

> 
> Is it just me or was some nice summary output added to the make
> process? I get a nice list of modules that didn't compile and the ones
> where the library could not be found.

Are you compiling on a different platform? The nice output has been around for a
while, bu only on non-Windows platforms.




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


Re: Best practice for operations on streams of text

2009-05-07 Thread Terry Reedy

MRAB wrote:

James wrote:

Hello all,
I'm working on some NLP code - what I'm doing is passing a large
number of tokens through a number of filtering / processing steps.

The filters take a token as input, and may or may not yield a token as
a result. For example, I might have filters which lowercases the
input, filter out boring words and filter out duplicates chained
together.

I originally had code like this:
for t0 in token_stream:
  for t1 in lowercase_token(t0):
for t2 in remove_boring(t1):
  for t3 in remove_dupes(t2):
yield t3


For that to work at all, the three functions would have to turn each 
token into an iterable of 0 or 1 tokens.  Hence the inner 'loops' would 
execute 0 or 1 times.  Better to return a token or None, and replace the 
three inner 'loops' with three conditional statements (ugly too) or less 
efficiently (due to lack of short circuiting),


t = remove_dupes(remove_boring(lowercase_token(t0)))
if t is not None: yield t


Apart from being ugly as sin, I only get one token out as
StopIteration is raised before the whole token stream is consumed.


That puzzles me.  Your actual code must be slightly different from the 
above and what I imagine the functions to be.  But nevermind, because



Any suggestions on an elegant way to chain together a bunch of
generators, with processing steps in between?


MRAB's suggestion is the way to go.  Your automatically get 
short-circuiting because each generator only gets what is passed on. 
And resuming a generator is much faster that re-calling a function.



What you should be doing is letting the filters accept an iterator and
yield values on demand:

def lowercase_token(stream):
for t in stream:
yield t.lower()

def remove_boring(stream):
for t in stream:
if t not in boring:
yield t

def remove_dupes(stream):
seen = set()
for t in stream:
if t not in seen:
yield t
seen.add(t)

def compound_filter(token_stream):
stream = lowercase_token(token_stream)
stream = remove_boring(stream)
stream = remove_dupes(stream)
for t in stream(t):
yield t


I also recommend the Beazly reference Herron gave.

tjr

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


Re: Python 2.4.3 array memory leak

2009-05-07 Thread danmcle...@yahoo.com
On May 7, 3:58 pm, "danmcle...@yahoo.com" 
wrote:
> On May 7, 3:47 pm, "danmcle...@yahoo.com" 
> wrote:
>
>
>
> > On May 7, 3:31 pm, "danmcle...@yahoo.com" 
> > wrote:
>
> > > I am using the array module to instantiate many arrays in my
> > > application. It seems like there is a memory leak in there somewhere.
> > > Can anyone confim this and let me know what, if anything, I can do
> > > about it? I am using Fedora Core 5 Linux:
>
> > > import commands
> > > import array
> > > import itertools
> > > import sys
>
> > > from itertools import repeat
>
> > > print '*** before ***'
> > > print commands.getoutput('cat /proc/meminfo').split('\n')[1]
> > > for i in range(100):
> > > a = array.array('I', repeat(0, int(2E6)))
> > > del a
> > > print '*** after ***'
> > > print commands.getoutput('cat /proc/meminfo').split('\n')[1]
>
> > > Output:
> > > *** before ***
> > > MemFree:   1459772 kB
> > > *** after ***
> > > MemFree:   1457688 kB
>
> > I hate to reply to my own thread but I wanted to update it. I tried
> > the same code using ctypes arrays and see no memory leak:
>
> > import commands
> > import array
> > import itertools
> > import sys
> > import ctypes
>
> > from itertools import repeat
> > from ctypes import *
>
> > print '*** before ***'
> > print commands.getoutput('cat /proc/meminfo').split('\n')[1]
> > for i in range(100):
> > a = ARRAY(c_uint, int(2E6))
> > del a
> > print '*** after ***'
> > print commands.getoutput('cat /proc/meminfo').split('\n')[1]
>
> > *** before ***
> > MemFree:   1416364 kB
> > *** after ***
> > MemFree:   1416364 kB
>
> The above code was not correct. I actually do see a memory leak when
> using ctypes arrays also. What is going on?
>
> import commands
> import array
> import itertools
> import sys
> import ctypes
>
> from itertools import repeat
> from ctypes import *
>
> print '*** before ***'
> print commands.getoutput('cat /proc/meminfo').split('\n')[1]
> for i in range(100):
> a = ARRAY(c_uint, int(2E6))()
> del a
> print '*** after ***'
> print commands.getoutput('cat /proc/meminfo').split('\n')[1]
>
> Output
> *** before ***
> MemFree:   1564096 kB
> *** after ***
> MemFree:   1556884 kB


Maybe the problem is with the way I was looking at free memory. I
changed my code to look at virtual memory allocated to the process in
question and I do not see any appreciable before/after difference.

import commands
import array
import itertools
import sys
import os

from itertools import repeat

deltas = []
print '*** before ***'
s = commands.getoutput('cat /proc/%d/status' % os.getpid()).split('\n')
[12]
print s
for i in range(100):
a = array.array('I', repeat(0, int(2E6)))
del a

print '*** after ***'
s = commands.getoutput('cat /proc/%d/status' % os.getpid()).split('\n')
[12]
print s

Output:

*** before ***
VmSize: 5952 kB
*** after ***
VmSize: 5956 kB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.4.3 array memory leak

2009-05-07 Thread danmcle...@yahoo.com
On May 7, 3:47 pm, "danmcle...@yahoo.com" 
wrote:
> On May 7, 3:31 pm, "danmcle...@yahoo.com" 
> wrote:
>
>
>
> > I am using the array module to instantiate many arrays in my
> > application. It seems like there is a memory leak in there somewhere.
> > Can anyone confim this and let me know what, if anything, I can do
> > about it? I am using Fedora Core 5 Linux:
>
> > import commands
> > import array
> > import itertools
> > import sys
>
> > from itertools import repeat
>
> > print '*** before ***'
> > print commands.getoutput('cat /proc/meminfo').split('\n')[1]
> > for i in range(100):
> > a = array.array('I', repeat(0, int(2E6)))
> > del a
> > print '*** after ***'
> > print commands.getoutput('cat /proc/meminfo').split('\n')[1]
>
> > Output:
> > *** before ***
> > MemFree:   1459772 kB
> > *** after ***
> > MemFree:   1457688 kB
>
> I hate to reply to my own thread but I wanted to update it. I tried
> the same code using ctypes arrays and see no memory leak:
>
> import commands
> import array
> import itertools
> import sys
> import ctypes
>
> from itertools import repeat
> from ctypes import *
>
> print '*** before ***'
> print commands.getoutput('cat /proc/meminfo').split('\n')[1]
> for i in range(100):
> a = ARRAY(c_uint, int(2E6))
> del a
> print '*** after ***'
> print commands.getoutput('cat /proc/meminfo').split('\n')[1]
>
> *** before ***
> MemFree:   1416364 kB
> *** after ***
> MemFree:   1416364 kB


The above code was not correct. I actually do see a memory leak when
using ctypes arrays also. What is going on?


import commands
import array
import itertools
import sys
import ctypes

from itertools import repeat
from ctypes import *

print '*** before ***'
print commands.getoutput('cat /proc/meminfo').split('\n')[1]
for i in range(100):
a = ARRAY(c_uint, int(2E6))()
del a
print '*** after ***'
print commands.getoutput('cat /proc/meminfo').split('\n')[1]

Output
*** before ***
MemFree:   1564096 kB
*** after ***
MemFree:   1556884 kB
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess.Popen howto?

2009-05-07 Thread norseman

Øystein Johansen (OJOHANS) wrote:

Hi,
 
I have problems understanding the subprocess.Popen object. I have a 
iterative calculation in a process running and I want to pipe the output 
(stdout) from this calculation to a Python script.
 
Let me include a simple code that simulates the calculating process:

/* This code simulates a big iterative calculation */
#include 
#include 
 
int main()

{
 float val[2] = { M_PI, M_E };
 int i;
 
 for ( i = 0; i < 2 i++) {

  sleep( 15 );   /* It's a hard calculation. It take 15 seconds */
  printf("Value: %5.6f\n", val[i] );
  fflush( stdout );
 }
 return 0;
}
 
let's compile this to mycalc: gcc -o mycalc calc.c ... (untested code)
 
In C I have this code which starts the mycalc process and handles the 
output from it:
 
#include 

#include 
#define BUF_SIZE 256
 
int main()

{
 FILE *pip;
 char line[BUF_SIZE];
 
 pip = popen("mycalc", "r");

 assert( pip != NULL );
 
 while ( fgets( line, BUF_SIZE, pip )) {

  printf( "Hello; I got: %s \n", line );
  fflush( stdout );
 }
 pclose( pip );
 return 0;
}
How can I make such while-loop in Python? I assume I should use 
subprocess.Popen(), but I can't figure out how?
 
-Øystein
 
 


---
The information contained in this message may be CONFIDENTIAL and is
intended for the addressee only. Any unauthorised use, dissemination of the
information or copying of this message is prohibited. If you are not the
addressee, please notify the sender immediately by return e-mail and delete
this message.
Thank you.




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



If you don't like a lot of typing that obscures the process,
take a look at os.Popen2  Pg.39 or so in Lib.pdf for 2.5.2
In this case - the popen3 is probably your best bet.

I took a test run on "subprocess" a few months ago. My review:
excessive typing to accomplish the simple.  BlackBox stuff is supposed 
to be short and sweet.


BlackBox was the term applied to drivers and couplers back when.
Back when: one started by writing a subroutine that got used.
   next one got to write a program
   next one got to write an application
   then a BlackBox
   from there one could graduate to OS
That was back when!


to repeat from another of my postings:
---
processPython 2.5.2 (r252:60911, Mar  4 2008, 10:40:55)
[GCC 3.3.6] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> import os
>>> AbWd = os.spawnlp( os.P_WAIT,"abiword","abiword","")

The P_WAIT stops python until the program (abiword in this case) 
completes.  The "" at the end are for tokens to be given to the program 
and yes - contrary to manual, the program MUST be there TWICE (complete 
with any path needed).


for windows this works:
(for cut and paste from cmd.exe, see:
  Re: Copy & Paste in a Dos box  from norseman  05/06/2009 4:28PM
)

Python 2.5.1 ... on win32
>>> import os
>>> result = os.spawnl( os.P_WAIT, "d:\\winmcad\\mcad","")

Runs the program mcad. Returns to python when mcad exits.
---


In your case:  substitute ..."your_compiled_c_program", " >yourPy.py")
at the obvious places.

In case this isn't clear;
  method 1:  py1.py starts compiled.c which redirects to yourPy.py
  method 2:  py1.py uses os.popen3(compiled.c...) & the two work it out.
In either case the receiver at the end stays open until completion so 
sleep() things are not needed.  (may need to test for EOL and EOT)


HTH

Steve
norse...@hughes.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.4.3 array memory leak

2009-05-07 Thread danmcle...@yahoo.com
On May 7, 3:31 pm, "danmcle...@yahoo.com" 
wrote:
> I am using the array module to instantiate many arrays in my
> application. It seems like there is a memory leak in there somewhere.
> Can anyone confim this and let me know what, if anything, I can do
> about it? I am using Fedora Core 5 Linux:
>
> import commands
> import array
> import itertools
> import sys
>
> from itertools import repeat
>
> print '*** before ***'
> print commands.getoutput('cat /proc/meminfo').split('\n')[1]
> for i in range(100):
> a = array.array('I', repeat(0, int(2E6)))
> del a
> print '*** after ***'
> print commands.getoutput('cat /proc/meminfo').split('\n')[1]
>
> Output:
> *** before ***
> MemFree:   1459772 kB
> *** after ***
> MemFree:   1457688 kB

I hate to reply to my own thread but I wanted to update it. I tried
the same code using ctypes arrays and see no memory leak:

import commands
import array
import itertools
import sys
import ctypes

from itertools import repeat
from ctypes import *

print '*** before ***'
print commands.getoutput('cat /proc/meminfo').split('\n')[1]
for i in range(100):
a = ARRAY(c_uint, int(2E6))
del a
print '*** after ***'
print commands.getoutput('cat /proc/meminfo').split('\n')[1]

*** before ***
MemFree:   1416364 kB
*** after ***
MemFree:   1416364 kB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newcomer to Python tutorial question

2009-05-07 Thread Terry Reedy

Alan Cameron wrote:



why is the printed result of


basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)

{'orange', 'banana', 'pear', 'apple'}

in the sequence given?



It appears that I used a reserved term when I used 'sequence'.


No and Sort-of.

No: We often use it in the normal English sense of ordered items, as I 
and I think others assume you did.  Your question is quite legitimate, 
and the answer, as indicated, is how an implementation interacts with 
the sequence of additions.


Sort-of: The library manual section of Sequence Types lists the sequence 
operations common to all or most built-in Python sequence classes.  But 
it does not explicitly define sequence.  Ranges, which are iterables 
that directly support only indexing and len(), are called sequences. 
Dicts, which are iterables that support len() but are usually not 
indexed by integers, are not.  So that suggests a minimal definition of 
sequence, but all the other sequence classes support much more that is 
typically assumed.


Keywords are reserved terms in the language such as 'if' and 'None' that 
are specially recognized by the parser and which affect compilation. 
Identifiers of the form '__x...y__' are reserved names.  Non-terminal 
terms in the grammar are reserved terms, in a sense, within the 
reference manual, but 'expression_list', not 'sequence', is used for 
comma-separated sequences of expressions in code.  The comma-separated 
sequence of items in a function call is separately defined as an 
'argument_list' because 'keyword_item's like 'a=b' and '*' and '**' are 
not expressions and because there are some order restrictions on 
argument items.


Terry Jan Reedy

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


Re: Python 3.1 beta 1

2009-05-07 Thread bearophileHUGS
Terry Reedy:
bearophile:
> > Well, I'd like function call semantics pass-in keyword arguments to
> > use OrderedDicts then... :-)

[...]
> It would require a sufficiently fast C implementation.

Right.
Such dict is usually small, so if people want it ordered, it may be
better to just use an array of name-value structs instead of a dict or
ordered dict. Iterating on a 10-pair array is fast on modern CPUs.

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


Python 2.4.3 array memory leak

2009-05-07 Thread danmcle...@yahoo.com
I am using the array module to instantiate many arrays in my
application. It seems like there is a memory leak in there somewhere.
Can anyone confim this and let me know what, if anything, I can do
about it? I am using Fedora Core 5 Linux:

import commands
import array
import itertools
import sys

from itertools import repeat

print '*** before ***'
print commands.getoutput('cat /proc/meminfo').split('\n')[1]
for i in range(100):
a = array.array('I', repeat(0, int(2E6)))
del a
print '*** after ***'
print commands.getoutput('cat /proc/meminfo').split('\n')[1]

Output:
*** before ***
MemFree:   1459772 kB
*** after ***
MemFree:   1457688 kB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best practice for operations on streams of text

2009-05-07 Thread MRAB

James wrote:

Hello all,
I'm working on some NLP code - what I'm doing is passing a large
number of tokens through a number of filtering / processing steps.

The filters take a token as input, and may or may not yield a token as
a result. For example, I might have filters which lowercases the
input, filter out boring words and filter out duplicates chained
together.

I originally had code like this:
for t0 in token_stream:
  for t1 in lowercase_token(t0):
for t2 in remove_boring(t1):
  for t3 in remove_dupes(t2):
yield t3

Apart from being ugly as sin, I only get one token out as
StopIteration is raised before the whole token stream is consumed.

Any suggestions on an elegant way to chain together a bunch of
generators, with processing steps in between?


What you should be doing is letting the filters accept an iterator and
yield values on demand:

def lowercase_token(stream):
for t in stream:
yield t.lower()

def remove_boring(stream):
for t in stream:
if t not in boring:
yield t

def remove_dupes(stream):
seen = set()
for t in stream:
if t not in seen:
yield t
seen.add(t)

def compound_filter(token_stream):
stream = lowercase_token(token_stream)
stream = remove_boring(stream)
stream = remove_dupes(stream)
for t in stream(t):
yield t
--
http://mail.python.org/mailman/listinfo/python-list


Re: SimpleXMLRPCServer and creating a new object on for each new client request.

2009-05-07 Thread Piet van Oostrum
> Jelle Smet  (JS) wrote:

>JS> Hi list,
>JS> My goals is to have concurrent and separated client sessions using xmlrpc.
>JS> Initially my though was that SimpleXMLRPCServer was able to create a new
>JS> object instance for each incoming request.

>JS> But this doesn't appear to be the case, unless I'm overlooking something,
>JS> if so please point me out.

You create a single instance of your class and then register that. There
is nothing in your code that makes the server believe it should create a
new instance for each request. 

And then of course this instance always returns the same random number.
It could generate a new random number for each call as follows:
   def show_random(self):
return random.randrange(0,10)
but I guess this is not what you want.

Otherwise you would have to register a function that creates a new
instance on every call.
But as Martin P. Hellwig has noted, it wouldn't give you sessions anyway.

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Downloading most recently modified files

2009-05-07 Thread Shawn Milochik
On Thu, May 7, 2009 at 2:19 PM, AllenLars  wrote:
>
> I am trying to code a script that will allow me to go to ftp site and
> download files based on most recently modified file (date, time).  I am
> brand new to programming.  Any and all help is appreciated.
> --


I've actually written code to do this, and it's fairly easy. Just use
the FTP module to run the "ls" (directory listing) command and parse
the results to get the filenames and timestamps. Then you will be able
to easily do download requests for the file(s) you want.

Perhaps someone else on the list can chime in with a more elegant solution.

Here's enough to get you started:

from ftplib import FTP   #(http://docs.python.org/library/ftplib.html)

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


Re: Which python version do I use with "virtualenv"?

2009-05-07 Thread Duncan Booth
OldGrantonian  wrote:

> Where do I find the win32 extensions?

http://www.google.com/search?q=python+win32

Any of the first 4 hits should help.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best practice for operations on streams of text

2009-05-07 Thread Gary Herron

James wrote:

Hello all,
I'm working on some NLP code - what I'm doing is passing a large
number of tokens through a number of filtering / processing steps.

The filters take a token as input, and may or may not yield a token as
a result. For example, I might have filters which lowercases the
input, filter out boring words and filter out duplicates chained
together.

I originally had code like this:
for t0 in token_stream:
  for t1 in lowercase_token(t0):
for t2 in remove_boring(t1):
  for t3 in remove_dupes(t2):
yield t3

Apart from being ugly as sin, I only get one token out as
StopIteration is raised before the whole token stream is consumed.

Any suggestions on an elegant way to chain together a bunch of
generators, with processing steps in between?

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


David Beazly has a very interesting talk on using generators for 
building and linking together individual stream filters.  Its very cool 
and surprisingly eye-opening.


See "Generator Tricks for Systems Programmers" at  
http://www.dabeaz.com/generators/


Gary Herron


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


Re: Python 3.1 beta 1

2009-05-07 Thread Terry Reedy

bearophileh...@lycos.com wrote:


Is the order inside OrderedDict kept with a double linked list of the
items?


That is one of the things Raymond tried.  Check the code for what he 
settled on for the Python version.  I believe he thinks the best C 
implementation might be different from the best Python version.



The OrderedDict constructor and update() method both accept

>> keyword arguments, but their order is lost because Python's
>> function call semantics pass-in keyword arguments using a regular
>> unordered dictionary.


This is unfortunate :-(
Well, I'd like function call semantics pass-in keyword arguments to
use OrderedDicts then... :-)


This possibility has been discussed on pydev.
It would require a sufficiently fast C implementation.

tjr

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


Re: Which python version do I use with "virtualenv"?

2009-05-07 Thread OldGrantonian
On May 7, 9:03 pm, Emile van Sebille  wrote:
> On 5/7/2009 12:53 PM OldGrantonian said...
>
>
>
> > On May 7, 12:34 pm, Duncan Booth  wrote:
> >> OldGrantonian  wrote:
> >>> Thanks to both Steven D'Aprano and Ant :)
> >  Sounds like you've downloaded the Python 2.5 version of Easy Install.
> >>> There's no Python 2.6 version of EasyInstall :(
> >> I wonder what I've been running then?
>
> >>> For 2.5, there is:
> >>> setuptools-0.6c9.win32-py2.5.exe
> >>> But for 2.6, it's:
> >>> setuptools-0.6c9-py2.6.egg
> >>> For any other egg file, I would use EasyInstall, but I don't think I
> >>> can use EasyInstall to install EasyInstall :)
> >> No, but you can use ez_setup.
>
> >> Go tohttp://peak.telecommunity.com/dist/ez_setup.pyandsave the content
> >> of that file as ez_setup.py (cut and paste into your favourite editor may
> >> be the simplest way) then run it with your chosen Python. It will find and
> >> install the appropriate version of easy install.
>
> >> --
> >> Duncan Boothhttp://kupuguy.blogspot.com
>
> > ez_setup worked fine. Thanks for that :)
>
> > According to the web site:
>
> >http://pypi.python.org/pypi/virtualenv
>
> > the next step is to do:
>
> > virtualenv ENV
>
> > If I do that, I get the following message:
>
> > 
>
> > C:\Python26\Scripts>virtualenv ENV
> > Traceback (most recent call last):
> >   File "C:\Python26\Scripts\virtualenv-script.py", line 8, in 
> >     load_entry_point('virtualenv==1.3.3', 'console_scripts',
> > 'virtualenv')()
> >   File "C:\Python26\lib\site-packages\virtualenv-1.3.3-py2.6.egg
> > \virtualenv.py", line 420
> >     unzip_setuptools=options.unzip_setuptools)
> >   File "C:\Python26\lib\site-packages\virtualenv-1.3.3-py2.6.egg
> > \virtualenv.py", line 499
> >     home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir)
> >   File "C:\Python26\lib\site-packages\virtualenv-1.3.3-py2.6.egg
> > \virtualenv.py", line 521
> >     import win32api
> > ImportError: No module named win32api
>
> > C:\Python26\Scripts>
>
> > 
>
> > Any advice?
>
> Install the win32 extensions or install the 2.6 Activestate release.
>
> Emile


Thanks for the response :)

Where do I find the win32 extensions?

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


Re: Which one is best Python or Java for developing GUI applications?

2009-05-07 Thread norseman

Tim Rowe wrote:

2009/5/6 Dennis Lee Bieber :


(the "near" is because I feel Ada is
stricter than any other language)


Try SPARK -- it's Ada based, but /much/ stricter. It's just right for
some really critical stuff, but is no sort of an answer to "Which one
is best Python or Java for developing GUI"!


==

"...really critical stuff..."Then the only real choice is assembly!

And correct - that's nothing to do with Python vs Java.

Back to the question:
Python has one advantage that has not been mentioned.  It allows the 
programmer to start with prior coding practices and 'ease' into OOP 
because Python happily allows a mix of traditional and OOP coding.


Beyond that - "There is no accounting for taste."  You are on your own.
You see - with daughter #1 I need pencil and paper to explain things.
  with daughter #2 I sit on my hands and narrate correctly the
first time.
Many things have no "one is better" option beyond individual quirks. Or 
shall we say preferences?  The old - "This works for me" is right one.


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


Re: list comprehension question

2009-05-07 Thread Terry Reedy

J Kenneth King wrote:


Keep in mind that nested comprehensions are still available because
they do have a use case that justifies their existence.


Nested comprehensions are available because because the syntax makes 
them available by default and making a fiddly exception would be 
contrary to Python's style.  A list comp creates an iterable. A list 
comp requires use of an iterable.  Therefore, a list comp may use a list 
comp.



However, I
think the Python documentation warns against their use because people
might rely on them for problems where they aren't necessary and since
they are difficult to read... it can lead to difficult to read code.


Whenever the expression that results in the iterable used by a list comp 
is sufficiently complex, readability is improved by pulling it out as a 
separate statement. Nested list comps are often examplex of such 
sufficiently complex expressions, but not the only possible one.


tjr

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


Re: Best practice for operations on streams of text

2009-05-07 Thread J Kenneth King
James  writes:

> Hello all,
> I'm working on some NLP code - what I'm doing is passing a large
> number of tokens through a number of filtering / processing steps.
>
> The filters take a token as input, and may or may not yield a token as
> a result. For example, I might have filters which lowercases the
> input, filter out boring words and filter out duplicates chained
> together.
>
> I originally had code like this:
> for t0 in token_stream:
>   for t1 in lowercase_token(t0):
> for t2 in remove_boring(t1):
>   for t3 in remove_dupes(t2):
> yield t3
>
> Apart from being ugly as sin, I only get one token out as
> StopIteration is raised before the whole token stream is consumed.
>
> Any suggestions on an elegant way to chain together a bunch of
> generators, with processing steps in between?
>
> Thanks,
> James

Co-routines my friends. Google will help you greatly in discovering
this processing wonder.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Which python version do I use with "virtualenv"?

2009-05-07 Thread Emile van Sebille

On 5/7/2009 12:53 PM OldGrantonian said...

On May 7, 12:34 pm, Duncan Booth  wrote:

OldGrantonian  wrote:

Thanks to both Steven D'Aprano and Ant :)

 Sounds like you've downloaded the Python 2.5 version of Easy Install.

There's no Python 2.6 version of EasyInstall :(

I wonder what I've been running then?




For 2.5, there is:
setuptools-0.6c9.win32-py2.5.exe
But for 2.6, it's:
setuptools-0.6c9-py2.6.egg
For any other egg file, I would use EasyInstall, but I don't think I
can use EasyInstall to install EasyInstall :)

No, but you can use ez_setup.

Go tohttp://peak.telecommunity.com/dist/ez_setup.pyand save the content
of that file as ez_setup.py (cut and paste into your favourite editor may
be the simplest way) then run it with your chosen Python. It will find and
install the appropriate version of easy install.

--
Duncan Boothhttp://kupuguy.blogspot.com



ez_setup worked fine. Thanks for that :)

According to the web site:

http://pypi.python.org/pypi/virtualenv

the next step is to do:

virtualenv ENV

If I do that, I get the following message:



C:\Python26\Scripts>virtualenv ENV
Traceback (most recent call last):
  File "C:\Python26\Scripts\virtualenv-script.py", line 8, in 
load_entry_point('virtualenv==1.3.3', 'console_scripts',
'virtualenv')()
  File "C:\Python26\lib\site-packages\virtualenv-1.3.3-py2.6.egg
\virtualenv.py", line 420
unzip_setuptools=options.unzip_setuptools)
  File "C:\Python26\lib\site-packages\virtualenv-1.3.3-py2.6.egg
\virtualenv.py", line 499
home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir)
  File "C:\Python26\lib\site-packages\virtualenv-1.3.3-py2.6.egg
\virtualenv.py", line 521
import win32api
ImportError: No module named win32api

C:\Python26\Scripts>



Any advice?



Install the win32 extensions or install the 2.6 Activestate release.

Emile

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


Best practice for operations on streams of text

2009-05-07 Thread James
Hello all,
I'm working on some NLP code - what I'm doing is passing a large
number of tokens through a number of filtering / processing steps.

The filters take a token as input, and may or may not yield a token as
a result. For example, I might have filters which lowercases the
input, filter out boring words and filter out duplicates chained
together.

I originally had code like this:
for t0 in token_stream:
  for t1 in lowercase_token(t0):
for t2 in remove_boring(t1):
  for t3 in remove_dupes(t2):
yield t3

Apart from being ugly as sin, I only get one token out as
StopIteration is raised before the whole token stream is consumed.

Any suggestions on an elegant way to chain together a bunch of
generators, with processing steps in between?

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


Re: Unable to build libpython2.5.so on OS X 10.4

2009-05-07 Thread Piet van Oostrum
> elwinter  (e) wrote:

>e> Hi Ned. The Python module I am building is actually the Python module
>e> for ROOT, a large package from CERN. However, the problem arises
>e> before that code enters the picture, when I am building Python itself.
>e> All I want to do is create "libpython2.5.dylib", or its equivalent,
>e> and I can't seem to make that happen on Tiger.

The standard installer for Python 2.5.4 when installed on Tiger, will
contain a file libpython2.5.a which is a symbolic link to
/Library/Frameworks/Python.framework/Versions/2.5/Python, which
according to the file command, is a shared library. So it is not a
static library, despite of its name!
>e> Thanks,
>e> Eric

>e> On May 7, 12:41 pm, Ned Deily  wrote:
>>> In article
>>> ,
>>>  Eric Winter  wrote:
>>> 
>>> > Hi all. I'm trying to build some internal code that needs to link
>>> > against libpython2.5.so on a OS X 10.4 (Tiger) machine. It seems that
>>> > no matter what combination of options and environment variables I give
>>> > to the configure script from python 2.5.1, all I get is the
>>> > libpython2.5.a (the static library). I've googled the problem and
>>> > searched the comp.lang.python archives, but I have been unable to find
>>> > anything that works.
>>> 
>>> Perhaps I misunderstand, but if you are trying to build a C extension
>>> for an existing Python 2.5 installation, using Distutils from that
>>> installation should take care of everything for you.  Is there a
>>> setup.py file by any chance?  Are you using a standard python
>>> installation (i.e. python.org installer for instance)?  More details
>>> might help.
>>> 
>>> --
>>>  Ned Deily,
>>>  n...@acm.org


-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: P2P text chat engine

2009-05-07 Thread Emile van Sebille

On 5/7/2009 11:23 AM Diez B. Roggisch said...

Navanjo schrieb:

If you have the source code of a p2p text chat engine please send to me


I found that & a pot of gold under my bed. Care to give me your address 
so that I can send it to you?




Yeah -- this is how it starts.  Before too long you'll need my bank 
account info to facilitate the transfer...


:)

Emile

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


Re: Which python version do I use with "virtualenv"?

2009-05-07 Thread OldGrantonian
On May 7, 12:34 pm, Duncan Booth  wrote:
> OldGrantonian  wrote:
> > Thanks to both Steven D'Aprano and Ant :)
>
> >>>  Sounds like you've downloaded the Python 2.5 version of Easy Install.
>
> > There's no Python 2.6 version of EasyInstall :(
>
> I wonder what I've been running then?
>
>
>
> > For 2.5, there is:
>
> > setuptools-0.6c9.win32-py2.5.exe
>
> > But for 2.6, it's:
>
> > setuptools-0.6c9-py2.6.egg
>
> > For any other egg file, I would use EasyInstall, but I don't think I
> > can use EasyInstall to install EasyInstall :)
>
> No, but you can use ez_setup.
>
> Go tohttp://peak.telecommunity.com/dist/ez_setup.pyand save the content
> of that file as ez_setup.py (cut and paste into your favourite editor may
> be the simplest way) then run it with your chosen Python. It will find and
> install the appropriate version of easy install.
>
> --
> Duncan Boothhttp://kupuguy.blogspot.com


ez_setup worked fine. Thanks for that :)

According to the web site:

http://pypi.python.org/pypi/virtualenv

the next step is to do:

virtualenv ENV

If I do that, I get the following message:



C:\Python26\Scripts>virtualenv ENV
Traceback (most recent call last):
  File "C:\Python26\Scripts\virtualenv-script.py", line 8, in 
load_entry_point('virtualenv==1.3.3', 'console_scripts',
'virtualenv')()
  File "C:\Python26\lib\site-packages\virtualenv-1.3.3-py2.6.egg
\virtualenv.py", line 420
unzip_setuptools=options.unzip_setuptools)
  File "C:\Python26\lib\site-packages\virtualenv-1.3.3-py2.6.egg
\virtualenv.py", line 499
home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir)
  File "C:\Python26\lib\site-packages\virtualenv-1.3.3-py2.6.egg
\virtualenv.py", line 521
import win32api
ImportError: No module named win32api

C:\Python26\Scripts>



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


Re: Python 3.1 beta 1

2009-05-07 Thread pruebauno
On May 6, 9:32 pm, Benjamin Peterson  wrote:
> On behalf of the Python development team, I'm thrilled to announce the first 
> and
> only beta release of Python 3.1.
>
> Python 3.1 focuses on the stabilization and optimization of features and 
> changes
> Python 3.0 introduced.  For example, the new I/O system has been rewritten in 
> C
> for speed.  File system APIs that use unicode strings now handle paths with
> undecodable bytes in them. [1] Other features include an ordered dictionary
> implementation and support for ttk Tile in Tkinter.  For a more extensive list
> of changes in 3.1, seehttp://doc.python.org/dev/py3k/whatsnew/3.1.htmlor
> Misc/NEWS in the Python distribution.
>
> Please note that this is a beta release, and as such is not suitable for
> production environments.  We continue to strive for a high degree of quality,
> but there are still some known problems and the feature sets have not been
> finalized.  This beta is being released to solicit feedback and hopefully
> discover bugs, as well as allowing you to determine how changes in 3.1 might
> impact you.  If you find things broken or incorrect, please submit a bug 
> report
> at
>
>    http://bugs.python.org
>
> For more information and downloadable distributions, see the Python 3.1 
> website:
>
>    http://www.python.org/download/releases/3.1/
>
> See PEP 375 for release schedule details:
>
>    http://www.python.org/dev/peps/pep-0375/
>
> Enjoy,
> -- Benjamin
>
> Benjamin Peterson
> benjamin at python.org
> Release Manager
> (on behalf of the entire python-dev team and 3.1's contributors)


Congratulations!

Is it just me or was some nice summary output added to the make
process? I get a nice list of modules that didn't compile and the ones
where the library could not be found.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Threading and GIL

2009-05-07 Thread googler . 1 . webmaster
hey, thanks, that works fine. I wrapped it around, done a lot of tests
and it works fine.
Just had done a few other things to make it stable.

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


Re: Newcomer to Python tutorial question

2009-05-07 Thread Peter Otten
Alan Cameron wrote:

> "Alan Cameron"  wrote in message
> news:hrfml.50224$tb.4...@newsfe07.ams2...
>>I am not sure of this is the right place to ask a question about the
>>tutorial
>>
>> http://docs.python.org/3.0/tutorial/datastructures.html#sets
>>
>> why is the printed result of
>>
> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
> print(basket)
>> {'orange', 'banana', 'pear', 'apple'}
>>
>> in the sequence given?
>>
>>
> 
> Thanks to all who replied.
> I assume therefore that the order in which the items of the set are
> printed could vary each time it is printed?

If you don't add or remove items the printed order will not change in the 
current implementation. But as shown in my other post it is possible to 
create sets with equal contents that are printed differently. The actual 
order depends on the set's history of insertions/deletions, so it is not 
truly random. 

But these are implementation details that may change across versions of 
python and your code should never rely on them. If you want a defined order 
convert the set to a sorted list before printing:

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> sorted(basket)
['apple', 'banana', 'orange', 'pear']

Peter

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


Re: Newcomer to Python tutorial question

2009-05-07 Thread Alan Cameron
"Chris Rebert"  wrote in message 
news:mailman.5238.1241723354.11746.python-l...@python.org...
> On Thu, May 7, 2009 at 11:58 AM, Alan Cameron  
> wrote:
>> "Alan Cameron"  wrote in message
>> news:hrfml.50224$tb.4...@newsfe07.ams2...
>>>I am not sure of this is the right place to ask a question about the
>>>tutorial
>>>
>>> http://docs.python.org/3.0/tutorial/datastructures.html#sets
>>>
>>> why is the printed result of
>>>
>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>> print(basket)
>>> {'orange', 'banana', 'pear', 'apple'}
>>>
>>> in the sequence given?
>>>
>>>
>>
>> Thanks to all who replied.
>> I assume therefore that the order in which the items of the set are 
>> printed
>> could vary each time it is printed?
>
> Due to the underlying dict-based implementation, the order will stay
> the same until you modify the set (i.e. add or remove an element), at
> which point it may change; it's basically the same behavior as with
> printing a dict.
>
> So this will always print the same thing twice:
> print basket
> print basket
>
> Whereas this might not:
> print basket
> #modify the set
> basket.discard("banana")
> basket.add("banana")
> print basket
>
> Cheers,
> Chris

Thanks Chris,

It appears that I used a reserved term when I used 'sequence'. I just had 
not reached that far in the tutorial.
I have many years of programming (roughly 50) and want to learn new 
languages.
I find tutorials always fraught with problems due to the knowledge of the 
writer exceeding the knowledge of the reader and using terms and examples 
not yet covered in the tutorial thus far.
I am persevering with my initial foray into Python.

-- 
Alan Cameron 


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


RE: Wing vs Netbeans IDE?

2009-05-07 Thread J. Clifford Dyer
On Thu, 2009-05-07 at 10:49 -0700, Benjamin J. Racine wrote:
> I'd love to see an updated shootout between these three, as I cannot for the 
> life of me seem to be able to settle down with one of them.
> 
> Things I don't like: 
> Wing's lack of integrated mercurial/svn support.

Wing *does* have integrated SVN support already, but nothing for the
distributed systems yet.  I just purchased a Wing license this past
week.  So far I'm very happy with it, though I can't speak to a
comparison with other IDEs. 




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


Re: What would YOU like to see in a txt to html converter?

2009-05-07 Thread Stefan Behnel
Florian Wollenschein wrote:
> Will Wang wrote:
>> *emphasis*
>> **strong emphasis**
>> ***very strong emphasis***
>> _underlined_
>> =verbatim and monospace=
>>
>> emacs-muse : http://mwolson.org/projects/EmacsMuse.html
> 
> Thank you for this information. I already thought of using dots or
> asterisks or whatever to let the user format the text instead of using
> html tags (this would be quite paradox ;-)

First thing I'd look at is actually docutils' RestructuredText (ReST).

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


Re: Newcomer to Python tutorial question

2009-05-07 Thread Chris Rebert
On Thu, May 7, 2009 at 11:58 AM, Alan Cameron  wrote:
> "Alan Cameron"  wrote in message
> news:hrfml.50224$tb.4...@newsfe07.ams2...
>>I am not sure of this is the right place to ask a question about the
>>tutorial
>>
>> http://docs.python.org/3.0/tutorial/datastructures.html#sets
>>
>> why is the printed result of
>>
> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
> print(basket)
>> {'orange', 'banana', 'pear', 'apple'}
>>
>> in the sequence given?
>>
>>
>
> Thanks to all who replied.
> I assume therefore that the order in which the items of the set are printed
> could vary each time it is printed?

Due to the underlying dict-based implementation, the order will stay
the same until you modify the set (i.e. add or remove an element), at
which point it may change; it's basically the same behavior as with
printing a dict.

So this will always print the same thing twice:
print basket
print basket

Whereas this might not:
print basket
#modify the set
basket.discard("banana")
basket.add("banana")
print basket

Cheers,
Chris
-- 
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-07 Thread bearophileHUGS
Francis Carr:

I don't know who are you talking to, but I can give you few answers
anyway.

>collections of multiply-recursive functions (which get used very frequently -- 
>by no means is it an uncommon situation, as you suggest in your initial post),<

They may be frequent in Scheme (because it's often used as an almost
pure language), but in Python code they are quite rare. I have used
two mutual recursive functions only once in non-toy Python code in two
or more years.



>Yet -- scheme does not provide out-of-the-box support for your proposed 
>"let-a-function-implicitly- refer-to-itself" idea.  This suggests that the 
>idea itself runs counter to more important aspects of a programming language.<

I see. It's not a very implicit thing, because you have to call a
function anyway, it's just it has a fixed name, like __func__.
I think it doesn't runs counter to Python & D languages (I have asked
for a similar feature in D2 too, and the designers seem to have
accepted the idea, already suggested there by another person in the
past).

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


Re: P2P text chat engine

2009-05-07 Thread Diez B. Roggisch

Navanjo schrieb:

If you have the source code of a p2p text chat engine please send to me


I found that & a pot of gold under my bed. Care to give me your address 
so that I can send it to you?


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


Re: hex(dummy)[2:] - issue...

2009-05-07 Thread Florian Wollenschein

Tim Chase wrote:

I need some advice :-)
I'm using hex(dummy)[2:] to represent a color in hexadecimal format 
for the bgcolor in an html file. dummy is the color value in RGB of 
course...


Now, if there's an R, G or B value of zero, this command only prints 
one single 0 instead of two. What's wrong with the code?


You can try

 PLACES = 2 # 6?
 hex(dummy)[2:].zfill(PLACES)

Alternatively, you can output decimal numbers in HTML/CSS with

  rgb(r, g, b)

such as

  style="rgb(255,0,0)"

However, I recommend doing this via CSS unless you have a strong reason 
to sully your HTML with style information.


-tkc









hey tkc,

I used your first alternative. This did it! Thanks a lot.
I think I will write the style stuff into a .css file in the next few 
days but until then I'm just working on get my program to work...


Listick
http://www.listick.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple way of handling errors

2009-05-07 Thread Matt Nordhoff
Steven D'Aprano wrote:
> On Wed, 06 May 2009 20:21:38 -0700, TomF wrote:
> 
>>> The only reason you would bother going to the time and effort of
>>> catching the error, printing your own error message, and then exiting,
>>> is if you explicitly want to hide the traceback from the user.
>> Well, to me, exposing the user to such raw backtraces is unprofessional,
>> which is why I try to catch user-caused errors.  But I suppose I have an
>> answer to my question.
> 
> That depends on your audience. Not every program is written to be used 
> for a technical incompetent audience. Some users actually *want* to see 
> the errors.
> 
> But certainly there are large classes of applications where you do want 
> to suppress the traceback. That's why I said "if you explicitly want to 
> hide the traceback from the user" rather than "don't do this".
> 
> The idiom I use is to wrap the *entire* application in a single 
> try...except block, and then put all your user-friendly error handling in 
> one place, instead of scattered over the entire application:
> 
> 
> try:
> main(sys.argv[1:])
> except KeyboardInterrupt, SystemExit:

That should be:

except (KeyboardInterrupt, SystemExit):

;-D

> raise
> except Exception, e:
> log(e)
> print >>sys.stderr, str(e)
> sys.exit(1)
> 
> 
> 
> Hope this helps.
-- 
--
http://mail.python.org/mailman/listinfo/python-list


[RELEASED] Python 3.1 beta 1

2009-05-07 Thread Benjamin Peterson
On behalf of the Python development team, I'm thrilled to announce the first and
only beta release of Python 3.1.

Python 3.1 focuses on the stabilization and optimization of features and changes
Python 3.0 introduced.  For example, the new I/O system has been rewritten in C
for speed.  File system APIs that use unicode strings now handle paths with
undecodable bytes in them. [1] Other features include an ordered dictionary
implementation and support for ttk Tile in Tkinter.  For a more extensive list
of changes in 3.1, see http://doc.python.org/dev/py3k/whatsnew/3.1.html or
Misc/NEWS in the Python distribution.

Please note that this is a beta release, and as such is not suitable for
production environments.  We continue to strive for a high degree of quality,
but there are still some known problems and the feature sets have not been
finalized.  This beta is being released to solicit feedback and hopefully
discover bugs, as well as allowing you to determine how changes in 3.1 might
impact you.  If you find things broken or incorrect, please submit a bug report
at

 http://bugs.python.org

For more information and downloadable distributions, see the Python 3.1 website:

 http://www.python.org/download/releases/3.1/

See PEP 375 for release schedule details:

 http://www.python.org/dev/peps/pep-0375/



Enjoy,
-- Benjamin

Benjamin Peterson
benjamin at python.org
Release Manager
(on behalf of the entire python-dev team and 3.1's contributors)
--
http://mail.python.org/mailman/listinfo/python-list


subprocess.Popen howto?

2009-05-07 Thread OJOHANS
Hi,
 
I have problems understanding the subprocess.Popen object. I have a iterative 
calculation in a process running and I want to pipe the output (stdout) from 
this calculation to a Python script.
 
Let me include a simple code that simulates the calculating process:
/* This code simulates a big iterative calculation */
#include 
#include 
 
int main()
{
 float val[2] = { M_PI, M_E };
 int i;
 
 for ( i = 0; i < 2 i++) {
  sleep( 15 );   /* It's a hard calculation. It take 15 seconds */
  printf("Value: %5.6f\n", val[i] );
  fflush( stdout );
 }
 return 0;
}
 
let's compile this to mycalc: gcc -o mycalc calc.c ... (untested code)
 
In C I have this code which starts the mycalc process and handles the output 
from it:
 
#include 
#include 
#define BUF_SIZE 256
 
int main()
{
 FILE *pip;
 char line[BUF_SIZE];
 
 pip = popen("mycalc", "r");
 assert( pip != NULL );
 
 while ( fgets( line, BUF_SIZE, pip )) {
  printf( "Hello; I got: %s \n", line );
  fflush( stdout );
 }
 pclose( pip );
 return 0;
}

How can I make such while-loop in Python? I assume I should use 
subprocess.Popen(), but I can't figure out how?
 
-Øystein
 
 


---
The information contained in this message may be CONFIDENTIAL and is
intended for the addressee only. Any unauthorised use, dissemination of the
information or copying of this message is prohibited. If you are not the
addressee, please notify the sender immediately by return e-mail and delete
this message.
Thank you.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Could this expression parser be more 'Pythonic'?

2009-05-07 Thread Amr
Hi John,

Thanks for the tips, I will check them out.

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


Re: Newcomer to Python tutorial question

2009-05-07 Thread Peter Otten
Alan Cameron wrote:

> I am not sure of this is the right place to ask a question about the
> tutorial
> 
> http://docs.python.org/3.0/tutorial/datastructures.html#sets
> 
> why is the printed result of
> 
 basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
 print(basket)
> {'orange', 'banana', 'pear', 'apple'}
> 
> in the sequence given?

As already said by others, the order of items in a set is not part of the 
concept of a set. 

You can even have sets with equal contents that display differently:

Python 3.0.1+ (r301:69556, Apr 15 2009, 17:25:52)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = {'orange', 'banana', 'apple', 'orange', 'pear', 'apple'}
>>> b = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> a == b
True
>>> repr(a) == repr(b)
False
>>> a
{'orange', 'pear', 'apple', 'banana'}
>>> b
{'orange', 'pear', 'banana', 'apple'}

Peter

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


Re: Newcomer to Python tutorial question

2009-05-07 Thread Alan Cameron
"Alan Cameron"  wrote in message 
news:hrfml.50224$tb.4...@newsfe07.ams2...
>I am not sure of this is the right place to ask a question about the 
>tutorial
>
> http://docs.python.org/3.0/tutorial/datastructures.html#sets
>
> why is the printed result of
>
 basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
 print(basket)
> {'orange', 'banana', 'pear', 'apple'}
>
> in the sequence given?
>
>

Thanks to all who replied.
I assume therefore that the order in which the items of the set are printed 
could vary each time it is printed?


-- 
Alan Cameron 


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


Re: What would YOU like to see in a txt to html converter?

2009-05-07 Thread News123
Florian Wollenschein wrote:
> As you might have mentioned I'm just working on a txt to html converter
> called "thc". This project is intended for me to learn Python and now
> pyQT4 to which I changed a few days ago (started with Tkinter).
> 
> I have implemented the following features so far:
> 
> - Giving a title for the html
> - Choose whether it's Transitional or Strict Doctype
> - Select a background color
> - Show the converted file with the standard browser
> - Working on a font size slider
> 
> I don't really know if this is of any use for anybody but it's just a
> fun project by a beginner :-)
> 
> Now I'd like to know what kind of features you'd like to see in version
> 0.3 of thc!?
> 
> Please post them...
> 
> Have fun!
> Listick
> http://www.lictick.org

I would first think about your personal requirements / use cases.
What kind of texts do you want to convert?

I think there's already quite some text to html converters, which you
could take as inspiration.
Most of them were written for a specific purpose though and started from
text files with some 'formatting syntax'

Exanples:
man2html   converts man pages to html
pod2html   covnerts perl online documentation to html

There's also converters from certain wiki formats to html.

There's also source code formatters for certain programming languages
or log file to html converters which color certain message types


If it is just for plain text with no special formattings,
then you need probably only:
- escape all characters, which have to be escap for html. (but there is
probably already a function for it.
)
- seperate paragraphs (at double new lines or at single new lines. This
could be an option)

- additionally you could allow to specify a html prefix (before the
converted text) and a html post fix after the converted text.

- I would handle settings lik color / font size etc with style sheets
and not within the generated html. If you want you could autgenerate
style sheets from some function arguments. They could contain Font color
/ background color / font formatting . . . .

- you could add a configuration, that automatically tags certain words
with certain tags, to allow simle keyword hihglighting.


It all depends on your use case.





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


Re: Newcomer to Python tutorial question

2009-05-07 Thread Florian Wollenschein

Alan Cameron wrote:
I am not sure of this is the right place to ask a question about the 
tutorial


http://docs.python.org/3.0/tutorial/datastructures.html#sets

why is the printed result of


basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)

{'orange', 'banana', 'pear', 'apple'}

in the sequence given?



A set is not ordered and eliminates duplicate elements. So the output is 
random in terms of the order and only shows each single item once...


Correct me if I'm wrong :-)

Listick
http://www.listick.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: What would YOU like to see in a txt to html converter?

2009-05-07 Thread Florian Wollenschein

Will Wang wrote:

"Florian" == Florian Wollenschein  
writes:


Florian> As you might have mentioned I'm just working on a txt to html 
converter called
Florian> "thc". This project is intended for me to learn Python and now 
pyQT4 to which I
Florian> changed a few days ago (started with Tkinter).

Florian> I have implemented the following features so far:

Florian> - Giving a title for the html
Florian> - Choose whether it's Transitional or Strict Doctype
Florian> - Select a background color
Florian> - Show the converted file with the standard browser
Florian> - Working on a font size slider

Florian> I don't really know if this is of any use for anybody but it's 
just a fun
Florian> project by a beginner :-)

Florian> Now I'd like to know what kind of features you'd like to see in 
version 0.3 of
Florian> thc!?

Florian> Please post them...

Florian> Have fun!
Florian> Listick
Florian> http://www.lictick.org

You could learn something from emacs-muse. That plugin can help emacs to
convert txt to html, tex, pdf, docbook and some other document format.

In emacs-muse, the title and subtitle is defined like this:

*emphasis*
**strong emphasis**
***very strong emphasis***
_underlined_
=verbatim and monospace=

emacs-muse : http://mwolson.org/projects/EmacsMuse.html


Thank you for this information. I already thought of using dots or 
asterisks or whatever to let the user format the text instead of using 
html tags (this would be quite paradox ;-)


Please keep on posting ideas...

Thanks again,
Listick
http://www.listick.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newcomer to Python tutorial question

2009-05-07 Thread Arnaud Delobelle
"Alan Cameron"  writes:

> I am not sure of this is the right place to ask a question about the 
> tutorial
>
> http://docs.python.org/3.0/tutorial/datastructures.html#sets
>
> why is the printed result of
>
 basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
 print(basket)
> {'orange', 'banana', 'pear', 'apple'}
>
> in the sequence given?

A set is an unordered container, but due to the nature of an object
representation (which is a sequence of characters), its representation
has to list the elements in a certain order.  However, this order is not
significant.

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


Re: Newcomer to Python tutorial question

2009-05-07 Thread Chris Rebert
On Thu, May 7, 2009 at 11:35 AM, Alan Cameron 
wrote> I am not sure of this is the right place to ask a question
about the
> tutorial
>
> http://docs.python.org/3.0/tutorial/datastructures.html#sets
>
> why is the printed result of
>
 basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
 print(basket)
> {'orange', 'banana', 'pear', 'apple'}
>
> in the sequence given?

Because it's *not a sequence* at all, it's a set. Sets are unordered
and contain no duplicate items, hence why the output ordering is
arbitrary and only the unique subset of original elements is present.

Further info: 
http://docs.python.org/3.0/library/stdtypes.html#set-types-set-frozenset

Cheers,
Chris
-- 
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Get Into The World Of YOUSUF JUSANI

2009-05-07 Thread muhammadanushanif
Get The Most Valuable and Best For Investment Properties IN ASIA, !!
Real Estate Builders.. Real Estate Dealer Buy, Sell REAL EASTAE IN
GULF ,DUBAI AND AUSTRIA


FOR MORE INFO http://www.yousufjusani.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Newcomer to Python tutorial question

2009-05-07 Thread Alan Cameron
I am not sure of this is the right place to ask a question about the 
tutorial

http://docs.python.org/3.0/tutorial/datastructures.html#sets

why is the printed result of

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)
{'orange', 'banana', 'pear', 'apple'}

in the sequence given?

-- 
Alan Cameron 


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


Re: Threading and GIL

2009-05-07 Thread Carl Banks
On May 7, 12:20 am, googler.1.webmas...@spamgourmet.com wrote:
> thats the reason why its not working. Imagine the end() method of the
> thread object is called so the C++ Function is opened where the code
> for this method is in.

You're going to have to post some code if you want better help; this
description is unintelligible.  I don't know what you mean by end()
method, nor whether it's a Python method or C++ method, nor what
exactly you mean by thread object (C++ or Python object?) or C++
Function.


> At a line the Code ...->End() is called which waits that the C++
> Thread class
> is finished. BUT here is the problem: In the Method of the C++ class
> which is in threaded mode can't run because its still waiting that the
> GIL
> is released by the thread which executed the ->End() command.
>
> So the app has a deadlock when it arrives at   ->End() and
> PyGILState_Ensure
> function.

So you have to release the GIL before calling End().  Just surround End
() by Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.  (Presumably
you know the thread state when you call End(); if you don't then
surround the calls to Py_{BEGIN,END}_ALLOW_THREADS with calls to
PyGILState_{Ensure,Release}.  Yes, that means you acquire the GIL just
so you can be sure that you've released it.  I know of no other way to
be sure you don't have the GIL.)

If you are trying to kill a different thread, and I can't quite tell
if that's what you're doing, then be aware that it is very tricky to
do right and most think it to be a bad idea.  If you don't allow the
thread you're killing to clean up it can deadlock, and even if you do,
you have to be careful to clean up properly and you have to be
constantly on guard for what might happen in a thread is killed in the
middle of something.


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


Re: Updating an Imported Function

2009-05-07 Thread Diez B. Roggisch

Donovan Parks schrieb:

Hello,

I'm new to Python and have what is probably a very basic question. I
am writing a helloWorld() function within a file called helloWorld.py:

def helloWorld():
print 'hi'

Now, I can import and run this function:

import helloWorld
helloWorld.helloWorld()

Which will print 'hi' as expected. Now, I'd like to update this
function in my text editor so it is:

def helloWorld():
print 'hello world'

Without having to exit my Python interpreter, how can I import this
revised function? If I do the import again:

import helloWorld

And run helloWorld.helloWorld() it will still print out just 'hi'.
I've tried deleting this function (a weird concept to me as I come
from a C++ background) using del helloWorld and than importing again,
but the function will still print out just 'hi'.

Can this be done? How so?


reload(helloWorld)

But there are some caveats, and IMHO reloading isn't worth the trouble - 
it is *so* easy to write a second script, test.py or whatever, that  you 
just call from a shell. And this has the added benefit that you can 
create even somewhat more elaborate toy-code.


If one wants to play around with objects created, either do

python -i test.py

or try to use pdb, the python debugger, through

import pdb; pdb.set_trace()

to get an interactive prompt at whatever point you want.

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


Re: What would YOU like to see in a txt to html converter?

2009-05-07 Thread Will Wang
> "Florian" == Florian Wollenschein  
> writes:

Florian> As you might have mentioned I'm just working on a txt to html 
converter called
Florian> "thc". This project is intended for me to learn Python and now 
pyQT4 to which I
Florian> changed a few days ago (started with Tkinter).

Florian> I have implemented the following features so far:

Florian> - Giving a title for the html
Florian> - Choose whether it's Transitional or Strict Doctype
Florian> - Select a background color
Florian> - Show the converted file with the standard browser
Florian> - Working on a font size slider

Florian> I don't really know if this is of any use for anybody but it's 
just a fun
Florian> project by a beginner :-)

Florian> Now I'd like to know what kind of features you'd like to see in 
version 0.3 of
Florian> thc!?

Florian> Please post them...

Florian> Have fun!
Florian> Listick
Florian> http://www.lictick.org

You could learn something from emacs-muse. That plugin can help emacs to
convert txt to html, tex, pdf, docbook and some other document format.

In emacs-muse, the title and subtitle is defined like this:

*emphasis*
**strong emphasis**
***very strong emphasis***
_underlined_
=verbatim and monospace=

emacs-muse : http://mwolson.org/projects/EmacsMuse.html
--
http://mail.python.org/mailman/listinfo/python-list


Downloading most recently modified files

2009-05-07 Thread AllenLars

I am trying to code a script that will allow me to go to ftp site and
download files based on most recently modified file (date, time).  I am
brand new to programming.  Any and all help is appreciated.
-- 
View this message in context: 
http://www.nabble.com/Downloading-most-recently-modified-files-tp23432457p23432457.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: What would YOU like to see in a txt to html converter?

2009-05-07 Thread norseman

Dotan Cohen wrote:

As you might have mentioned I'm just working on a txt to html converter
called "thc". This project is intended for me to learn Python and now pyQT4
to which I changed a few days ago (started with Tkinter).

I have implemented the following features so far:

- Giving a title for the html
- Choose whether it's Transitional or Strict Doctype


Don't give this choice. What benefit does this give the user?


- Select a background color
- Show the converted file with the standard browser


That should probably be valid [X]HTML and be done with it.


- Working on a font size slider


This should be a browser feature, not a page feature. Use the default
sizes of the HTML elements, and let the UA override those defaults as
the user sees fit ot configure it.

If you think that there should be a font size slider, then file a
feature request at the bug tracker of your favourite browser.


I don't really know if this is of any use for anybody but it's just a fun
project by a beginner :-)

Now I'd like to know what kind of features you'd like to see in version 0.3
of thc!?



You should probably convert the text to UTF-8 and make sure to declare
that with a meta tag.

You might want to look at markdown for a nice way to have hyperlink support.

Lists conversion, like these:
* item one
* item two
* item three

1. item one
2. item two
3. item three



Actually I would like to see a good HTML to txt or odt converter. 
Perhaps someone you know has the time and inclination to make one.
In Unix, grep is a fantastic search tool.  Since HTML's today seem to be 
one page one file, trying to search a "help collection" for a phrase is 
useless in the practical sense.


I mean no offense to your effort. There are many who wish a good version 
of such a converter.  It's just that I personally wish HTMLs used for 
Help and Documentation were banned from the universe. To me, a well 
written, easily understood, no frills, fully grep'able text file that 
covers the subject well is a truly fantastic thing to be well cherished.



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


Updating an Imported Function

2009-05-07 Thread Donovan Parks
Hello,

I'm new to Python and have what is probably a very basic question. I
am writing a helloWorld() function within a file called helloWorld.py:

def helloWorld():
print 'hi'

Now, I can import and run this function:

import helloWorld
helloWorld.helloWorld()

Which will print 'hi' as expected. Now, I'd like to update this
function in my text editor so it is:

def helloWorld():
print 'hello world'

Without having to exit my Python interpreter, how can I import this
revised function? If I do the import again:

import helloWorld

And run helloWorld.helloWorld() it will still print out just 'hi'.
I've tried deleting this function (a weird concept to me as I come
from a C++ background) using del helloWorld and than importing again,
but the function will still print out just 'hi'.

Can this be done? How so?

Thanks for any and all help.

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


RE: Wing vs Netbeans IDE?

2009-05-07 Thread Benjamin J. Racine
I'd love to see an updated shootout between these three, as I cannot for the 
life of me seem to be able to settle down with one of them.

Things I don't like: 
Wing's lack of integrated mercurial/svn support.
The clunkiness and scattered plugin approach of Eclipse (the latter is relavent 
when starting work on new machines all the time).
Netbeans project browser doesn't show class or functions inside the files.
Netbeans autocompletion doesn't seem immediately impressive.

But...
Wing has mentioned future support of svn,git,bazaar,mercurial,etc in the future.
QT designer is integrated with Eclipse.  So is Photran, which is convenient for 
some of science types.
It seems that there are reasons to be optimistic about the future of netbeans.  
It seems to be well put together so far, but the least mature.

I know that this comes up time and again, but I think a feature-specific debate 
over these might be worth revisiting for a lot of newcomers.

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


Re: Unable to build libpython2.5.so on OS X 10.4

2009-05-07 Thread Ned Deily
In article 
<0e05eca2-b460-4e01-aa54-cc1055f51...@q14g2000vbn.googlegroups.com>,
 elwinter  wrote:
> The Python module I am building is actually the Python module
> for ROOT, a large package from CERN. However, the problem arises
> before that code enters the picture, when I am building Python itself.
> All I want to do is create "libpython2.5.dylib", or its equivalent,
> and I can't seem to make that happen on Tiger.

Any chance you can use the python.org installer for 2.5.4?  Or the 
Macports version?  They both are supported on Tiger.




Again, I may be missing something but libpythonx.x by itself is not very 
useful, i.e. it's not your usual standalone lib.  You'll almost 
certainly need the whole python installation.  There are a number of 
ways to build python on OS X (google will find them or ask on the Mac 
python sig) but, unless you have some special requirement, use an 
existing python installation and build the ROOT Python module with that.

-- 
 Ned Deily,
 n...@acm.org

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


Re: What would YOU like to see in a txt to html converter?

2009-05-07 Thread Dotan Cohen
> As you might have mentioned I'm just working on a txt to html converter
> called "thc". This project is intended for me to learn Python and now pyQT4
> to which I changed a few days ago (started with Tkinter).
>
> I have implemented the following features so far:
>
> - Giving a title for the html
> - Choose whether it's Transitional or Strict Doctype

Don't give this choice. What benefit does this give the user?

> - Select a background color
> - Show the converted file with the standard browser

That should probably be valid [X]HTML and be done with it.

> - Working on a font size slider

This should be a browser feature, not a page feature. Use the default
sizes of the HTML elements, and let the UA override those defaults as
the user sees fit ot configure it.

If you think that there should be a font size slider, then file a
feature request at the bug tracker of your favourite browser.

> I don't really know if this is of any use for anybody but it's just a fun
> project by a beginner :-)
>
> Now I'd like to know what kind of features you'd like to see in version 0.3
> of thc!?
>

You should probably convert the text to UTF-8 and make sure to declare
that with a meta tag.

You might want to look at markdown for a nice way to have hyperlink support.

Lists conversion, like these:
* item one
* item two
* item three

1. item one
2. item two
3. item three

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
--
http://mail.python.org/mailman/listinfo/python-list


Re: Wing vs Netbeans IDE?

2009-05-07 Thread nnp
I've tried Wing but not NetBeans. I would personally recommend Eclipse
with the PyDev plugin. I prefer it to Wing by *far* and if you prefer
Eclipse to NetBeans for Java then it might be worth your while
checking it out. If you take a few minutes to learn a few of the
shortcuts in Eclipse you can really cut down the time to do a lot of
administrative/organisational tasks.

On Windows I remember Eclipse + Pydev being a bit of a memory hog but
on OS X and Linux it works smoothly.

On Thu, May 7, 2009 at 6:24 PM, Lawrence Hanser  wrote:
> Dear Colleagues,
>
> I have been using NetBeans for a month or so now and am reasonably
> happy with it.  I'm considering other options, and ran across Wing.
> I'm interested in opinions about NetBeans and Wing as IDE for Python.
>
> Thanks,
>
> Larry
> --
> http://mail.python.org/mailman/listinfo/python-list
>

-- 
http://www.unprotectedhex.com
http://www.smashthestack.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: list comprehension question

2009-05-07 Thread J Kenneth King
Steven D'Aprano  writes:

> On Wed, 06 May 2009 09:48:51 -0400, J Kenneth King wrote:
>
>> Emile van Sebille  writes:
>> 
>>> On 5/5/2009 9:15 AM J Kenneth King said...
>>>
 List comprehensions can make a reader of your code apprehensive
 because it can read like a run-on sentence and thus be difficult to
 parse. The Python documentation discourages their use and I believe
 for good reason.
>>>
>>> Can you provide a link for this?  I'd like to see specifically what's
>>> being discouraged, as I'd be surprised to find routine usage frowned
>>> upon.
>>>
>>> Emile
>> 
>> http://docs.python.org/tutorial/datastructures.html#nested-list-
> comprehensions
>> 
>> 
>> "If you’ve got the stomach for it, list comprehensions can be nested.
>> They are a powerful tool but – like all powerful tools – they need to be
>> used carefully, if at all."
>
> How does this discourage the use of list comprehensions? At most, it 
> warns that complicated list comps are tricky. Complicated *anything* are 
> tricky.

They are tricky and need to be used carefully, *if at all*.

IMO this means that if there's a way to do it without a nested list
comprehension, then that solution should be preferred.

>> and
>> 
>> "In real world, you should prefer builtin functions to complex flow
>> statements."
>
> That's ridiculous. The example given is a special case. That's like 
> saying "Loops are hard, so in the real world, if you want a loop, find a 
> builtin function that does what you want instead."
>
> What's the "builtin function" we're supposed to prefer over a "complex 
> flow statement" like this?

It's not ridiculous and says nothing of the sort.  You're jumping to
conclusions.  If you have a problem with it, I suggest you complain to
the Python documentation people.  I don't make this stuff up.

Just look at many of the example solutions provided in this thread to
the OP's problem. The examples in the link I provided are also good as
are ones provided in the itertools documentation.

Keep in mind that nested comprehensions are still available because
they do have a use case that justifies their existence. However, I
think the Python documentation warns against their use because people
might rely on them for problems where they aren't necessary and since
they are difficult to read... it can lead to difficult to read code.
--
http://mail.python.org/mailman/listinfo/python-list


Wing vs Netbeans IDE?

2009-05-07 Thread Lawrence Hanser
Dear Colleagues,

I have been using NetBeans for a month or so now and am reasonably
happy with it.  I'm considering other options, and ran across Wing.
I'm interested in opinions about NetBeans and Wing as IDE for Python.

Thanks,

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


Re: Unable to build libpython2.5.so on OS X 10.4

2009-05-07 Thread elwinter
Hi Ned. The Python module I am building is actually the Python module
for ROOT, a large package from CERN. However, the problem arises
before that code enters the picture, when I am building Python itself.
All I want to do is create "libpython2.5.dylib", or its equivalent,
and I can't seem to make that happen on Tiger.

Thanks,
Eric

On May 7, 12:41 pm, Ned Deily  wrote:
> In article
> ,
>  Eric Winter  wrote:
>
> > Hi all. I'm trying to build some internal code that needs to link
> > against libpython2.5.so on a OS X 10.4 (Tiger) machine. It seems that
> > no matter what combination of options and environment variables I give
> > to the configure script from python 2.5.1, all I get is the
> > libpython2.5.a (the static library). I've googled the problem and
> > searched the comp.lang.python archives, but I have been unable to find
> > anything that works.
>
> Perhaps I misunderstand, but if you are trying to build a C extension
> for an existing Python 2.5 installation, using Distutils from that
> installation should take care of everything for you.  Is there a
> setup.py file by any chance?  Are you using a standard python
> installation (i.e. python.org installer for instance)?  More details
> might help.
>
> --
>  Ned Deily,
>  n...@acm.org

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


Re: Logging exceptions to a file

2009-05-07 Thread segfaulthunter
On May 7, 1:19 pm, Pierre GM  wrote:
> On May 7, 5:32 am, Lie Ryan  wrote:
>
>
>
> > Pierre GM wrote:
> > > All,
> > > I need to log messages to both the console and a given file. I use the
> > > following code (on Python 2.5)
>
> >  import logging
> >  #
> >  logging.basicConfig(level=logging.DEBUG,)
> >  logfile = logging.FileHandler('log.log')
> >  logfile.setLevel(level=logging.INFO)
> >  logging.getLogger('').addHandler(logfile)
> >  #
> >  mylogger = logging.getLogger('mylogger')
> >  #
> >  mylogger.info("an info message")
>
> > > So far so good, but I'd like to record (possibly unhandled) exceptions
> > > in the logfile.
> > > * Do I need to explicitly trap every single exception ?
> > > * In that case, won't I get 2 log messages on the console (as
> > > illustrated in the code below:
> >  try:
> >      1/0
> >  except ZeroDivisionError:
> >      mylogger.exception(":(")
> >      raise
>
> > > Any comments/idea welcomed
> > > Cheers.
>
> > Although it is usually not recommended to use a catch-all except, this
> > is the case where it might be useful. JUST DON'T FORGET TO RE-RAISE THE
> > EXCEPTION.
>
> > if __name__ == '__main__':
> >      try:
> >          main():
> >      except Exception, e:
> >          # log('Unhandled Exception', e)
> >          raise
>
> OK for a simple script, but the (unhandled) exceptions need to be
> caught at the module level. Any idea?

Override sys.excepthook. http://docs.python.org/library/sys.html#sys.excepthook
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-07 Thread Arnaud Delobelle
Luis Alberto Zarrabeitia Gomez  writes:

> A bit offtopic: a while ago I think I saw a recipe for a decorator
> that, via bytecode hacks, would bind otherwise global names to the
> local namespace of the function. Can anyone remember it/point me to
> it? An @bind decorator that would 'localize' all the global names,
> including the still unexistent but already know function name, would
> guarantee that at least recursion calls the same function instead of
> "whatever happens to be bound to their name at runtime". If it wasn't
> a hack, anyway.

I remember a discussion on python-ideas, and I wrote this decorator at
the time:


def new_closure(vals):
args = ','.join('x%i' % i for i in range(len(vals)))
f = eval("lambda %s:lambda:(%s)" % (args, args))
return f(*vals).func_closure

def localize(f):
f_globals = dict((n, f.func_globals[n]) for n in f.func_code.co_names)
f_closure = ( f.func_closure and
  new_closure([c.cell_contents for c in f.func_closure]) )
return type(f)(f.func_code, f_globals, f.func_name,
   f.func_defaults, f_closure)


Unfortunately it fails for recursive functions:


>>> @localize
... def fac(n):
... return 1 if n <= 1 else n*fac(n - 1)
... 
Traceback (most recent call last):
  File "", line 1, in 
  File "localize.py", line 7, in localize
f_globals = dict((n, f.func_globals[n]) for n in f.func_code.co_names)
  File "localize.py", line 7, in 
f_globals = dict((n, f.func_globals[n]) for n in f.func_code.co_names)
KeyError: 'fac'


It can be fixed, but not very easily precisely because the function is
recursive.  I've hacked a quick way to do it below.


def reclocalize(f):
def wrapper(*args, **kwargs):
return recf(*args, **kwargs)
def getglobal(name):
return wrapper if name == f.__name__ else f.func_globals[name]
f_globals = dict((n, getglobal(n)) for n in f.func_code.co_names)
f_closure = ( f.func_closure and
  new_closure([c.cell_contents for c in f.func_closure]) )
recf = type(f)(f.func_code, f_globals, f.func_name,
   f.func_defaults, f_closure)
return wrapper


Now it works as intended:


>>> @reclocalize
... def fac(n):
... return 1 if n <= 1 else n*fac(n - 1)
... 
>>> fac(10)
3628800
>>> foo = fac
>>> del fac
>>> foo(10)
3628800

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


Re: Logging exceptions to a file

2009-05-07 Thread Stephen Hansen
>
>
>  > > So far so good, but I'd like to record (possibly unhandled) exceptions
> > > in the logfile.
> > > * Do I need to explicitly trap every single exception ?
> > > * In that case, won't I get 2 log messages on the console (as
> > > illustrated in the code below:
>

Check out sys.excepthook, something vaguely like:

import sys

def handle_exceptions(exctype, value, traceback): logging.exception("An
unhandled exception was detected.")

sys.excepthook = handle_exceptions
--
http://mail.python.org/mailman/listinfo/python-list


What would YOU like to see in a txt to html converter?

2009-05-07 Thread Florian Wollenschein
As you might have mentioned I'm just working on a txt to html converter 
called "thc". This project is intended for me to learn Python and now 
pyQT4 to which I changed a few days ago (started with Tkinter).


I have implemented the following features so far:

- Giving a title for the html
- Choose whether it's Transitional or Strict Doctype
- Select a background color
- Show the converted file with the standard browser
- Working on a font size slider

I don't really know if this is of any use for anybody but it's just a 
fun project by a beginner :-)


Now I'd like to know what kind of features you'd like to see in version 
0.3 of thc!?


Please post them...

Have fun!
Listick
http://www.lictick.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unable to build libpython2.5.so on OS X 10.4

2009-05-07 Thread Ned Deily
In article 
,
 Eric Winter  wrote:
> Hi all. I'm trying to build some internal code that needs to link
> against libpython2.5.so on a OS X 10.4 (Tiger) machine. It seems that
> no matter what combination of options and environment variables I give
> to the configure script from python 2.5.1, all I get is the
> libpython2.5.a (the static library). I've googled the problem and
> searched the comp.lang.python archives, but I have been unable to find
> anything that works.

Perhaps I misunderstand, but if you are trying to build a C extension 
for an existing Python 2.5 installation, using Distutils from that 
installation should take care of everything for you.  Is there a 
setup.py file by any chance?  Are you using a standard python 
installation (i.e. python.org installer for instance)?  More details 
might help.

-- 
 Ned Deily,
 n...@acm.org

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


  1   2   >