Re: Newbi Q: Recursively reverse lists but NOT strings?

2007-10-14 Thread George Sakkis
On Oct 15, 2:30 am, Gary Herron <[EMAIL PROTECTED]> wrote:
> Dmitri O.Kondratiev wrote:
>
> > The function I wrote (below) reverses lists all right:
>
> > def reverse(xs):
> > if xs == []:
> > return []
> > else:
> > return (reverse (xs[1:])) + [xs[0]]
>
> > >>> reverse ([1,2,3])
> > [3, 2, 1]
>
> > Yet when I try to reverse a string I  get:
>
> > >>> reverse ("abc")
>
> > ...
> > ...
> > ...
>
> >   File "C:\wks\python-wks\reverse.py", line 5, in reverse
>
> > return (reverse (xs[1:])) + [xs[0]]
>
> >   File "C:\wks\python-wks\reverse.py", line 5, in reverse
>
> > return (reverse (xs[1:])) + [xs[0]]
>
> >   File "C:\wks\python-wks\reverse.py", line 2, in reverse
>
> > if xs == []:
>
> > RuntimeError: maximum recursion depth exceeded in cmp
>
> > What's wrong? Why recursion never stops?
>
> If you are doing this as an python-learning exercise, then read on.   If
> you are doing this reversal for real code, then try:
>
>   xs.reverse() for in-place reversal of a list (but not a string), or
>   result = xs[::-1] for creating a reversed copy of either a string or a
> list
>
> Your recursion stops when xs == [], but when you're stripping characters
> off a string,  like 'abc', the remaining portion will be 'bc', then 'c',
> than '', but never [] so you 'll never stop.
>
> Try:
>
> if xs == []:
> return []
> elif xs == '':
> return ''
> else:
> ...

The 'else' clause also breaks for strings: the second operand is a
list, which cannot be concatenated to strings. Here's a version that
works for any type with the common slicing semantics:

def reverse(xs):
 if not xs:
return xs
 else:
return reverse(xs[1:]) + xs[:1]

print reverse([1,2,3])
print reverse((1,2,3))
print reverse('123')


George

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


Re: Newbi Q: Recursively reverse lists but NOT strings?

2007-10-14 Thread Marc 'BlackJack' Rintsch
On Mon, 15 Oct 2007 02:11:27 -0400, Victor B. Gonzalez wrote:

> On Sunday 14 October 2007 5:06:19 pm Dmitri O.Kondratiev wrote:
>> The function I wrote (below) reverses lists all right:
>>
>> def reverse(xs):
>> if xs == []:
>> return []
>> else:
>> return (reverse (xs[1:])) + [xs[0]]
>>
>> >>> reverse ([1,2,3])
>>
>> [3, 2, 1]
>>
>> Yet when I try to reverse a string I  get:
>> >>> reverse ("abc")
>>
>> ...
>> ...
>> ...
>>
>>   File "C:\wks\python-wks\reverse.py", line 5, in reverse
>>
>> return (reverse (xs[1:])) + [xs[0]]
>>
>>   File "C:\wks\python-wks\reverse.py", line 5, in reverse
>>
>> return (reverse (xs[1:])) + [xs[0]]
>>
>>   File "C:\wks\python-wks\reverse.py", line 2, in reverse
>>
>> if xs == []:
>>
>> RuntimeError: maximum recursion depth exceeded in cmp
>>
>>
>>
>> What's wrong? Why recursion never stops?

Becauese you test if `xs` is an empty list which is never true when you
call the function with a string.  So it never ends.  '' != []

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbi Q: Recursively reverse lists but NOT strings?

2007-10-14 Thread Gary Herron
Dmitri O.Kondratiev wrote:
>
> The function I wrote (below) reverses lists all right: 
>
> def reverse(xs):
> if xs == []:
> return []
> else:
> return (reverse (xs[1:])) + [xs[0]]
>
>  
> >>> reverse ([1,2,3])
> [3, 2, 1]
> >>> 
>
>
> Yet when I try to reverse a string I  get:
>
> >>> reverse ("abc")
>
> ...
> ...
> ...
>
>   File "C:\wks\python-wks\reverse.py", line 5, in reverse
>
> return (reverse (xs[1:])) + [xs[0]]
>
>   File "C:\wks\python-wks\reverse.py", line 5, in reverse
>
> return (reverse (xs[1:])) + [xs[0]]
>
>   File "C:\wks\python-wks\reverse.py", line 2, in reverse
>
> if xs == []:
>
> RuntimeError: maximum recursion depth exceeded in cmp
>
> >>> 
>
> What's wrong? Why recursion never stops?
>
If you are doing this as an python-learning exercise, then read on.   If
you are doing this reversal for real code, then try:

  xs.reverse() for in-place reversal of a list (but not a string), or
  result = xs[::-1] for creating a reversed copy of either a string or a
list


Your recursion stops when xs == [], but when you're stripping characters
off a string,  like 'abc', the remaining portion will be 'bc', then 'c',
than '', but never [] so you 'll never stop.

Try:

if xs == []:
return []
elif xs == '':
return ''
else:
...


Gary Herron


>
> Thanks,
> Dima

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


Re: Newbi Q: Recursively reverse lists but NOT strings?

2007-10-14 Thread Victor B. Gonzalez
On Sunday 14 October 2007 5:06:19 pm Dmitri O.Kondratiev wrote:
> The function I wrote (below) reverses lists all right:
>
> def reverse(xs):
> if xs == []:
> return []
> else:
> return (reverse (xs[1:])) + [xs[0]]
>
> >>> reverse ([1,2,3])
>
> [3, 2, 1]
>
> Yet when I try to reverse a string I  get:
> >>> reverse ("abc")
>
> ...
> ...
> ...
>
>   File "C:\wks\python-wks\reverse.py", line 5, in reverse
>
> return (reverse (xs[1:])) + [xs[0]]
>
>   File "C:\wks\python-wks\reverse.py", line 5, in reverse
>
> return (reverse (xs[1:])) + [xs[0]]
>
>   File "C:\wks\python-wks\reverse.py", line 2, in reverse
>
> if xs == []:
>
> RuntimeError: maximum recursion depth exceeded in cmp
>
>
>
> What's wrong? Why recursion never stops?
>
> Thanks,
> Dima


I didn't try anything but it looks like your calling your function in your 
else block like this (e.g., reverse('bc')) everytime. your else block isn't 
really ending itself, just repeating itself.

I could be wrong but from a quick glance you'll need to end it for sure when 
dealing with recursion.

maybe also trying to reverse using the iterator function reversed() or this 
shortcut may help e.g, 'abc'[::-1] -> 'cba'.

good luck!

-- 
Best Regards
Victor B. Gonzalez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple HTML template engine?

2007-10-14 Thread John Nagle
allen.fowler wrote:
> Hello,
> 
> Can anyone recommend a simple python template engine for generating
> HTML that relies only on the Pyhon Core modules?
> 
> No need for caching, template compilation, etc.
> 
> Speed is not a major issue.
> 
> I just need looping and conditionals. Template inheritance would be a
> bonus.

 HTMLTemplate is a minimal system for that sort of thing.
It doesn't drag in some big "framework".

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


Re: The fundamental concept of continuations

2007-10-14 Thread George Neuner
On Mon, 15 Oct 2007 11:56:39 +1300, Lawrence D'Oliveiro
<[EMAIL PROTECTED]> wrote:

>In message <[EMAIL PROTECTED]>, Barb Knox wrote:
>
>> Instead of function A returning to its caller, the
>> caller provides an additional argument (the "continuation") which is a
>> function B to be called by A with A's result(s).
>
>That's just a callback. I've been doing that in C code (and other
>similar-level languages) for years.

Callbacks are a form of continuation.  However, general continuations
such as those in Scheme, carry with them their execution context.
This allows them to used directly for things like user-space
threading.

George
--
for email reply remove "/" from address
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Entering username & password automatically using urllib.urlopen

2007-10-14 Thread James Matthews
if you want to hardcode the password in the url. What you need to do is
http:username:[EMAIL PROTECTED]

On 10/14/07, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
>
> rodrigo schrieb:
> > I am trying to retrieve a password protected page using:
> >
> > get = urllib.urlopen('http://password.protected.url";').read()
> >
> > While doing this interactively, I'm asked for  the username, then the
> > password at the terminal.
> > Is there any way to do this non-interactively? To hardcode the user/
> > pass into the script so I can get the page automatically?
> >
> > (This is not a cracking attempt, I am trying to retrieve a page I have
> > legitimate access to, just doing it automatically when certain
> > conditions are met.)
>
> Is that HTTP-auth? Then this might help:
>
> http://www.voidspace.org.uk/python/articles/authentication.shtml
>
> BTW, use urllib2.
>
> Diez
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://www.goldwatches.com/
http://www.jewelerslounge.com
-- 
http://mail.python.org/mailman/listinfo/python-list

use lines as argument to a command

2007-10-14 Thread Shoryuken
I'm new to Python, so my question may sounds naive. Here is it.

I have a text file like this:

www.a.com
www.b.com
www.c.com
...

I want to read one line from this file at a time, which I know how to
do. And use it as an argument to a command, for example, telnet www.a.com
and so on. However I have no idea how to do this task.

My purpose is to generate a brief report.

Thank you in advance.

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


Simple HTML template engine?

2007-10-14 Thread allen.fowler
Hello,

Can anyone recommend a simple python template engine for generating
HTML that relies only on the Pyhon Core modules?

No need for caching, template compilation, etc.

Speed is not a major issue.

I just need looping and conditionals. Template inheritance would be a
bonus.

I've seen Genshi and Cheetah, but they seem way too complex.

Any ideas?

I'm sure I could build something myself, but I'm sure this has already
been done quite a few times.  Why re-invent the wheel, right?


Thank you,
Allen

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


RE: Entering username & password automatically using urllib.urlopen

2007-10-14 Thread Ryan Ginstrom
> On Behalf Of rodrigo
> I am trying to retrieve a password protected page using:
> 
> get = urllib.urlopen('http://password.protected.url";').read()

I would suggest looking at mechanize.
http://wwwsearch.sourceforge.net/mechanize/

from mechanize import Browser

USERNAME = "user"
PASSWORD = "secret"
LOGIN_PAGE = "http://password.protected.url/";

browser = Browser()
browser.open( LOGIN_PAGE )

# log in
browser.select_form( nr=0 ) # Assuming log in form is first form on the page
# Check the form for the actual field names...
browser['user'] = USERNAME
browser['pass'] = PASSWORD
browser.submit()

# Content goodness follows...

##
Of course, this assumes that the site doesn't use some kind of JavaScript
trickery to prevent automation like the above. In that case, you'd have to
use something like PAMIE
http://sourceforge.net/projects/pamie/

HTH,
Ryan Ginstrom

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


Re: int to str in list elements..

2007-10-14 Thread Alex Martelli
Abandoned <[EMAIL PROTECTED]> wrote:

> Hi..
> I have a list as a=[1, 2, 3  ] (4 million elements)
> and
> b=",".join(a)
> than
> TypeError: sequence item 0: expected string, int found
> I want to change list to  a=['1','2','3'] but i don't want to use FOR
> because my list very very big.
> I'm sorry my bad english.
> King regards

Try b=','.join(map(str, a)) -- it WILL take up some memory (temporarily)
to build the huge resulting string, but there's no real way to avoid
that.

It does run a bit faster than a genexp with for...:

brain:~ alex$ python -mtimeit -s'a=range(4000*1000)'
'b=",".join(map(str,a))'
10 loops, best of 3: 3.37 sec per loop

brain:~ alex$ python -mtimeit -s'a=range(4000*1000)' 'b=",".join(str(x)
for x i
n a)'
10 loops, best of 3: 4.36 sec per loop


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


Re: Entering username & password automatically using urllib.urlopen

2007-10-14 Thread Daniel Larsson
You form the URL thus:

http://:@:/

This is defined in RFC 1738 

On 10/14/07, rodrigo <[EMAIL PROTECTED]> wrote:
>
> I am trying to retrieve a password protected page using:
>
> get = urllib.urlopen('http://password.protected.url";').read()
>
> While doing this interactively, I'm asked for  the username, then the
> password at the terminal.
> Is there any way to do this non-interactively? To hardcode the user/
> pass into the script so I can get the page automatically?
>
> (This is not a cracking attempt, I am trying to retrieve a page I have
> legitimate access to, just doing it automatically when certain
> conditions are met.)
>
> Thanks,
>
> Rodrigo
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: GLE-like python package

2007-10-14 Thread rasmus
On Oct 14, 12:34 pm, Wildemar Wildenburger
<[EMAIL PROTECTED]> wrote:
> Cesar G. Miguel wrote:
> > I think this is what you're looking for:
>
> >http://pyx.sourceforge.net/
>
> It damn sure is (a straight ripoff of GLE ;))!
>
> The syntax seems a bit messier than GLE (naturally) but since it is
> python I'm willing to bite that bullet.
>
> Thanks :)
> /W

In case you're interested in making interactive visualizations, you
might want to look at my own python package SUMMON:
http://people.csail.mit.edu/rasmus/summon/index.shtml

Matt

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


Re: Python on imac

2007-10-14 Thread w . greg . phillips
On Oct 13, 7:21 pm, John Velman <[EMAIL PROTECTED]> wrote:
> I'm considering moving from Linux to imac.   I've recently returned to
> Python (was never very expert) to develop a small gui application.  At
> present I plan to use PyGTK with Pango and Cairo.

You should be aware that unless something has changed recently, PyGTK
runs under X11 and is not native Aqua. This makes it a bit clunky to
deal with.

Greg

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


Re: Order of tuples in dict.items()

2007-10-14 Thread Paul Rubin
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> I've never seen the point of a sorted dictionary, it's easy to just say:
> for key, value in sorted(D.items())

You might want just a subrange of the dictionary (say the 100th
through 150th items in sorted order) without having to sort the entire
dictionary.

Also, with the right data structures you can support fast non-mutating
updates, i.e.

e = d.updated(x=3)

is equivalent to:

e = dict((x,y) for x,y in d.iteritems())   # copy all entries from d
e[x] = 3  # do the update

but the sorted version can work in O(log n) time instead of O(n).  The
new dictionary shares most of its contents with the old dictionary,
except now you can no longer mutate one without mutating the other, so
better not do any in-place updates.

Usage case (inspired by Happs State which was inspired by Prevayler):
You are writing a web app that has to remember a lot of request data
and you don't want to use an SQL database (too much overhead).  Your
app gets requests containing name/value pairs.  It responds with the
old value and then updates its stored value.  I.e. your server process
looks like:

   d = {}
   while True:
  name, new_value = get_request()
  old_value = d.get(name, None)
  d[name] = new_value
  send_response(old_value)

This is very efficient (just in-memory dictionary access, no SQL
garbage) but has any obvious problem: what if the computer crashes?
You have to store the stuff on disk, too.  So you put:

 log_to_disk(name, new_value)

right after the get_request.  If the computer crashes, reboot it and
play back the log from the beginning.

But that's no good either, the server could run for years nonstop and
get billions of updates and you don't want to play them back from the
beginning.  You want to take a checkpoint now and then, so you can
restart from there:

   d = {}
   while True:
  name, new_value = get_request()
  log_to_disk(name, new_value, timestamp())
  if checkpoint_now():   # do this once an hour or so
  log_to_disk(pickle(d), timestamp())
  old_value = d.get(name, None)
  d[name] = new_value
  send_response(old_value)

Now to restore, you find the newest pickle, read it in, and then apply
any logged updates with a newer timestamp, i.e. just the last hour's worth.

But this is no good either, because d can have millions of items, and
your server freezes while you're pickling and writing it.  You want a
separate thread doing that--except d is busily mutating while that
operation is in progress!  You can go crazy with locks, rollback
buffers, and all the insanity that SQL servers use, or with the sorted
immutable dictionary, you can simply write:

   d = frozendict()
   while True:
  name, new_value = get_request()
  log_to_disk(name, new_value, timestamp())
  if checkpoint_now():   # do this once an hour or so
  in_new_thread(log_to_disk, (pickle(d), timestamp()))
  old_value = d.get(name, None)# look mom, no freeze-up
  d = d.updated(name, new_value)
  send_response(old_value)

By making d.updated() create a new immutable dict that's separate from
d, you now don't have to worry about locks or synchronization or any
of that crap.  When the pickler is done with the old d, its references
are gone and the GC reclaims its storage.  Of course you can do more
elaborate checkpointing on subsets of the data etc. with the same
methods.  

Really it's the presence of the O(log n) .updated() operation, rather
than sorting, that makes this type of structure interesting, but the
usual implementation involves balanced tree structures so the sorting
comes naturally.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Order of tuples in dict.items()

2007-10-14 Thread John Machin
On Oct 15, 8:27 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> I've never seen the point of a sorted dictionary, it's easy to just say:
>
> for key, value in sorted(D.items())

There are several applications that involve finding i such that key[i]
<= query < key[i+1] where the keys are sorted and unique ... perhaps
with a huge sentinel key at the end. Examples include sliding-scale
taxes, and looking up prices for shares or managed funds. The code to
do this in Python using the bisect module is about as clear as the
equivalent SQL :-)

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


Re: The fundamental concept of continuations

2007-10-14 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Barb Knox wrote:

> Instead of function A returning to its caller, the
> caller provides an additional argument (the "continuation") which is a
> function B to be called by A with A's result(s).

That's just a callback. I've been doing that in C code (and other
similar-level languages) for years.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pydev code completion problem

2007-10-14 Thread Lukasz Mierzejewski
> He is right. What would you expect from this piece of code:
> 
> 
> foo = random.choose([A(), B(), C(), ..., Z()])

Thank you all for dispelling my stupid doubts!

> What PyDev does is to implement some heuristics that can guess easy 
> cases - as you saw for yourself. But there is a limit to what can be 
> done. Instead, it might even introduce errors.

I have just checked WingIDE and Komodo IDE and those PyDev heuristics do
much better work then code completion solutions in WingIDE and Komodo...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Order of tuples in dict.items()

2007-10-14 Thread Steven D'Aprano
On Sun, 14 Oct 2007 13:26:27 -0700, Erik Max Francis wrote:

> Will McGugan wrote:
> 
>> If I have two dictionaries containing identical values, can I be sure
>> that the items() method will return tuples in the same order?
[...]
>> Can I rely on this behavior?
> 
> Probably not.

Definitely not. See Paul Hankin's earlier post in this thread.


> Dictionaries do not have an ordering that you should
> count on.  In practice, the order in which you get the items if you
> iterate over a dictionary is dependent on the hashing function, which
> can potentially change over time.

Well, I suppose it *is* possible for Python to change its hash function 
in some future version, but Python hashing is highly optimized, very fast 
and not likely to change.

It's especially not likely to change in the middle of a run of your 
program, say between calling a.items() and calling b.items().

However, the very nature of hash tables is that they are dependent on the 
order that items are added and removed; Python dicts are hash tables, and 
sure enough, their order is dependent on the order that items are added 
and removed. Here's the simplest example I could come up with:

>>> {-1: 'a', -2: 'b'}
{-2: 'b', -1: 'a'}
>>> {-2: 'b', -1: 'a'}
{-1: 'a', -2: 'b'}



> This is a case where most implementations _probably_ will return
> identical dictionaries in the same order when iterated over (of course,
> different implementations will have different orderings, but you don't
> care about that), but I wouldn't take the chance and rely on such an
> implementation detail.

I think this is a case of being right for the wrong reasons.


> If you want to keep track of the order in which objects were added to a
> dictionary, you'll need to keep a separate list of (sorted) keys, which
> is easy enough.

Keeping a list of keys *in the order they are added* is not the same as 
keeping a list of keys *sorted*. Here's an obvious example:

D = {}
D['b'] = 2
D['a'] = 1
D['c'] = 3

Insertion order: bac
Sorted order: abc


> If you're lazy there are plenty of recipes around for
> things like `SortedDictionary` or `sorteddict`.

I've never seen the point of a sorted dictionary, it's easy to just say:

for key, value in sorted(D.items())

An OrderedDict, that remembers the order that items are added, might be a 
good addition to the standard library. But that would depend on folks 
agreeing on its semantics.



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


Re: pydev code completion problem

2007-10-14 Thread Lukasz Mierzejewski
> But maybe someone use Komodo IDE or Wing IDE and can tell how they handle
> situations like this? How works code completion in those IDE's?

I've downloaded and checked both of them (both have Linux version which is
nice thing). Both did worse job with code completion then PyDev with my
simple example. 

In my opinion PyDev code completion is really superior to Komodo's and
WingIDE's...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pydev code completion problem

2007-10-14 Thread Steven D'Aprano
On Sun, 14 Oct 2007 21:57:12 +, Lukasz Mierzejewski wrote:

> On Sun, 14 Oct 2007 20:36:07 +, cyberco wrote:
> 
>> Confirmed (with exactly the same software).
>> 
>> Please discuss this issue at the PyDev discussion forum:
>> http://sourceforge.net/forum/forum.php?forum_id=293649
> 
> 
> Thank you for replay, but I'm still not sure what to think about it...
> Marc 'BlackJack' Rintsch in his replay to my post says that it would be
> to complicated for IDE to keep track of all objects... isn't he right?


*shakes head sadly*

Young programmers today, with your IDEs and code completion and syntax 
highlighting... when I was your age, we used "ed" and liked it!


http://www.gnu.org/fun/jokes/ed.msg.html



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


Re: compile for ARM

2007-10-14 Thread mickeyl
Rafael Marin Perez <[EMAIL PROTECTED]> wrote:
> Hello
> 
> I'm Rafael Marin, and work as reseacher in University of Murcia (Spain).
> 
> I want to install and compile modules of python2.4 in a ARMv5b
> architecture.
> 
> Any idea?

Use OpenEmbedded [http://openembedded.org], I've already done everything
that's necessary to get a fine-grained packaged Python distribution from there.

By the power of OE, I'm using Python on my Linksys NSLU2, my Neo1973 mobile
phone, my Zaurus, my iPAQ, etc. :)

Cheers,

Mickey.

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


hi hi hi

2007-10-14 Thread Tagrislam
Hi Hi Hi
my name is tagreed  , I am from Syria
I've seen many places of the world on TV screen and few that I've
visited either for fun or/ and business
as you know when we travel we meet a lot different cultures and
people.
I found in many places I've been to ; that people stereotyped Islam
(that's my religion ) they prejudge Muslims from what they see in
media incidents.
Allow me to share with you here some information about Jesus Christ .
Muslims believe in Jesus Christ ( peace and blessings of ( Allah=god )
be upon him as one of the mightiest messengers from ( Allah = god ).
We believe he is born miraculously by the word of Allah without father
Like ADAM Been created without father nor mother.
And marry ( mar yam ) is his mother the pious . pure female nay Allah
be pleased with her.

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


Re: pydev code completion problem

2007-10-14 Thread Diez B. Roggisch
Lukasz Mierzejewski schrieb:
> On Sun, 14 Oct 2007 20:36:07 +, cyberco wrote:
> 
>> Confirmed (with exactly the same software).
>>
>> Please discuss this issue at the PyDev discussion forum:
>> http://sourceforge.net/forum/forum.php?forum_id=293649
> 
> 
> Thank you for replay, but I'm still not sure what to think about it...
> Marc 'BlackJack' Rintsch in his replay to my post says that it would be to
> complicated for IDE to keep track of all objects... isn't he right?

He is right. What would you expect from this piece of code:


foo = random.choose([A(), B(), C(), ..., Z()])



What PyDev does is to implement some heuristics that can guess easy 
cases - as you saw for yourself. But there is a limit to what can be 
done. Instead, it might even introduce errors.

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


Re: pydev code completion problem

2007-10-14 Thread Lukasz Mierzejewski
On Sun, 14 Oct 2007 20:36:07 +, cyberco wrote:

> Confirmed (with exactly the same software).
> 
> Please discuss this issue at the PyDev discussion forum:
> http://sourceforge.net/forum/forum.php?forum_id=293649


Thank you for replay, but I'm still not sure what to think about it...
Marc 'BlackJack' Rintsch in his replay to my post says that it would be to
complicated for IDE to keep track of all objects... isn't he right?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pydev code completion problem

2007-10-14 Thread Lukasz Mierzejewski
> I can confirm and it's something I would expect.  It is obvious to *you*
> that there is a `One` object in that list, but it would get very

Thank you for confirmation and your time!

> quickly very complicated for an IDE to keep track of objects if not
> even impossible.

I guess that you are right, but I wonder if there exists some
'tricks/magic' to overcome the fact that python is dynamically typed...

Tomorrow I will try Wing IDE...
But maybe someone use Komodo IDE or Wing IDE and can tell how they handle
situations like this? How works code completion in those IDE's?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: int to str in list elements..

2007-10-14 Thread John Machin
On Oct 15, 4:02 am, Abandoned <[EMAIL PROTECTED]> wrote:
> Hi..
> I have a list as a=[1, 2, 3  ] (4 million elements)
> and
> b=",".join(a)
> than
> TypeError: sequence item 0: expected string, int found
> I want to change list to  a=['1','2','3'] but i don't want to use FOR
> because my list very very big.

What is your worry: memory or time? The result string will be very
very very big. What will you do with the result string -- write it to
a file? If so, look at the cPickle module.

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


Re: Simple Text Processing Help

2007-10-14 Thread John Machin
On Oct 14, 11:48 pm, [EMAIL PROTECTED] wrote:
> Hi all,
>
> I started Python just a little while ago and I am stuck on something
> that is really simple, but I just can't figure out.
>
> Essentially I need to take a text document with some chemical
> information in Czech and organize it into another text file.  The
> information is always EINECS number, CAS, chemical name, and formula
> in tables.  I need to organize them into lines with | in between.  So
> it goes from:
>
> 200-763-1 71-73-8
> nátrium-tiopentál   C11H18N2O2S.Na   to:
>
> 200-763-1|71-73-8|nátrium-tiopentál|C11H18N2O2S.Na
>
> but if I have a chemical like: kyselina močová
>
> I get:
> 200-720-7|69-93-2|kyselina|močová
> |C5H4N4O3|200-763-1|71-73-8|nátrium-tiopentál
>
> and then it is all off.
>
> How can I get Python to realize that a chemical name may have a space
> in it?
>

Your input file could be in one of THREE formats:
(1) fields are separated by TAB characters (represented in Python by
the escape sequence '\t', and equivalent to '\x09')
(2) fields are fixed width and padded with spaces
(3) fields are separated by a random number of whitespace characters
(and can contain spaces).

What makes you sure that you have format 3? You might like to try
something like
lines = open('your_file.txt').readlines()[:4]
print lines
print map(len, lines)
This will print a *precise* representation of what is in the first
four lines, plus their lengths. Please show us the output.

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

Newbi Q: Recursively reverse lists but NOT strings?

2007-10-14 Thread Dmitri O.Kondratiev
The function I wrote (below) reverses lists all right:

def reverse(xs):
if xs == []:
return []
else:
return (reverse (xs[1:])) + [xs[0]]


>>> reverse ([1,2,3])
[3, 2, 1]
>>>


Yet when I try to reverse a string I  get:

>>> reverse ("abc")

...
...
...

  File "C:\wks\python-wks\reverse.py", line 5, in reverse

return (reverse (xs[1:])) + [xs[0]]

  File "C:\wks\python-wks\reverse.py", line 5, in reverse

return (reverse (xs[1:])) + [xs[0]]

  File "C:\wks\python-wks\reverse.py", line 2, in reverse

if xs == []:

RuntimeError: maximum recursion depth exceeded in cmp

>>>

What's wrong? Why recursion never stops?

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

Re: pydev code completion problem

2007-10-14 Thread cyberco
Confirmed (with exactly the same software).

Please discuss this issue at the PyDev discussion forum:
http://sourceforge.net/forum/forum.php?forum_id=293649

2B

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


Re: Python on imac

2007-10-14 Thread Erik Jones

On Oct 13, 2007, at 8:23 PM, Adam Atlas wrote:

> On Oct 13, 7:21 pm, John Velman <[EMAIL PROTECTED]> wrote:
>> I'm considering moving from Linux to imac.   I've recently  
>> returned to
>> Python (was never very expert) to develop a small gui  
>> application.  At
>> present I plan to use PyGTK with Pango and Cairo.
>>
>> What surprises may I be in for :-)
>>
>> (Currently using slackware 11.0 on an old (8 years) slow (400mhz)  
>> machine.)
>>
>> Thanks,
>>
>> John Velman
>
> Well... I think OS X currently comes with Python 2.3 or 2.4. I
> recommend getting Fink (fink.sourceforge.net), which is basically a
> DPKG/APT repository for OS X plus an added system for automatically
> building packages from source. It'll keep the system up to date with
> the latest 2.5 release (and future versions).
>
> If you're using PyGTK, you will need to install Apple X11 (can't
> remember if it's installed by default yet), since OS X's window
> manager is not X11-based. Fink can also install GTK+, etc. for you.
> Other than that, most things should work as on Linux, more or less.

He doesn't need Fink for up to date Python version as os x binaries  
are available from the www.python.org.

Erik Jones

Software Developer | Emma®
[EMAIL PROTECTED]
800.595.4401 or 615.292.5888
615.292.0777 (fax)

Emma helps organizations everywhere communicate & market in style.
Visit us online at http://www.myemma.com


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


Re: pydev code completion problem

2007-10-14 Thread Marc 'BlackJack' Rintsch
On Sun, 14 Oct 2007 19:45:07 +, Lukasz Mierzejewski wrote:

> Let's assume that we have something like this:
> 
> class One:
>   def fun(self):
>   return 1
> 
> class Two:
>   li = []
>   li.append(One())
> 
>   one = li[0]
>   print one.fun()
> 
>   one2 = li.pop()
>   print one2.fun()
> 
>   one3 = One()
>   print one3.fun()

Indention is messed up here.  At least the ``return`` in `One.fun()`.  And
what is class `Two` meant to do?

> Only for 'one3' variable code completion is working fine (as expected it
> show fun()).
> For 'one' code completion shows something (but not fun()).
> For 'one2' code completion shows nothing :-(
> 
> I use Eclipse 3.3.1 with PyDev 1.3.9 on Ubuntu 7.04.
> 
> Can anyone confirm or deny this behavior of PyDev?

I can confirm and it's something I would expect.  It is obvious to *you*
that there is a `One` object in that list, but it would get very quickly
very complicated for an IDE to keep track of objects if not even
impossible.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cross-platform GUI development

2007-10-14 Thread David Tremouilles
"crappy",  "waaay better"
I will not feed the troll...
Pygtk on mac just do the work for me on a more than satisfying way.

David

2007/10/13, Diez B. Roggisch <[EMAIL PROTECTED]>:
> David Tremouilles schrieb:
> > No issue with pygtk on mac!
> > Actually I develop on this platform everyday. Macport take care of the
> > installation for me http://www.macports.org/ (Fink should do the work
> > too).
> > Of course native GTK on OSX could be nice but definitely not needed at
> > this point in time.
>
> It sure looks crappy in comparison to the rest of the OSX apps - and
> given that with Qt (and of course the brilliant PyObjc-bridge) there
> exist options that look & feel waaay better, I wouldn't consider using GTK.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Order of tuples in dict.items()

2007-10-14 Thread Erik Max Francis
Will McGugan wrote:

> If I have two dictionaries containing identical values, can I be sure 
> that the items() method will return tuples in the same order?
> 
> I tried an experiment with CPython and it does appear to be the case.
> 
>  >>> a=dict(a=1, b=1, c=2)
>  >>> b=dict(c=2, a=1, b=1)
>  >>> a
> {'a': 1, 'c': 2, 'b': 1}
>  >>> b
> {'a': 1, 'c': 2, 'b': 1}
>  >>> a.items()
> [('a', 1), ('c', 2), ('b', 1)]
>  >>> b.items()
> [('a', 1), ('c', 2), ('b', 1)]
> 
> Can I rely on this behavior?

Probably not.  Dictionaries do not have an ordering that you should 
count on.  In practice, the order in which you get the items if you 
iterate over a dictionary is dependent on the hashing function, which 
can potentially change over time.

This is a case where most implementations _probably_ will return 
identical dictionaries in the same order when iterated over (of course, 
different implementations will have different orderings, but you don't 
care about that), but I wouldn't take the chance and rely on such an 
implementation detail.

If you want to keep track of the order in which objects were added to a 
dictionary, you'll need to keep a separate list of (sorted) keys, which 
is easy enough.  If you're lazy there are plenty of recipes around for 
things like `SortedDictionary` or `sorteddict`.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   The public cannot be too curious concerning the characters of public
men. -- Samuel Adams
-- 
http://mail.python.org/mailman/listinfo/python-list


pydev code completion problem

2007-10-14 Thread Lukasz Mierzejewski
Hi, I need help with pydev code completion...

Let's assume that we have something like this:

class One:
def fun(self):
return 1

class Two:
li = []
li.append(One())

one = li[0]
print one.fun()

one2 = li.pop()
print one2.fun()

one3 = One()
print one3.fun()

Only for 'one3' variable code completion is working fine (as expected it
show fun()).
For 'one' code completion shows something (but not fun()).
For 'one2' code completion shows nothing :-(

I use Eclipse 3.3.1 with PyDev 1.3.9 on Ubuntu 7.04.

Can anyone confirm or deny this behavior of PyDev?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: int to str in list elements..

2007-10-14 Thread Tobias K.
1. Use a generator expression:
b = ",".join(str(i) for i in a)

or

2. Use imap
from itertools import imap
b = ",".join(imap(str, a))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python on imac

2007-10-14 Thread John Velman
Thanks to all.  I'll look into wx before I get too much further.

John V.

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


Re: Python on imac

2007-10-14 Thread Alex Martelli
Raffaele Salmaso <[EMAIL PROTECTED]> wrote:

> Alex Martelli wrote:
> > I use Mac OSX 10.4 and this assertion seems unfounded -- I can't see any
> > wx as part of the stock Python (2.3.5).  Maybe you mean something else?
> Very old version, see
> /System/Library/Frameworks/Python.framework/Versions/2.3/Extras/lib/python
> /wx-2.5.3-mac-unicode
>

Ah, I see it now, thanks.


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


int to str in list elements..

2007-10-14 Thread Abandoned
Hi..
I have a list as a=[1, 2, 3  ] (4 million elements)
and
b=",".join(a)
than
TypeError: sequence item 0: expected string, int found
I want to change list to  a=['1','2','3'] but i don't want to use FOR
because my list very very big.
I'm sorry my bad english.
King regards

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


Re: Simple Text Processing Help

2007-10-14 Thread Marc 'BlackJack' Rintsch
On Sun, 14 Oct 2007 16:57:06 +, patrick.waldo wrote:

> Thank you both for helping me out.  I am still rather new to Python
> and so I'm probably trying to reinvent the wheel here.
> 
> When I try to do Paul's response, I get
tokens = line.strip().split()
> []

What is in `line`?  Paul wrote this in the body of the ``for`` loop over
all the lines in the file.

> So I am not quite sure how to read line by line.

That's what the ``for`` loop over a file or file-like object is doing. 
Maybe you should develop your script in smaller steps and do some printing
to see what you get at each step.  For example after opening the input
file:

for line in input:
print line # prints the whole line.
tokens = line.split()
print tokens   # prints a list with the split line.

> tokens = input.read().split() gets me all the information from the
> file.

Right it reads *all* of the file, not just one line.

>  tokens[2:-1] = [u' '.join(tokens[2:-1])] works just fine, like
> in the example; however, how can I loop this for the entire document?

Don't read the whole file but line by line, just like Paul showed you.

> Also, when I try output.write(tokens), I get "TypeError: coercing to
> Unicode: need string or buffer, list found".

`tokens` is a list but you need to write a unicode string.  So you have to
reassemble the parts with '|' characters in between.  Also shown by Paul.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Last iteration?

2007-10-14 Thread Paul McGuire
On Oct 14, 5:58 am, Paul Hankin <[EMAIL PROTECTED]> wrote:
> On Oct 14, 8:00 am, Paul McGuire <[EMAIL PROTECTED]> wrote:
> > def signal_last(lst):
> > last2 = None
> > it = iter(lst)
> > try:
> > last = it.next()
> > except StopIteration:
> > last = None
> > for last2 in it:
> > yield False, last
> > last = last2
> > yield True, last
>
> This yields a value when the iterator is empty, which Diez's solution
> didn't. Logically, there is no 'last' element in an empty sequence,
> and it's obscure to add one. Peter Otten's improvement to Diez's code
> looks the best to me: simple, readable and correct.
>

Of course!  For some reason I thought I was improving Peter Otten's
version, but when I modified my submission to behave as you stated, I
ended right back with what Peter had submitted.  Agreed - nice and
neat!

-- Paul


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


Re: Python on imac

2007-10-14 Thread Raffaele Salmaso
Alex Martelli wrote:
> I use Mac OSX 10.4 and this assertion seems unfounded -- I can't see any
> wx as part of the stock Python (2.3.5).  Maybe you mean something else?
Very old version, see
/System/Library/Frameworks/Python.framework/Versions/2.3/Extras/lib/python/wx-2.5.3-mac-unicode
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Text Processing Help

2007-10-14 Thread patrick . waldo
Thank you both for helping me out.  I am still rather new to Python
and so I'm probably trying to reinvent the wheel here.

When I try to do Paul's response, I get
>>>tokens = line.strip().split()
[]

So I am not quite sure how to read line by line.

tokens = input.read().split() gets me all the information from the
file.  tokens[2:-1] = [u' '.join(tokens[2:-1])] works just fine, like
in the example; however, how can I loop this for the entire document?
Also, when I try output.write(tokens), I get "TypeError: coercing to
Unicode: need string or buffer, list found".

Any ideas?

















On Oct 14, 4:25 pm, Paul Hankin <[EMAIL PROTECTED]> wrote:
> On Oct 14, 2:48 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > Hi all,
>
> > I started Python just a little while ago and I am stuck on something
> > that is really simple, but I just can't figure out.
>
> > Essentially I need to take a text document with some chemical
> > information in Czech and organize it into another text file.  The
> > information is always EINECS number, CAS, chemical name, and formula
> > in tables.  I need to organize them into lines with | in between.  So
> > it goes from:
>
> > 200-763-1 71-73-8
> > nátrium-tiopentál   C11H18N2O2S.Na   to:
>
> > 200-763-1|71-73-8|nátrium-tiopentál|C11H18N2O2S.Na
>
> > but if I have a chemical like: kyselina močová
>
> > I get:
> > 200-720-7|69-93-2|kyselina|močová
> > |C5H4N4O3|200-763-1|71-73-8|nátrium-tiopentál
>
> > and then it is all off.
>
> > How can I get Python to realize that a chemical name may have a space
> > in it?
>
> In the original file, is every chemical on a line of its own? I assume
> it is here.
>
> You might use a regexp (look at the re module), or I think here you
> can use the fact that only chemicals have spaces in them. Then, you
> can split each line on whitespace (like you're doing), and join back
> together all the words between the 3rd (ie index 2) and the last (ie
> index -1) using tokens[2:-1] = [u' '.join(tokens[2:-1])]. This uses
> the somewhat unusual python syntax for replacing a section of a list
> with another list.
>
> The approach you took involves reading the whole file, and building a
> list of all the chemicals which you don't seem to use: I've changed it
> to a per-line version and removed the big lists.
>
> path = "c:\\text_samples\\chem_1_utf8.txt"
> path2 = "c:\\text_samples\\chem_2.txt"
> input = codecs.open(path, 'r','utf8')
> output = codecs.open(path2, 'w', 'utf8')
>
> for line in input:
> tokens = line.strip().split()
> tokens[2:-1] = [u' '.join(tokens[2:-1])]
> chemical = u'|'.join(tokens)
> print chemical + u'\n'
> output.write(chemical + u'\r\n')
>
> input.close()
> output.close()
>
> Obviously, this isn't tested because I don't have your chem_1_utf8.txt
> file.
>
> --
> Paul Hankin


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

Re: GLE-like python package

2007-10-14 Thread Wildemar Wildenburger
Cesar G. Miguel wrote:
> I think this is what you're looking for:
> 
> http://pyx.sourceforge.net/
> 
It damn sure is (a straight ripoff of GLE ;))!

The syntax seems a bit messier than GLE (naturally) but since it is 
python I'm willing to bite that bullet.

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


Re: Python on imac

2007-10-14 Thread Kevin Walzer
Alex Martelli wrote:
> James Stroud <[EMAIL PROTECTED]> wrote:
>...
>> For OS X 10.4, wx has come as part of the stock python install. You may
> 
> I use Mac OSX 10.4 and this assertion seems unfounded -- I can't see any
> wx as part of the stock Python (2.3.5).  Maybe you mean something else?
> 
> 
> Alex

It's a very old version of wxPython: 2.5.3, I think. Run ls /usr/lib | 
grep wx and see what you get. Do likewise for ls /Library/Python/2.3 | 
grep wx.

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


Re: GLE-like python package

2007-10-14 Thread Cesar G. Miguel
On Oct 14, 12:54 pm, Wildemar Wildenburger
<[EMAIL PROTECTED]> wrote:
> Hello there,
>
> I'm exploring possibilities of using python as an alternative to Matlab.
> The obvious way to go seems to be matplotlib for plotting, but I do like
> GLE http://glx.sourceforge.net/> a lot. One reason is that with GLE
> you can also do diagrams, that is, descriptive pictures (like
> http://glx.sourceforge.net/examples/diagrams/index.html>)
>
> Is there anything similar for python?
>
> /W

I think this is what you're looking for:

http://pyx.sourceforge.net/

Cesar

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


Re: Python on imac

2007-10-14 Thread Alex Martelli
James Stroud <[EMAIL PROTECTED]> wrote:
   ...
> For OS X 10.4, wx has come as part of the stock python install. You may

I use Mac OSX 10.4 and this assertion seems unfounded -- I can't see any
wx as part of the stock Python (2.3.5).  Maybe you mean something else?


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


GLE-like python package

2007-10-14 Thread Wildemar Wildenburger
Hello there,

I'm exploring possibilities of using python as an alternative to Matlab. 
The obvious way to go seems to be matplotlib for plotting, but I do like 
GLE http://glx.sourceforge.net/> a lot. One reason is that with GLE 
you can also do diagrams, that is, descriptive pictures (like 
http://glx.sourceforge.net/examples/diagrams/index.html>)

Is there anything similar for python?

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


Re: Python on imac

2007-10-14 Thread byte8bits
On Oct 14, 1:27 am, James Stroud <[EMAIL PROTECTED]> wrote:

> For OS X 10.4, wx has come as part of the stock python install. You may
> want to consider going that route if you develop exclusively for OS
> X--it will keep the size of your distribution down.
>
> James

wx works well on Macs... Linux and Windows too. I second this
suggestion.

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


Re: Entering username & password automatically using urllib.urlopen

2007-10-14 Thread byte8bits
On Oct 13, 11:41 pm, rodrigo <[EMAIL PROTECTED]> wrote:
> I am trying to retrieve a password protected page using:
>
> get = urllib.urlopen('http://password.protected.url";').read()
>
> While doing this interactively, I'm asked for  the username, then the
> password at the terminal.
> Is there any way to do this non-interactively? To hardcode the user/
> pass into the script so I can get the page automatically?
>
> (This is not a cracking attempt, I am trying to retrieve a page I have
> legitimate access to, just doing it automatically when certain
> conditions are met.)
>
> Thanks,
>
> Rodrigo

The pexpect module works nicely for automating tasks that normally
require user interaction.

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


Re: Order of tuples in dict.items()

2007-10-14 Thread Paul Hankin
On Oct 14, 3:28 pm, Will McGugan <[EMAIL PROTECTED]> wrote:
> If I have two dictionaries containing identical values, can I be sure
> that the items() method will return tuples in the same order?
> ...
> Can I rely on this behavior?

No. To quote the python documentation:

> Keys and values are listed in an arbitrary order which is
> non-random, varies across Python implementations, and
> depends on the dictionary's history of insertions and deletions.

In general, looking at documentation is better than experimenting when
you want to know if something is either always true or mostly true.

--
Paul Hankin

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


Order of tuples in dict.items()

2007-10-14 Thread Will McGugan
Hi,

If I have two dictionaries containing identical values, can I be sure 
that the items() method will return tuples in the same order?

I tried an experiment with CPython and it does appear to be the case.

 >>> a=dict(a=1, b=1, c=2)
 >>> b=dict(c=2, a=1, b=1)
 >>> a
{'a': 1, 'c': 2, 'b': 1}
 >>> b
{'a': 1, 'c': 2, 'b': 1}
 >>> a.items()
[('a', 1), ('c', 2), ('b', 1)]
 >>> b.items()
[('a', 1), ('c', 2), ('b', 1)]

Can I rely on this behavior?

Regards,

Will McGugan

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


Re: Simple Text Processing Help

2007-10-14 Thread Paul Hankin
On Oct 14, 2:48 pm, [EMAIL PROTECTED] wrote:
> Hi all,
>
> I started Python just a little while ago and I am stuck on something
> that is really simple, but I just can't figure out.
>
> Essentially I need to take a text document with some chemical
> information in Czech and organize it into another text file.  The
> information is always EINECS number, CAS, chemical name, and formula
> in tables.  I need to organize them into lines with | in between.  So
> it goes from:
>
> 200-763-1 71-73-8
> nátrium-tiopentál   C11H18N2O2S.Na   to:
>
> 200-763-1|71-73-8|nátrium-tiopentál|C11H18N2O2S.Na
>
> but if I have a chemical like: kyselina močová
>
> I get:
> 200-720-7|69-93-2|kyselina|močová
> |C5H4N4O3|200-763-1|71-73-8|nátrium-tiopentál
>
> and then it is all off.
>
> How can I get Python to realize that a chemical name may have a space
> in it?

In the original file, is every chemical on a line of its own? I assume
it is here.

You might use a regexp (look at the re module), or I think here you
can use the fact that only chemicals have spaces in them. Then, you
can split each line on whitespace (like you're doing), and join back
together all the words between the 3rd (ie index 2) and the last (ie
index -1) using tokens[2:-1] = [u' '.join(tokens[2:-1])]. This uses
the somewhat unusual python syntax for replacing a section of a list
with another list.

The approach you took involves reading the whole file, and building a
list of all the chemicals which you don't seem to use: I've changed it
to a per-line version and removed the big lists.

path = "c:\\text_samples\\chem_1_utf8.txt"
path2 = "c:\\text_samples\\chem_2.txt"
input = codecs.open(path, 'r','utf8')
output = codecs.open(path2, 'w', 'utf8')

for line in input:
tokens = line.strip().split()
tokens[2:-1] = [u' '.join(tokens[2:-1])]
chemical = u'|'.join(tokens)
print chemical + u'\n'
output.write(chemical + u'\r\n')

input.close()
output.close()

Obviously, this isn't tested because I don't have your chem_1_utf8.txt
file.

--
Paul Hankin

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

a good website for softwares,sports,movies and music ,sex etc.

2007-10-14 Thread panguohua
www.space666.com



good!

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


[no subject]

2007-10-14 Thread 353851029352


01smil;Name=01smil
Description: application/smil
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Simple Text Processing Help

2007-10-14 Thread Marc 'BlackJack' Rintsch
On Sun, 14 Oct 2007 13:48:51 +, patrick.waldo wrote:

> Essentially I need to take a text document with some chemical
> information in Czech and organize it into another text file.  The
> information is always EINECS number, CAS, chemical name, and formula
> in tables.  I need to organize them into lines with | in between.  So
> it goes from:
> 
> 200-763-1 71-73-8
> nátrium-tiopentál   C11H18N2O2S.Na   to:

Is that in *one* line in the input file or two lines like shown here?

> 200-763-1|71-73-8|nátrium-tiopentál|C11H18N2O2S.Na
> 
> but if I have a chemical like: kyselina močová
> 
> I get:
> 200-720-7|69-93-2|kyselina|močová
> |C5H4N4O3|200-763-1|71-73-8|nátrium-tiopentál
> 
> and then it is all off.
> 
> How can I get Python to realize that a chemical name may have a space
> in it?

If the two elements before and the one element after the name can't
contain spaces it is easy:  take the first two and the last as it is and
for the name take from the third to the next to last element = the name
and join them with a space.

In [202]: parts = '123 456 a name with spaces 789'.split()

In [203]: parts[0]
Out[203]: '123'

In [204]: parts[1]
Out[204]: '456'

In [205]: ' '.join(parts[2:-1])
Out[205]: 'a name with spaces'

In [206]: parts[-1]
Out[206]: '789'

This works too if the name doesn't have a space in it:

In [207]: parts = '123 456 name 789'.split()

In [208]: parts[0]
Out[208]: '123'

In [209]: parts[1]
Out[209]: '456'

In [210]: ' '.join(parts[2:-1])
Out[210]: 'name'

In [211]: parts[-1]
Out[211]: '789'

> #read and enter into a list
> chem_file = []
> chem_file.append(input.read())

This reads the whole file and puts it into a list.  This list will
*always* just contain *one* element.  So why a list at all!?

> #split words and store them in a list
> for word in chem_file:
> words = word.split()

*If* the list would contain more than one element all would be processed
but only the last is bound to `words`.  You could leave out `chem_file` and
the loop and simply do:

words = input.read().split()

Same effect but less chatty.  ;-)

The rest of the source seems to indicate that you don't really want to read
in the whole input file at once but process it line by line, i.e. chemical
element by chemical element.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Simple Text Processing Help

2007-10-14 Thread patrick . waldo
Hi all,

I started Python just a little while ago and I am stuck on something
that is really simple, but I just can't figure out.

Essentially I need to take a text document with some chemical
information in Czech and organize it into another text file.  The
information is always EINECS number, CAS, chemical name, and formula
in tables.  I need to organize them into lines with | in between.  So
it goes from:

200-763-1 71-73-8
nátrium-tiopentál   C11H18N2O2S.Na   to:

200-763-1|71-73-8|nátrium-tiopentál|C11H18N2O2S.Na

but if I have a chemical like: kyselina močová

I get:
200-720-7|69-93-2|kyselina|močová
|C5H4N4O3|200-763-1|71-73-8|nátrium-tiopentál

and then it is all off.

How can I get Python to realize that a chemical name may have a space
in it?

Thank you,
Patrick

So far I have:

#take tables in one text file and organize them into lines in another

import codecs

path = "c:\\text_samples\\chem_1_utf8.txt"
path2 = "c:\\text_samples\\chem_2.txt"
input = codecs.open(path, 'r','utf8')
output = codecs.open(path2, 'w', 'utf8')

#read and enter into a list
chem_file = []
chem_file.append(input.read())

#split words and store them in a list
for word in chem_file:
words = word.split()

#starting values in list
e=0   #EINECS
c=1   #CAS
ch=2  #chemical name
f=3   #formula

n=0
loop=1
x=len(words)  #counts how many words there are in the file

print '-'*100
while loop==1:
if nhttp://mail.python.org/mailman/listinfo/python-list

Re: Safely dealing with arbitrary file objects

2007-10-14 Thread Paul Hankin
On Oct 14, 5:01 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> I have found myself writing functions rather like these:
>
> def openfile(filename):
> if filename == '-':
> # convention for shell scripts in Unix-land is to use
> # '-' for stdin/stdout for reading/writing.
> outfile = sys.stdout
> if filename == '2-':
> outfile = sys.stderr
> else:
> outfile = file(filename, 'w')
> return outfile
>
> def closefile(fileobj):
> # don't close standard file objects, or their replacements
> if not fileobj in (sys.stdout, sys.stderr, sys.stdin,
> sys.__stdout__, sys.__stderr__, sys.__stdin__):
> fileobj.close()
>
> def processfile(filename):
> outfile = openfile(filename)
> try:
> # lots of processing here, which may raise exceptions
> var = "stuff happens"
> outfile.write(var)
> finally:
> closefile(outfile)
>
> A question:
>
> I know I'm being paranoid about not closing files I shouldn't close, but
> am I being excessively paranoid, or not paranoid enough?
>
> Suggestions for improvements welcome; while I'm happy to read suggestions
> using the new with statement, I can't yet rely on having Python 2.5 or
> better so I have to stick to try...finally.

With with:

import sys

class leave_open(object):
def __init__(self, obj):
self.obj = obj
def __enter__(self):
return self.obj
def __exit__(self, *exc_info):
pass

def open_file(name, special={'-':sys.stdout, '2-':sys.stderr}):
if name in special:
return leave_open(special[name])
else:
return open(name, 'w')

def process_file(filename):
with open_file(filename) as outfile:
outfile.write("stuff happens")


Without with:

import sys

def open_file(name, special={'-':sys.stdout, '2-':sys.stderr}):
if name in special:
return False, special[name]
return True, open(name, 'w')

def process_file(filename):
should_close, outfile = open_file(filename)
try:
outfile.write('stuff happens')
finally:
if should_close:
outfile.close()

--
Paul Hankin

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


Re: Last iteration?

2007-10-14 Thread Diez B. Roggisch
Peter Otten schrieb:
> Diez B. Roggisch wrote:
> 
>> Florian Lindner wrote:
> 
>>> can I determine somehow if the iteration on a list of values is the
>>> last iteration?
> 
>>  def last_iter(iterable):
>> it = iter(iterable)
>> buffer = [it.next()]
>> for i in it:
>> buffer.append(i)
>> old, buffer = buffer[0], buffer[1:]
>> yield False, old
>> yield True, buffer[0]
> 
> This can be simplified a bit since you never have to remember more than on
> item:
> 
 def mark_last(items):
> ... items = iter(items)
> ... last = items.next()
> ... for item in items:
> ... yield False, last
> ... last = item
> ... yield True, last
> ...
 list(mark_last([]))
> []
 list(mark_last([1]))
> [(True, 1)]
 list(mark_last([1,2]))
> [(False, 1), (True, 2)]

Nice.

I tried to come up with that solution in the first place - but most 
probably due to an java-coding induced brain overload it didn't work 
out:) But I wanted a general purpose based solution to be available that 
doesn't count on len() working on an arbitrary iterable.

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


Re: Last iteration?

2007-10-14 Thread Paul Hankin
On Oct 14, 8:00 am, Paul McGuire <[EMAIL PROTECTED]> wrote:
> On Oct 12, 5:58 am, Florian Lindner <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hello,
> > can I determine somehow if the iteration on a list of values is the last
> > iteration?
>
> > Example:
>
> > for i in [1, 2, 3]:
> >if last_iteration:
> >   print i*i
> >else:
> >   print i
>
> > that would print
>
> > 1
> > 2
> > 9
>
> > Can this be acomplished somehow?
>
> > Thanks,
>
> > Florian
>
> Maybe it's a leftover from my C++ days, but I find the iteration-based
> solutions the most appealing.  This is a refinement of the previous
> post by Diez Roggisch.  The test method seems to match your desired
> idiom pretty closely:
>
> def signal_last(lst):
> last2 = None
> it = iter(lst)
> try:
> last = it.next()
> except StopIteration:
> last = None
> for last2 in it:
> yield False, last
> last = last2
> yield True, last

This yields a value when the iterator is empty, which Diez's solution
didn't. Logically, there is no 'last' element in an empty sequence,
and it's obscure to add one. Peter Otten's improvement to Diez's code
looks the best to me: simple, readable and correct.

--
Paul Hankin

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


Re: Entering username & password automatically using urllib.urlopen

2007-10-14 Thread Diez B. Roggisch
rodrigo schrieb:
> I am trying to retrieve a password protected page using:
> 
> get = urllib.urlopen('http://password.protected.url";').read()
> 
> While doing this interactively, I'm asked for  the username, then the
> password at the terminal.
> Is there any way to do this non-interactively? To hardcode the user/
> pass into the script so I can get the page automatically?
> 
> (This is not a cracking attempt, I am trying to retrieve a page I have
> legitimate access to, just doing it automatically when certain
> conditions are met.)

Is that HTTP-auth? Then this might help:

http://www.voidspace.org.uk/python/articles/authentication.shtml

BTW, use urllib2.

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


Re: Paste and WSGI 2.0 [WAS: Yet another comparison of Python Web Frameworks]

2007-10-14 Thread Graham Dumpleton
On Oct 14, 6:46 pm, Michele Simionato <[EMAIL PROTECTED]>
wrote:
> Now, since you are here, there is an unrelated question that I want to
> ask you, concerning the future of Paste with respect to WSGI 2.0.
> I do realize that at this stage WSGI 2.0, is only a draft

Hmmm, not sure where people keep getting this idea that there exists a
WSGI 2.0 draft.

The only thing that exists that I know of is:

  http://www.wsgi.org/wsgi/WSGI_2.0

This is at this point merely a collection of ideas for change, or
areas where the existing WSGI 1.0 is deficient. There are a various
things around this where decisions would need to be made or solutions
developed before one could even consider calling it a draft. I
certainly wouldn't necessarily go off making decisions based on what
may or may not be in WSGI 2.0. :-)

Graham

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


Paste and WSGI 2.0 [WAS: Yet another comparison of Python Web Frameworks]

2007-10-14 Thread Michele Simionato
On Oct 14, 2:52 am, Ian Bicking <[EMAIL PROTECTED]> wrote:
> That said, going without a framework (which at least in his article is
> what Michele seems to be comparing Pylons against) isn't always so
> bad.  I started writing an Atompub server in Pylons, but felt like I
> was spending too much time navigating around what the framework setup
> and not enough time just paying attention to what Atompub really is.
> So I ended up writing it (as FlatAtomPub), effectively without a
> framework (though developing it at the same time as WebOb, so I leaned
> on that quite a bit).  The development went quite well, and for a web
> service like Atompub that's probably what I'd recommend (at least to
> experienced developers -- you might find yourself left to drift
> otherwise without a clear idea of where to start).
>
> But for writing a traditional web application, I'd still use Pylons.
> The choices Pylons have made are with that in mind, and it doesn't at
> all exclude other forms of development in the process.  You could
> actually drop a FlatAtomPub instance right into a Pylons app, for
> instance.  Pylons is a small enough framework that it really is quite
> reasonable to pick and choose and use a very minimal style with it.

I think we do agree entirely, it is just that the application we have
in
mind is more a collection of web services than a traditional Web
application.
Now, since you are here, there is an unrelated question that I want to
ask you, concerning the future of Paste with respect to WSGI 2.0.
I do realize that at this stage WSGI 2.0, is only a draft, still I
would
like to know:

1. if you think that WSGI 2.0 is good idea (I expect you will say
"yes")
2. if you plan to support it in Paste and if yes when (I mean, in a
month,
   in a year, in three years?)
3. if you already have thought of a migration plan and, in that case,
   what your strategy would likely be.

Thanks for sharing,



  Michele Simionato

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


Re: unicodedata implementation - categories

2007-10-14 Thread Martin v. Löwis
> 1) Why doesn't the category method raise an Exception, like the name method
> does?

As Chris explains, the result category means "Other, Not Assigned".
Python returns this category because it's the truth: for those
characters, the value of the "category" property really *is* Cn;
it means that they are not assigned.

If you are wondering how unicodedata.c comes up with the result:
the unassigned characters get a record index of 0, and that has a
category value of 0, which is "Cn".

> 2) Given that the category method doesn't currently raise an Exception,
> please could someone explain how the category is calculated? I have tried to
> figure it out based on the CPython code, but I have thus far failed, and I
> would also prefer to have it explicitly defined, rather than mandating that
> a Jython (.NET, etc) implementation uses the same (possibly non-optimal for
> Java) data structures and algorithms. 

You definitely should *not* follow the Python implementation. Instead,
the Unicode database is defined by the Unicode consortium, so the
Unicode standard is the ultimate specification.

To implement it in Java, I recommend to use java.lang.Character.getType.
If that returns java.lang.Character.UNASSIGNED, return "Cn".

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


Re: Foreign Character Problems In Python 2.5 and Tkinter

2007-10-14 Thread Juha S.
[EMAIL PROTECTED] wrote:
> As a noob I've struggled a bit, but basically what I've come up with
> is => if the information is strings and especially strings stored in
> any style of list/dict, it takes a loop to write the lines to file
> myfile[ i ] + '\n' to keep each line for Python I/O purposes. If
> you're done with Python manipulation and want WIN, MAC, or UNIX to
> begin file I/O, then, you need the consideration of 
> from the os module, or code it in yourself, e.g. '\r\n'. The fact you
> are using codec iso-latin-1 (or iso-8859-1) doesn't change the '\n'
> from Python's viewpoint -- that is: '\n' is still '\n'. When your
> efforts are I/O with binary encoding the data, it's all Python's
> viewpoint.
>
>   

Ah, it was so simple. I replaced any '\n' characters with 'os.linesep' 
in the source as you suggested, and now everything works beautifully. 
Thanks for the help, guys!
-- 
http://mail.python.org/mailman/listinfo/python-list


Pymedia audio analyzer

2007-10-14 Thread Carlos Leite
Is there any other option to analyze audio frequencies?

Or

Any here try to use pymedia to a simple audio FingerPrint.

A cant understand  what the information the asBands() really giveme.
The Docs, say that asBands() return a List of tupples  grouped by
frquenciy, and the first two values are frquency limits. But I dont
thonk so ! Its not seems to be correct!

THis is part of my output to an audio file of 2 seconds and a 1000Hz frequency
And the code is below
But I read a lot, search .. and I still cant understand what this
tuples really means.

Thanks oin advance

190.283203125;0.244085595012
211.42578125;1.08019864559
253.7109375;3.9267279307
317.138671875;9.92583847046
359.423828125;30.9667332967
422.8515625;2023.64868164
507.421875;1721.98303223
591.9921875;45.5271911621
697.705078125;6.53225898743
824.560546875;2.08980056218
972.55859375;0.794676959515
1141.69921875;0.362428373761
1331.98242188;0.29334748875
1564.55078125;0.218693238038
1839.40429688;0.278315830231
2156.54296875;0.146333972613
2537.109375;0.26632910683
2981.10351563;0.496793937683
3509.66796875;0.742335747028
4122.80273438;0.619799894445
4841.65039063;0.941718482971
5687.35351563;0.703689981014
6681.0546875;1.38942857222
7843.89648438;1.78449742244
9218.1640625;3.77672335976
190.283203125;0.194098889828
211.42578125;1.05994915962
253.7109375;3.90520095825
317.138671875;10.0715675354
359.423828125;31.0263417562
422.8515625;2023.83581543
507.421875;1721.99328613
591.9921875;45.4988830566
697.705078125;6.51365725199
824.560546875;2.10594912938
972.55859375;0.806965708733
1141.69921875;0.369390010834
1331.98242188;0.381403446198
1564.55078125;0.279652008644
1839.40429688;0.307544994354
2156.54296875;0.252535131243
2537.109375;0.34709642047
2981.10351563;0.604796524048
3509.66796875;0.553077500442
4122.80273438;1.07670492284
4841.65039063;1.21294984818
5687.35351563;1.33566446507
6681.0546875;1.47083462802
7843.89648438;2.5437119704
9218.1640625;4.14210630718
import pymedia.audio.sound as sound
import pymedia.audio.acodec as acodec
import sys

freqs=''
def playFile(file_name):
#Leitura do arquivo
file_extension = file_name.split('.' )[ -1 ].lower()
parms = {'id': acodec.getCodecID(file_extension), 'ext': file_extension}
decoder = acodec.Decoder(parms)
f = open(file_name, 'rb')
s = f.read(8192)
r = decoder.decode(s)
sampleFreqs= []
#snd = sound.Output(r.sample_rate, r.channels, sound.AFMT_S16_LE)
SAMPLES= 500
NUM_FREQS= 12
BANDS= 25
resampler= sound.Resampler( (r.sample_rate,r.channels), (r.sample_rate,1) )
analyzer= sound.SpectrAnalyzer( 1, SAMPLES, 512 )
arqb = open('saida_bands.txt' , 'w')
arqf = open('saida_freqs.txt', 'w')
arqb.write('%s \n' %(f.name))
contador = 0
while len(s)> 0:
contador = contador + 1
if r:
#snd.play(r.data)
s = f.read(512)
r = decoder.decode(s)

snd= sound.Output( r.sample_rate, r.channels, sound.AFMT_S16_LE )
s1= resampler.resample( r.data )
bTmp= analyzer.asBands( BANDS, s1 )
sampleFreqs.append( ( snd.getPosition()+ snd.getLeft(), bTmp ) )
fTmp= analyzer.asFrequencies(r.data)
#print (bTmp )
for k in bTmp:
for l in k:
#print l
arqb.write('%s;%s \n' % (l[0].__str__(),l[1].__str__(),))

arqb.write('Frame: %s \n' % (contador.__str__()))
arqf.write ('Leitura: %s \n ' % (contador.__str__()))
arqf.write ('Freq: %s \n ' % (fTmp.__str__()))
arqb.write('LOOPS: %s \n' % (contador.__str__()))
arqb.close()
arqf.close()
if __name__ == "__main__":
file_name = sys.argv[1]
playFile(file_name)

-- 
Carlos Leite
www.znc.com.br
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Last iteration?

2007-10-14 Thread Paul McGuire
On Oct 12, 5:58 am, Florian Lindner <[EMAIL PROTECTED]> wrote:
> Hello,
> can I determine somehow if the iteration on a list of values is the last
> iteration?
>
> Example:
>
> for i in [1, 2, 3]:
>if last_iteration:
>   print i*i
>else:
>   print i
>
> that would print
>
> 1
> 2
> 9
>
> Can this be acomplished somehow?
>
> Thanks,
>
> Florian

Maybe it's a leftover from my C++ days, but I find the iteration-based
solutions the most appealing.  This is a refinement of the previous
post by Diez Roggisch.  The test method seems to match your desired
idiom pretty closely:

def signal_last(lst):
last2 = None
it = iter(lst)
try:
last = it.next()
except StopIteration:
last = None
for last2 in it:
yield False, last
last = last2
yield True, last

def test(t):
for isLast, item in signal_last(t):
if isLast:
print "...and the last item is", item
else:
print item

test("ABC")
test([])
test([1,2,3])

Prints:

A
B
...and the last item is C
...and the last item is None
1
2
...and the last item is 3

-- Paul

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


Re: First class lexical closures

2007-10-14 Thread Kay Schluehr
On Oct 14, 7:54 am, Jon Harrop <[EMAIL PROTECTED]> wrote:
> Just debating somewhere else whether or not Python might be considered a
> functional programming language. Lua, Ruby and Perl all seem to provide
> first class lexical closures.
>
> What is the current state of affairs in Python? Last time I looked they were
> just removing (?!) closures...
>
> --
> Dr Jon D Harrop, Flying Frog 
> Consultancyhttp://www.ffconsultancy.com/products/?u

Python has ( ever had ) first class functions. They can be defined
everywhere within each statement and therefore within other function
definitions. They are lexical closures. Pythons support for
*anonymous* closures is somewhat weak. They are not on equal footing
with named functions and they don't play a generative role in the
language ( there is no single piece of language semantics described by
lambda expressions ). There was some willing to remove them in Python
3.0 alltogether. This decision was withdrawn but their power wasn't
extended either.


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


First class lexical closures

2007-10-14 Thread Jon Harrop

Just debating somewhere else whether or not Python might be considered a
functional programming language. Lua, Ruby and Perl all seem to provide
first class lexical closures.

What is the current state of affairs in Python? Last time I looked they were
just removing (?!) closures...

-- 
Dr Jon D Harrop, Flying Frog Consultancy
http://www.ffconsultancy.com/products/?u
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python on imac

2007-10-14 Thread James Stroud
John Velman wrote:
> I'm considering moving from Linux to imac.   I've recently returned to
> Python (was never very expert) to develop a small gui application.  At
> present I plan to use PyGTK with Pango and Cairo.
> 
> What surprises may I be in for :-)
> 
> (Currently using slackware 11.0 on an old (8 years) slow (400mhz) machine.)
> 
> Thanks,
> 
> John Velman

For OS X 10.4, wx has come as part of the stock python install. You may 
want to consider going that route if you develop exclusively for OS 
X--it will keep the size of your distribution down.

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA  90095

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


Re: Safely dealing with arbitrary file objects

2007-10-14 Thread Scott David Daniels
Steven D'Aprano wrote:
> I have found myself writing functions rather like these:
> 
> def openfile(filename):
> if filename == '-':
> # convention for shell scripts in Unix-land is to use
> # '-' for stdin/stdout for reading/writing.
> outfile = sys.stdout
> if filename == '2-':
> outfile = sys.stderr
> else:
> outfile = file(filename, 'w')
> return outfile
> 
> def closefile(fileobj):
> # don't close standard file objects, or their replacements
> if not fileobj in (sys.stdout, sys.stderr, sys.stdin, 
> sys.__stdout__, sys.__stderr__, sys.__stdin__):
> fileobj.close()
> 
> 
> def processfile(filename):
> outfile = openfile(filename)
> try:
> # lots of processing here, which may raise exceptions
> var = "stuff happens"
> outfile.write(var)
> finally:
> closefile(outfile)
> 
> 
> 
> A question:
> 
> I know I'm being paranoid about not closing files I shouldn't close, but 
> am I being excessively paranoid, or not paranoid enough?
> 
> Suggestions for improvements welcome; while I'm happy to read suggestions 
> using the new with statement, I can't yet rely on having Python 2.5 or 
> better so I have to stick to try...finally.

How about a wrapper that passes along all but 'close', so you don't
have to worry about closing something you means to leave open.
Something like:

 class DontCloseOutput(file):
 '''subclass file only to allow isinstance checks to work out'''
 def __init__(self, referent):
 self._actual = referent
 self.closed = False

 def close(self):
 self.closed = True

 def write(self, data):
 if self.closed:
 raise IOError('Tried to write closed pseudo-file')
 return self._actual.write(data)


 def writeopen(filename):
 if filename == '-':
 # convention for shell scripts in Unix-land is to use
 # '-' for stdin/stdout for reading/writing.
 return DontCloseOutput(sys.stdout)
 if filename == '2-':
 return DontCloseOutput(sys.stderr)
 else:
 return open(filename, 'w')  # BTW, open is the preferred way
 # file was for a short time.

You of course can do similar things (probably forwarding more message)
with readopen.

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


Re: Error on base64.b64decode() ?!

2007-10-14 Thread Tim Roberts
Christoph Krammer <[EMAIL PROTECTED]> wrote:

>On 12 Okt., 17:09, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
>> If you get an incorrect padding error, try appending a "=" and decoding
>> again.  If you get the error again, try appending one more "=".  If it
>> still doesn't work, then you might be out of luck.
>
>This seems to work in some cases, but not all. Whats the deal with
>this adding of "="? Is there an implementation error in python, or are
>other implemenations of base64 more robust then they have to be?

The base64 algorithm converts 3 incoming bytes to 4 encoded bytes.  When
you decode base64, the input string MUST be a multiple of 4 bytes.  Equal
signs are used to pad the strings to 4n bytes.

The web site you used might be doing that alignment for you.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Memory Problems in Windows 2003 Server

2007-10-14 Thread Tim Roberts
AMD <[EMAIL PROTECTED]> wrote:
>
>I do the reading one line at a time, the problem seems to be with the 
>dictionary I am creating.

I don't know whether Python dictionaries must live in a contiguous piece of
memory, but if so, that could be the issue.  The system DLLs in Server 2003
have been "rebased" in such a way that they chop up the virtual address
space more than XP.  Even though there is more virtual memory available, it
is fragmented.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Safely dealing with arbitrary file objects

2007-10-14 Thread Steven D'Aprano
I have found myself writing functions rather like these:

def openfile(filename):
if filename == '-':
# convention for shell scripts in Unix-land is to use
# '-' for stdin/stdout for reading/writing.
outfile = sys.stdout
if filename == '2-':
outfile = sys.stderr
else:
outfile = file(filename, 'w')
return outfile

def closefile(fileobj):
# don't close standard file objects, or their replacements
if not fileobj in (sys.stdout, sys.stderr, sys.stdin, 
sys.__stdout__, sys.__stderr__, sys.__stdin__):
fileobj.close()


def processfile(filename):
outfile = openfile(filename)
try:
# lots of processing here, which may raise exceptions
var = "stuff happens"
outfile.write(var)
finally:
closefile(outfile)



A question:

I know I'm being paranoid about not closing files I shouldn't close, but 
am I being excessively paranoid, or not paranoid enough?

Suggestions for improvements welcome; while I'm happy to read suggestions 
using the new with statement, I can't yet rely on having Python 2.5 or 
better so I have to stick to try...finally.


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


Entering username & password automatically using urllib.urlopen

2007-10-14 Thread rodrigo
I am trying to retrieve a password protected page using:

get = urllib.urlopen('http://password.protected.url";').read()

While doing this interactively, I'm asked for  the username, then the
password at the terminal.
Is there any way to do this non-interactively? To hardcode the user/
pass into the script so I can get the page automatically?

(This is not a cracking attempt, I am trying to retrieve a page I have
legitimate access to, just doing it automatically when certain
conditions are met.)

Thanks,

Rodrigo

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


Re: Python on imac

2007-10-14 Thread Tommy Nordgren

On 14 okt 2007, at 01.21, John Velman wrote:

> I'm considering moving from Linux to imac.   I've recently returned to
> Python (was never very expert) to develop a small gui application.  At
> present I plan to use PyGTK with Pango and Cairo.
>
> What surprises may I be in for :-)
>
> (Currently using slackware 11.0 on an old (8 years) slow (400mhz)  
> machine.)
>
> Thanks,
>
> John Velman
> -- 
> http://mail.python.org/mailman/listinfo/python-list
Mac OS X Tiger comes with Python 2.3 installed.
Installers for later versions are available at www.python.org
No need to use package managers
--
Skinheads are so tired of immigration, that they are going to move to  
a country that don't accept immigrants!
Tommy Nordgren
[EMAIL PROTECTED]



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