Invalid syntax with print "Hello World"

2009-03-12 Thread Henrik Bechmann
obviously total mewbiew:

My first program in Python Windows

print "Hello World"

I select Run/Run Module and get an error:

Syntax error, with the closing quote highlighted.

Tried with single quotes as well. Same problem.

Can someone explain my mistake?

Thanks,

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


Re: NameError: name 'execfile' is not defined

2009-03-12 Thread Gary Herron

Henrik Bechmann wrote:

Newbie issue:

I downloaded http://www.python.org/download/releases/3.0.1/ (windows
insaller), opened the interpreter, wrote a print "Hello World" program
in helloworld.py, and in the interpreter typed

execfile("helloworld.py")

Got back

NameError: name 'execfile' is not defined

(following tutorial in David Beazley's Python Essential Reference).

Is execfile not supported in 3?
  


That's correct. 

From http://docs.python.org/dev/3.0/whatsnew/3.0.html you can find this 
line:


   Removed execfile().   Instead of execfile(fn) use exec(open(fn).read()).

Gary Herron


Thanks,

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


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


Re: Invalid syntax with print "Hello World"

2009-03-12 Thread Gary Herron

Henrik Bechmann wrote:

obviously total mewbiew:

My first program in Python Windows

print "Hello World"

I select Run/Run Module and get an error:

Syntax error, with the closing quote highlighted.

Tried with single quotes as well. Same problem.

Can someone explain my mistake?
  


You are apparently using Python2 syntax in Python3.  Python3 has made 
some incompatible changes from previous version of Python2. 


 In Python2: print "Hello World"
 In Python3: print("Hello World")


Either download Python2.5 (or 2.6) to go with your tutorial, or find a 
Python3 tutorial to go with your Python3 installation.Once you are 
familiar with either version of the language, you will find that the 
differences are not very large, but using out-of-sync tutorials and 
implementations will be the source of much frustration.


Welcome to Python.

Enjoy.

Gary Herron




Thanks,

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


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


Re: Invalid syntax with print "Hello World"

2009-03-12 Thread Daniel Fetchinson
> obviously total mewbiew:
>
> My first program in Python Windows
>
> print "Hello World"
>
> I select Run/Run Module and get an error:
>
> Syntax error, with the closing quote highlighted.
>
> Tried with single quotes as well. Same problem.
>
> Can someone explain my mistake?

Are you using python 3.0? In this case please see:

http://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function

HTH,
Daniel



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


Re: Invalid syntax with print "Hello World"

2009-03-12 Thread John Machin
On Mar 12, 5:57 pm, Henrik Bechmann  wrote:
> obviously total mewbiew:
>
> My first program in Python Windows

What is that you are callind "Python Windows"? What version of Python
are you running?

2.X: print "Hello World"
should work.

3.X: print is now a function,
print("Hello World")
should work.

If that gets you going: read the tutorial that belongs to the version
of Python that you are using.
If it doesn't, come back here with a bit more detail.

BTW, don't indent your first line. Make sure it starts in column 1.

HTH,
John
>
> print "Hello World"
>
> I select Run/Run Module and get an error:
>
> Syntax error, with the closing quote highlighted.
>
> Tried with single quotes as well. Same problem.
>
> Can someone explain my mistake?
>
> Thanks,
>
> - Henrik

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


Rough draft: Proposed format specifier for a thousands separator

2009-03-12 Thread Raymond Hettinger
If anyone here is interested, here is a proposal I posted on the
python-ideas list.

The idea is to make numbering formatting a little easier with the new
format() builtin
in Py2.6 and Py3.0:  http://docs.python.org/library/string.html#formatspec


-


Motivation:

Provide a simple, non-locale aware way to format a number
with a thousands separator.

Adding thousands separators is one of the simplest ways to
improve the professional appearance and readability of
output exposed to end users.

In the finance world, output with commas is the norm.  Finance
users
and non-professional programmers find the locale approach to be
frustrating, arcane and non-obvious.

It is not the goal to replace locale or to accommodate every
possible convention.  The goal is to make a common task easier
for many users.


Research so far:

Scanning the web, I've found that thousands separators are
usually one of COMMA, PERIOD, SPACE, or UNDERSCORE.  The
COMMA is used when a PERIOD is the decimal separator.

James Knight observed that Indian/Pakistani numbering systems
group by hundreds.   Ben Finney noted that Chinese group by
ten-thousands.

Visual Basic and its brethren (like MS Excel) use a completely
different style and have ultra-flexible custom format specifiers
like: "_($* #,##0_)".



Proposal I (from Nick Coghlan]:

A comma will be added to the format() specifier mini-language:

[[fill]align][sign][#][0][minimumwidth][,][.precision][type]

The ',' option indicates that commas should be included in the
output as a
thousands separator. As with locales which do not use a period as
the
decimal point, locales which use a different convention for digit
separation will need to use the locale module to obtain
appropriate
formatting.

The proposal works well with floats, ints, and decimals.  It also
allows easy substitution for other separators.  For example:

format(n, "6,f").replace(",", "_")

This technique is completely general but it is awkward in the one
case where the commas and periods need to be swapped.

format(n, "6,f").replace(",", "X").replace(".", ",").replace
("X", ".")


Proposal II (to meet Antoine Pitrou's request):

Make both the thousands separator and decimal separator user
specifiable
but not locale aware.  For simplicity, limit the choices to a
comma, period,
space, or underscore..

[[fill]align][sign][#][0][minimumwidth][T[tsep]][dsep precision]
[type]

Examples:

format(1234, "8.1f")--> '  1234.0'
format(1234, "8,1f")--> '  1234,0'
format(1234, "8T.,1f")  --> ' 1.234,0'
format(1234, "8T .f")   --> ' 1 234,0'
format(1234, "8d")  --> '1234'
format(1234, "8T,d")  -->   '   1,234'

This proposal meets mosts needs (except for people wanting
grouping
for hundreds or ten-thousands), but it comes at the expense of
being a little more complicated to learn and remember.  Also, it
makes it
more challenging to write custom __format__ methods that follow
the
format specification mini-language.

For the locale module, just the "T" is necessary in a formatting
string
since the tool already has procedures for figuring out the actual
separators from the local context.



Comments and suggestions are welcome but I draw the line at supporting
Mayan numbering conventions ;-)


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


Re: Question on periods in strings

2009-03-12 Thread Gabriel Genellina
En Wed, 11 Mar 2009 23:42:45 -0200, Philip Bloom   
escribió:



Thanks for the welcome :)

You're right.  Here's with the missed line (I was cutting out commented  
parts).  Hopefully these are all cut/paste-able.


#test A
#runs in 5.8 seconds.
from datetime import datetime
testvar2='9a00'
startTime = datetime.now()
filehandle=open('testwriting.txt','w')
for var in range(1000):
filehandle.write(testvar2)
filehandle.close()
print (datetime.now() - startTime)


#test B
[using '9.00' -- otherwise identical]

I do use the same filename, but I've run the tests in different orders  
and it's made no difference.  Repeatedly running the same test results  
in the same numbers with only minor fluctuations (as would be expected  
from cache issues).  Ten runs in a row of Test B all result in about 11  
seconds each.  Ten runs in a row of Test A all result in about 6 seconds  
each.


I could not reproduce this. You've got better hardware than mine,  
certainly (I had to remove a 0 to get reasonable times) but I got almost  
identical results with both versions. I've tested also with 3.0 (and I had  
to take another 0 off!) with the same results.
I have no idea why you see a difference. Unless the antivirus is  
interfering, or you have some crazy driver monitoring disk activity and  
the dot triggers something...
Try using a different language - I'd say this is totally unrelated to  
Python.


--
Gabriel Genellina

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


Re: wxPython fast and slow

2009-03-12 Thread David Bolen
iu2  writes:

> A question about CallAfter: As I understand, this function is intended
> to be used from within threads, where it queues the operation to be
> performed in the GUI queue.

I agree with the second half of the sentence but not the first.
CallAfter is intended to queue up a delayed call (via the GUI queue),
but it can be used anywhere you wish that behavior.  Yes, it's also
one of the very few functions that can be called from a thread other
than the GUI thread, but it works just as well from the GUI thread.

Or to quote its docstring:

Call the specified function after the current and pending event
handlers have been completed.  This is also good for making GUI
method calls from non-GUI threads.  Any extra positional or
keyword args are passed on to the callable when it is called.

> How does it work in this situation? Does it queue the opreation for
> some idle time or does it perform it right away?

You can actually see the source in _core.py in your wx installation.
It always executes via a wx.PostEvent call.

> And another question, if I may, I used to make tight loops in windows
> API, planting inside them a command that processes messages from the
> GUI queue and returns when no more messages exists. Something like
> this:
>
> loop {
>   operations
>   process_gui_messages
> }
>
> The loop ran quickly and the GUI remained responsive during the loop.
> I did it on window API using a function I defined similar to this one:

I don't think there's much difference in the above and doing your
operations during one of the events.  In both cases "operations" is
going to block any further event processing so cannot be lengthy or
the GUI will feel unresponsive.  "Lengthy" varies but I'd certainly
put it in the neighborhood of small fractions of a second.

Your original code took almost 2 seconds for the "operations" part
(before getting back to processing GUI messages through the main
loop), which certainly seems too long.

> void ProcessMessages()
> {
>   while (PeekMessage()) {
> TranslateMessage(..);
> DispatchMessage(..);
>   }
> }

Not quite positive, but if you're talking about implementing this as a
nested dispatch loop (e.g., called from within an existing event), you
can do that via wxYield.  Of course, as with any nested event loop
processing, you have to be aware of possible reentrancy issues.

> This technique is not good for long loops, where the user may activate
> other long GUI opreations during the tight loop and make a mess.
> But it carries out the job well where during the time of the loop the
> user may only access to certain features, such as pressing a button to
> cancel the operation, operating the menu to exit the program, etc.
> This scheme saves some state-machine code that is required when using
> event-based programming.

Maybe - for my own part, I'm not completely convinced and tend to far
prefer avoiding nested event loop dispatching.  There are some times
when it might be unavoidable, but I tend to find it indicative that I
might want to re-examine what I am doing.

It seems to me that as long as you have to keep the "operations" step
of your loop small enough, you have to be able to divide it up.  So
you'll need some state no matter what to be able to work through each
stage of the overall "operations" in between calls to process the GUI.

At that point, whether it's a local variable within the scope of the
looping code, or just some instance variables in the object handling
the event loop seems about the same amount of state management.

For example, in your original code you could probably consider the
generator and/or 'x' your local state.  But the current step in the
movement could just as easily be an instance variable.

> Does wxPython have something like ProcessMessages?

If you just mean a way to process pending messages wxYield may be
sufficient.

If you want to take over the primary dispatch loop for the application,
normally that has been handed off to wxWidgets via wxApp.MainLoop.  However,
I believe you can build your own main dispatch loop if you want, as there
are functions in wxApp like ProcessPendingEvents, Pending, Dispatch and
so on.  You may need to explicitly continue to support Idle events in
your own loop if desired.

If you need to get into more details, it's probably better dealt with
on the wxPython mailing list.

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


Re: Stopping SocketServer on Python 2.5

2009-03-12 Thread Mark Tolonen


"Falcolas"  wrote in message 
news:[email protected]...

On Mar 11, 1:11 pm, David George  wrote:

Again, problem here is the issue of being unable to kill the server
while it's waiting on a request. In theory, i could force it to
continue by sending some sort of junk data with the method i use to
stop the server, but that seems a bit hacky, don't you think?


Dave,

I agree, it does.

I'm in a bit over my head at this point, but does setting
self.socket.settimeout(0.5) cause the call to get_request (and thus
self.socket.accept()) to timeout? If so, that may be your ticket,
since socket.error exceptions are already caught by the TCPServer
class.


Here's the relevant code from Python 2.6's SocketServer.py.  It uses 
select() to see if a request is waiting to be serviced so handle_request 
won't block.  If the poll interval expires the while loop will check the 
__serving flag.  Not ideal, but better than requiring a client to connect 
before the flag is checked.  The comment lists another idea:


  def serve_forever(self, poll_interval=0.5):
   """Handle one request at a time until shutdown.

   Polls for shutdown every poll_interval seconds. Ignores
   self.timeout. If you need to do periodic tasks, do them in
   another thread.
   """
   self.__serving = True
   self.__is_shut_down.clear()
   while self.__serving:
   # XXX: Consider using another file descriptor or
   # connecting to the socket to wake this up instead of
   # polling. Polling reduces our responsiveness to a
   # shutdown request and wastes cpu at all other times.
   r, w, e = select.select([self], [], [], poll_interval)
   if r:
   self._handle_request_noblock()
   self.__is_shut_down.set()

-Mark


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


Re: Question on periods in strings

2009-03-12 Thread John Machin
On Mar 12, 12:42 pm, "Philip Bloom"  wrote:

> The range is not actually a meaningful adjustment as the time results are 
> identical switching out xrange (as I believe they should be since in 2.6 
> range maps to xrange for the most part according to some of the docs).  

Please do
import sys; print sys.version
and copy/paste the results into your reply.

Sorry, "in 2.6 range maps to xrange for the most part" is just plain
wrong and/or meaningless. In version X.Y, nothing "maps to" anything
else, for any value of X or Y.

What you may have read is that in 2.X, range() produces a list, and
xrange() produces a magic gadget whose type is 'xrange', and that in
3.X, xrange() has disappeared, range() produces a similar gadget to
what xrange() did, and if you want a list, you have to do list(range
()). This is a very interesting phenomenon, but it *doesn't* mean that
xrange and range are equivalent for your problem.

Note that on my machine (running Python 2.6.1 under Windows XP SP 3)
doing y = range(1000) grabs about 154MB of memory. In the absence
of any information from you about how much spare memory you have,
Gabriel's point was quite valid.

What are OS (+ version etc) are you running, and how much physical
memory is free when you start running these scripts?

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


Re: Read a content file from a P7M

2009-03-12 Thread Luca
On Wed, Mar 11, 2009 at 5:05 PM, Luca  wrote:
> There is standard or sugested way in python to read the content of a P7M file?
>
> I don't need no feature like verify sign, or sign using a certificate.
> I only need to extract the content file of the p7m (a doc, a pdf, ...)

I'm there again!

I found a document and some exaples related to the M2Crypto library
http://eckhart.stderr.org/doc/python-m2crypto-doc/doc/howto.smime.html

I tryed to use this:

>>> from M2Crypto import BIO, SMIME, X509
>>> p7, data = SMIME.smime_load_pkcs7('/Users/luca/Desktop/testsigned.pdf.p7m')
Traceback (most recent call last):
  File "", line 1, in ?
  File "build/bdist.macosx-10.5-i386/egg/M2Crypto/SMIME.py", line 91,
in smime_load_pkcs7
M2Crypto.SMIME.SMIME_Error: no content type

May be this is the wrong library... but even Google can't help me a
lot with this problem :-(


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


Re: A Dangling Tk Entry

2009-03-12 Thread r
On Mar 11, 1:09 am, Marc 'BlackJack' Rintsch  wrote:

> Then he did it consequently wrong.  `frame_delay` is always `None` here
> so the ``return`` is useless.
>
> You asked what this code means and now you don't like the answer that
> it's somewhat useless code!?
>
> Ciao,
>         Marc 'BlackJack' Rintsch

Oh this is not the first time Walter has asked for help and then
scoffed at those who wish to help him. Just look back through a few of
his posts. I had ignored the other rudeness but i won't anymore.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What happened to NASA at Python? :(

2009-03-12 Thread Michele Simionato
On Mar 12, 4:26 am, r  wrote:
> On Mar 11, 10:09 pm, [email protected] wrote:
>
> > In fact, graphics were added for several organizations.  I believe they will
> > be chosen randomly.  NASA is still there.
>
> > --http://mail.python.org/mailman/listinfo/python-list
>
> Whew! Thats good news, i thought we had lost their support.

That's pretty much impossible. I am sure NASA uses all programming
languages in existence,
plus probably many internal ones we never heard of.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What happened to NASA at Python? :(

2009-03-12 Thread Mikael Olofsson

[email protected] wrote:

In fact, graphics were added for several organizations.  I believe they will
be chosen randomly.  NASA is still there.


In that case, they must be using the random number generator from 
Dilbert. You know, the one that said 9, 9, 9, 9,...


I, at least, get the same parking lot graphics every time I reload the page.

/MiO

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


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-12 Thread Raymond Hettinger
> If anyone here is interested, here is a proposal I posted on the
> python-ideas list.
>
> The idea is to make numbering formatting a little easier with
> the new format() builtin:
> http://docs.python.org/library/string.html#formatspec

Here's a re-post (hopefully without the line wrapping problems
in the previous post).

Raymond

-



Motivation:
---

Provide a simple, non-locale aware way to format a number
with a thousands separator.

Adding thousands separators is one of the simplest ways to
improve the professional appearance and readability of output
exposed to end users.

In the finance world, output with commas is the norm.  Finance
users and non-professional programmers find the locale
approach to be frustrating, arcane and non-obvious.

It is not the goal to replace locale or to accommodate every
possible convention.  The goal is to make a common task easier
for many users.


Research so far:


Scanning the web, I've found that thousands separators are
usually one of COMMA, PERIOD, SPACE, or UNDERSCORE.  The
COMMA is used when a PERIOD is the decimal separator.

James Knight observed that Indian/Pakistani numbering systems
group by hundreds.   Ben Finney noted that Chinese group by
ten-thousands.

Visual Basic and its brethren (like MS Excel) use a completely
different style and have ultra-flexible custom format
specifiers like: "_($* #,##0_)".



Proposal I (from Nick Coghlan):
---

A comma will be added to the format() specifier mini-language:

[[fill]align][sign][#][0][minimumwidth][,][.precision][type]

The ',' option indicates that commas should be included in the
output as a thousands separator. As with locales which do not
use a period as the decimal point, locales which use a
different convention for digit separation will need to use the
locale module to obtain appropriate formatting.

The proposal works well with floats, ints, and decimals.
It also allows easy substitution for other separators.
For example:

  format(n, "6,f").replace(",", "_")

This technique is completely general but it is awkward in the
one case where the commas and periods need to be swapped:

  format(n, "6,f").replace(",", "X").replace(".", ",").replace("X",
".")


Proposal II (to meet Antoine Pitrou's request):
---

Make both the thousands separator and decimal separator user
specifiable but not locale aware.  For simplicity, limit the
choices to a comma, period, space, or underscore.

[[fill]align][sign][#][0][minimumwidth][T[tsep]][dsep precision][type]

Examples:

  format(1234, "8.1f")--> '  1234.0'
  format(1234, "8,1f")--> '  1234,0'
  format(1234, "8T.,1f")  --> ' 1.234,0'
  format(1234, "8T .f")   --> ' 1 234,0'
  format(1234, "8d")  --> '1234'
  format(1234, "8T,d")--> '   1,234'

This proposal meets mosts needs (except for people wanting
grouping for hundreds or ten-thousands), but iIt comes at the
expense of being a little more complicated to learn and
remember.  Also, it makes it more challenging to write custom
__format__ methods that follow the format specification
mini-language.

For the locale module, just the "T" is necessary in a
formatting string since the tool already has procedures for
figuring out the actual separators from the local context.

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


PythonWin, python thread and PostQuitMessage?

2009-03-12 Thread arnaud
Hi All,

I'm not so much involved in any Windows programming however I needed
to write a client for the Windows platform. I have this very simple
question which I've been unable to answer. I'm listening for keyboard
strokes using the pyhook library. I'm doing this in a dedicated
thread. The gui just controls the thread. When I want to pause
listening for keyboard strokes I wanted to do a PostQuitMessage() to
the thread. However this does not work since it either kills the whole
app or just does not happen in the thread it's supposed to. I've now
made an ugly workaround using PumpWaitingMessages and a delay.

def run(self):
print "Wkeylog run called"
# Hook Keyboard
self.hm.HookKeyboard()
while self.log:
win32gui.PumpWaitingMessages()
time.sleep(0.02)

i can now just cancel the process by setting self.log to False. I
wanted to do just:

def run(self):
print "Wkeylog run called"
# Hook Keyboard
self.hm.HookKeyboard()
win32gui.PumpMessages()

However I'm unable to stop this process. Can anyone shred al light
here?

Rg,

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


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-12 Thread Ulrich Eckhardt
Raymond Hettinger wrote:
>> The idea is to make numbering formatting a little easier with
>> the new format() builtin:
>> http://docs.python.org/library/string.html#formatspec
[...]
> Scanning the web, I've found that thousands separators are
> usually one of COMMA, PERIOD, SPACE, or UNDERSCORE.  The
> COMMA is used when a PERIOD is the decimal separator.
> 
> James Knight observed that Indian/Pakistani numbering systems
> group by hundreds.   Ben Finney noted that Chinese group by
> ten-thousands.

IIRC, some cultures use a non-uniform grouping, like e.g. "123 456 78.9".
For that, there is also a grouping reserved in the locale (at least in
those of C++ IOStreams, that is). Further, an that seems to also be one of
your concerns, there are different ways to represent negative numbers like
e.g. "(123)" or "-456".


> Make both the thousands separator and decimal separator user
> specifiable but not locale aware.  For simplicity, limit the
> choices to a comma, period, space, or underscore.
> 
> [[fill]align][sign][#][0][minimumwidth][T[tsep]][dsep precision][type]
> 
> Examples:
> 
>   format(1234, "8.1f")--> '  1234.0'
>   format(1234, "8,1f")--> '  1234,0'
>   format(1234, "8T.,1f")  --> ' 1.234,0'
>   format(1234, "8T .f")   --> ' 1 234,0'
>   format(1234, "8d")  --> '1234'
>   format(1234, "8T,d")--> '   1,234'


How about this?
   format(1234, "8.1", tsep=",")
  --> ' 1,234.0'
   format(1234, "8.1", tsep=".", dsep=",")
  --> ' 1.234,0'
   format(123456, tsep=" ", grouping=(3, 2,))
  --> '1 234 56'

IOW, why not explicitly say what you want using keyword arguments with
defaults instead of inventing an IMHO cryptic, read-only mini-language?
Seriously, the problem I see with this proposal is that its aim to be as
short as possible actually makes the resulting format specifications
unreadable. Could you even guess what "8T.,1f" should mean if you had not
written this?

> This proposal meets mosts needs (except for people wanting
> grouping for hundreds or ten-thousands), but iIt comes at the
> expense of being a little more complicated to learn and
> remember.

Too expensive for my taste.

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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


__import__ with dict values

2009-03-12 Thread alex goretoy
How would I import with __import__ from dict values?
I want sys.path value inside d['syspath'], below code doesn't work for me


d={}
d['sys']='sys'
d['path']='path'

d['syspath']=__import__(d['sys'],fromlist=[d['path']])

and how come does  above line doesn't give me diff value than below line?

d['syspath']=__import__(d['sys'])

Meaning, when I do this doesn't work. Which makes sense.
d['syspath']()
d['syspath'].d['path']

but this works both with fromlist and without.

d['syspath'].path


-Alex Goretoy
http://www.goretoy.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: What happened to NASA at Python? :(

2009-03-12 Thread James Matthews
>From what I see most startups are jumping to Python to rapidly setup their
prototypes.

On Thu, Mar 12, 2009 at 10:38 AM, Mikael Olofsson  wrote:

> [email protected] wrote:
>
>> In fact, graphics were added for several organizations.  I believe they
>> will
>> be chosen randomly.  NASA is still there.
>>
>
> In that case, they must be using the random number generator from Dilbert.
> You know, the one that said 9, 9, 9, 9,...
>
> I, at least, get the same parking lot graphics every time I reload the
> page.
>
> /MiO
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://www.goldwatches.com/

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


Re: What happened to NASA at Python? :(

2009-03-12 Thread Dotan Cohen
> I, at least, get the same parking lot graphics every time I reload the page.
>

If you click "and more" link, you will come to a page of success
stories, one of which is this:
http://python.org/about/success/usa/

It is not as prominent as the earlier Nasa logo, though.

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il

א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת
ا-ب-ت-ث-ج-ح-خ-د-ذ-ر-ز-س-ش-ص-ض-ط-ظ-ع-غ-ف-ق-ك-ل-م-ن-ه‍-و-ي
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
ä-ö-ü-ß-Ä-Ö-Ü
--
http://mail.python.org/mailman/listinfo/python-list


Re: c.Win32_OperatingSystem question.

2009-03-12 Thread bryan rasmussen
Hi,

well coming back to the project and looking over it I realized I had
somehow messed up the names for some Win32 Operating System properties
- for example ComputerOrganization instead of Organization. Not sure
where I got the values from cause I've just be copying the properties
I want from scriptomatic output.




Cheers,
Bryan Rasmussen

On Sat, Feb 28, 2009 at 8:15 PM, Tim Golden  wrote:
> bryan rasmussen wrote:
>>
>> Maybe there's a more specific list I should ask this question on but I
>> don't know what it is. I'm using Tim Golden's wmi stuff, and putting
>> my output into an XML document.
>>
>> I have the following bit of code
>>
> [.. snip ...]
>>
>> At the end of that thhe only text node thaht comes out is
>> ComputerName, WMI is running - Am I using the wrong names for things
>> here? When I try to get the same values using WScript and WQL to
>> extract from Win32_OperatingSystem I get all the values.
>
>
> I'd love to help here, but you're not making it easy. I'm not
> clear if you're suggesting there's a problem with WMI or with
> ElementTree or with something else. Can you narrow down, please
> so I don't have to invent a code wrapper for your code fragment.
> Try producing an instantly-runnable piece of code which demonstrates
> the problem and I'll happily have a look from the WMI perspective at
> least.
>
> TJG
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question on periods in strings

2009-03-12 Thread Bruno Desthuilliers

Philip Bloom a écrit :
(snip)

from datetime import datetime
startTime = datetime.now()

(snip)

print (datetime.now() - startTime)


A bit OT, but you may want to use timeit.Timer for this kind of 
microbenchmarks.


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


Re: __import__ with dict values

2009-03-12 Thread alex goretoy
I have resolved this problem in my code. It has something to do with your
current working directory when you append cwd/jars to sys.path and try to
import from interactive console
-Alex Goretoy
http://www.goretoy.com



On Thu, Mar 12, 2009 at 4:58 AM, alex goretoy
wrote:

> How would I import with __import__ from dict values?
> I want sys.path value inside d['syspath'], below code doesn't work for me
>
>
> d={}
> d['sys']='sys'
> d['path']='path'
>
> d['syspath']=__import__(d['sys'],fromlist=[d['path']])
>
> and how come does  above line doesn't give me diff value than below line?
>
> d['syspath']=__import__(d['sys'])
>
> Meaning, when I do this doesn't work. Which makes sense.
> d['syspath']()
> d['syspath'].d['path']
>
> but this works both with fromlist and without.
>
> d['syspath'].path
>
>
> -Alex Goretoy
> http://www.goretoy.com
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: __import__ with dict values

2009-03-12 Thread alex goretoy
yay, no more

exec ("import " + "sys")

in my code

-Alex Goretoy
http://www.goretoy.com



On Thu, Mar 12, 2009 at 5:42 AM, alex goretoy
wrote:

> I have resolved this problem in my code. It has something to do with your
> current working directory when you append cwd/jars to sys.path and try to
> import from interactive console
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Thu, Mar 12, 2009 at 4:58 AM, alex goretoy  > wrote:
>
>> How would I import with __import__ from dict values?
>> I want sys.path value inside d['syspath'], below code doesn't work for me
>>
>>
>> d={}
>> d['sys']='sys'
>> d['path']='path'
>>
>> d['syspath']=__import__(d['sys'],fromlist=[d['path']])
>>
>> and how come does  above line doesn't give me diff value than below line?
>>
>> d['syspath']=__import__(d['sys'])
>>
>> Meaning, when I do this doesn't work. Which makes sense.
>> d['syspath']()
>> d['syspath'].d['path']
>>
>> but this works both with fromlist and without.
>>
>> d['syspath'].path
>>
>>
>> -Alex Goretoy
>> http://www.goretoy.com
>>
>>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: __import__ with dict values

2009-03-12 Thread alex goretoy
or eval for that matter
-Alex Goretoy
http://www.goretoy.com



On Thu, Mar 12, 2009 at 5:43 AM, alex goretoy
wrote:

> yay, no more
>
> exec ("import " + "sys")
>
> in my code
>
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Thu, Mar 12, 2009 at 5:42 AM, alex goretoy  > wrote:
>
>> I have resolved this problem in my code. It has something to do with your
>> current working directory when you append cwd/jars to sys.path and try to
>> import from interactive console
>> -Alex Goretoy
>> http://www.goretoy.com
>>
>>
>>
>> On Thu, Mar 12, 2009 at 4:58 AM, alex goretoy <
>> [email protected]> wrote:
>>
>>> How would I import with __import__ from dict values?
>>> I want sys.path value inside d['syspath'], below code doesn't work for me
>>>
>>>
>>> d={}
>>> d['sys']='sys'
>>> d['path']='path'
>>>
>>> d['syspath']=__import__(d['sys'],fromlist=[d['path']])
>>>
>>> and how come does  above line doesn't give me diff value than below line?
>>>
>>> d['syspath']=__import__(d['sys'])
>>>
>>> Meaning, when I do this doesn't work. Which makes sense.
>>> d['syspath']()
>>> d['syspath'].d['path']
>>>
>>> but this works both with fromlist and without.
>>>
>>> d['syspath'].path
>>>
>>>
>>> -Alex Goretoy
>>> http://www.goretoy.com
>>>
>>>
>>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: __import__ with dict values

2009-03-12 Thread alex goretoy
note i would still like to be able to do __import__("sys")."path"

maybe if __import__ had __str__ defined, How is my thinking on this?
and how would I achieve something like this?
-Alex Goretoy
http://www.goretoy.com



On Thu, Mar 12, 2009 at 5:44 AM, alex goretoy
wrote:

> or eval for that matter
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Thu, Mar 12, 2009 at 5:43 AM, alex goretoy  > wrote:
>
>> yay, no more
>>
>> exec ("import " + "sys")
>>
>> in my code
>>
>> -Alex Goretoy
>> http://www.goretoy.com
>>
>>
>>
>> On Thu, Mar 12, 2009 at 5:42 AM, alex goretoy <
>> [email protected]> wrote:
>>
>>> I have resolved this problem in my code. It has something to do with your
>>> current working directory when you append cwd/jars to sys.path and try to
>>> import from interactive console
>>> -Alex Goretoy
>>> http://www.goretoy.com
>>>
>>>
>>>
>>> On Thu, Mar 12, 2009 at 4:58 AM, alex goretoy <
>>> [email protected]> wrote:
>>>
 How would I import with __import__ from dict values?
 I want sys.path value inside d['syspath'], below code doesn't work for
 me


 d={}
 d['sys']='sys'
 d['path']='path'

 d['syspath']=__import__(d['sys'],fromlist=[d['path']])

 and how come does  above line doesn't give me diff value than below
 line?

 d['syspath']=__import__(d['sys'])

 Meaning, when I do this doesn't work. Which makes sense.
 d['syspath']()
 d['syspath'].d['path']

 but this works both with fromlist and without.

 d['syspath'].path


 -Alex Goretoy
 http://www.goretoy.com


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


Re: Invalid syntax with print "Hello World"

2009-03-12 Thread steven.oldner
On Mar 12, 2:25 am, John Machin  wrote:
> On Mar 12, 5:57 pm, Henrik Bechmann  wrote:
>
> > obviously total mewbiew:
>
> > My first program in Python Windows
>
> What is that you are callind "Python Windows"? What version of Python
> are you running?
>
> 2.X: print "Hello World"
> should work.
>
> 3.X: print is now a function,
> print("Hello World")
> should work.
>
> If that gets you going: read the tutorial that belongs to the version
> of Python that you are using.
> If it doesn't, come back here with a bit more detail.
>
> BTW, don't indent your first line. Make sure it starts in column 1.
>
> HTH,
> John
>
>
>
>
>
> > print "Hello World"
>
> > I select Run/Run Module and get an error:
>
> > Syntax error, with the closing quote highlighted.
>
> > Tried with single quotes as well. Same problem.
>
> > Can someone explain my mistake?
>
> > Thanks,
>
> > - Henrik- Hide quoted text -
>
> - Show quoted text -

Henrik,

Welcome to the list.  As a newbie myself, I ran into the Python3 vrs
2.6 issue.  May I suggest starting with 2.6?  There is many more books
and internet stuff you can learn with in 2.6 - and the examples will
work. As Garry wrote, once you understand 2.6, 3.0 will not be a
challenge.

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


Re: __import__ with dict values

2009-03-12 Thread alex goretoy
__import__(opt['imp_mod']).options

eval(opt['imp_mod']+"."+opt['imp_opt'])

how to make top work like bottom?
-Alex Goretoy
http://www.goretoy.com



On Thu, Mar 12, 2009 at 5:56 AM, alex goretoy
wrote:

> note i would still like to be able to do __import__("sys")."path"
>
> maybe if __import__ had __str__ defined, How is my thinking on this?
> and how would I achieve something like this?
> -Alex Goretoy
> http://www.goretoy.com
>
>
>
> On Thu, Mar 12, 2009 at 5:44 AM, alex goretoy  > wrote:
>
>> or eval for that matter
>> -Alex Goretoy
>> http://www.goretoy.com
>>
>>
>>
>> On Thu, Mar 12, 2009 at 5:43 AM, alex goretoy <
>> [email protected]> wrote:
>>
>>> yay, no more
>>>
>>> exec ("import " + "sys")
>>>
>>> in my code
>>>
>>> -Alex Goretoy
>>> http://www.goretoy.com
>>>
>>>
>>>
>>> On Thu, Mar 12, 2009 at 5:42 AM, alex goretoy <
>>> [email protected]> wrote:
>>>
 I have resolved this problem in my code. It has something to do with
 your current working directory when you append cwd/jars to sys.path and try
 to import from interactive console
 -Alex Goretoy
 http://www.goretoy.com



 On Thu, Mar 12, 2009 at 4:58 AM, alex goretoy <
 [email protected]> wrote:

> How would I import with __import__ from dict values?
> I want sys.path value inside d['syspath'], below code doesn't work for
> me
>
>
> d={}
> d['sys']='sys'
> d['path']='path'
>
> d['syspath']=__import__(d['sys'],fromlist=[d['path']])
>
> and how come does  above line doesn't give me diff value than below
> line?
>
> d['syspath']=__import__(d['sys'])
>
> Meaning, when I do this doesn't work. Which makes sense.
> d['syspath']()
> d['syspath'].d['path']
>
> but this works both with fromlist and without.
>
> d['syspath'].path
>
>
> -Alex Goretoy
> http://www.goretoy.com
>
>

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


Re: Invalid syntax with print "Hello World"

2009-03-12 Thread Dotan Cohen
> Welcome to the list.  As a newbie myself, I ran into the Python3 vrs
> 2.6 issue.  May I suggest starting with 2.6?  There is many more books
> and internet stuff you can learn with in 2.6 - and the examples will
> work. As Garry wrote, once you understand 2.6, 3.0 will not be a
> challenge.
>

I do not think that is the best way to go about learning Python. Why
learn an arguably depreciating version when the new version is
available. I agree that there are not many tutorial written for Python
3 however there are enough to get going: most of the Python 2
tutorials are redundant. Sticking to Python 3 tutorials will give him
a higher signal-to-noise ratio in the tutorials that he finds.

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il

א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת
ا-ب-ت-ث-ج-ح-خ-د-ذ-ر-ز-س-ش-ص-ض-ط-ظ-ع-غ-ف-ق-ك-ل-م-ن-ه‍-و-ي
А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
ä-ö-ü-ß-Ä-Ö-Ü
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-12 Thread Raymond Hettinger
[Ulrich Eckhardt]
> IOW, why not explicitly say what you want using keyword arguments with
> defaults instead of inventing an IMHO cryptic, read-only mini-language?

That makes sense to me but I don't think that's the way the format()
builtin was implemented (see PEP 3101 which was implemented Py2.6 and
3.0).
It is a simple pass-through to a __format__ method for each
formattable
object.  I don't see how keywords would fit in that framework.  What
is
proposed is similar to locale module's existing "n" specifier except
that
this lets you say exactly what you want instead of deferring to the
locale
settings.

The mini-language seems to already be the way of things (just as it is
many other languages including PHP, C, Fortran, and whatnot).  I'm
just
proposing an addition "T," so you add commas as a thousands separator.


Raymond

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


Input data from .txt file and object array problem

2009-03-12 Thread SamuelXiao
I want to input data by using pickle
First of all, I have a database.txt
The content is like:

AAA,aaalink
BBB,bbblink
CCC,ccclink
...,...

AAA,BBB,CCC is Language name, and aaalink,bbblink,ccclink is their
respective link.
I want to store data by using pickle.  Meanwhile , I got a problem.
#I have created a class:
class Lang:
def __init__(self,lname="",tlink="",alink=""):
self.lname = lname #lname is the Language
self.tlink = tlink #tlink is the tutorial link
self.alink = alink #alink is the a link to school Library 
finding
the first returned Language book

def alibrary_link(self,alink):
self.alink = alink

def tutorial_link(self,tlink):
self.tlink = tlink

def lang_name(self,lname):
self.lname = lname

def _display(self):
string = "+++"  + \
"+" + lname \
"+" + tlink \
"+" + alink \
"+"

def Print(self):
print self._display()

def originData():
fo = ("/database.txt","r+")
lines = fo.readlines()
for line in lines:
pair = line.split(",")
temp = Lang();
temp.lname = pair[0]
temp.tlink = pair[1]
temp.alink = findbook(temp.lname)
#stopping here, because I don't know how to do here...
   #I want to use object array here...
   #Then using pickle to dump the object...
   # Is this work?  Or there is another better method to do so?

I hope to create an object array to store all the language and its
information from database.txt.
How can I do that?  I am a beginner to Python.  Any help would be
appreciated.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What happened to NASA at Python? :(

2009-03-12 Thread skip

>> If they were so keen on new graphics, why did 2.6 revert
>> to the same icons that 2.4 used? (At least they did on my
>> machine. After installing 2.6, I no longer had the new
>> 2.5 icons but had reverted to the earlier ones.)

Can you be more specific?  Is this a Windows thing?  Did you submit a bug
report?

-- 
Skip Montanaro - [email protected] - http://www.smontanaro.net/
--
http://mail.python.org/mailman/listinfo/python-list


cross platform accessing paths (windows, linux ...)

2009-03-12 Thread Vlastimil Brom
Hi all,
I'd like to ask for some advice on how to acomplish file access in a
cross platform way.
My application is a kind of viewer of text and corresponding image
files (stored in separate subdirectories) and I'm going to deploy it
as binaries for windows and source files (again in separate
directories);
Of course the text and image data should be shared for the source and
executable version.
The program should be runnable without instalation, e.g. directly from
a CD-ROM, flashdisk etc. (supposing the working python ...
installation while using the source version).
the directory structure looks like:
my_viewer
 - src
 - bin
 - txt
 - img

While writing the source on windows, I didn't notice problems, as the
simple path
"../txt/text_1.txt"
worked well with open(...). (script file executed with the associated
python.exe)
However on Linux (Kubuntu 8.0.4) the files in neighbour directories
were not found most of the time (probably depending on how the script
was run - console; file manager Krusader ...)
After a lot of trials and gradually solving some corner issues, I
ended up with:

def path_from_pardir(path):
return 
os.path.realpath(os.path.normpath(os.path.join(os.path.dirname(__file__),
os.pardir, path)))
#  __file__ is substituted with sys.path[0] if not present

real_path = path_from_pardir("txt/text_1.txt")

The above seems to work both on windows and linux, but it very much
looks like woodoo code for me;
as I have rather limited experiences on Linux, I'd like to ask, how
this would be best done in a cross platform way; or is the above realy
the way to go?
(I hope, using / as path separator should be fine, as it is also
supported on windows and other OS would use the slash anyway; is it
true, or do I have to use os.sep (which would complicate the code
slightly more)?
Are there any issues I'm likely to run into say on Mac with this approach?

I'm using python 2.5.4 on windows XPp SP3, and the default python
2.5.2 on Kubuntu 8.0.4;
(as I probably can't reasonably use 2.6 here for deployment with py2exe).

Any hints or comments are much appreciated; thanks in advance!

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


Re: Building python 64-bit on OS 10.5?

2009-03-12 Thread Dan Yamins
Dear all:

I've two questions:

1)  I've been trying to building python as a 64-bit version on OS 10.5.
I'm not too familiar with building python from scratch, and a number of
basic attempts made from piecing together things I've seen on the web have
failed.   (For instance,

 ./configure --enable-framework --disable-toolbox-glue
--with-universal-archs=all  --with-gcc="gcc -m64"

leads to a failure when I try to do "make", as do all other similar variants
I've tried.)

So, is there a good source where I can find step-by-step 64-bit build
instructions?  (I'd like to do it if possible as a framework build.)  I've
looked it up a lot on google but am mostly getting fragments of descriptions
of errors with other people's builds.

 2)  I often use a number of python extensions like matplot, pylab, and
ipython.   Will these (especially the graphics parts) be able to build on
top of my 64-bit installation?  Is there some way to find out if they will
likely work without actually having to build them?

Thanks!

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


multiprocessing + atexit

2009-03-12 Thread Neal Becker
I have some code that uses atexit (remove old log files).  Before converting 
to use multiprocessing, it worked.  Since converting, it seems to not be 
running the atexit code (old log files are not removed).

Any known issues with multiprocessing + atexit?


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


Re: Question on periods in strings

2009-03-12 Thread skip

Gabriel> I could not reproduce this.

Nor can I.  I didn't see the original post.  What were the hardware
parameters and Python version?

-- 
Skip Montanaro - [email protected] - http://www.smontanaro.net/
--
http://mail.python.org/mailman/listinfo/python-list


Re: What happened to NASA at Python? :(

2009-03-12 Thread skip

>> In fact, graphics were added for several organizations.  I believe
>> they will be chosen randomly.  NASA is still there.

MiO> In that case, they must be using the random number generator from
MiO> Dilbert. You know, the one that said 9, 9, 9, 9,...

Sorry, randomly chosen whenever the front page is rebuilt by one of the web
gnomes.  It's not chosen randomly on each page fetch.

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


Re: cross platform accessing paths (windows, linux ...)

2009-03-12 Thread Mike Mazurek
You might want to look at the path module:

http://pypi.python.org/pypi/path.py/2.2

It will probably make your code more readable.

On Thu, Mar 12, 2009 at 8:10 AM, Vlastimil Brom wrote:

> Hi all,
> I'd like to ask for some advice on how to acomplish file access in a
> cross platform way.
> My application is a kind of viewer of text and corresponding image
> files (stored in separate subdirectories) and I'm going to deploy it
> as binaries for windows and source files (again in separate
> directories);
> Of course the text and image data should be shared for the source and
> executable version.
> The program should be runnable without instalation, e.g. directly from
> a CD-ROM, flashdisk etc. (supposing the working python ...
> installation while using the source version).
> the directory structure looks like:
> my_viewer
>  - src
>  - bin
>  - txt
>  - img
>
> While writing the source on windows, I didn't notice problems, as the
> simple path
> "../txt/text_1.txt"
> worked well with open(...). (script file executed with the associated
> python.exe)
> However on Linux (Kubuntu 8.0.4) the files in neighbour directories
> were not found most of the time (probably depending on how the script
> was run - console; file manager Krusader ...)
> After a lot of trials and gradually solving some corner issues, I
> ended up with:
>
> def path_from_pardir(path):
>return
> os.path.realpath(os.path.normpath(os.path.join(os.path.dirname(__file__),
> os.pardir, path)))
> #  __file__ is substituted with sys.path[0] if not present
>
> real_path = path_from_pardir("txt/text_1.txt")
>
> The above seems to work both on windows and linux, but it very much
> looks like woodoo code for me;
> as I have rather limited experiences on Linux, I'd like to ask, how
> this would be best done in a cross platform way; or is the above realy
> the way to go?
> (I hope, using / as path separator should be fine, as it is also
> supported on windows and other OS would use the slash anyway; is it
> true, or do I have to use os.sep (which would complicate the code
> slightly more)?
> Are there any issues I'm likely to run into say on Mac with this approach?
>
> I'm using python 2.5.4 on windows XPp SP3, and the default python
> 2.5.2 on Kubuntu 8.0.4;
> (as I probably can't reasonably use 2.6 here for deployment with py2exe).
>
> Any hints or comments are much appreciated; thanks in advance!
>
> regards,
>   Vlasta
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-12 Thread MRAB

Raymond Hettinger wrote:
[snip]

Proposal I (from Nick Coghlan):
---

A comma will be added to the format() specifier mini-language:

[[fill]align][sign][#][0][minimumwidth][,][.precision][type]

The ',' option indicates that commas should be included in the
output as a thousands separator. As with locales which do not
use a period as the decimal point, locales which use a
different convention for digit separation will need to use the
locale module to obtain appropriate formatting.

The proposal works well with floats, ints, and decimals.
It also allows easy substitution for other separators.
For example:

  format(n, "6,f").replace(",", "_")

This technique is completely general but it is awkward in the
one case where the commas and periods need to be swapped:

  format(n, "6,f").replace(",", "X").replace(".", ",").replace("X",
".")


Proposal II (to meet Antoine Pitrou's request):
---

Make both the thousands separator and decimal separator user
specifiable but not locale aware.  For simplicity, limit the
choices to a comma, period, space, or underscore.

[[fill]align][sign][#][0][minimumwidth][T[tsep]][dsep precision][type]

Examples:

  format(1234, "8.1f")--> '  1234.0'
  format(1234, "8,1f")--> '  1234,0'
  format(1234, "8T.,1f")  --> ' 1.234,0'
  format(1234, "8T .f")   --> ' 1 234,0'
  format(1234, "8d")  --> '1234'
  format(1234, "8T,d")--> '   1,234'

This proposal meets mosts needs (except for people wanting
grouping for hundreds or ten-thousands), but iIt comes at the
expense of being a little more complicated to learn and
remember.  Also, it makes it more challenging to write custom
__format__ methods that follow the format specification
mini-language.

For the locale module, just the "T" is necessary in a
formatting string since the tool already has procedures for
figuring out the actual separators from the local context.


[snip]
I'd probably prefer Proposal I with "." representing the decimal point
and "," representing the grouping (thousands) separator, although I'd
add an "L" flag to indicate that it should use the locale to provide the
actual characters to be used and even the number of digits for the
grouping:

[[fill]align][sign][#][0][minimumwidth][,][.precision][L][type]

Examples:

  Assuming the locale has:

decimal point:  ","
grouping separator: "."
grouping spacing:   3

  format(123456, "10.1f")--> '  123456.0'
  format(123456, "10.1Lf")   --> ' 123.456,0'
  format(123456, "10,.1f")   --> ' 123,456.0'
  format(123456, "10,.1Lf")  --> ' 123.456,0'

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


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-12 Thread Hendrik van Rooyen
"Ulrich Eckhardt"  wrote:

>IOW, why not explicitly say what you want using keyword arguments with
>defaults instead of inventing an IMHO cryptic, read-only mini-language?
>Seriously, the problem I see with this proposal is that its aim to be as
>short as possible actually makes the resulting format specifications
>unreadable. Could you even guess what "8T.,1f" should mean if you had not
>written this?

+1

Look back in history, and see how COBOL did it with the
PICTURE - dead easy and easily understandable.
Compared to that, even the C printf stuff  and python's %
are incomprehensible.

- Hendrik


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


loop performance in global namespace (python-2.6.1)

2009-03-12 Thread Poor Yorick

In the following snippet, the loop in the global namespace takes twice as long
as the loop in the function namespace.  Why?

limit = 5000

def f1():
counter = 0
while counter < limit:
counter += 1
time1 = time.time()
f1()
print(time.time() - time1)
print('number of locals: ', len(locals()))

time1 = time.time()
counter = 0
while counter < limit:
counter += 1
print(time.time() - time1)
print('number of locals: ', len(locals()))

--
Yorick

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


Re: [Tutor] loop performance in global namespace (python-2.6.1)

2009-03-12 Thread spir
Le Thu, 12 Mar 2009 11:13:33 -0400,
Kent Johnson  s'exprima ainsi:

> Because local name lookup is faster than global name lookup. Local
> variables are stored in an array in the stack frame and accessed by
> index. Global names are stored in a dict and accessed with dict access
> (dict.__getitem__()).

? I thought this was mainly because a name has first to be searched 
(unsuccessfully) locally before a global lookup is launched.
Also, are locals really stored in an array? How does lookup then proceed? Is it 
a kind of (name,ref) sequence?

Denis
--
la vita e estrany
--
http://mail.python.org/mailman/listinfo/python-list


Re: Input data from .txt file and object array problem

2009-03-12 Thread odeits
On Mar 12, 5:03 am, SamuelXiao  wrote:
> I want to input data by using pickle
> First of all, I have a database.txt
> The content is like:
>
> AAA,aaalink
> BBB,bbblink
> CCC,ccclink
> ...,...
>
> AAA,BBB,CCC is Language name, and aaalink,bbblink,ccclink is their
> respective link.
> I want to store data by using pickle.  Meanwhile , I got a problem.
> #I have created a class:
> class Lang:
>         def __init__(self,lname="",tlink="",alink=""):
>                 self.lname = lname #lname is the Language
>                 self.tlink = tlink #tlink is the tutorial link
>                 self.alink = alink #alink is the a link to school Library 
> finding
> the first returned Language book
>
>         def alibrary_link(self,alink):
>                 self.alink = alink
>
>         def tutorial_link(self,tlink):
>                 self.tlink = tlink
>
>         def lang_name(self,lname):
>                 self.lname = lname
>
>         def _display(self):
>                 string = "+++"  + \
>                                 "+" + lname \
>                                 "+" + tlink \
>                                 "+" + alink \
>                                 "+"
>
>         def Print(self):
>                 print self._display()
>
> def originData():
>         fo = ("/database.txt","r+")
>         lines = fo.readlines()
>         for line in lines:
>                 pair = line.split(",")
>                 temp = Lang();
>                 temp.lname = pair[0]
>                 temp.tlink = pair[1]
>                 temp.alink = findbook(temp.lname)
>         #stopping here, because I don't know how to do here...
>        #I want to use object array here...
>        #Then using pickle to dump the object...
>        # Is this work?  Or there is another better method to do so?
>
> I hope to create an object array to store all the language and its
> information from database.txt.
> How can I do that?  I am a beginner to Python.  Any help would be
> appreciated.

check out the csv module for the parsing of the file
http://docs.python.org/library/csv.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: can python import class or module directly from a zip package

2009-03-12 Thread Coonay
On Mar 11, 9:47 pm, Lorenzo  wrote:
> On Mar 10, 2:13 pm, Flank  wrote:
>
> > can python import class or  module directly from  a zip package ,just
> > like jave does from jar package without extracting the class file into
> > directory
>
> > so far as i know ,python module should be unzip to file system in
> > order to use them,
>
> After a little digging/googling, the answer came right from the docs:
>
> http://docs.python.org/library/zipimport.html
>
> I think that this module is just right what you need.
>
> Cheers!

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


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-12 Thread John Machin
On Mar 12, 9:56 pm, Raymond Hettinger  wrote:
> [Ulrich Eckhardt]
>
> > IOW, why not explicitly say what you want using keyword arguments with
> > defaults instead of inventing an IMHO cryptic, read-only mini-language?
>
> That makes sense to me but I don't think that's the way the format()
> builtin was implemented (see PEP 3101 which was implemented Py2.6 and
> 3.0).
> It is a simple pass-through to a __format__ method for each
> formattable
> object.  I don't see how keywords would fit in that framework.  What
> is
> proposed is similar to locale module's existing "n" specifier except
> that
> this lets you say exactly what you want instead of deferring to the
> locale
> settings.
>
> The mini-language seems to already be the way of things (just as it is
> many other languages including PHP, C, Fortran, and whatnot).  I'm
> just
> proposing an addition "T," so you add commas as a thousands separator.
>

... and why not C (centum) for hundreds (can't have H(ollerith)) and W
for wan (the Chinese word for 10 thousand)?


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


Re: Invalid syntax with print "Hello World"

2009-03-12 Thread Paul Boddie
On 12 Mar, 12:45, Dotan Cohen  wrote:
>

[starting with 2.6]

> I do not think that is the best way to go about learning Python. Why
> learn an arguably depreciating version when the new version is
> available. I agree that there are not many tutorial written for Python
> 3 however there are enough to get going: most of the Python 2
> tutorials are redundant. Sticking to Python 3 tutorials will give him
> a higher signal-to-noise ratio in the tutorials that he finds.

So we are to conclude that Python 2 is redundant now, are we?

I don't think it's bad advice to suggest that people learn Python 2 if
they want to get stuff done, and since people keep saying how Python 3
is really the same language, let us entertain that assertion and
encourage people to take advantage of its predecessor: the thing which
actually powers the overwhelming majority of Python-powered systems
today and for the foreseeable future.

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


Re: Invalid syntax with print "Hello World"

2009-03-12 Thread Henrik Bechmann
On Mar 12, 7:45 am, Dotan Cohen  wrote:
> > Welcome to the list.  As a newbie myself, I ran into the Python3 vrs
> > 2.6 issue.  May I suggest starting with 2.6?  There is many more books
> > and internet stuff you can learn with in 2.6 - and the examples will
> > work. As Garry wrote, once you understand 2.6, 3.0 will not be a
> > challenge.
>
> I do not think that is the best way to go about learning Python. Why
> learn an arguably depreciating version when the new version is
> available. I agree that there are not many tutorial written for Python
> 3 however there are enough to get going: most of the Python 2
> tutorials are redundant. Sticking to Python 3 tutorials will give him
> a higher signal-to-noise ratio in the tutorials that he finds.
>
> --
> Dotan Cohen
>
> http://what-is-what.comhttp://gibberish.co.il
>
> א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת
> ا-ب-ت-ث-ج-ح-خ-د-ذ-ر-ز-س-ش-ص-ض-ط-ظ-ع-غ-ف-ق-ك-ل-م-ن-ه‍-و-ي
> А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я
> а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я
> ä-ö-ü-ß-Ä-Ö-Ü

Thanks everyone!

Now that I know what the issue is (2 vs 3), I'll be able to resolve
those kinds of issues in the future.

Thanks again!

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


Re: NameError: name 'execfile' is not defined

2009-03-12 Thread Henrik Bechmann
On Mar 12, 3:15 am, Gary Herron  wrote:
> Henrik Bechmann wrote:
> > Newbie issue:
>
> > I downloadedhttp://www.python.org/download/releases/3.0.1/(windows
> > insaller), opened the interpreter, wrote a print "Hello World" program
> > in helloworld.py, and in the interpreter typed
>
> > execfile("helloworld.py")
>
> > Got back
>
> > NameError: name 'execfile' is not defined
>
> > (following tutorial in David Beazley's Python Essential Reference).
>
> > Is execfile not supported in 3?
>
> That's correct.
>
>  Fromhttp://docs.python.org/dev/3.0/whatsnew/3.0.htmlyou can find this
> line:
>
>     Removed execfile().   Instead of execfile(fn) use exec(open(fn).read()).
>
> Gary Herron
>
> > Thanks,
>
> > - Henrik
> > --
> >http://mail.python.org/mailman/listinfo/python-list

Excellent. Thanks very much!

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


Re: Stopping SocketServer on Python 2.5

2009-03-12 Thread David George

On 2009-03-12 08:03:06 +, "Mark Tolonen"  said:



"Falcolas"  wrote in message 
news:[email protected]...

On Mar 11, 1:11 pm, David George  wrote:

Again, problem here is the issue of being unable to kill the server
while it's waiting on a request. In theory, i could force it to
continue by sending some sort of junk data with the method i use to
stop the server, but that seems a bit hacky, don't you think?


Dave,

I agree, it does.

I'm in a bit over my head at this point, but does setting
self.socket.settimeout(0.5) cause the call to get_request (and thus
self.socket.accept()) to timeout? If so, that may be your ticket,
since socket.error exceptions are already caught by the TCPServer
class.


Here's the relevant code from Python 2.6's SocketServer.py.  It uses 
select() to see if a request is waiting to be serviced so 
handle_request won't block.  If the poll interval expires the while 
loop will check the __serving flag.  Not ideal, but better than 
requiring a client to connect before the flag is checked.  The comment 
lists another idea:


   def serve_forever(self, poll_interval=0.5):
"""Handle one request at a time until shutdown.

Polls for shutdown every poll_interval seconds. Ignores
self.timeout. If you need to do periodic tasks, do them in
another thread.
"""
self.__serving = True
self.__is_shut_down.clear()
while self.__serving:
# XXX: Consider using another file descriptor or
# connecting to the socket to wake this up instead of
# polling. Polling reduces our responsiveness to a
# shutdown request and wastes cpu at all other times.
r, w, e = select.select([self], [], [], poll_interval)
if r:
self._handle_request_noblock()
self.__is_shut_down.set()

-Mark


Thanks to everybody for helping me with this matter, but eventually 
i've had to settle for a simpler and probably far less elegant solution 
due to time constraints.


It seems that SocketServer.py in 2.6 doesn't directly rely on anything 
that's in Python 2.6, so i've simply copied the code across and i'm 
using it in place of the version built into Python 2.5.


I will probably return to this at a later date and try for a more 
elegant solution, but right now university deadlines are looming!


Thanks all,

Dave


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


How to send an email with GMail in Python from Windows

2009-03-12 Thread ∂ √ ¡ ŋ ∂ ♪ ђ
Hi
Can somebody help me with sending an email using Python from GMail
Here's what I tried but it fails always.


import smtplib
import base64

smtpserver = 'smtp.gmail.com'
AUTHREQUIRED = 0 # if you need to use SMTP AUTH set to 1
smtpuser = '[email protected]' # for SMTP AUTH, set SMTP username here
smtppass = '*' # for SMTP AUTH, set SMTP password here

RECIPIENTS = ['[email protected]']
SENDER = '[email protected]'
mssg = open('mssg.txt', 'r').read() # I am reading from this file on
the same directory

session = smtplib.SMTP(smtpserver,'465')
session.ehlo()
#session.esmtp_features["auth"] = "LOGIN PLAIN"
session.connect(smtpserver,'465')
session.ehlo()
session.starttls()
session.set_debuglevel(1)
session.helo()

if AUTHREQUIRED:
try:
session.login(smtpuser, smtppass)

except SMTPAuthenticationError, e:
# if login fails, try again using a manual plain login method
smtp.docmd("AUTH LOGIN", base64.b64encode( smtpuser ))
smtp.docmd(base64.b64encode( smtppass ), "")
smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg)
if smtpresult:
errstr = ""
for recip in smtpresult.keys():
errstr = """Could not delivery mail to: %s

Server said: %s
%s

%s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr)
raise smtplib.SMTPException, errstr

This is the Stack Trace I got when I ran the above script after a very
long time(>15min)

Traceback (most recent call last):
File "C:\Python26\Mail.py", line 13, in 
session = smtplib.SMTP(smtpserver,'465')
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 296, in connect
(code, msg) = self.getreply()
File "C:\Python26\lib\smtplib.py", line 340, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

Tool completed with exit code 1

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


Re: How to send an email with GMail in Python from Windows

2009-03-12 Thread dorzey
You might want to try - http://libgmail.sourceforge.net/. This is a
Python binding for GMail; I've used it a little and it did the job for
me.

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


Re: How to send an email with GMail in Python from Windows

2009-03-12 Thread gordyt
Howdy Avinash,

Here is a simple example for you.

from smtplib import SMTP
HOST = "smtp.gmail.com"
PORT = 587
ACCOUNT = ""# put your gmail email account here
PASSWORD = ""   # put your gmail email password here

def send_email(to_addrs, subject, msg):
server = SMTP(HOST,PORT)
server.set_debuglevel(1)# you don't need this (comment out to
avoid debug messages)
server.ehlo()
server.starttls()
server.ehlo()
server.login(ACCOUNT, PASSWORD)
server.sendmail(ACCOUNT, to_addrs,
"""From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s\r\n.\r\n""" % (
ACCOUNT, ",".join(to_addrs), subject, msg
)
)
server.quit()

if __name__ == "__main__":
send_email( ['[email protected]'], 'this is just a test',
"hello world!" )


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


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-12 Thread pruebauno
On Mar 12, 3:30 am, Raymond Hettinger  wrote:
> If anyone here is interested, here is a proposal I posted on the
> python-ideas list.
>
> The idea is to make numbering formatting a little easier with the new
> format() builtin
> in Py2.6 and Py3.0:  http://docs.python.org/library/string.html#formatspec
>
> -
>
> Motivation:
>
>     Provide a simple, non-locale aware way to format a number
>     with a thousands separator.
>
>     Adding thousands separators is one of the simplest ways to
>     improve the professional appearance and readability of
>     output exposed to end users.
>
>     In the finance world, output with commas is the norm.  Finance
> users
>     and non-professional programmers find the locale approach to be
>     frustrating, arcane and non-obvious.
>
>     It is not the goal to replace locale or to accommodate every
>     possible convention.  The goal is to make a common task easier
>     for many users.
>
> Research so far:
>
>     Scanning the web, I've found that thousands separators are
>     usually one of COMMA, PERIOD, SPACE, or UNDERSCORE.  The
>     COMMA is used when a PERIOD is the decimal separator.
>
>     James Knight observed that Indian/Pakistani numbering systems
>     group by hundreds.   Ben Finney noted that Chinese group by
>     ten-thousands.
>
>     Visual Basic and its brethren (like MS Excel) use a completely
>     different style and have ultra-flexible custom format specifiers
>     like: "_($* #,##0_)".
>
> Proposal I (from Nick Coghlan]:
>
>     A comma will be added to the format() specifier mini-language:
>
>     [[fill]align][sign][#][0][minimumwidth][,][.precision][type]
>
>     The ',' option indicates that commas should be included in the
> output as a
>     thousands separator. As with locales which do not use a period as
> the
>     decimal point, locales which use a different convention for digit
>     separation will need to use the locale module to obtain
> appropriate
>     formatting.
>
>     The proposal works well with floats, ints, and decimals.  It also
>     allows easy substitution for other separators.  For example:
>
>         format(n, "6,f").replace(",", "_")
>
>     This technique is completely general but it is awkward in the one
>     case where the commas and periods need to be swapped.
>
>         format(n, "6,f").replace(",", "X").replace(".", ",").replace
> ("X", ".")
>
> Proposal II (to meet Antoine Pitrou's request):
>
>     Make both the thousands separator and decimal separator user
> specifiable
>     but not locale aware.  For simplicity, limit the choices to a
> comma, period,
>     space, or underscore..
>
>     [[fill]align][sign][#][0][minimumwidth][T[tsep]][dsep precision]
> [type]
>
>     Examples:
>
>         format(1234, "8.1f")    -->     '  1234.0'
>         format(1234, "8,1f")    -->     '  1234,0'
>         format(1234, "8T.,1f")  -->     ' 1.234,0'
>         format(1234, "8T .f")   -->     ' 1 234,0'
>         format(1234, "8d")      -->     '    1234'
>         format(1234, "8T,d")      -->   '   1,234'
>
>     This proposal meets mosts needs (except for people wanting
> grouping
>     for hundreds or ten-thousands), but it comes at the expense of
>     being a little more complicated to learn and remember.  Also, it
> makes it
>     more challenging to write custom __format__ methods that follow
> the
>     format specification mini-language.
>
>     For the locale module, just the "T" is necessary in a formatting
> string
>     since the tool already has procedures for figuring out the actual
>     separators from the local context.
>
> Comments and suggestions are welcome but I draw the line at supporting
> Mayan numbering conventions ;-)
>
> Raymond

As far as I am concerned the most simple version plus a way to swap
around commas and period is all that is needed. The rest can be done
using one replace (because the decimal separator is always one of two
options). This should cover everywhere but the far east. 80% of cases
for 20% of implementation complexity.

For example:

[[fill]align][sign][#][0][,|.][minimumwidth][.precision][type]

> format(1234, ".8.1f")  --> ' 1.234,0'
> format(1234, ",8.1f")  --> ' 1,234.0'

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


default shelve on linux corrupts, does different DB system help?

2009-03-12 Thread Paul Sijben
I have the problem that my shelve(s) sometimes corrupt (looks like it
has after python has run out of threads).

I am using the default shelve so on linux I get the dbhash version.
Is there a different DB type I can choose that is known to be more
resilient? And if so, what is the elegant way of doing that?

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


Re: Input data from .txt file and object array problem

2009-03-12 Thread Piet van Oostrum
> SamuelXiao  (S) wrote:

>S> I want to input data by using pickle
>S> First of all, I have a database.txt
>S> The content is like:

>S> AAA,aaalink
>S> BBB,bbblink
>S> CCC,ccclink
>S> ...,...

>S> AAA,BBB,CCC is Language name, and aaalink,bbblink,ccclink is their
>S> respective link.
>S> I want to store data by using pickle.  Meanwhile , I got a problem.
>S> #I have created a class:
>S> class Lang:
>S> def __init__(self,lname="",tlink="",alink=""):
>S> self.lname = lname #lname is the Language
>S> self.tlink = tlink #tlink is the tutorial link
>S> self.alink = alink #alink is the a link to school Library 
>finding
>S> the first returned Language book

>S> def alibrary_link(self,alink):
>S> self.alink = alink

>S> def tutorial_link(self,tlink):
>S> self.tlink = tlink

>S> def lang_name(self,lname):
>S> self.lname = lname

>S> def _display(self):
>S> string = "+++"  + \
>S> "+" + lname \
>S> "+" + tlink \
>S> "+" + alink \
>S> "+"

This will not do very much. The string is calculated and then thrown
away. You will need also a "return string" to make it useful.

>S> def Print(self):
>S> print self._display()

>S> def originData():
>S> fo = ("/database.txt","r+")
>S> lines = fo.readlines()
>S> for line in lines:
>S> pair = line.split(",")
>S> temp = Lang();
>S> temp.lname = pair[0]
>S> temp.tlink = pair[1]
>S> temp.alink = findbook(temp.lname)

Why do you set these attributes directly while you also have methods for
this (like lang_name, tutorial_link)? Or better use 
temp = Lang(pair[0], pair[1], findbook(temp.lname))

>S> #stopping here, because I don't know how to do here...
>S>#I want to use object array here...
>S>#Then using pickle to dump the object...
>S># Is this work?  Or there is another better method to do so?
>S> I hope to create an object array to store all the language and its
>S> information from database.txt.

I guess you want to put them in a list. Then use 
objList.append(temp)
here and 
objList = [] before the loop.

>S> How can I do that?  I am a beginner to Python.  Any help would be
>S> appreciated.

You can use pickle to store the list is a file after reading.
Something like (untested):

import pickle # or use the faster cPickle module.

output = open('somefile', 'wb')

# Pickle object list
pickle.dump(objList, output)

output.close()

But as this is only textual data (I think) there is not much profit in
using pickle. Unless you have other things added in your class. You
could also write these things to a simple text file, for example with
the csv module.

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


Re: Killing subservient threads

2009-03-12 Thread Aahz
In article ,
Christian Heimes   wrote:
>Gabriel Genellina wrote:
>>
>> 1) make the child window set a flag in the thread (let's say,
>> t.terminate = True). And make the polling thread check the flag
>> periodically (you possibly already have a loop there - just break the
>> loop when you detect that self.terminate became true)
>
>threading.Condition() and threading.Event() are especially designed for
>the job. Please use them appropriately.

Personally, I prefer to just use Queue for everything.  See
http://pythoncraft.com/OSCON2001/index.html
for examples, including one with Tkinter.

Side note: because of the Subject: line, I have to mention a website for
those who haven't seen it (requires Flash enabled):
http://www.subservientchicken.com/
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"All problems in computer science can be solved by another level of 
indirection."  --Butler Lampson
--
http://mail.python.org/mailman/listinfo/python-list


question on msvcrt.dll versioning

2009-03-12 Thread rogerdpack
It appears from sites like
http://www.develer.com/oss/GccWinBinaries
at the bottom that at least this developer made an effort to link
against the same version of msvcrt.dll that the python exe was
compiled with [ex: vc2008 -> msvcr90.dll].  Is this pain necessary?
Are there known drawbacks to not doing this anyone can think of? [just
trying to plan releases for windows ruby shtuffs with similar
problems].
Thanks!
-=roger
--
http://mail.python.org/mailman/listinfo/python-list


Re: pymssql text type

2009-03-12 Thread Aahz
[posted and e-mailed, please reply to group]

In article <[email protected]>,
marc wyburn   wrote:
>Hi, I'm trying to pass a text blob to MS SQL Express 2008 but get the
>follwoing error.
>
>(, OperationalError("SQL Server
>message 102, severity 15, state 1, line 1:\nIncorrect syntax near
>'assigned'.\n",), )
>
>the string it is having an issue with is
>
>(\r\n\r\n\tLogon ID:\t\t(0x0,0xE892A8)\r\n\r\n\tLogon Type:\t2\r\n\r
>\n')

What is the code you're trying to execute and what is the full traceback?
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"All problems in computer science can be solved by another level of 
indirection."  --Butler Lampson
--
http://mail.python.org/mailman/listinfo/python-list


Re: "import" not working?

2009-03-12 Thread Aahz
In article ,
Rhodri James  wrote:
>
>Just so that we're clear, this is a *really* *bad* habit to get into.
>Not appending to sys.path, though that isn't often a good idea, but
>failing to escape your backslashes.  This works because '\D' happens
>not to be a valid escape sequence: if your directory had instead been
>called "newtypes" then "C:\newtypes" would not have had the result you
>were expecting at all.  If you really mean a backslash to be in any
>literal string, you should always double it:
>
>sys.path.append("C:\\DataFileTypes")

My preference:

sys.path.append(r"C:\DataFileTypes")

This doesn't work if you need to add a trailing backslash, though.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"All problems in computer science can be solved by another level of 
indirection."  --Butler Lampson
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to assert that method accepts specific types

2009-03-12 Thread Aahz
In article <3f26a2f1-94cf-4083-9bda-7076959ad...@k19g2000yqg.googlegroups.com>,
Darren Dale   wrote:
>
>class Test(object):
>@accepts(int)
>def check(self, obj):
>print obj
>
>t = Test()
>t.check(1)
>
>but now I want Test.check to accept an instance of Test as well. Does
>anyone know how this can be accomplished? The following class
>definition for Test raises a NameError:
>
>class Test(object):
>@accepts(int, Test)
>def check(self, obj):
>print obj

Are you using Python 2.6 or later?  You could probably write a tricky
class decorator that re-wraps all wrapped methods
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"All problems in computer science can be solved by another level of 
indirection."  --Butler Lampson
--
http://mail.python.org/mailman/listinfo/python-list


Re: Input data from .txt file and object array problem

2009-03-12 Thread SamuelXiao
On Mar 12, 11:17 pm, Piet van Oostrum  wrote:
> > SamuelXiao  (S) wrote:
> >S> I want to input data by using pickle
> >S> First of all, I have a database.txt
> >S> The content is like:
> >S> AAA,aaalink
> >S> BBB,bbblink
> >S> CCC,ccclink
> >S> ...,...
> >S> AAA,BBB,CCC is Language name, and aaalink,bbblink,ccclink is their
> >S> respective link.
> >S> I want to store data by using pickle.  Meanwhile , I got a problem.
> >S> #I have created a class:
> >S> class Lang:
> >S>       def __init__(self,lname="",tlink="",alink=""):
> >S>               self.lname = lname #lname is the Language
> >S>               self.tlink = tlink #tlink is the tutorial link
> >S>               self.alink = alink #alink is the a link to school Library 
> >finding
> >S> the first returned Language book
> >S>       def alibrary_link(self,alink):
> >S>               self.alink = alink
> >S>       def tutorial_link(self,tlink):
> >S>               self.tlink = tlink
> >S>       def lang_name(self,lname):
> >S>               self.lname = lname
> >S>       def _display(self):
> >S>               string = "+++"  + \
> >S>                               "+" + lname \
> >S>                               "+" + tlink \
> >S>                               "+" + alink \
> >S>                               "+"
>
> This will not do very much. The string is calculated and then thrown
> away. You will need also a "return string" to make it useful.
>
> >S>       def Print(self):
> >S>               print self._display()
> >S> def originData():
> >S>       fo = ("/database.txt","r+")
> >S>       lines = fo.readlines()
> >S>       for line in lines:
> >S>               pair = line.split(",")
> >S>               temp = Lang();
> >S>               temp.lname = pair[0]
> >S>               temp.tlink = pair[1]
> >S>               temp.alink = findbook(temp.lname)
>
> Why do you set these attributes directly while you also have methods for
> this (like lang_name, tutorial_link)? Or better use
>                 temp = Lang(pair[0], pair[1], findbook(temp.lname))
>
> >S>       #stopping here, because I don't know how to do here...
> >S>        #I want to use object array here...
> >S>        #Then using pickle to dump the object...
> >S>        # Is this work?  Or there is another better method to do so?
> >S> I hope to create an object array to store all the language and its
> >S> information from database.txt.
>
> I guess you want to put them in a list. Then use
>                 objList.append(temp)
> here and
> objList = [] before the loop.
>
> >S> How can I do that?  I am a beginner to Python.  Any help would be
> >S> appreciated.
>
>     You can use pickle to store the list is a file after reading.
>     Something like (untested):
>
> import pickle # or use the faster cPickle module.
>
> output = open('somefile', 'wb')
>
> # Pickle object list
> pickle.dump(objList, output)
>
> output.close()
>
> But as this is only textual data (I think) there is not much profit in
> using pickle. Unless you have other things added in your class. You
> could also write these things to a simple text file, for example with
> the csv module.
>
> --
> Piet van Oostrum 
> URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
> Private email: [email protected]

Hi, odeits, Piet van Oostrum, thanks for your reply.  But I found that
my school's server have problem with reading csv file.  So, I think I
have to do it another way.  By the way, is there any better way to
store data?  Actually, what I want to do is like:

1. Given a post or an essay, I want to find any language names in the
post or essay matching with data in my database.txt
2. Then insert  about the matched word.

My original version is super slow because each time go to and back
from the library website wastes a lot of times.  I hope to use class
to store the data in database.txt first, then store the book
information from library.  Then visited matched word no need to go to
search again.  Just simply insert  about it.  But my problem
is how to store object array and call it out?  Thanks for any help.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-12 Thread Raymond Hettinger
On Mar 12, 7:51 am, [email protected] wrote:
> On Mar 12, 3:30 am, Raymond Hettinger  wrote:
>
>
>
> > If anyone here is interested, here is a proposal I posted on the
> > python-ideas list.
>
> > The idea is to make numbering formatting a little easier with the new
> > format() builtin
> > in Py2.6 and Py3.0:  http://docs.python.org/library/string.html#formatspec
>
> > -
>
> > Motivation:
>
> >     Provide a simple, non-locale aware way to format a number
> >     with a thousands separator.
>
> >     Adding thousands separators is one of the simplest ways to
> >     improve the professional appearance and readability of
> >     output exposed to end users.
>
> >     In the finance world, output with commas is the norm.  Finance
> > users
> >     and non-professional programmers find the locale approach to be
> >     frustrating, arcane and non-obvious.
>
> >     It is not the goal to replace locale or to accommodate every
> >     possible convention.  The goal is to make a common task easier
> >     for many users.
>
> > Research so far:
>
> >     Scanning the web, I've found that thousands separators are
> >     usually one of COMMA, PERIOD, SPACE, or UNDERSCORE.  The
> >     COMMA is used when a PERIOD is the decimal separator.
>
> >     James Knight observed that Indian/Pakistani numbering systems
> >     group by hundreds.   Ben Finney noted that Chinese group by
> >     ten-thousands.
>
> >     Visual Basic and its brethren (like MS Excel) use a completely
> >     different style and have ultra-flexible custom format specifiers
> >     like: "_($* #,##0_)".
>
> > Proposal I (from Nick Coghlan]:
>
> >     A comma will be added to the format() specifier mini-language:
>
> >     [[fill]align][sign][#][0][minimumwidth][,][.precision][type]
>
> >     The ',' option indicates that commas should be included in the
> > output as a
> >     thousands separator. As with locales which do not use a period as
> > the
> >     decimal point, locales which use a different convention for digit
> >     separation will need to use the locale module to obtain
> > appropriate
> >     formatting.
>
> >     The proposal works well with floats, ints, and decimals.  It also
> >     allows easy substitution for other separators.  For example:
>
> >         format(n, "6,f").replace(",", "_")
>
> >     This technique is completely general but it is awkward in the one
> >     case where the commas and periods need to be swapped.
>
> >         format(n, "6,f").replace(",", "X").replace(".", ",").replace
> > ("X", ".")
>
> > Proposal II (to meet Antoine Pitrou's request):
>
> >     Make both the thousands separator and decimal separator user
> > specifiable
> >     but not locale aware.  For simplicity, limit the choices to a
> > comma, period,
> >     space, or underscore..
>
> >     [[fill]align][sign][#][0][minimumwidth][T[tsep]][dsep precision]
> > [type]
>
> >     Examples:
>
> >         format(1234, "8.1f")    -->     '  1234.0'
> >         format(1234, "8,1f")    -->     '  1234,0'
> >         format(1234, "8T.,1f")  -->     ' 1.234,0'
> >         format(1234, "8T .f")   -->     ' 1 234,0'
> >         format(1234, "8d")      -->     '    1234'
> >         format(1234, "8T,d")      -->   '   1,234'
>
> >     This proposal meets mosts needs (except for people wanting
> > grouping
> >     for hundreds or ten-thousands), but it comes at the expense of
> >     being a little more complicated to learn and remember.  Also, it
> > makes it
> >     more challenging to write custom __format__ methods that follow
> > the
> >     format specification mini-language.
>
> >     For the locale module, just the "T" is necessary in a formatting
> > string
> >     since the tool already has procedures for figuring out the actual
> >     separators from the local context.
>
> > Comments and suggestions are welcome but I draw the line at supporting
> > Mayan numbering conventions ;-)
>
> > Raymond
>
> As far as I am concerned the most simple version plus a way to swap
> around commas and period is all that is needed.

Thanks for the feedback.

FWIW, posted a cleaned-up version of the proposal at
  http://www.python.org/dev/peps/pep-0378/


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


Python/Django forum-building software Snap/SCT, any reviews?

2009-03-12 Thread John Crawford
I'm looking for good open-source software for forums. There is a *lot* out 
there, for instance Lussumo's Vanilla gets good reviews, but most are 
PHP-based, and I would obviously prefer to use Python, with or without Django. 

Two packages that are Django-based that I have found, are Snap and SCT. They 
both look pretty good (and Snap was influenced by Vanilla). Does anyone have 
any experience with these packages, and comments about them? Thanks

John C>
"For all your days, prepare, and meet them ever alike;
When you are the anvil, bear - when the hammer, strike."

Posted with NewzToolz. Free RAR, PAR, and yEnc decoders.
Get your free copy at www.techsono.com.



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


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-12 Thread Paul Rubin
Raymond Hettinger  writes:
> FWIW, posted a cleaned-up version of the proposal at
>   http://www.python.org/dev/peps/pep-0378/

It would be nice if the PEP included a comparison between the proposed
scheme and how it is done in other programs and languages.  For
example, I think Common Lisp has a feature for formatting thousands.
Spreadsheets like Excel probably have something similar.  Those
programs are pretty well evolved and probably address the important
real use cases by now.  It might be best to follow an existing example
(with adjustments for Pythonification as necessary) to the extent
possible.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python contextmanagers and ruby blocks

2009-03-12 Thread Aahz
In article ,
Alia K   wrote:
>Aahz wrote:
>>
>> Longer answer: the way in Python to achieve the full power of Ruby
>> blocks is to write a function.
>
>You are most likely right... there is probably no need to introduce
>ruby-like blocks to python where iteration comes naturally with list
>comprehensions and generators. But for the simple case of entering a
>block of code as one does with @contextmanager I suppose it would be
>nice to make a generator with a single yield statement a
>contextmanager by default such that [...]

There has been some discussion of this on the python-ideas mailing list;
if this is a subject you care about, you may want to read up on the
history and join the list.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"All problems in computer science can be solved by another level of 
indirection."  --Butler Lampson
--
http://mail.python.org/mailman/listinfo/python-list


PyCon Update

2009-03-12 Thread Raymond Hettinger
As of today, we still have rooms at the Hyatt.
If you haven't registered yet and want to attend,
it is not sold out.

http://us.pycon.org/2009/


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


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-12 Thread Raymond Hettinger
[Paul Rubin]
> It would be nice if the PEP included a comparison between the proposed
> scheme and how it is done in other programs and languages.

Good idea.  I'm hoping that people will post those here.
In my quick research, it looks like many languages offer
nothing more than the usual C style % formatting and defer
the rest for a local aware module.


>  For
> example, I think Common Lisp has a feature for formatting thousands.

Do you have more detail?


> Spreadsheets like Excel probably have something similar.

I addressed that in the PEP in the section on VB and relatives.  Their
approach doesn't graft-on to our existing approach.  They use format
specifiers like: "_($* #,##0_)".


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


Re: Invalid syntax with print "Hello World"

2009-03-12 Thread Luis Zarrabeitia
On Thursday 12 March 2009 07:45:55 am Dotan Cohen wrote:
> I do not think that is the best way to go about learning Python. Why
> learn an arguably depreciating version when the new version is
> available. 

Because it is not only the language that matters, you also need the libraries 
to accomplish real-world tasks. As a language, python2 is an impressive one, 
and python3 is a great improvement over python2, but python3 still lacks some 
of the libraries and framewoks that makes programming in python so extremely 
delightful (yes, I like python :D).

I don't consider python2 deprecated (can't be deprecated yet!), and as a 
teacher and/or student, I'd recomment to teach/learn python2.5-2.6, keeping 
an eye on all those features that are new in python3... and backporting 
everything that is possible to backport.

> I agree that there are not many tutorial written for Python 
> 3 however there are enough to get going: most of the Python 2
> tutorials are redundant. Sticking to Python 3 tutorials will give him
> a higher signal-to-noise ratio in the tutorials that he finds.

That is true. We need python tutorials aimed at python2.6 :D

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
--
http://mail.python.org/mailman/listinfo/python-list


Re: ipython / vs \ in readline on MS Windows (and ipython help grepper)

2009-03-12 Thread Jason Scheirer
On Mar 10, 3:34 pm, bdb112  wrote:
> Q1/ I run a standard python ditribution with ipython and readline
> under cygwin.  The tab filename completion works fine in the OS (bash
> shell) as expected, and tab filename completion at the ipython command
> line works, but with MS style path separators (backslash: run examples
> \test.py) which the run command itself interprets unix style
> ERROR: File `examplestest.py` not found.
>
> Also Q2/ can I "less" or "grep" the output from help(my_fun)
>
> Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
> (Intel)]
> IPython 0.8.4 -- An enhanced Interactive Python.

Cygwin does not magically change the platform you are on, the fact
that you are on Windows is hard-coded into the Python.exe binary. Look
for references to os.path.sep in IPython. Windows does let you use
forward slashes as path separators, though, so I am not entirely sure
what your issue is.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Candidate for a new itertool

2009-03-12 Thread pruebauno
On Mar 7, 8:47 pm, Raymond Hettinger  wrote:
> The existing groupby() itertool works great when every element in a
> group has the same key, but it is not so handy when groups are
> determined by boundary conditions.
>
> For edge-triggered events, we need to convert a boundary-event
> predicate to groupby-style key function.  The code below encapsulates
> that process in a new itertool called split_on().
>
> Would love you guys to experiment with it for a bit and confirm that
> you find it useful.  Suggestions are welcome.
>
> Raymond
>
> -
>
> from itertools import groupby
>
> def split_on(iterable, event, start=True):
>     'Split iterable on event boundaries (either start events or stop
> events).'
>     # split_on('X1X23X456X', 'X'.__eq__, True)  --> X1 X23 X456 X
>     # split_on('X1X23X456X', 'X'.__eq__, False) --> X 1X 23X 456X
>     def transition_counter(x, start=start, cnt=[0]):
>         before = cnt[0]
>         if event(x):
>             cnt[0] += 1
>         after = cnt[0]
>         return after if start else before
>     return (g for k, g in groupby(iterable, transition_counter))
>
> if __name__ == '__main__':
>     for start in True, False:
>         for g in split_on('X1X23X456X', 'X'.__eq__, start):
>             print list(g)
>         print
>
>     from pprint import pprint
>     boundary = '--===2615450625767277916==\n'
>     email = open('email.txt')
>     for mime_section in split_on(email, boundary.__eq__):
>         pprint(list(mime_section, 1, None))
>         print '= = ' * 30

For me your examples don't justify why you would need such a general
algorithm. A split function that works on iterables instead of just
strings seems straightforward, so maybe we should have that and
another one function with examples of problems where a plain split
does not work.
Something like this should work for the two examples you gave were the
boundaries are a known constants (and therefore there is really no
need to keep them. I can always add them later):

def split_on(iterable, boundary):
l=[]
for el in iterable:
if el!=boundary:
l.append(el)
else:
yield l
l=[]
yield l

def join_on(iterable, boundary):
it=iter(iterable)
firstel=it.next()
for el in it:
yield boundary
for x in el:
yield x

if __name__ == '__main__':
lst=[]
for g in split_on('X1X23X456X', 'X'):
print list(g)
lst.append(g)
print
print list(join_on(lst,'X'))
--
http://mail.python.org/mailman/listinfo/python-list


Re: PythonWin, python thread and PostQuitMessage?

2009-03-12 Thread Gabriel Genellina

En Thu, 12 Mar 2009 07:21:35 -0200,  escribió:


I'm not so much involved in any Windows programming however I needed
to write a client for the Windows platform. I have this very simple
question which I've been unable to answer. I'm listening for keyboard
strokes using the pyhook library. I'm doing this in a dedicated
thread. The gui just controls the thread. When I want to pause
listening for keyboard strokes I wanted to do a PostQuitMessage() to
the thread. However this does not work since it either kills the whole
app or just does not happen in the thread it's supposed to. I've now
made an ugly workaround using PumpWaitingMessages and a delay.


If you have a GUI, then very likely it has its own message loop, so you  
should not create another.



def run(self):
print "Wkeylog run called"
# Hook Keyboard
self.hm.HookKeyboard()
while self.log:
win32gui.PumpWaitingMessages()
time.sleep(0.02)

i can now just cancel the process by setting self.log to False. I
wanted to do just:

def run(self):
print "Wkeylog run called"
# Hook Keyboard
self.hm.HookKeyboard()
win32gui.PumpMessages()


Then, if you remove PumpMesages and PumpWaitingMessages, there is nothing  
left... so this thread is useless.
Perhaps you want to *process* keyboard events in another thread - in this  
case, use a Queue object to send events to the worker thread, from the  
main thread where the message loop resides.


--
Gabriel Genellina

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


Re: "Byte" type?

2009-03-12 Thread Scott David Daniels

John Nagle wrote:

Martin v. Löwis wrote:

Please don't call something dumb that you don't fully understand

...- do you have to convert twice?

Depends on how you write your code. If you use the bytearray type
(which John didn't, despite his apparent believe that he did),
then no conversion additional conversion is needed.


According to PEP 3137, there should be no distinction between
the two for read purposes.  In 2.6, there is.  That's a bug.

If we something like the following for the bytes type in 2.7, perhaps
we could improve the 2.X behavior (and make everyone happier).

class bytes(str):

def __getitem__(self, index):
# keep exceptions the same
result = super(bytes, self).__getitem__(index)
if isinstance(index, int):
# Picking out a single char
return ord(result)
 # otherwise, it an extraction, return a similar type.
 return bytes(result)

def __repr__(self):
# make a nice visible-in-debugger type
return 'b' + super(bytes, self).__repr__()


At the very least, you can smuggle this into your programs
to check out their behavior.

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


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-12 Thread Raymond Hettinger
[Paul Rubin]
> I think Common Lisp has a feature for formatting thousands.

I found the Common Lisp spec for this and added it to the PEP.


Raymond

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


Re: "import" not working?

2009-03-12 Thread Scott David Daniels

Aahz wrote:

In article ,
Rhodri James  wrote: ...

sys.path.append("C:\\DataFileTypes")


My preference:
sys.path.append(r"C:\DataFileTypes")
This doesn't work if you need to add a trailing backslash, though.


Also my preference (except, due to aging eyes and bad fonts, I prefer
single quotes unless doubles are needed).  I solve the trailing
backslash problem as so:
   sys.path.append(r'C:\DataFileTypes' '\\')

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


Re: Python 2.7 MSI / pywin32 snapshots [was: Windows install to custom location ...]

2009-03-12 Thread Scott David Daniels

Tim Golden wrote:

Scott David Daniels wrote:

Tim Golden wrote:

... Anyhow, at the end I have a working Python 2.7a0 running
under Windows.


Do you mean 3.1a0?  As far as I know, 2.7a0 requires the use
of the time machine, as it is expected to be 3 months out.

If you do get an installer built, even having a semi-official copy
around for those of us not on the MS compiler upgrade train to
do a little alpha (and/or beta) testing as well.


I've uploaded a couple of installers here:

 http://timgolden.me.uk/python/downloads/snapshots/

Currently, there's the Python Subversion trunk (py2.7) and the 
corresponding pywin32, built from the latest CVS. I believe

I've got everything in there, altho' the platform test was
failing irreproducibly when I last looked.


Thanks so much for these.  Yes, they work (and I'm happily running
little experiments).

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


Raw String Question

2009-03-12 Thread Jim Garrison

I'm an experienced Perl developer learning Python, but I seem to
be missing something about raw strings.  Here's a transcript of
a Python shell session:

 Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit 
(Intel)] on win32

 Type "copyright", "credits" or "license()" for more information.

 
 Personal firewall software may warn about the connection IDLE
 makes to its subprocess using this computer's internal loopback
 interface.  This connection is not visible on any external
 interface and no data is sent to or received from the Internet.
 

 IDLE 3.0
 >>> r"a\b"
 'a\\b'
 >>> r"a\"
 SyntaxError: EOL while scanning string literal (, line 1)
 >>> r"a\ "
 'a\\ '
 >>> r"a\""
 'a\\"'

It seems the parser is interpreting the backslash as an escape
character in a raw string if the backslash is the last character.
Is this expected?
--
http://mail.python.org/mailman/listinfo/python-list


Re: __import__ with dict values

2009-03-12 Thread Gabriel Genellina
En Thu, 12 Mar 2009 09:27:35 -0200, alex goretoy  
 escribió:



note i would still like to be able to do __import__("sys")."path"


p = __import__("sys").path

That's a convoluted way of doing:

import sys
p = sys.path

(except that the latter one inserts "sys" in the current namespace)


maybe if __import__ had __str__ defined, How is my thinking on this?
and how would I achieve something like this?


__str__ has absolutely nothing to do.


__import__(opt['imp_mod']).options

eval(opt['imp_mod']+"."+opt['imp_opt'])

how to make top work like bottom?


If you think you have to use eval: you don't. Never.

module = __import__(opt['imp_mod'])
module.options

If the name "options" is not known until runtime, use getattr:

getattr(module, name_of_attribute)

The above assumes you want an attribute (like logging.ERROR). If you want  
a sub-module (a module inside a package) use __import__("dotted.name") and  
then retrieve the module by name from sys.modules; see  
http://docs.python.org/library/functions.html#__import__



--
Gabriel Genellina

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


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-12 Thread Paul Rubin
Raymond Hettinger  writes:
> In my quick research, it looks like many languages offer
> nothing more than the usual C style % formatting and defer
> the rest for a local aware module.

Hendrik van Rooyen's mention of Cobol's "picture" (aka PIC)
specifications might be added to the list.  Cautionary tale: I once
had a similar idea and suggested including a bastardized version of
PIC in an extension language for something I worked on once.  Another
programmer then coded a reasonable PIC subset and we shipped it.
Turned out that a number of our users were Cobol experts and once we
had anything like PIC, they expected the weirdest and most obscure
features (of which there were quite a few) of real Cobol PIC to work.
We ended up having to assign someone a fairly lengthy task of figuring
out the Cobol spec and implementing every last damn PIC feature.  But
I digress.


> > example, I think Common Lisp has a feature for formatting thousands.
> Do you have more detail?

 http://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node200.html

gives as an example:

 (format nil "The answer is ~:D." (expt 47 x)) 
=> "The answer is 229,345,007."

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


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-12 Thread Paul Rubin
Raymond Hettinger  writes:
> I found the Common Lisp spec for this and added it to the PEP.

Ah, cool, I simultaneously looked for it and posted about it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Raw String Question

2009-03-12 Thread Tim Chase

  >>> r"a\"
  SyntaxError: EOL while scanning string literal (, line 1)

It seems the parser is interpreting the backslash as an escape
character in a raw string if the backslash is the last character.
Is this expected?


Yep...as documented[1], "even a raw string cannot end in an odd 
number of backslashes".


-tkc


[1]
http://docs.python.org/reference/lexical_analysis.html




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


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-12 Thread Scott David Daniels

Raymond Hettinger wrote:
<... a generally interesting PEP...>

Missing from this PEP:
 output below the decimal point.

show results for something like:
  format(12345.54321, "15,.5f") --> '  12,345.543,21'

Explain the interaction on sizes and lengths (which numbers are digits,
which are length [I vote for length on overall, digits on precision]),
and what happens with length-4 -- I'd say explicitly 1000 is show as
"1,000" despite style sheets that prefer "1000" and "10,000".

FWIW, I agree with pruebano, do the simplest easily usable thing, and
provide a way to swap  the commas and periods.  The rest can be ponied
in by string processing.

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


Re: Building python 64-bit on OS 10.5?

2009-03-12 Thread Ned Deily
In article 
<[email protected]>,
 > I've two questions:
> 
> 1)  I've been trying to building python as a 64-bit version on OS 10.5.
> I'm not too familiar with building python from scratch, and a number of
> basic attempts made from piecing together things I've seen on the web have
> failed.   (For instance,
> 
>  ./configure --enable-framework --disable-toolbox-glue
> --with-universal-archs=all  --with-gcc="gcc -m64"
> 
> leads to a failure when I try to do "make", as do all other similar variants
> I've tried.)
> 
> So, is there a good source where I can find step-by-step 64-bit build
> instructions?  (I'd like to do it if possible as a framework build.)  I've
> looked it up a lot on google but am mostly getting fragments of descriptions
> of errors with other people's builds.

It's hard to diagnose a problem with so little information.  What 
version of python?  What failure?  In general, though, make sure you 
have a recent version of Apple's Developer Tools (aka Xcode) installed 
to get the Apple-supported gcc and friends.  There are a number of ways 
to build either a 64-bit only or a universal build that supports 32- and 
64-bit architectures.  See, for example, Graham Dumpleton's instructions 
at the bottom of this page:



>  2)  I often use a number of python extensions like matplot, pylab, and
> ipython.   Will these (especially the graphics parts) be able to build on
> top of my 64-bit installation?  Is there some way to find out if they will
> likely work without actually having to build them?

You may be able to find out more by checking forums specific to those 
products and/or the Mac python forum.

-- 
 Ned Deily,
 [email protected]

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


Re: Minimilistic Python on Linux?

2009-03-12 Thread Royce Wilson
Thanks, much better. What exactly do I lose when I launch python without
site.py?

On Wed, Mar 11, 2009 at 10:27 PM, Gabriel Genellina
wrote:

> En Thu, 12 Mar 2009 00:41:18 -0200, Royce Wilson 
> escribió:
>
>> On Wed, Mar 11, 2009 at 9:33 PM, Royce Wilson  wrote:
>>
>>  Thanks for the quick responses. When I view sys.modules I get this:
>>>
>>>  sre_compile _collections locale _sre functools encodings site operator
>>> io
>>> __main__ copyreg _weakref abc builtins encodings.cp437 errno
>>> sre_constants
>>> re encodings.latin_1 collections ntpath nt genericpath stat zipimport
>>> _codecs encodings.utf_8 encodings.cp1252 sys codecs _bytesio _thread
>>> os.path
>>> _functools _locale keyword signal _stringio _weakrefset encodings.aliases
>>> sre_parse os _abcoll _fileio
>>>
>>> Each module is seperated by a space.
>>>
>>> Can you give me in instructions on how to remove the site.py
>>> dependencies?
>>>
>>
> Start python with the -S option
>
>
> --
> Gabriel Genellina
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: loop performance in global namespace (python-2.6.1)

2009-03-12 Thread Duncan Booth
Poor Yorick  wrote:

> In the following snippet, the loop in the global namespace takes twice
> as long as the loop in the function namespace.  Why?
> 
Accessing global variables is generally slower than accessing local 
variables. Locals are effectively stored in a vector so the bytecode can go 
straight to the first local or the second local. Globals require a 
dictionary lookup.
--
http://mail.python.org/mailman/listinfo/python-list


Re: loop performance in global namespace (python-2.6.1)

2009-03-12 Thread Scott David Daniels

Poor Yorick wrote:
In the following snippet, the loop in the global namespace takes twice 
as long as the loop in the function namespace.  Why?


Locals are known to have no outside interaction, and so are not looked
up by name.  your code could have a thread that did,

 global counter
 while True:
 time.sleep(.1)
 counter *= 2


For that matter, it could do ... del counter ... and force a NameError
in your second loop.

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


Re: What happened to NASA at Python? :(

2009-03-12 Thread r
On Mar 12, 3:31 am, Michele Simionato 
wrote:

> That's pretty much impossible. I am sure NASA uses all programming
> languages in existence,
> plus probably many internal ones we never heard of.

True but...

>>> all([NASA.does_endorse(lang) for lang in NASA['languages']])
False

As the code suggests NASA doesn't sport an endorsement of X languages
on every X language's webpage, which i feel is very important for
Python's image, along with Google(Even more important!!), ILM, and
others.

I am really not worried if NASA *actually* uses Python or not(or to
what extent), just as long as they "say" they do is good enough for
me. *wink-wink*
--
http://mail.python.org/mailman/listinfo/python-list


Re: Raw String Question

2009-03-12 Thread Jim Garrison

Tim Chase wrote:

  >>> r"a\"
  SyntaxError: EOL while scanning string literal (, line 1)

It seems the parser is interpreting the backslash as an escape
character in a raw string if the backslash is the last character.
Is this expected?


Yep...as documented[1], "even a raw string cannot end in an odd number 
of backslashes".


-tkc


[1]
http://docs.python.org/reference/lexical_analysis.html


OK, I'm curious as to the reasoning behind saying that

   When an 'r' or 'R' prefix is present, a character following a
   backslash is included in the string without change, and all
   backslashes are left in the string.

which sounds reasonable, but then saying in effect "Oh wait, let's
introduce a special case and make it impossible to have a literal
backslash as the last character of a string without doubling it".

So you have a construct (r'...') whose sole reason for existence
is to ignore escapes, but it REQUIRES an escape mechanism for one
specific case (which comes up frequently in Windows pathnames).

I would suggest that this is pathologically inconsistent (now donning
my flameproof underwear "-)

At the very least the "all backslashes are left in the string" quote
from the Lexical Analysis page (rendered in italics no less) needs to
be reworded to include the exception instead of burying this in a
parenthetical side-comment.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Raw String Question

2009-03-12 Thread Nick Craig-Wood
Jim Garrison  wrote:
>   >>> r"a\b"
>'a\\b'
>   >>> r"a\"
>SyntaxError: EOL while scanning string literal (, line 1)
>   >>> r"a\ "
>'a\\ '
>   >>> r"a\""
>'a\\"'
> 
>  It seems the parser is interpreting the backslash as an escape
>  character in a raw string if the backslash is the last character.
>  Is this expected?

Yes

http://docs.python.org/reference/lexical_analysis.html#string-literals

  Specifically, a raw string cannot end in a single backslash (since
  the backslash would escape the following quote character).

The usual way round this is like this

>>> r"a" "\\"
'a\\'
>>>

Which isn't terribly elegant, but it doesn't happen very often.

-- 
Nick Craig-Wood  -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


RE: Question on periods in strings

2009-03-12 Thread Philip Bloom
Thanks.  I now know the cause of this, the suggestion to fling it in a few 
languages made it obvious.  All of them were sharing the issue.  Specifically 
that Trend MicroOffice Scan was the stalling factor, which was significantly 
boosting write times and if the write had any periods it would send it way off 
into the moon.  So yeah, the antivirus program was the culprit.

  Python was interestingly less affected than C# which saw a 15 times slowdown 
from the same effect.

Anyhow, sorry for bothering the list on what is clearly not a python problem, 
but thanks as well for helping lead me to the bottom of this mystery.


 -Original Message-
From: [email protected] 
[mailto:[email protected]] On Behalf Of 
Gabriel Genellina
Sent: Thursday, March 12, 2009 12:42 AM
To: [email protected]
Subject: Re: Question on periods in strings

En Wed, 11 Mar 2009 23:42:45 -0200, Philip Bloom   
escribió:

> Thanks for the welcome :)
>
> You're right.  Here's with the missed line (I was cutting out commented  
> parts).  Hopefully these are all cut/paste-able.
>
> #test A
> #runs in 5.8 seconds.
> from datetime import datetime
> testvar2='9a00'
> startTime = datetime.now()
> filehandle=open('testwriting.txt','w')
> for var in range(1000):
> filehandle.write(testvar2)
> filehandle.close()
> print (datetime.now() - startTime)
>
>
> #test B
> [using '9.00' -- otherwise identical]
>
> I do use the same filename, but I've run the tests in different orders  
> and it's made no difference.  Repeatedly running the same test results  
> in the same numbers with only minor fluctuations (as would be expected  
> from cache issues).  Ten runs in a row of Test B all result in about 11  
> seconds each.  Ten runs in a row of Test A all result in about 6 seconds  
> each.

I could not reproduce this. You've got better hardware than mine,  
certainly (I had to remove a 0 to get reasonable times) but I got almost  
identical results with both versions. I've tested also with 3.0 (and I had  
to take another 0 off!) with the same results.
I have no idea why you see a difference. Unless the antivirus is  
interfering, or you have some crazy driver monitoring disk activity and  
the dot triggers something...
Try using a different language - I'd say this is totally unrelated to  
Python.

-- 
Gabriel Genellina

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

__
This email has been scanned by the MessageLabs Email Security System.
For more information please visit http://www.messagelabs.com/email 
__

__
This email has been scanned by the MessageLabs Email Security System.
For more information please visit http://www.messagelabs.com/email 
__
--
http://mail.python.org/mailman/listinfo/python-list


Re: cross platform accessing paths (windows, linux ...)

2009-03-12 Thread Vlastimil Brom
> On Thu, Mar 12, 2009 at 8:10 AM, Vlastimil Brom 
> wrote:
>>
>> Hi all,
>> I'd like to ask for some advice on how to acomplish file access in a
>> cross platform way.
>> ...
>>
Any hints or comments are much appreciated; thanks in advance!
>>
>> regards,
>>   Vlasta


2009/3/12 Mike Mazurek :
> You might want to look at the path module:
>
> http://pypi.python.org/pypi/path.py/2.2
>
> It will probably make your code more readable.
>

Hi Mike,
thank you for the tip, I didn't know that module.
Actually I was trying to reduce the external dependencies (python and
wxpython only sofar); I'll look into it to see the improvement.
I guess, the need for such module actually seems to confirm, that the
path manipulation can be tricky in some cases ...

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


Re: Raw String Question

2009-03-12 Thread Duncan Booth
Jim Garrison  wrote:

> OK, I'm curious as to the reasoning behind saying that
> 
> When an 'r' or 'R' prefix is present, a character following a
> backslash is included in the string without change, and all
> backslashes are left in the string.
> 
> which sounds reasonable, but then saying in effect "Oh wait, let's
> introduce a special case and make it impossible to have a literal
> backslash as the last character of a string without doubling it".
> 
> So you have a construct (r'...') whose sole reason for existence
> is to ignore escapes, but it REQUIRES an escape mechanism for one
> specific case (which comes up frequently in Windows pathnames).
> 

You have a construct whose primary intent is to make it easier to write 
regular expressions without doubling all the backslashes. Regular 
expressions are quite likely to contain both single and double quote marks, 
so you need some way to include both kinds of quote marks. Regular 
expressions also cannot end with a single backslash.

If you need Windows pathnames then you can almost always just write them 
using forward slashes (and use os.path.normpath() on them if you really 
need backslashes).

There are many other strings which cannot be easily represented as a raw 
string: they are a convenience but not a replacement for ordinary string 
literals.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Raw String Question

2009-03-12 Thread Jim Garrison

Tim Chase wrote:

  >>> r"a\"
  SyntaxError: EOL while scanning string literal (, line 1)

It seems the parser is interpreting the backslash as an escape
character in a raw string if the backslash is the last character.
Is this expected?


Yep...as documented[1], "even a raw string cannot end in an odd number 
of backslashes".


So how do you explain this?

>>> r'a\'b'
"a\\'b"

The backslash is kept, but it causes the following quote to be escaped.
--
http://mail.python.org/mailman/listinfo/python-list


Getting final url when original url redirects

2009-03-12 Thread IanR
I'm processing RSS content from a # of given sources.  Most of the
time the url given by the RSS feed redirects to the real URL (I'm
guessing they do this for tracking purposes)

For example.

This is a url that I get from and RSS feed,
http://www.pheedcontent.com/click.phdo?i=d22e9bc7641aab8a0566526f61806512
It redirects to
http://www.macsimumnews.com/index.php/archive/klipsch_developing_headphones_for_new_ipod_shuffle/

I want to record the final URL and not the URL I get from the RSS feed
(However sometimes there is no redirect so I might want the original
URL)

I've tried sniffing the header and don't see any "Location:"... I
think sites are using different ways to redirect.  Does anyone have
any suggestions on how I might handle this?

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


unbiased benchmark

2009-03-12 Thread Sam Ettessoc
Dear sir,

I would like to share a benchmark I did. The computer used was a
2160MHz Intel Core Duo w/ 2000MB of 667MHz DDR2 SDRAM running MAC OS
10.5.6 and a lots of software running (a typical developer
workstation).

Python benchmark:
HAMBURGUESA:benchmark sam$ echo 1+1 > bench.py
HAMBURGUESA:benchmark sam$ time python bench.py
real0m0.064s
user0m0.049s
sys 0m0.013s

Ruby benchmark:
HAMBURGUESA:benchmark sam$ echo 1+1 > bench.rb
HAMBURGUESA:benchmark sam$ time ruby bench.rb
real0m0.006s
user0m0.003s
sys 0m0.003s

Can you believe it? Ruby is 10 times faster than Python.

On a side note, when I subscribed to the Python mailing list, it took
less than 200ms before I got the confirmation email. For the Ruby
mailing list, it took over 9000ms! Which is 4500% less performant!

Sam Ettessoc
p.s. I have no affiliation with ruby or python devloppement team.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Raw String Question

2009-03-12 Thread Albert Hopkins

> > Yep...as documented[1], "even a raw string cannot end in an odd number 
> > of backslashes".
> 
> So how do you explain this?
> 
>  >>> r'a\'b'
>  "a\\'b"

That doesn't "end in an odd number of backslashes."

Python is __repr__esenting a raw string as a "regular" string.
Literally they are equivalent:

>>> a = r'a\'b'
>>> b = "a\\'b"
>>> a
"a\\'b"
>>> b
"a\\'b"
>>> print a
a\'b
>>> print b
a\'b
>>> a == b
True


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


Re: What happened to NASA at Python? :(

2009-03-12 Thread Martin v. Löwis
>>> The Python home page no longer sports a promotion from NASA. What
>>> happened, did we lose NASA. Where did they go?
>> The python.org guys just decided it would be nice to have some
>> different graphics.
> 
> If they were so keen on new graphics, why did 2.6 revert
> to the same icons that 2.4 used? 

None of the people selecting the graphics had anything to do with
the icon in the 2.6 MSI file. Why are you assuming there is any
connection?

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


Re: unbiased benchmark

2009-03-12 Thread Grant Edwards
On 2009-03-12, Sam Ettessoc  wrote:
> Dear sir,

[Rather odd "benchmark" troll elided.]


> Sam Ettessoc
> p.s. I have no affiliation with ruby or python devloppement team.

A fact for which I'm sure both communities are grateful.

-- 
Grant Edwards   grante Yow! I feel like a wet
  at   parking meter on Darvon!
   visi.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: unbiased benchmark

2009-03-12 Thread Daniel Fetchinson
> Dear sir,
>
> I would like to share a benchmark I did. The computer used was a
> 2160MHz Intel Core Duo w/ 2000MB of 667MHz DDR2 SDRAM running MAC OS
> 10.5.6 and a lots of software running (a typical developer
> workstation).
>
> Python benchmark:
> HAMBURGUESA:benchmark sam$ echo 1+1 > bench.py
> HAMBURGUESA:benchmark sam$ time python bench.py
> real  0m0.064s
> user  0m0.049s
> sys   0m0.013s
>
> Ruby benchmark:
> HAMBURGUESA:benchmark sam$ echo 1+1 > bench.rb
> HAMBURGUESA:benchmark sam$ time ruby bench.rb
> real  0m0.006s
> user  0m0.003s
> sys   0m0.003s
>
> Can you believe it? Ruby is 10 times faster than Python.
>
> On a side note, when I subscribed to the Python mailing list, it took
> less than 200ms before I got the confirmation email. For the Ruby
> mailing list, it took over 9000ms! Which is 4500% less performant!
>
> Sam Ettessoc
> p.s. I have no affiliation with ruby or python devloppement team.

Even more amazingly, it takes approximately 30% less time to say
'ruby' than to say 'python'!!!


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


finally successful in ods with python, just one help needed.

2009-03-12 Thread Krishnakant
Hello all specially John and Terry.

I finally got my way around odfpy and could manage the spreadsheet to
some extent.

However I now have a small but unexpected problem.

I would be very happy if some one could help me understand why is the
text not getting centered in the spreadsheet I create.

The cell merging is happening but no text centering in those merged
cells.

If any one is interested I can send my part of code snippid.
to just tell in short, it just has the sudo code as 
create document

create a style to set centered text 

create table and add rows to which cells are added.
the cell has a p (paragraph ) element with the style of centered text
applied.

cells are merged 

but no centering happens.

Please let me know if any one wanted me to send the code off the list.

Even better, if some one has a code snippid which can just do that.

happy hacking.
Krishnakant.




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


Re: unbiased benchmark

2009-03-12 Thread Chris Rebert
On Thu, Mar 12, 2009 at 1:07 PM, Sam Ettessoc  wrote:
> I would like to share a benchmark I did. The computer used was a
> 2160MHz Intel Core Duo w/ 2000MB of 667MHz DDR2 SDRAM running MAC OS
> 10.5.6 and a lots of software running (a typical developer
> workstation).
>
> Python benchmark:
> HAMBURGUESA:benchmark sam$ echo 1+1 > bench.py
> HAMBURGUESA:benchmark sam$ time python bench.py
> real    0m0.064s
> user    0m0.049s
> sys     0m0.013s
>
> Ruby benchmark:
> HAMBURGUESA:benchmark sam$ echo 1+1 > bench.rb
> HAMBURGUESA:benchmark sam$ time ruby bench.rb
> real    0m0.006s
> user    0m0.003s
> sys     0m0.003s
>
> Can you believe it? Ruby is 10 times faster than Python.

I submit that you are effectively just comparing start-up times:

$ time ruby < /dev/null

real0m0.006s
user0m0.003s
sys 0m0.003s

$ time python < /dev/null

real0m0.020s
user0m0.011s
sys 0m0.009s

Since Python includes a full interactive interpreter REPL, whereas
Ruby doesn't, you're comparing apples to oranges. A more fair
comparison would be to compare python and irb:

$ time irb http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >