Code objects

2007-07-23 Thread Evan Klitzke
I was playing around with the inspect module tonight, and I have a
question about "code components". Can an object have more than one
code component? For example, will the following code ever create a
list whose length is greater than one?

import inspect

# Some code here defining an object/function foo

components = [cc[1] for cc in inspect.getmembers(foo,\
inspect.iscode)]

-- 
Evan Klitzke <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need Help with base64

2007-07-23 Thread Tim Roberts
pycraze <[EMAIL PROTECTED]> wrote:
>
>int base641_decodestring(char* pcstr,int size,char** ppcdest)
>{
>  unsigned char cin[4] = {""};
>  unsigned char cout[3] = {""};
>  unsigned char  cv = 0;
>  int ni = 0;
>  int nlen = 0;
>  char* cptr = pcstr;
>  *ppcdest = malloc(sizeof(char)*160);
>  if (!*ppcdest)
>{
>return 1;
>}
>  memset(*ppcdest,0,sizeof(char)*160);
>
>  char* pcstring = malloc( sizeof(char) * SIZE);
>if (!pcstring)
>  {
>  aps_log("APS_log.txt","\nbae64.c:base64encode:malloc failed
>\n");
>  return 1;
>  }
>  memset(pcstring,'\0',SIZE);

Those last 7 lines must have been leftover; pcstring is not used in this
routine.

>for( nlen = 0, ni = 0; ni < 4; ni++ )
>  {
>cv = 0;
>while(  cv == 0 )
>  {
>cv = (unsigned char) *cptr;
>cv = (unsigned char) ((cv < 43 || cv > 122) ? 0 :
>cd64[ cv - 43 ]);
>if( cv )
>{
>cv = (unsigned char) ((cv == '$') ? 0 : cv - 61);
>}
>}
>if( cptr++ )
>  {
>nlen++;
>if( cv )
>{
>cin[ ni ] = (unsigned char) (cv - 1);
>}
>}
>else
>  {
>cin[ni] = 0;
>}
>}
>if( nlen )
>  {
>decodeblock( cin, cout );
>
>}
>  memcpy(*ppcdest,cout,160);
>  return 0;

"cout" is an array of 3 characters.  Where do you think the memcpy is going
to find 160 bytes?  I suspect you intended to have this loop inside a
SECOND loop, copying 3 characters at a time into *ppcdest.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python Trainers, Promote Thyself!

2007-07-23 Thread Jeff Rush
With the recent establishment of the wiki page on python.org for those who
offer training services for the Python language, we now have 23 listed, 
worldwide.

http://wiki.python.org/moin/PythonTraining

Many of the trainers are individuals or small companies, and it can be hard to
get the attention of the big IT houses.  While skill credentials and a
portfolio of past training gigs are important, perhaps one of the best
promoters is when someone has actually experienced one of your classes.  They
gain insight into your speaking style, how you relate to the students and your
ability to explain complex technical subjects in an approachable way.  No
class syllabus can convey that.  The Python community has a valuable resource
that can give you the next best thing.  Screencasting!

Screencasting is a multimedia creation that focuses on the instructor's
desktop, with voiceover guidance.  It can be in the format of an online
slideshow, a guided sourcecode walkthrough or a follow-along interactive
session.  They can be as long or short as you wish and they have opportunities
for branding, by using custom wallpaper behind your talks desktop and musical
lead-in/fade-out.

Screencasts can be hosted on www.showmedo.com or, if done with a large font,
video.google.com.  They can also be embedded in your website while hosted
elsewhere, as shown at:

http://www.python.org/doc/av/5minutes/

You can learn more about the details with a talk series I put together:

Casting Your Knowledge, With Style
http://www.showmedo.com/videos/series?name=bETR23HwS

But perhaps you're really busy on current projects and short on time. Consider
 arranging an audio interview about an upcoming seminar you're offering and
making it available as a podcast.  Ron Stephens of Python 411 makes available
an excellent collection of podcasts and may be interested in hosting yours.

Unlike face-to-face presentation opportunities, screencasts/podcasts have the
additional benefit that they promote your training offerings while you're busy
on other gigs.  It's almost like cloning yourself and having more time for
promotion.  It's all about leverage.

Jeff Rush
Python Advocacy Coordinator
-- 
http://mail.python.org/mailman/listinfo/python-list


wxPython Internationalization

2007-07-23 Thread [EMAIL PROTECTED]
I know this may have a very simple answer, nonetheless.  I am wishing
to find the cleanest and most pythonic way of implementing the
following:

I am creating a internationalized application in wxPython and have
sorted the directory structure in the following manner:

start.py


metamenus.py
main.py

[various files]

[various files]

Here's the code for the files shown above:

# start.py

if __name__ == '__main__':
import .main
app = .MyApp(0)
app.MainLoop()

# main.py

import wx
from metamenus import MenuBarEx

class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title,
wx.DefaultPosition, wx.Size(380, 250))

menu = \
[[
[_('&File')],
[_('Open a new document')],
[_('Save the document')]
],
[
[_('&Edit')]
],
[
[_('&View')]
],
[
[_('&Quit\tCtrl+Q')],
[_('Quit the Application')],
[_('&Help')]
]]

self.mainmenu = MenuBarEx(self, menu)

def OnQuit(self, event):
self.Close()

class MyApp(wx.App):
def OnInit(self):
self.frame = MyFrame(None, -1, 'Title')
self.frame.Raise()
self.frame.Refresh()
self.frame.Show(True)
return True

So here's my question.  I wish to add the following code so that the _
method will become of use.

Here is the code http://wiki.wxpython.org/Internationalization
recommends:

import wx
import os
import platform
import codecs
import sys
import gettext

def main():
# initialise language settings:
path = sys.path[0].decode(sys.getfilesystemencoding())
try:
langIni = codecs.open(os.path.join(path,u'language.ini'),'r',
'utf-8')
except IOError:
language = u'en' #defaults to english
pass
else:
language = langIni.read()

locales = {
u'en' : (wx.LANGUAGE_ENGLISH, u'en_US.UTF-8'),
u'es' : (wx.LANGUAGE_SPANISH, u'es_ES.UTF-8'),
u'fr' : (wx.LANGUAGE_FRENCH, u'fr_FR.UTF-8'),
}
mylocale = wx.Locale(locales[language][0], wx.LOCALE_LOAD_DEFAULT)
langdir = os.path.join(path,u'locale')
Lang = gettext.translation(u'messages', langdir,
languages=[language])
Lang.install(unicode=1)

if platform.system() == 'Linux':
try:
# to get some language settings to display properly:
os.environ['LANG'] = locales[language][1]

except (ValueError, KeyError):
pass


#-> Code to launch application goes here. <-#



if __name__ == '__main__':
if 'unicode' not in wx.PlatformInfo:
print "\nInstalled version: %s\nYou need a unicode build of
wxPython to run this application.\n"%version
else:
main()

So my question is, where would the best place be to implement the code
above?  In start.py, main.py, in a separate file altogether? The
problem I seem to be having is needing an instance of wx.App before
the code recommended by the http://wiki.wxpython.org/Internationalization
can become of use.

I've come up with solutions to my dilemma but none seem to be
especially clean.  Any recommendations would be great.  Also if any
clarifications are needed let me know.

Thanks

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


Re: Parsing XML with ElementTree (unicode problem?)

2007-07-23 Thread oren . tsur
On Jul 23, 4:46 pm, "Richard Brodie" <[EMAIL PROTECTED]> wrote:
> <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
>
> > so what's the difference? how comes parsing is fine
> > in the first case but erroneous in the second case?
>
> You may have guessed the encoding wrong. It probably
> wasn't utf-8 to start with but iso8859-1 or similar.
> What actual byte value is in the file?

I tried it with different encodings and it didn't work. Anyways, I
would expect it to be utf-8 since the XML response to the amazon query
indicates a utf-8 (check it with
http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=189P5TE3VP7N9MN0G302&Operation=ItemLookup&ItemId=1400079179&ResponseGroup=Reviews&ReviewPage=166

 in your browser, the first line in the source is )

but the thing is that the parser parses it all right from the web (the
amazon response) but fails to parse the locally saved file.

> > 2. there is another problem that might be similar I get a similar
> > error if the content of the (locally saved) xml have special
> > characters such as '&'
>
> Either the originator of the XML has messed up, or whatever
> you have done to save a local copy has mangled it.

I think i made a mess. I changed the '&' in the original response to
'and' because the parser failed to parse the '&' (in the locally saved
file) just like it failed with the French characters. Again, parsing
the original response was just fine.

Thanks again,

Oren


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


Re: code packaging

2007-07-23 Thread Paul Rubin
[EMAIL PROTECTED] (John J. Lee) writes:
> You can go further: in addition to developing a Debian package (or a
> few of them) for your own project, build your OS image using
> debootstrap (you'll probably want your own local repository(ies), for
> reproducibility).  Then you do your development in a virtual machine
> or chroot environment.  That way you develop in the same (or very
> similar) environment to the one in which your code will eventually be
> deployed (one difference being the use of an version control checkout
> rather a .deb install for the code you're actually working on, unless
> troubleshooting problems that are somehow tied up with that particular
> aspect of deployment).  I've seen this working in a real-world
> project.

Thanks for these suggestions.  Buildbot (per Ben Finney) looks
interesting as does the above, and Ryan's notes about experience with
Windows installers is also appreciated.  Whether lot of build
automation would have been worth it at the beginning of the thing I'm
working on or not, we probably need to move towards it now that more
of the system is running.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confused with csv.reader copies

2007-07-23 Thread Jeethu Rao
Robert Dailey wrote:
> First, take a look at my example code:
> -
> import csv
>
> def pass1( reader ):
>   print reader.next()
>   print reader.next()
>
> def pass2( reader ):
>   print reader.next()
>   print reader.next()
>
> reader = csv.reader( open( "C:/IT/Method/SpaceImpact/code/tools/
> ProfileViewer/performance_profile.csv", "rb" ) )
>
> pass1( reader )
> pass2( reader )
> -
>   
Like Gabriel suggested, using itertools.tee should do the trick.

-

import csv
from itertools import tee

def pass1( reader ):
print reader.next()
print reader.next()

def pass2( reader ):
print reader.next()
print reader.next()

reader1,reader2 = tee( csv.reader( open( "C:/IT/Method/SpaceImpact/code/tools/
ProfileViewer/performance_profile.csv", "rb" ) ) )

pass1( reader1 )
pass2( reader2 )
-


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


Re: Where do they tech Python officialy ?

2007-07-23 Thread Paul Rubin
NicolasG <[EMAIL PROTECTED]> writes:
> Does some one have any suggestions on which University to attend ?
> Alternatives solutions are welcome..

If you have a good programming background in other languages, you
should easily be able to pick up Python by reading the manual.

If you don't have a programming background and want to acquire one
through a university program, then it doesn't matter that much what
language the university uses, since if it's not Python, after
completing the program you'll still be able to easily pick up Python
by reading the manual.


If you're having trouble with Python because you're new at
programming, I can sympathize--I don't think it's the most
beginner-friendly of languages despite the efforts in that direction
by the designers.  But once you understand the principles of
programming, Python is easy.

I think Python is not used in university programs very much.  Look for
one that uses SICP (Scheme) or CTM (Mozart/Oz) or a functional
language like Haskell, in preference to the ones that use Java (the
Cobol of the 1990's).  With some reasonable experience in Scheme or
Mozart or Haskell, plus a Python manual, you'll be well on your way.

The SICP textbook is here:  

http://mitpress.mit.edu/sicp/

Maybe it's gotten a little bit old fashioned by now, but it's still
good reading.
-- 
http://mail.python.org/mailman/listinfo/python-list


Usergroups Forming: Arizona and Carolina US Regions

2007-07-23 Thread Jeff Rush
Two new Python usergroups are being organized!

= Arizona =

Michael March is starting a group for those in the Flagstaff/Phoenix/Tucson
region of Arizona.  The first meeting to get organized will be held on *Monday
July 30th* at 6:30pm.  Location is not yet set -- need input from potential
attendees.

If you are interested, a mailing list and wiki page have been established:

  http://mail.python.org/mailman/listinfo/sunpiggies

  http://wiki.python.org/moin/ValleyOfTheSunPiggies

And also a Meetup.com group, where you can sign up to receive automated
calendar reminders of group activities.

  http://python.meetup.com/184/


= North/South Carolina =

While there is an existing group TriZPUG for the Raleigh-Durham-Chapel Hill
region, a new group is being formed for the *Charlotte and North-Central South
Carolina area*.  No meetings have yet been scheduled - to participate in
discussions join the Google Group:

  http://groups.google.com/group/charpy


= Other Groups =

There are 34 states with Python usergroups, leaving 16 without any Python
organizations at all -- and this is just in the United States.  We would like
to encourage the formation of more groups worldwide.  If you've been wishing
there were meetings near you, step forward and help initiate or revitalize
one.  There are experienced organizers waiting to mentor you on the mailing 
list:

  http://mail.python.org/mailman/listinfo/group-organizers

Usergroups are a lot of fun, a source of employment opportunities and a great
way to enhance your programming and teaching skills.  The Python Software
Foundation and the experienced group organizers are ready to support you in
your efforts.

Jeff Rush
Python Advocacy Coordinator

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


Re: pylint style convention

2007-07-23 Thread Ben Finney
[EMAIL PROTECTED] (Mick Charles Beaver) writes:

> Here's a snippet:

pylint is reporting line numbers. Can you show us line numbers for
this snippet?

> #==
> if __name__ == '__main__':
> parser = optparse.OptionParser(usage='usage: %prog [OPTIONS]')
> parser.add_option('-c', '--config',
>   action='store',
>   type='string',
>   dest='configFilename',
>   help='config file containing defaults')
> (options, args) = parser.parse_args()
> #==
> 
> Now, PyLint reports the following convention warnings:
> C:158: Invalid name "parser" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$)
> C:170: Invalid name "options" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$)
> C:170: Invalid name "args" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$)

These warnings are for line 158 and line 170, which covers a range of
13 lines. Your code snippet is only 8 lines long. So at least one of
those two lines that have warnings reported are not in the code you've
shown to us.

-- 
 \"Too many Indians spoil the golden egg."  -- Sir Joh |
  `\   Bjelke-Petersen |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: idiom for RE matching

2007-07-23 Thread Gabriel Genellina
En Tue, 24 Jul 2007 00:23:46 -0300, Gordon Airporte <[EMAIL PROTECTED]>  
escribió:

> [EMAIL PROTECTED] wrote:
>> if your search is not overly complicated, i think regexp is not
>> needed. if you want, you can post a sample what you want to search,
>> and some sample input.
>
> I'm afraid it's pretty complicated :-). I'm doing analysis of hand
> histories that online poker sites leave for you. Here's one hand of a
> play money ring game:
>
>
> Full Tilt Poker Game #2042984473: Table Play Chip 344 - 10/20 - Limit
> Hold'em - 18:07:20 ET - 2007/03/22
> Seat 1: grandmarambo (1,595)
> Seat 4: justnoldfoolm (2,430)
> justnoldfoolm posts the small blind of 5
> rickrn posts the big blind of 10
> The button is in seat #1
> *** HOLE CARDS ***
> Dealt to moi [Jd 2c]
> justnoldfoolm bets 10
> [more sample lines]
>
> So I'm picking out all kinds of info about my cards, my stack, my
> betting, my position, board cards, other people's cards, etc. For
> example, this pattern picks out which player bet and how much:
>
> betsRe   = re.compile('^(.*) bets ([\d,]*)')
>
> I have 13 such patterns. The files I'm analyzing are just a session's
> worth of histories like this, separated by \n\n\n. All of this
> information needs to be organized by hand or by when it happened in a
> hand, so I can't just run patterns over the whole file or I'll lose  
> context.
> (Of course, in theory I could write a single monster expression that
> would chop it all up properly and organize by context, but it would be
> next to impossible to write/debug/maintain.)

But you don't HAVE to use a regular expression. For so simple and  
predictable input, using partition or 'xxx in string' is around 4x faster:

import re

betsRe = re.compile('^(.*) bets ([\d,]*)')

def test_partition(line):
   who, bets, amount = line.partition(" bets ")
   if bets:
 return who, amount

def test_re(line):
   r = betsRe.match(line)
   if r:
 return r.group(1), r.group(2)

line1 = "justnoldfoolm bets 10"
assert test_re(line1) == test_partition(line1) == ("justnoldfoolm", "10")
line2 = "Uncalled bet of 20 returned to justnoldfoolm"
assert test_re(line2) == test_partition(line2) == None

py> timeit.Timer("test_partition(line1)", "from __main__ import  
*").repeat()
:2: SyntaxWarning: import * only allowed at module level
[1.1922188434563594, 1.2086988709458808, 1.1956522407177488]
py> timeit.Timer("test_re(line1)", "from __main__ import *").repeat()
:2: SyntaxWarning: import * only allowed at module level
[5.2871529761464018, 5.2763971398599523, 5.2791986132315714]

As is often the case, a regular expression is NOT the right tool to use in  
this case.

-- 
Gabriel Genellina

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


Re: idiom for RE matching

2007-07-23 Thread Gordon Airporte
[EMAIL PROTECTED] wrote:
> if your search is not overly complicated, i think regexp is not
> needed. if you want, you can post a sample what you want to search,
> and some sample input.

I'm afraid it's pretty complicated :-). I'm doing analysis of hand 
histories that online poker sites leave for you. Here's one hand of a 
play money ring game:


Full Tilt Poker Game #2042984473: Table Play Chip 344 - 10/20 - Limit 
Hold'em - 18:07:20 ET - 2007/03/22
Seat 1: grandmarambo (1,595)
Seat 4: justnoldfoolm (2,430)
Seat 5: rickrn (1,890)
Seat 7: harlan312 (820)
Seat 8: moi (335)
justnoldfoolm posts the small blind of 5
rickrn posts the big blind of 10
The button is in seat #1
*** HOLE CARDS ***
Dealt to moi [Jd 2c]
harlan312 calls 10
moi folds
grandmarambo calls 10
justnoldfoolm raises to 20
rickrn folds
harlan312 calls 10
grandmarambo calls 10
*** FLOP *** [7s 8s 2s]
justnoldfoolm bets 10
harlan312 raises to 20
grandmarambo calls 20
justnoldfoolm raises to 30
harlan312 calls 10
grandmarambo calls 10
*** TURN *** [7s 8s 2s] [3d]
justnoldfoolm bets 20
harlan312 calls 20
grandmarambo calls 20
*** RIVER *** [7s 8s 2s 3d] [7h]
justnoldfoolm bets 20
harlan312 folds
grandmarambo folds
Uncalled bet of 20 returned to justnoldfoolm
justnoldfoolm mucks
justnoldfoolm wins the pot (220)
*** SUMMARY ***
Total pot 220 | Rake 0
Board: [7s 8s 2s 3d 7h]
Seat 1: grandmarambo (button) folded on the River
Seat 4: justnoldfoolm (small blind) collected (220), mucked
Seat 5: rickrn (big blind) folded before the Flop
Seat 7: harlan312 folded on the River
Seat 8: moi didn't bet (folded)


So I'm picking out all kinds of info about my cards, my stack, my 
betting, my position, board cards, other people's cards, etc. For 
example, this pattern picks out which player bet and how much:

betsRe   = re.compile('^(.*) bets ([\d,]*)')

I have 13 such patterns. The files I'm analyzing are just a session's 
worth of histories like this, separated by \n\n\n. All of this 
information needs to be organized by hand or by when it happened in a 
hand, so I can't just run patterns over the whole file or I'll lose context.
(Of course, in theory I could write a single monster expression that 
would chop it all up properly and organize by context, but it would be 
next to impossible to write/debug/maintain.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code indentation

2007-07-23 Thread Gabriel Genellina
En Mon, 23 Jul 2007 16:53:01 -0300, ...:::JA:::...  
<[EMAIL PROTECTED]> escribió:

>> If you are using the tokenize module as suggested some time ago, try to
>> analyze the token sequence you get using { } (or perhaps begin/end pairs
>> in your own language, that are easier to distinguish from a dictionary
>> display) and the sequence you get from the "real" python code. Then  
>> write
>> a script to transform one into another:
>
>> from tokenize import generate_tokens
>> from token import tok_name
>  >from cStringIO import StringIO
>
>> def analyze(source):
>   >   g = generate_tokens(StringIO(source).readline)
>>  for toknum, tokval, _, _, _  in g:
>  >print tok_name[toknum], repr(tokval)
>
>> I think you basically will have to ignore INDENT, DEDENT, and replace
>> NAME+"begin" with INDENT, NAME+"end" with DEDENT.
>
> So..how can I do this?
> I will appreciate any help!

Try with a simple example. Let's say you want to convert this:

for x in range(10):
begin
print x
end

into this:

for x in range(10):
   print x

Using the analyze() function above, the former block (pseudo-python) gives  
this sequence of tokens:

NAME 'for'
NAME 'x'
NAME 'in'
NAME 'range'
OP '('
NUMBER '10'
OP ')'
OP ':'
NEWLINE '\n'
NAME 'begin'
NEWLINE '\n'
NAME 'print'
NAME 'x'
NEWLINE '\n'
NAME 'end'
ENDMARKER ''

The latter block ("real" python) gives this sequence:

NAME 'for'
NAME 'x'
NAME 'in'
NAME 'range'
OP '('
NUMBER '10'
OP ')'
OP ':'
NEWLINE '\n'
INDENT '  '
NAME 'print'
NAME 'x'
DEDENT ''
ENDMARKER ''

If you feed this token sequence into untokenize, in response you get a  
source code equivalent to the "real" python example above. So, to convert  
your "pseudo" python into the "real" python, it's enough to convert the  
first token sequence into the second - and from that, you can reconstruct  
the "real" python code. Converting from one sequence into the other is a  
programming exercise and has nothing to do with the details of the  
tokenize module, nor is very Python-specific - looking at both sequences  
you should figure out how to convert one into the other. (Hint: a few  
additional newlines are not important)

It is even simpler than the example given in the tokenize documentation:  
 - which transforms  
3.1416 into Decimal("3.1416") by example.

Once you get this simple case working, you may try what happens with this:

for x in range(10):
   begin
 print x
   end

and this:

for x in range(10): begin
   print x
end

and later this:

for x in range(10):
   begin
 print x
end

You are now using explicit begin/end pairs to group statements, so  
indentation is no more significant. You may want to preprocess the  
pseudo-python source, stripping any leading blanks, before using tokenize  
- else you'll get indentation errors (which are bogus in your  
pseudo-python dialect).

Since this will be your own Python dialect, don't expect that someone else  
will do the work for you - you'll have to do it yourself. But it's not too  
dificult if you do the things in small steps. In case you get stuck at any  
stage and have specific questions feel free to ask.

-- 
Gabriel Genellina

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


classmethod & staticmethod

2007-07-23 Thread james_027
hi,

python's staticmethod is the equivalent of java staticmethod right?

with classmethod, I can call the method without the need for creating
an instance right? since the difference between the two is that
classmethod receives the class itself as implicti first argument. From
my understanding classmethod are for dealing with class attributes?

Can somebody teach me the real use of classmethod & staticmethod?

Thanks
james

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


Re: Re-running unittest

2007-07-23 Thread Israel Fernández Cabrera
Hi Gabriel

> Perhaps the best option is to run the tests in another process. Use any of
> the available IPC mechanisms to gather the test results. This has the
> added advantage of isolating the tested code from your GUI testing
> framework; all requested resources are released to the OS; the tests run
> in a predictable environment; etc.

This could be a solution it will complicate the GUI design, for
example the current test number to implement a progress bar or
something like that, but I think a well designed IPC may help again.
Thks again for the tips, regards


-- 

Israel Fdez. Cabrera
[EMAIL PROTECTED]
Linux registered user No.: 270292
[http://counter.li.org]

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


Re: set_proxy in urllib2 is driving my crazy

2007-07-23 Thread O.R.Senthil Kumaran
* est <[EMAIL PROTECTED]> [2007-07-23 09:50:17]:

> A simple py script
> 
> import urllib2
> req=urllib2.Request("http://www.google.com";)
> req.set_proxy("127.0.0.1:1","http")
> print urllib2.urlopen(req).read()
> 

Try to use the ProxyHandler of urllib2.

import urllib2
proxy_url = 'http://' + PROXY_USER + ':' + PROXY_PASSWORD + \ '@' + PROXY_IP + 
':' + PROXY_PORT
proxy_support = urllib2.ProxyHandler({'http': proxy_url})
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
print urllib2.urlopen(req).read()

> urllib2.URLError: 

The error indicates a network issue. Please see the difference when you use
the ProxyHandler to try it.


-- 
O.R.Senthil Kumaran
http://uthcode.sarovar.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Subclassing int

2007-07-23 Thread G

Thanks a lot Matt and Steve. I replaced __int__ with __new__ and it worked


On 7/23/07, Matt McCredie <[EMAIL PROTECTED]> wrote:


Do you guys know why the if statement is not evaluated?


For immutable types __new__ is called before __init__. There are some
details here: http://docs.python.org/ref/customization.html. Also, it
isn't really clear what you want to do if the value is set to None anyway.
In your example you return None, but that simply won't work since you can't
return anything from __init__. Perhaps your need could be met by a function
instead:


def INT(x):
if x is None:
return None
else: return int(x)


-Matt



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

[XBOX] Python XBOX360 Migration Question

2007-07-23 Thread [EMAIL PROTECTED]
Hello ALL,

I have just migrated python-core to xbox360. I wonder if someone else
has already done it yet ?
The ctypes-module-migration puzzle me because I seldom use powerpc
assembly.
Can someone give me a hint ??

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


Re: pylint style convention

2007-07-23 Thread Michael Hoffman
Mick Charles Beaver wrote:
> Hello,
> 
> I've been looking into using PyLint on some of my programs, just as a
> best practices kind of thing.
> 
> Here's a snippet:
> #==
> if __name__ == '__main__':
> parser = optparse.OptionParser(usage='usage: %prog [OPTIONS]')
> parser.add_option('-c', '--config',
>   action='store',
>   type='string',
>   dest='configFilename',
>   help='config file containing defaults')
> (options, args) = parser.parse_args()
> #==
> 
> Now, PyLint reports the following convention warnings:
> C:158: Invalid name "parser" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$)
> C:170: Invalid name "options" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$)
> C:170: Invalid name "args" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$)
> 
> Which style convention is it referring to? Should these really be all
> caps?

There's a style convention that global constants at file scope are 
defined in all caps.

Personally, I do all my optparsing in a special function rather than in 
the __name__ == '__main__' block.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Hacking with __new__

2007-07-23 Thread Sandra-24
Ok here's the problem, I'm modifying a 3rd party library (boto) to
have more specific exceptions. I want to change S3ResponseError into
about 30 more specific errors. Preferably I want to do this by
changing as little code as possible. I also want the new exceptions to
be a subclass of the old S3ResponseError so as to not break old code
that catches it. If I meet these two requirements I expect my
modification to make it into boto and then I won't have to worry about
maintaining a seperate version.

So thinking myself clever with python I thought I could change
S3ResponseError to have a __new__ method which returns one of the 30
new exceptions. That way none of the raise S3ResponseError code needs
changing. No problem. The trouble comes with those exceptions being
subclasses of S3ResponseError, because __new__ is called again and
goofs everything up.

I think there may be a way to solve this but after playing around in
the shell for a while, I give up. I'm less concerned with the original
problem than I am curious about the technical challenge. Can anyone
tell me if it's possible to do meet both of my requirements?

Thanks,
-Sandra

Here's my shell code if you want to play with it too (Bar is
S3ResponseError, Zoo is a more specific error, Foo is just the base
class of Bar.)

>>> class Foo(object):
... def __new__(cls, *args):
... print 'Foo.__new__', len(args)
... return super(Foo, cls).__new__(cls, *args)
...
... def __init__(self, a, b, c):
... print 'Foo.__init__', 3
... self.a = a
... self.b = b
... self.c = c
...
>>> class Bar(Foo):
... def __new__(cls, a, b, c, *args):
... print 'Bar.__new__', len(args)
... if args:
... return super(Bar, cls).__new__(cls, a, b, c, *args)
...
... return Zoo(a, b, c, 7)
...
>>> class Zoo(Bar):
... def __init__(self, a, b, c, d):
... print 'Zoo.__init__', 4
... Foo.__init__(self, a, b, c)
... self.d = d
...
>>> Bar(1,2,3)
Bar.__new__ 0
Bar.__new__ 1
Foo.__new__ 4
Zoo.__init__ 4
Foo.__init__ 3
Traceback (most recent call last):
  File "", line 1, in 
TypeError: __init__() takes exactly 5 arguments (4 given)

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


Re: Re-running unittest

2007-07-23 Thread Gabriel Genellina
At 23/07/2007 09:59, "Israel Fernández Cabrera" <[EMAIL PROTECTED]> wrote:

(Please keep posting on the list - many other people may have better ideas  
on this)

> Well... probably my English and my intentions to not ti write
> to much made my explanation unclear. The code I wrote was just
> to illustrate my problem, is not the "real" code. Your
> assumptions were OK, I?m loading the test inside and IDE, but
> not IDLE. What I want to to is to "discover" the tests, and
> then provide a GUI to execute them easily, like Eclipse does.
> As you say, I get test objects and code objects created that is
> why I use reload to "refresh" the module object. My concern is
> that in the sample code, all the Unittest related objects are
> recreated and the objects are loaded from a string before
> executing the tests, but still they remain in memory.
> I have used "reload" just to prove the problem could be fixed
> like that, to confirm the source of the problem, I agree this
> is not a good solution.
> The fixing test looks strange but was the easier way I found to
> reproduce the problem since the test does not actually "test"
> any outside object, was just a way to change the passing/no
> passing status of the test.
> Thks for your time hope this time I made myself clear ;)

I think you can't use reload in this scenario. Your framework would have  
to know which modules to reload, which names to rebind, which imports to  
re-execute, which objects to re-create... Reloading without intimate  
knowledge of how the reloaded module is used is hard, if not impossible.
Perhaps the best option is to run the tests in another process. Use any of  
the available IPC mechanisms to gather the test results. This has the  
added advantage of isolating the tested code from your GUI testing  
framework; all requested resources are released to the OS; the tests run  
in a predictable environment; etc.

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


Subclassing int

2007-07-23 Thread G

Hi,

   I am trying to subclass int to allow a constructor to accept None. I am
trying the following

class INT(int):
   def __init__(self, x):
   if x is  None:
   return None
   else:
   int.__init__(x)

b = INT(x=None)

When i run the previous code i get the following error:
b = INT(x=None)
TypeError: int() argument must be a string or a number, not 'NoneType'.

Do you guys know why the if statement is not evaluated?

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

Re: Subclassing int

2007-07-23 Thread Steve Holden
G wrote:
> Hi,
> 
> I am trying to subclass int to allow a constructor to accept None. I 
> am trying the following
> 
> class INT(int):
> def __init__(self, x):
> if x is  None:
> return None
> else:
> int.__init__(x)
> 
> b = INT(x=None)
> 
> When i run the previous code i get the following error:
>  b = INT(x=None)
> TypeError: int() argument must be a string or a number, not 'NoneType'.
> 
> Do you guys know why the if statement is not evaluated?
> 
> Thanks for your help
> 
Probably because you need to override the __new__() method rather than 
the __init__() method:

 >>> class INT(int):
...   def __new__(cls, arg=0):
... if arg is None:
...   return None
... else:
...   return int.__new__(cls, arg)
...
 >>> n = INT(3.2)
 >>> n
3
 >>> n = INT("42")
 >>> n
42
 >>> n = INT(None)
 >>> print n
None
 >>>

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: pylint style convention

2007-07-23 Thread Matt McCredie


Which style convention is it referring to? Should these really be all
caps?



I think pylint is expecting that any variables declared outside of a
function should be constants with special meanings (similar to #define or
enum values in c). So, I guess to get rid of that message you should do
something like this:


def main(args=None):
   if args is None:
   args = sys.argv

   parser = optparse.OptionParser(usage='usage: %prog [OPTIONS]')
   parser.add_option('-c', '--config',
 action='store',
 type='string',
 dest='configFilename',
 help='config file containing defaults')
   (options, args) = parser.parse_args(args)

if "__main__" == __name__:
   sys.exit(main())


Here is an article by GvR that goes over main functions in python:
http://www.artima.com/weblogs/viewpost.jsp?thread=4829. You didn't really
ask for it, but I think it is good reading. His examples all use getopt
though, instead of optparse. I have come up with my own (probably overkill
for 99% of python scripts) template that uses optparse. If you really want
to see it let me know and I will send it to you.

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

Re: Maintaining leading zeros with the lstrip string function?

2007-07-23 Thread Steve Holden
Randy Kreuziger wrote:
> Thanks for the basename suggestion.  That almost works.  I'm running 
> into a problem with some of the directory names when they include 
> \800x\   see below.
> �-
> import sys, os, string
> 
> teststring = 'C:\shoreline\dvd\prep area\800x\060623_1.jpg'
> print  os.path.basename(teststring)
> �-
> Results in
> 800x0623_1.jpg
>  
> But it needs to be
> 060623_1.jpg
> 
You need to be careful with those backslashes!

 >>> teststring = 'C:\shoreline\dvd\prep area\800x\060623_1.jpg'
 >>> teststring
'C:\\shoreline\\dvd\\prep area\\800x0623_1.jpg'
 >>> teststring = r'C:\shoreline\dvd\prep area\800x\060623_1.jpg'
 >>> teststring
'C:\\shoreline\\dvd\\prep area\\800x\\060623_1.jpg'
 >>>

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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

Re: [2.5] Regex doesn't support MULTILINE?

2007-07-23 Thread Gilles Ganault
On Sun, 22 Jul 2007 05:34:17 -0300, "Gabriel Genellina"
<[EMAIL PROTECTED]> wrote:
>Try to avoid using ".*" and ".+" (even the non greedy forms); in this  
>case, I think you want the scan to stop when it reaches the ending   
>or any other tag, so use: [^<]* instead.
>
>BTW, better to use a raw string to represent the pattern: pattern =  
>r"...\d+..."

Thanks everyone for the help. It did improve things significantly :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Maintaining leading zeros with the lstrip string function?

2007-07-23 Thread Randy Kreuziger
Thanks for the basename suggestion.  That almost works.  I'm running into a 
problem with some of the directory names when they include \800x\   see below.
―-
import sys, os, string

teststring = 'C:\shoreline\dvd\prep area\800x\060623_1.jpg'
print  os.path.basename(teststring)
―-
Results in 
800x0623_1.jpg
 
But it needs to be
060623_1.jpg

 
 
 

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

python a lonys

2007-07-23 Thread Nooby
http://www.directurl.de/39850293 thissi something new 4 u guys

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


pylint style convention

2007-07-23 Thread Mick Charles Beaver
Hello,

I've been looking into using PyLint on some of my programs, just as a
best practices kind of thing.

Here's a snippet:
#==
if __name__ == '__main__':
parser = optparse.OptionParser(usage='usage: %prog [OPTIONS]')
parser.add_option('-c', '--config',
  action='store',
  type='string',
  dest='configFilename',
  help='config file containing defaults')
(options, args) = parser.parse_args()
#==

Now, PyLint reports the following convention warnings:
C:158: Invalid name "parser" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$)
C:170: Invalid name "options" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$)
C:170: Invalid name "args" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$)

Which style convention is it referring to? Should these really be all
caps?

Thank you,
Mick

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


Re: Maintaining leading zeros with the lstrip string function?

2007-07-23 Thread Steven D'Aprano
On Mon, 23 Jul 2007 15:21:20 -0400, Miles wrote:

> Also, use raw strings ( r'\path\to\file' ) to avoid problems
> with backslashes being interpreted in strings.

Not quite. Raw strings are designed for building regular expressions, not
file names. Consequently, there are still a few cases where they won't
help you, e.g.:

>>> fname = 'mydoc.txt'
>>> fname = r'C:\My Documents\Something\' + fname
  File "", line 1
fname = r'C:\My Documents\Something\' + fname
^
SyntaxError: EOL while scanning single-quoted string

A better solution is to remember that Windows will accept a forward slash
anywhere it expects a backslash:


>>> fname = 'C:/My Documents/Something/' + fname 

(But again... the better, platform independent way to do this is with
os.path.)

-- 
Steven.

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


Re: Extracting attributes from compiled python code or parse trees

2007-07-23 Thread Gabriel Genellina
En Mon, 23 Jul 2007 18:13:05 -0300, Matteo <[EMAIL PROTECTED]> escribió:

> I am trying to get Python to extract attributes in full dotted form
> from compiled expression. For instance, if I have the following:
>
> param = compile('a.x + a.y','','single')
>
> then I would like to retrieve the list consisting of ['a.x','a.y'].
>
> The reason I am attempting this is to try and automatically determine
> data dependencies in a user-supplied formula (in order to build a
> dataflow network). I would prefer not to have to write my own parser
> just yet.

If it is an expression, I think you should use "eval" instead of "single"  
as the third argument to compile.

> Alternatively, I've looked at the parser module, but I am experiencing
> some difficulties in that the symbol list does not seem to match that
> listed in the python grammar reference (not surprising, since I am
> using python2.5, and the docs seem a bit dated)

Yes, the grammar.txt in the docs is a bit outdated (or perhaps it's a  
simplified one), see the Grammar/Grammar file in the Python source  
distribution.

> In particular:
>
 import parser
 import pprint
 import symbol
 tl=parser.expr("a.x").tolist()
 pprint.pprint(tl)
>
> [258,
>  [326,
>   [303,
>[304,
> [305,
>  [306,
>   [307,
>[309,
> [310,
>  [311,
>   [312,
>[313,
> [314,
>  [315,
>   [316, [317, [1, 'a']], [321, [23, '.'], [1,
> 'x',
>  [4, ''],
>  [0, '']]
>
 print symbol.sym_name[316]
> power
>
> Thus, for some reason, 'a.x' seems to be interpreted as a power
> expression, and not an 'attributeref' as I would have anticipated (in
> fact, the symbol module does not seem to contain an 'attributeref'
> symbol)

Using this little helper function to translate symbols and tokens:

names = symbol.sym_name.copy()
names.update(token.tok_name)
def human_readable(lst):
   lst[0] = names[lst[0]]
   for item in lst[1:]:
 if isinstance(item,list):
   human_readable(item)

the same tree becomes:

['eval_input',
  ['testlist',
   ['test',
['or_test',
 ['and_test',
  ['not_test',
   ['comparison',
['expr',
 ['xor_expr',
  ['and_expr',
   ['shift_expr',
['arith_expr',
 ['term',
  ['factor',
   ['power',
['atom', ['NAME', 'a']],
['trailer', ['DOT', '.'], ['NAME', 'x',
  ['NEWLINE', ''],
  ['ENDMARKER', '']]

which is correct is you look at the symbols in the (right) Grammar file.

But if you are only interested in things like a.x, maybe it's a lot  
simpler to use the tokenizer module, looking for the NAME and OP tokens as  
they appear in the source expression.


-- 
Gabriel Genellina

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


Re: Reading data from an ISA port

2007-07-23 Thread Diez B. Roggisch
Gabriel Dragffy schrieb:
> Dear list members
> 
> I must admit I am a new user of Python, but it is a language that I 
> enjoy using.
> 
> For one of my university projects I need to write a program that can 
> read several bytes from an ISA port. It has been suggested to me that I 
> look at using C or Pyinline. If I can I would prefer to continue to use 
> Python, and Pyinline won't play ball.
> 
> I am sure Python can do this for me, but the question is how? What 
> modules and code do I need to look? I'd be very grateful for any 
> suggestions and advice.

Python as-is won't help. It has no concept of memory addresses and 
direct access to them. However, a trivial C-extension together with the 
struct and/or ctypes module will help.

What you essentially need to code is a C-extension that will allow you 
to directly access memory. Wrap that either in an extension or using ctypes.

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


Re: Confused with csv.reader copies

2007-07-23 Thread Gabriel Genellina
En Mon, 23 Jul 2007 15:45:42 -0300, Robert Dailey <[EMAIL PROTECTED]>  
escribió:

> import csv
>
> def pass1( reader ):
>   print reader.next()
>   print reader.next()
>
> def pass2( reader ):
>   print reader.next()
>   print reader.next()
>
> reader = csv.reader( open( "C:/IT/Method/SpaceImpact/code/tools/
> ProfileViewer/performance_profile.csv", "rb" ) )
>
> pass1( reader )
> pass2( reader )

[expecting the two calls to print the same two lines]

> My understanding is that objects are passed by reference, meaning
> there is no hard copy of the data, however the copies passed to
> functions do not affect the version passed in. In other words, when I
> call "next" on the reference passed into each function, it should not
> affect the variable that was originally passed in.

Both functions receive the *same* reader object, not a copy. Calling  
next() affects the reader internal state, it doesn't matter where you call  
it from.
You should read this threads from last week:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/45732106f147ac07/
http://groups.google.com/group/comp.lang.python/browse_thread/thread/56e7d62bf66a435c/

> I'm attempting to use recursion to build a TreeCtrl in wxPython using
> this data, and I can't get it to work properly if the variable outside
> of the function call ends up having its state (e.g., its "next"
> pointer) modified by passing it into other functions.
>
> Any tips on getting this to work? I'm a native C++ programmer still
> learning Python, so I apologize for any confusion. Thanks.

The simplest way -if the file is not so huge- is to read the whole file  
and keep the results in a list: lines = list(reader)
There are other alternatives using the itertools module but aren't easy to  
grasp for a beginner.

-- 
Gabriel Genellina

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


Extracting attributes from compiled python code or parse trees

2007-07-23 Thread Matteo
Hello-
I am trying to get Python to extract attributes in full dotted form
from compiled expression. For instance, if I have the following:

param = compile('a.x + a.y','','single')

then I would like to retrieve the list consisting of ['a.x','a.y'].
I have tried using inspect to look at 'co_names', but when I do that,
I get:

>>> inspect.getmembers(param)[23]
('co_names', ('a', 'x', 'y'))

with no way to determine that 'x' and 'y' are both attributes of 'a'.

The reason I am attempting this is to try and automatically determine
data dependencies in a user-supplied formula (in order to build a
dataflow network). I would prefer not to have to write my own parser
just yet.

Alternatively, I've looked at the parser module, but I am experiencing
some difficulties in that the symbol list does not seem to match that
listed in the python grammar reference (not surprising, since I am
using python2.5, and the docs seem a bit dated)

In particular:

>>> import parser
>>> import pprint
>>> import symbol
>>> tl=parser.expr("a.x").tolist()
>>> pprint.pprint(tl)

[258,
 [326,
  [303,
   [304,
[305,
 [306,
  [307,
   [309,
[310,
 [311,
  [312,
   [313,
[314,
 [315,
  [316, [317, [1, 'a']], [321, [23, '.'], [1,
'x',
 [4, ''],
 [0, '']]

>>> print symbol.sym_name[316]
power

Thus, for some reason, 'a.x' seems to be interpreted as a power
expression, and not an 'attributeref' as I would have anticipated (in
fact, the symbol module does not seem to contain an 'attributeref'
symbol)

(for the curious, here is the relevant part of the AST for "a**x":
[316,
   [317, [1, 'a']],
   [36, '**'],
   [315, [316, [317, [1, 'x'
)

Anyway, I could write an AST analyzer that searches for the correct
pattern, but it would be relying on undocumented behavior, and I'm
hoping there is a better way.

(By the way, I realize that malicious users could almost certainly
subvert my proposed dependency mechanism, but for this project, I'm
guarding against Murphy, not Macchiavelli)

Thanks,
-matt

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


Re: Where do they tech Python officialy ?

2007-07-23 Thread Mike C. Fletcher
NicolasG wrote:
...
> I'm planning to save some money and attend a course in any of the
> universities that teach hard core Python.
>
> Does some one have any suggestions on which University to attend ?
>   
In Canada, the University of Toronto is planning to switch all 
first-year Comp-Sci courses to Python this September.  Last I heard the 
University of Waterloo allowed Python submissions for most assignments 
in most courses.  But those are "learn hard-core computer science using 
Python" solutions, not "learn hard-core Python" solutions.

If you really want to learn hard-core Python, probably your best bet is:

* read everything Tim Peters has ever written in comp.lang.python
  (this will take a few months), start with "import this"
* read everything the PyPy guys have ever written (particularly
  Christian and Armin)
* read and try to beat the more exotic recipes in the Python cookbook
* read the papers from the various PyCons on metaclasses and the
  like, build a couple of dozen metaclasses and descriptors

But jumping into "hardcore" first might not be the best approach.  Many 
would suggest just learning "normal" Python first, *then* moving onto 
the hardcore stuff.

HTH,
Mike

-- 

  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://www.vrplumber.com
  http://blog.vrplumber.com

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


Re: Can a low-level programmer learn OOP?

2007-07-23 Thread Paul McGuire
On Jul 23, 12:43 pm, [EMAIL PROTECTED] (Eddie Corns) wrote:
> Paul McGuire <[EMAIL PROTECTED]> writes:
> >On Jul 23, 5:53 am, [EMAIL PROTECTED] (Eddie Corns) wrote:
> >> Wolfgang Strobl <[EMAIL PROTECTED]> writes:
> >> >few of James Gimple's snippets from "Algorithms in SNOBOL4"
> >> >(->http://www.snobol4.org/) as an exercise using that library might help
> >> >to get a better appreciation. Perhaps I'll try, eventually ...
>
> >> I never noticed them or the PDF of the book there before.  Some Friday
> >> afternoon reading for sure.
>
> >> Personally I hope to get more to time to look at a combination of Lua and
> >> PEGs (http://en.wikipedia.org/wiki/Parsing_expression_grammar) for my 
> >> parsing
> >> needs.
>
> >> Eddie
> >If you get a chance to look at pyparsing, I'd be interested in your
> >comments.  The PEG page and the SNOBOL implementation have many
> >similar concepts with pyparsing (or is it the other way around?).
>
> It's on my list of things to get round to.
>
> I think what I'm really after though is a parsing DSL.  I only did only one
> fairly small project in SNOBOL but I was impressed at the ease with which I
> could express the problem (some googling suggested that many end users found
> the same).  I guess I want SNOBOL embedded in a modern language with scoping
> etc.  Python is antithetical to (this class of) DSLs (IMHO) :(
>
> Probably what I really need is parser combinators in Haskell or maybe camlp4
> or some such exotica but unfortunately I've never heard of them.
>
> Eddie- Hide quoted text -
>
> - Show quoted text -

I have had pyparsing users refer to pyparsing as an in-Python DSL, and
others make comparisons between pyparsing and Parsec (monadic
combinator in Haskell).  I'm not sure why you would say this approach
is antithetical to Python - the builtin support for operator
overloading, __call__, __len__, __nonzero__(soon to be __bool__),
__set/getattr__, etc. permit you to impart quite a bit of expressive
behavior to your parsing classes.  What I tried to do with pyparsing
was to emulate Python's builtin container classes and object instances
with the results that get returned from invoking a parser, so that the
after-parsing work would feel natural to established Python users.

If you want to just see some existing BNF's implemented in pyparsing,
you can view them online at the pyparsing wiki.  Here are some
representative examples:
http://pyparsing.wikispaces.com/space/showimage/simpleSQL.py
http://pyparsing.wikispaces.com/space/showimage/fourFn.py
http://pyparsing.wikispaces.com/space/showimage/jsonParser.py

-- Paul

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


sys.ps1 with formatting (linux)

2007-07-23 Thread Jon Dobson
I'm trying to set sys.ps1 and sys.ps2 with some formatting (linux) using:

python -i -c 'import sys; 
sys.ps1="\033[1m\033[32mspy>\033[0m";sys.ps2="\033[1m\033[32m   .\033[0m"'

I get the colored prompt(s) as you might expect, but I'm getting some strange 
behavior with wrapping.  Once the interactive command gets long enough to wrap, 
it wraps back to the same line (overwriting the beginning).  It doesn't break 
anything - the command gets interpreted correctly, it's just an ugly way to 
work.

What's even "cooler" is when I middle-mouse-paste a command and then try to 
edit the line, it moves up one line in the shell and prints the command I'm 
editing (minus the character I just deleted).  Once again, it's just a display 
issue - the commands still work.

I realize this is pretty obscure, but I'm just hoping someone else has seen and 
dealt with something like this...

tx

_
The information contained in this message and its attachments is
confidential and proprietary to LAIKA, Inc.  By opening this email
or any of its attachments, you agree to keep all such information
confidential and not to use, distribute, disclose or copy any part
of such information without the prior written consent of LAIKA,
Inc.  If you are not the intended recipient of this message, any use,
distribution, disclosure or copying of such information is prohibited.
If received in error, please contact the sender. 

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


Re: The Modernization of Emacs: exists already

2007-07-23 Thread Martijn Lievaart
On Wed, 18 Jul 2007 06:17:00 -0700, Xah Lee wrote:

> About a month ago, i posted a message about modernization of emacs. I
> enlisted several items that i think emacs should adapt.

And you are posting this to compl.lang.perl because.??

F'up set.

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


Re: URL parsing for the hard cases

2007-07-23 Thread Miles
On 7/23/07, Miles wrote:
> On 7/22/07, John Nagle wrote:
> > Is there any library function that correctly tests for an IP address vs. a
> > domain name based on syntax, i.e. without looking it up in DNS?
>
> import re, string
>
> NETLOC_RE = re.compile(r'''^ #start of string
> (?:([EMAIL PROTECTED])+@)?# 1:
> (?:\[([0-9a-fA-F:]+)\]|  # 2: IPv6 addr
> ([^\[\]:]+)) # 3: IPv4 addr or reg-name
> (?::(\d+))?  # 4: optional port
> $''', re.VERBOSE)#end of string
>
> def normalize_IPv4(netloc):
> try: # Assume it's an IP; if it's not, catch the error and return None
> host = NETLOC_RE.match(netloc).group(3)
> octets = [string.atoi(o, 0) for o in host.split('.')]
> assert len(octets) <= 4
> for i in range(len(octets), 4):
> octets[i-1:] = divmod(octets[i-1], 256**(4-i))
> for o in octets: assert o < 256
> host = '.'.join(str(o) for o in octets)
> except (AssertionError, ValueError, AttributeError): return None
> return host

Apparently this will generally work as well:

import re, socket

NETLOC_RE = ...

def normalize_IPv4(netloc):
try:
host = NETLOC_RE.match(netloc).group(3)
return socket.inet_ntoa(socket.inet_aton(host))
except (AttributeError, socket.error):
return None

Thanks to http://mail.python.org/pipermail/python-list/2007-July/450317.html

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


Re: inet_addr() in Python

2007-07-23 Thread brad
Steve Holden wrote:
> brad wrote:
>> Does Python have an equivalent to C's inet_addr()?
>>
> socket.inet_aton() produces a four-byte string you can pass as a struct 
> in_addr, if that's what you are looking for. If you want a number then 
> use the struct module to manipulate it further.
> 
>  >>> s.inet_aton('127.0.0.1')
> '\x7f\x00\x00\x01'
> 
> regards
>  Steve

Thanks! That works great for my needs. I should have read the socket 
documentation more thoroughly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: inet_addr() in Python

2007-07-23 Thread Steve Holden
brad wrote:
> Does Python have an equivalent to C's inet_addr()?
> 
socket.inet_aton() produces a four-byte string you can pass as a struct 
in_addr, if that's what you are looking for. If you want a number then 
use the struct module to manipulate it further.

 >>> s.inet_aton('127.0.0.1')
'\x7f\x00\x00\x01'

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Where do they tech Python officialy ?

2007-07-23 Thread supercooper
http://home.earthlink.net/~python-training/

I highly recommend Mark Lutz. Took the class last fall in Estes Park
and it was worth every penny.

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


Re: shutil.copyfile problem for GIS data

2007-07-23 Thread supercooper
import shutil
import os

src = "c:\mydata\test\mygeo.mdb"
dst = "v:\updated\data\mygeo.mdb"

shutil.copyfile(src,dst)

This should totally work, do it all the time, but no one can be
connected to the database, ie have ArcMap or ArcCatalog open at the
time of copy, or the .ldb lock will kill it. I do all of my copies in
the early AM.


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


code indentation

2007-07-23 Thread ...:::JA:::...
Hello,

In my previously post I have been talk about running code with exec in..
So now I have problem with code indentation, as Gabriel Genellina says:

>If you are using the tokenize module as suggested some time ago, try to
>analyze the token sequence you get using { } (or perhaps begin/end pairs
>in your own language, that are easier to distinguish from a dictionary
>display) and the sequence you get from the "real" python code. Then write
>a script to transform one into another:

>from tokenize import generate_tokens
> from token import tok_name
 >from cStringIO import StringIO

>def analyze(source):
  >   g = generate_tokens(StringIO(source).readline)
   >  for toknum, tokval, _, _, _  in g:
 >print tok_name[toknum], repr(tokval)

>I think you basically will have to ignore INDENT, DEDENT, and replace
>NAME+"begin" with INDENT, NAME+"end" with DEDENT.

So..how can I do this?
I will appreciate any help!

Regards,
Vedran
__ Vedran 
veki ICQ#: 264412055 Current ICQ status: + More ways to contact me Get ICQ! 
__ 


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


Re: Confused with csv.reader copies

2007-07-23 Thread Larry Bates
Robert Dailey wrote:
> First, take a look at my example code:
> -
> import csv
> 
> def pass1( reader ):
>   print reader.next()
>   print reader.next()
> 
> def pass2( reader ):
>   print reader.next()
>   print reader.next()
> 
> reader = csv.reader( open( "C:/IT/Method/SpaceImpact/code/tools/
> ProfileViewer/performance_profile.csv", "rb" ) )
> 
> pass1( reader )
> pass2( reader )
> -
> 
> The output is as follows:
> -
> ['0', 'root', '00:01:32.793591', '1']
> ['1', 'Engine::Tick', '00:00:25.886411', '1851']
> ['2', 'Sprite::Tick', '00:00:00.001495', '385']
> ['2', 'Entity::Tick', '00:00:00.001485', '45']
> -
> 
> I expected the output to be this:
> -
> ['0', 'root', '00:01:32.793591', '1']
> ['1', 'Engine::Tick', '00:00:25.886411', '1851']
> ['0', 'root', '00:01:32.793591', '1']
> ['1', 'Engine::Tick', '00:00:25.886411', '1851']
> -
> 
> My understanding is that objects are passed by reference, meaning
> there is no hard copy of the data, however the copies passed to
> functions do not affect the version passed in. In other words, when I
> call "next" on the reference passed into each function, it should not
> affect the variable that was originally passed in.
> 
> I'm attempting to use recursion to build a TreeCtrl in wxPython using
> this data, and I can't get it to work properly if the variable outside
> of the function call ends up having its state (e.g., its "next"
> pointer) modified by passing it into other functions.
> 
> Any tips on getting this to work? I'm a native C++ programmer still
> learning Python, so I apologize for any confusion. Thanks.
> 

By reference means that mutable objects can be modified (in place) by the
functions that they are passed into.  This is a common mistake people make when
they first get started.  Normally lists seem to throw people first.
I don't know how long the file is, but you probably should just read the entire
file into memory and process it from there.

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


Re: link between python and the windows command prompt

2007-07-23 Thread Larry Bates
yadin wrote:
> hi! i need to know how i can run ussal commands that i ussally type at
> the windows command prompt from a python file. that is  for example
> from the windows command prompt i ussually type "cd D:\folder\ nec2++ -
> i inputfile.nec -o outputfile.out "  now how can i execute this
> command that i ussually type at the windows command prompt from a
> python file?
> i know it has to do with the sys and os module but how specifically?
> what commands? any references?
> 
You can use os.system or if your needs are more complex, take a look at the
subprocess module.

import os
import sys

os.chdir('D:\\folder')
os.system('D:\\nec2++ -i inputfile.new -o outputfile.out')

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


Re: Maintaining leading zeros with the lstrip string function?

2007-07-23 Thread Carsten Haese
On Mon, 2007-07-23 at 11:41 -0700, Randy Kreuziger wrote:
> I need just the file name from a string containing the path to a file.
> The name of the file starts with zeros.  This is problematic because
> the  lstrip function strips them leaving this as the result:
> 6128.jpg
>  
>  
> How do I strip the path without losing the leading zeros in the file
> name?
>  
> —-
> import sys, os, win32com.client, string
> 
> teststring = 'C:\shoreline\dvd\prep area\800x\\006128.jpg'
> print string.lstrip(teststring, 'C:\shoreline\dvd\prep area\800x\\')

You're using the wrong tool for the job. lstrip removes any contiguous
string consisting of any of the characters in the string you give it.
You would have achieved the same wrong result with

teststring.lstrip(" 08:C\\adehilnoprsvx")

As you have discovered, this hungry caterpillar will eat the leading
zeroes of your filename. It doesn't see any difference between the
zeroes before the last \ and the zeroes after the last \. It just eats
them all. If the leading zeroes had been followed by an 8, it would have
eaten that, too.

The right tool for the job is os.path, more specifically
os.path.basename(teststring).

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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

Re: Maintaining leading zeros with the lstrip string function?

2007-07-23 Thread Miles
On 7/23/07, Randy Kreuziger <[EMAIL PROTECTED]> wrote:
> I need just the file name from a string containing the path to a file.  The
> name of the file starts with zeros.  This is problematic because the  lstrip
> function strips them leaving this as the result:
> 6128.jpg
>
>
> How do I strip the path without losing the leading zeros in the file name?
>
>  -
> import sys, os, win32com.client, string
>
> teststring = 'C:\shoreline\dvd\prep area\800x\\006128.jpg'
> print string.lstrip(teststring, 'C:\shoreline\dvd\prep area\800x\\')

lstrip removes *any* of the set of characters in the argument, not the
exact string[1].  Use of the string module for lstrip and other
functions[2] has been deprecated for using the string methods
directly, i.e. teststring.lstrip(...).

You should probably be using split (or basename) in the os.path
module.  Also, use raw strings ( r'\path\to\file' ) to avoid problems
with backslashes being interpreted in strings.

-Miles

[1] http://docs.python.org/lib/string-methods.html
[2] http://docs.python.org/lib/node42.html
-- 
http://mail.python.org/mailman/listinfo/python-list


inet_addr() in Python

2007-07-23 Thread brad
Does Python have an equivalent to C's inet_addr()?

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


Maintaining leading zeros with the lstrip string function?

2007-07-23 Thread Randy Kreuziger
I need just the file name from a string containing the path to a file.  The 
name of the file starts with zeros.  This is problematic because the  lstrip 
function strips them leaving this as the result:
6128.jpg
 
 
How do I strip the path without losing the leading zeros in the file name?
 
―-
import sys, os, win32com.client, string

teststring = 'C:\shoreline\dvd\prep area\800x\\006128.jpg'
print string.lstrip(teststring, 'C:\shoreline\dvd\prep area\800x\\')

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

Re: class C: vs class C(object):

2007-07-23 Thread Klaas
On Jul 20, 5:47 am, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
> > In particular, old-style classes are noticeably faster than
> > new-style classes for some things (I think it was attribute lookup
> > that surprised me recently, possibly related to the property
> > stuff...)
>
> Can you post an example that we can benchmark?  I ask because the
> opposite is usually claimed, that (as of Python 2.4 or 2.5) new-style
> classes are measurably faster.

Why do people ask for trivial examples?

$ cat classes.py
class Classic:
def __init__(self):
self.attr = 1

class NewStyle(object):
def __init__(self):
self.attr = 1

$ python -m timeit -s 'from classes import *; c = Classic()' 'c.attr'
:2: SyntaxWarning: import * only allowed at module level
100 loops, best of 3: 0.182 usec per loop

$ python -m timeit -s 'from classes import *; c = NewStyle()' 'c.attr'
:2: SyntaxWarning: import * only allowed at module level
100 loops, best of 3: 0.269 usec per loop

New style classes have more machinery to process for attribute/method
lookup, and are slower.

There are very few algorithms for which attribute access is the
bottleneck however (seeing as how easier they can be extracted out of
inner loops into locals, which are much faster than attribute access
on either type of class).

Using old-style classes for performance is a useful hack for python
perf wizards, but is a dangerous meme to perpetuate.

-Mike

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


Confused with csv.reader copies

2007-07-23 Thread Robert Dailey
First, take a look at my example code:
-
import csv

def pass1( reader ):
print reader.next()
print reader.next()

def pass2( reader ):
print reader.next()
print reader.next()

reader = csv.reader( open( "C:/IT/Method/SpaceImpact/code/tools/
ProfileViewer/performance_profile.csv", "rb" ) )

pass1( reader )
pass2( reader )
-

The output is as follows:
-
['0', 'root', '00:01:32.793591', '1']
['1', 'Engine::Tick', '00:00:25.886411', '1851']
['2', 'Sprite::Tick', '00:00:00.001495', '385']
['2', 'Entity::Tick', '00:00:00.001485', '45']
-

I expected the output to be this:
-
['0', 'root', '00:01:32.793591', '1']
['1', 'Engine::Tick', '00:00:25.886411', '1851']
['0', 'root', '00:01:32.793591', '1']
['1', 'Engine::Tick', '00:00:25.886411', '1851']
-

My understanding is that objects are passed by reference, meaning
there is no hard copy of the data, however the copies passed to
functions do not affect the version passed in. In other words, when I
call "next" on the reference passed into each function, it should not
affect the variable that was originally passed in.

I'm attempting to use recursion to build a TreeCtrl in wxPython using
this data, and I can't get it to work properly if the variable outside
of the function call ends up having its state (e.g., its "next"
pointer) modified by passing it into other functions.

Any tips on getting this to work? I'm a native C++ programmer still
learning Python, so I apologize for any confusion. Thanks.

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


link between python and the windows command prompt

2007-07-23 Thread yadin
hi! i need to know how i can run ussal commands that i ussally type at
the windows command prompt from a python file. that is  for example
from the windows command prompt i ussually type "cd D:\folder\ nec2++ -
i inputfile.nec -o outputfile.out "  now how can i execute this
command that i ussually type at the windows command prompt from a
python file?
i know it has to do with the sys and os module but how specifically?
what commands? any references?

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


Re: Where do they tech Python officialy ?

2007-07-23 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
NicolasG  <[EMAIL PROTECTED]> wrote:
>Hi,
>
>I want to be a professional python programmer, unfortunately I'm
>working on technical support and don't have the time/patience to start
>making projects my self. I tried to apply to some Python positions but
>unfortunately sometimes to work as a programmer is really hard in this
>world, every employee requires professional experience and you can't
>really start as a beginner..
>
>I'm planning to save some money and attend a course in any of the
>universities that teach hard core Python.
>
>Does some one have any suggestions on which University to attend ?
>Alternatives solutions are welcome..
.
.
.
Autodidacticism is an alternative; feel free to regard http://wiki.python.org/moin/PythonTraining > as a member of 
that class.  

If you, for example, were to teach yourself Python, then 
volunteer with prominent extensions or even the core (there's
plenty to do in regard to documentation and testing), you'd
soon have accumulated quite a bit of experience that enlightened
employers recognize is as professional as any other.

I leave to others the chore of summarizing all the universities
with Python offerings.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where do they tech Python officialy ?

2007-07-23 Thread BartlebyScrivener
On Jul 23, 11:52 am, NicolasG <[EMAIL PROTECTED]> wrote:
>
> Does some one have any suggestions on which University to attend ?
> Alternatives solutions are welcome..

You might like this thread.  Or go to comp.lang.python and search for
"python taught in schools"

http://tinyurl.com/2zlsxl

rd

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


Re: decorators tutorials

2007-07-23 Thread Jason
On Jul 23, 11:25 am, Jason <[EMAIL PROTECTED]> wrote:
> On Jul 23, 2:13 am, james_027 <[EMAIL PROTECTED]> wrote:
>
> > Hi,
>
> > I am learning python by learning django, and I stumble upon decorator
> > which is very cool, any beginners resources for python decorators,
> > although I can google it, I just want to get a good tutorial for this
> > topic.
>
> > Thanks
> > james

With apologies, there is an error in my previous WrapWithHelpDebug.
The last part of the function should read:
# Back in the WrapWithHelpDebug scope.
# HelpDebug is now a function objected defined in this scope.
return HelpDebug  # This line was missing


Now, my prior post shows how decorators work.  Functions are objects
created by Python's def statement.  They have access to the names in
all their enclosing scopes: the module's global scope and any
functions that they are nested in.

The WrapWithHelpDebug decorator wraps a function so uncaught
exceptions get caught, logged, and the Python debugger is started.
You won't notice much output from the logger usually, because the
default log level is set to "DEBUG".  That might be fine, but maybe
you want to pass the debugging level as a parameter.

import logging

def WrapWithHelpDebug(func, logLevel):
"""Returns a function object that transparently wraps the
parameter
with the HelpDebug function"""

# The def statement actually defines a function object and binds
# it to a name.  Since it is nested in this function, the def
# statement isn't evaluated until
def HelpDebug(*args, **keyargs):
"Assist with debugging a function."
# The func argument is a Pythong function object
# arg is the positional arguments that follow the
# first parameter, and keyargs has the keyword arguments.
try:
# The name "func" comes from the outer scope,
WrapWithHelpDebug
returnValue = func(*args, **keyargs)
return returnValue
except SystemExit:
raise  # Reraise the system exit exception
except Exception, error:
from logging import log
from sys import exc_info
import pdb

log(logLevel, "Caught Exception: %s", error)
# Start the debugger at the place where the
# exception occurred
pdb.post_mortem(exc_info()[2])
return  # Nothing to return when an exception occurred

# Back in the WrapWithHelpDebug scope.
# HelpDebug is now a function objected defined in this scope.
return HelpDebug

def DivXY(x, y):
"Divides X by Y"
return x / y
DivXY = WrapWithHelpDebug(DivXY, logging.DEBUG)

# Debug the following calls
DivXY(5.0, 2.1)  # This will succeed
DivXY(10.0, 0.0) # Causes a ZeroDivisionError exception

So, if we just need to add a new parameter, how do we do that with a
decorator?  Could we use "@WrapWithHelpDebug(logging.DEBUG)"?

No.  Remember, the decorator symbol is just a bit of syntactic sugar.
It turns:
@WrapWithHelpDebug(logging.DEBUG)
def DivXY(x, y):
"Divides X by Y"
return x / y

Into:
def DivXY(x, y):
"Divides X by Y"
return x / y
DivXY = WrapWithHelpDebug(logging.DEBUG)(DivXY)

Oops!  That implies that we're calling "WrapWithHelpDebug" with our
logging parameter.  To accommodate the extra parameter, we're going to
need to use Python's nested scopes again.  Here's a final version that
does everything we want:

import logging

def HelpDebugDecorator(logLevel):
"Returns a function object that will properly decorate a
function."

# Note that logLevel used in the nested function HelpDebug
# comes from this scope.

def WrapWithHelpDebug(func):
"""Returns a function object that transparently wraps the
parameter
with the HelpDebug function"""

# The def statement actually defines a function object and
binds
# it to a name.  Since it is nested in this function, the def
# statement isn't evaluated until
def HelpDebug(*args, **keyargs):
"Assist with debugging a function."
# The func argument is a Pythong function object
# arg is the positional arguments that follow the
# first parameter, and keyargs has the keyword arguments.
try:
# The name "func" comes from the outer scope,
WrapWithHelpDebug
returnValue = func(*args, **keyargs)
return returnValue
except SystemExit:
raise  # Reraise the system exit exception
except Exception, error:
from logging import log
from sys import exc_info
import pdb

log(logLevel, "Caught Exception: %s", error)
# Start the debugger at the place where the
# exception occurred
pdb.post_mortem(exc_info()[2])
return  # Nothing to return when an exception occurred

# Back in the WrapWithHelpDeb

Re: Can a low-level programmer learn OOP?

2007-07-23 Thread Eddie Corns
Paul McGuire <[EMAIL PROTECTED]> writes:

>On Jul 23, 5:53 am, [EMAIL PROTECTED] (Eddie Corns) wrote:
>> Wolfgang Strobl <[EMAIL PROTECTED]> writes:
>> >few of James Gimple's snippets from "Algorithms in SNOBOL4"
>> >(->http://www.snobol4.org/) as an exercise using that library might help
>> >to get a better appreciation. Perhaps I'll try, eventually ...
>>
>> I never noticed them or the PDF of the book there before.  Some Friday
>> afternoon reading for sure.
>>
>> Personally I hope to get more to time to look at a combination of Lua and
>> PEGs (http://en.wikipedia.org/wiki/Parsing_expression_grammar) for my parsing
>> needs.
>>
>> Eddie

>If you get a chance to look at pyparsing, I'd be interested in your
>comments.  The PEG page and the SNOBOL implementation have many
>similar concepts with pyparsing (or is it the other way around?).

It's on my list of things to get round to.

I think what I'm really after though is a parsing DSL.  I only did only one
fairly small project in SNOBOL but I was impressed at the ease with which I
could express the problem (some googling suggested that many end users found
the same).  I guess I want SNOBOL embedded in a modern language with scoping
etc.  Python is antithetical to (this class of) DSLs (IMHO) :(

Probably what I really need is parser combinators in Haskell or maybe camlp4
or some such exotica but unfortunately I've never heard of them.

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


Re: decorators tutorials

2007-07-23 Thread Steve Holden
james_027 wrote:
> Hi,
> 
>>> def check_login(func):
>>> def _check_login(*args):
>>> print "I am decorator"
>>> return func(*args)
>>> return _check_login
>>> @check_login
>>> def method2(input):
>>> print "I am method TWO. Input %s" % input
>> That looks okay. What is unclear?
>>
> 
> It just look complicated than using a simple function like this
> def check_login(msg):
>#...
> def my_func(toto, tata):
>#...
> 
> #call it like this
> check_login('msg')
> my_func('toto', 'tata')
> 
> I hope I could be able to understand clearly the decorators and use it
> to it efficiently
> 
Unfortunately your example isn't equivalent to the decorator version. 
The decorator syntax actually calls the decorator function using the 
following function as its argument, then replaces the function 
definition on with the result of the call on the decorator.

Your example just calls two functions one after the other without any 
relationship being established between them.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Pickled objects over the network

2007-07-23 Thread Steve Holden
Hendrik van Rooyen wrote:
> "Steve Holden" <[EMAIL PROTECTED]> wrote:
> 
>> Yes.
> 
> Why?
> 
It's difficult to establish, and then correctly implement, almost any 
security protocol without leaving cracks that attackers can lever open 
and use to inject code into your process's memory space.

By all means go ahead and hack on pickle to do what you want to. Just 
don't claim your solution is secure without a thorough review.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: decorators tutorials

2007-07-23 Thread Jason
On Jul 23, 2:13 am, james_027 <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I am learning python by learning django, and I stumble upon decorator
> which is very cool, any beginners resources for python decorators,
> although I can google it, I just want to get a good tutorial for this
> topic.
>
> Thanks
> james

Remember that functions in Python are created when their containing
scope is parsed.  Let's suppose you want a way to help you debug
function calls.  This should catch any uncaught exceptions, log a
message to the logging system, and start a pdb interpreter.  It should
allow the SystemExit exception to continue to propogate without doing
those actions.  The following example would do that appropriately:

def HelpDebug(func, *args, **keyargs):
"Assist with debugging a function."
# The func argument is a Pythong function object
# arg is the positional arguments that follow the
# first parameter, and keyargs has the keyword arguments.
try:
returnValue = func(*args, **keyargs)
return returnValue
except SystemExit:
raise  # Reraise the system exit exception
except Exception, error:
from logging import DEBUG, log
from sys import exc_info
import pdb

log(DEBUG, "Caught Exception: %s", error)
# Start the debugger at the place where the
# exception occurred
pdb.post_mortem(exc_info()[2])
return  # Nothing to return when an exception occurred

def DivXY(x, y):
"Divides X by Y"
return x / y


# Debug the following calls
HelpDebug(DivXY, 5.0, 2.1)  # This will succeed
HelpDebug(DivXY, 10.0, 0.0) # Causes a ZeroDivisionError exception

There's a serious problem, though.  If you'd like to remove the
debugging effect, you need to change all your "HelpDebug(DivXY,
xvalue, yvalue)" calls to "DivXY(xvalue, yvalue)".  Besides, you're
trying to get the result of DivXY, not HelpDebug.  The calling code
shouldn't care about HelpDebug at all.  We could do change HelpDebug
so it always calls DivXY, but then we need to create a new function
for each one we want to debug.

This is where nested scopes come in.  Other code should care about
calling DivXY, but not HelpDebug.  Furthermore, the caller shouldn't
be able to casually tell the difference between calling a regular
DivXY or the HelpDebug'ed DivXY.

Well, if the caller shouldn't be able to casually tell the difference
between DivXY with or without the debugging code, then we need to be
able to do the following:
value1 = DivXY(5.0, 2.1)   # The regular call
value2 = HelpDebugDivXY(5.0, 2.1)  # The debugged call

We could create a special "HelpDebugDivXY" function for every such
function, but that would quickly exhaust our patience, and introduce
lots of extra code that can have bugs.  Python has nested scoping,
though.  If you nest a function inside another function, the inner
function has access to the names in the outer function.

That doesn't sound too spectacular at first.  HOWEVER, in Python
functions are objects!  The outer function can return the inner
function object.  Even though the outer function has returned, /the
inner function still has access to the outer function's names/!  For
example:
>>> def GetPrintXFunc(x):
... "Returns a function that takes no parameters, but prints the
argument"
... # Inner function starts just below
... def PrintX():
..."Prints the object bound to the name x in enclosing scope."
...print "X is", x
... # A function object is now bound to the name "PrintX"
... return PrintX
...
>>> PrintSpam = GetPrintXFunc("Spam")
>>> PrintPi = GetPrintXFunc(3.14159)
>>> PrintSpam()
X is Spam
>>> PrintPi()
X is 3.14159
>>>

Both PrintSpam and PrintPi keep access to their enclosing scope's
arguments!  In Python, the "def" statement is actually a statement...
and IT ISN'T EVALUATED UNTIL ITS ENCLOSING SCOPE IS EXECUTED.

Take that in.  That is entirely unlike C or C++, where a function
definition is evaluated at compile time.  In Python, all statements
are evaluated at run time.  This works even for nested classes.
Here's the modified code to help us debug:

def WrapWithHelpDebug(func):
"""Returns a function object that transparently wraps the
parameter
with the HelpDebug function"""

# The def statement actually defines a function object and binds
# it to a name.  Since it is nested in this function, the def
# statement isn't evaluated until
def HelpDebug(*args, **keyargs):
"Assist with debugging a function."
# The func argument is a Pythong function object
# arg is the positional arguments that follow the
# first parameter, and keyargs has the keyword arguments.
try:
# The name "func" comes from the outer scope,
WrapWithHelpDebug
returnValue = func(*args, **keyargs)
return returnValue
except SystemExit:
raise  # Reraise the system exit exception
except Exception, erro

Re: Catching a key press

2007-07-23 Thread Petr Jakes
On 23  ec, 14:23, westymatt <[EMAIL PROTECTED]> wrote:
> linux primarily still a little lost in how to implementent this,
> however I understand what you are saying.

maybe you can use this:
http://tinyurl.com/2zyfmw

HTH

Petr Jakes

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


Re: Need Help with base64

2007-07-23 Thread Terry Reedy

"pycraze" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Hi ,
|
|  I am currently trying to implement base64 encoding and decoding
| scheme in C . Python has a module , base64 , that will  do the
| encoding and decoding with ease . I am aware of OpenSSL having support
| for base64 encoding and decoding , but i will have to now implement
| both in C without using the openssl libraries .
|
|I was able to download a code w.r.t. base 64 encoding and
| decoding . I am attaching the code below .

[C coce snipped]

|  But this code gives different hex values as compared to the
| python base64.encodestring and base64.decodestring respectively .
|
| I need some help on this matter . I need some pointers on
| where is the mistake for the above file .

Looking at the source code for those functions might tell you why you get 
different outputs. The python code for base64 is in /Lib.  Those two 
functions are thin wrappers around corresponding C-coded binascii 
functions.  You can access that module via this source tree directory:
http://svn.python.org/view/python/trunk/Modules/

The current binascii code is
http://svn.python.org/view/python/trunk/Modules/binascii.c?rev=55205&view=auto

The interpreter is open source with a liberal license that should allow you 
to pluck the functions for use elsewhere as long as the add a copyright 
notice.

Otherwise, I agree with Diez that this is OT here.

tjr



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


Re: Where do they tech Python officialy ?

2007-07-23 Thread Danyelle Gragsone
My school does damn near all of the main ones.. BUT python  .. lame..

On 7/23/07, NicolasG <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I want to be a professional python programmer, unfortunately I'm
> working on technical support and don't have the time/patience to start
> making projects my self. I tried to apply to some Python positions but
> unfortunately sometimes to work as a programmer is really hard in this
> world, every employee requires professional experience and you can't
> really start as a beginner..
>
> I'm planning to save some money and attend a course in any of the
> universities that teach hard core Python.
>
> Does some one have any suggestions on which University to attend ?
> Alternatives solutions are welcome..
>
> Regards,
> Nicolas G.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Where do they tech Python officialy ?

2007-07-23 Thread NicolasG
Hi,

I want to be a professional python programmer, unfortunately I'm
working on technical support and don't have the time/patience to start
making projects my self. I tried to apply to some Python positions but
unfortunately sometimes to work as a programmer is really hard in this
world, every employee requires professional experience and you can't
really start as a beginner..

I'm planning to save some money and attend a course in any of the
universities that teach hard core Python.

Does some one have any suggestions on which University to attend ?
Alternatives solutions are welcome..

Regards,
Nicolas G.

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


Reading data from an ISA port

2007-07-23 Thread Gabriel Dragffy
Dear list members

I must admit I am a new user of Python, but it is a language that I  
enjoy using.

For one of my university projects I need to write a program that can  
read several bytes from an ISA port. It has been suggested to me that  
I look at using C or Pyinline. If I can I would prefer to continue to  
use Python, and Pyinline won't play ball.

I am sure Python can do this for me, but the question is how? What  
modules and code do I need to look? I'd be very grateful for any  
suggestions and advice.

Best regards

Gabriel Dragffy

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


Re: decorators tutorials

2007-07-23 Thread Bruno Desthuilliers
james_027 a écrit :
> hi bruno,
> 
> That seems to be hard to read at all, or I am just very new to python?

or just new to higher order functions ? (ie: functions working on 
functions).

> With that decorator how do I take advantage of it compare when I just
> write a function that could do the same as what the decorator did? I
> could translate the could from above into ...
> 
> def check_login(msg):
>#...
> def my_func(toto, tata):
>#...
> 
> #call it like this
> check_login('msg')
> my_func('toto', 'tata')

The first (and already very important difference) is that, with your 
solution, you have to remember to explicitely call check_login before 
calling my_func, while the decorator will take care of this. This allow 
to factor out orthogonal behaviours (like permission management, logging 
etc). Now there are almost endless other possible uses - anything that 
requires adding metadata to functions (CherryPy's way of flagging 
request handlers), registering functions for later use (ie: entry points 
for a plugin system, rule-based dispatch etc), triggering other 
behaviours before and/or after the function call - possibly bypassing 
the call to the original function, etc, etc, etc.

Note that the important part here is not the @decorator syntax - which 
is just (nice) syntactic sugar - but the ability to use higher order 
functions.

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


Re: Can a low-level programmer learn OOP?

2007-07-23 Thread Paul McGuire
On Jul 23, 5:53 am, [EMAIL PROTECTED] (Eddie Corns) wrote:
> Wolfgang Strobl <[EMAIL PROTECTED]> writes:
> >few of James Gimple's snippets from "Algorithms in SNOBOL4"
> >(->http://www.snobol4.org/) as an exercise using that library might help
> >to get a better appreciation. Perhaps I'll try, eventually ...
>
> I never noticed them or the PDF of the book there before.  Some Friday
> afternoon reading for sure.
>
> Personally I hope to get more to time to look at a combination of Lua and
> PEGs (http://en.wikipedia.org/wiki/Parsing_expression_grammar) for my parsing
> needs.
>
> Eddie

If you get a chance to look at pyparsing, I'd be interested in your
comments.  The PEG page and the SNOBOL implementation have many
similar concepts with pyparsing (or is it the other way around?).

-- Paul

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


Re: decorators tutorials

2007-07-23 Thread Diez B. Roggisch
james_027 wrote:

> hi bruno,
> 
> That seems to be hard to read at all, or I am just very new to python?
> 
> With that decorator how do I take advantage of it compare when I just
> write a function that could do the same as what the decorator did? I
> could translate the could from above into ...
> 
> def check_login(msg):
>#...
> def my_func(toto, tata):
>#...
> 
> #call it like this
> check_login('msg')
> my_func('toto', 'tata')

A decorator can alter the function _in place_ - it is not neccessary to
alter code that calls my_func, as your example does. 

As an additional benefit, it separates concerns - my_func does some stuff,
but mixing it with login-related logic is cumbersome:

def my_func(parameters):
if not logged_in():
   do some redirection
do_the_real_work()

is much more error-prone than

@check_login
def my_func(parameters):
   do_the_real_work()

because then you can just skim the decorator and concentrate on the actual
code.

What one often reaches with decorators is something referred to as "aspect
orientied programming". 

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


Re: Parsing XML with ElementTree (unicode problem?)

2007-07-23 Thread Richard Brodie

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> so what's the difference? how comes parsing is fine
> in the first case but erroneous in the second case?

You may have guessed the encoding wrong. It probably
wasn't utf-8 to start with but iso8859-1 or similar.
What actual byte value is in the file?

> 2. there is another problem that might be similar I get a similar
> error if the content of the (locally saved) xml have special
> characters such as '&'

Either the originator of the XML has messed up, or whatever
you have done to save a local copy has mangled it. 


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


Parsing XML with ElementTree (unicode problem?)

2007-07-23 Thread oren . tsur
(this question was also posted in the devshed python forum:
http://forums.devshed.com/python-programming-11/parsing-xml-with-elementtree-unicode-problem-461518.html
).
-

(it's a bit longish but I hope I give all the information)

1. here is my problem: I'm trying to parse an XML file (saved locally)
using elementtree.parse but I get the following error:
xml.parsers.expat.ExpatError: not well-formed (invalid token): line
13, column 327
apparently, the problem is caused by the token 'Saunière' due to the
apostrophe.

the thing is that I'm sure that python (ElementTree module and parse()
function) can handle this type of encoding since I obtain my xml file
from the web by opening it with:

from elementtree import ElementTree
from urllib import urlopen
query = r'http://ecs.amazonaws.com/onca/xml?
Service=AWSECommerceService&AWSAccessKeyId=189P5TE3VP7N9MN0G302&Operation=ItemLookup&ItemId=1400079179&ResponseGroup=Reviews&ReviewPage=166'
root = ElementTree.parse(urlopen(query))

where query is a query to the AWS, and this specific query has the
'Saunière' in the response. (you could simply open the query with a
web browser and see the xml).

I create a local version of the XML file, containing only the tags
that are of interest. my file looks something like this (I replaced
some of the content with 'bla bla' string in order to make it fit
here):


805 3
5 6
2004-04-03
Not as good as Angels and Demons
I found that this book was not as good and thrilling as
Angels and Demons. bla bla.



827 4
2 8
2004-04-01
The Da Vinci Code, a master piece of words
The Da Vinci Code by Dan Brown is a well-written bla bla. The
story starts out in Paris, France with a murder of Jacque Saunière,
the head curator at Le Louvre.bla bla 



BUT, then trying:

fIn  = open(file,'r') #or even 'import codecs'  and opening with 'fIn
= codecs.open(file,encoding = 'utf-8')'
tree = ElementTree.parse(fIn)



where file is the saved file, I get the error above
(xml.parsers.expat.ExpatError: not well-formed (invalid token): line
13, column 327). so what's the difference? how comes parsing is fine
in the first case but erroneous in the second case? please advise.

2. there is another problem that might be similar I get a similar
error if the content of the (locally saved) xml have special
characters such as '&', for example in 'angles & demons' (vs. 'angles
and demons'). is it the same problem? same solution?

thanks!

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


Re: decorators tutorials

2007-07-23 Thread james_027
Hi,

> > def check_login(func):
> > def _check_login(*args):
> > print "I am decorator"
> > return func(*args)
> > return _check_login
>
> > @check_login
> > def method2(input):
> > print "I am method TWO. Input %s" % input
>
> That looks okay. What is unclear?
>

It just look complicated than using a simple function like this
def check_login(msg):
   #...
def my_func(toto, tata):
   #...

#call it like this
check_login('msg')
my_func('toto', 'tata')

I hope I could be able to understand clearly the decorators and use it
to it efficiently

Thanks
james

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


Python-URL! - weekly Python news and links (Jul 23)

2007-07-23 Thread Gabriel Genellina
QOTW:  "It's a good QOTW but social romantic nonsense nevertheless." - Kay
Schluehr

http://groups.google.com/group/comp.lang.python/browse_thread/thread/6348bfbb69642a4a/

"If it [the QOTW] were predictable, wouldn't it be boring?" - Peter Otten


An analysis of random.shuffle behavior and how large lists
can be handled without losing permutations:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/6c2c574c2142b601/

String interpolation uses %d,%f,%s as format specifiers, not
to declare the type of expected values:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/ab65ec5be19d4d5f

The importance of using the right encoding when dealing with
filenames coming from multiple systems:
http://comments.gmane.org/gmane.comp.python.general/531291

Several problems (not just being unsafe) using pickled
objects across a network:
http://comments.gmane.org/gmane.comp.python.general/531309

defaultdict, dict.setdefault and other alternatives to handle
missing keys in a dictionary, with some microbenchmarkings:

http://search.gmane.org/?query=Pythonic%20way%20for%20missing%20dict%20keys&group=gmane.comp.python.general&sort=date

Old-style vs. new-style classes revisited:
http://comments.gmane.org/gmane.comp.python.general/531464

Among the many riches on the Wiki for which we can give thanks are
the notes (photos, ...) David Boddie has aggregated from EuroPython2007:
http://wiki.python.org/moin/EuroPython2007

Sometimes one wants to know the class and method names currently
executing, and that appears to be tricky:
http://groups.google.com/group/comp.lang.python/msg/9ac405eeab899ee8



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

The Python Papers aims to publish "the efforts of Python enthusiats":
http://pythonpapers.org/
The Python Magazine is a technical monthly devoted to Python:
http://pythonmagazine.com

Readers have recommended the "Planet" sites:
http://planetpython.org
http://planet.python.org

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Python411 indexes "podcasts ... to help people learn Python ..."
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

Steve Bethard continues the marvelous tradition early borne by
Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim
Lesher of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance.
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donate.html

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch

Although unmaintained since 2002, the Cetus collection of Python
hyperlinks retains a few gems.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://aspn.activestate.com/ASPN/Cookbook/Py

Re: decorators tutorials

2007-07-23 Thread Ben Finney
james_027 <[EMAIL PROTECTED]> writes:

> Hi all,

(Please don't top-post your reply. Instead, remove from the quoted
material all the parts that are irrelevant to your reply, and post
underneath what you're responding to, in normal chronological order
like any other discussion.)

> I am having difficulty understanding decorator. The definition was
> clear for me, but the syntax is not so clear to me.
> 
> will decorators will always have to be in this way
> 
> def check_login(func):
> def _check_login(*args):
> print "I am decorator"
> return func(*args)
> return _check_login
> 
> @check_login
> def method2(input):
> print "I am method TWO. Input %s" % input

That looks okay. What is unclear?

-- 
 \"I went to court for a parking ticket; I pleaded insanity. I |
  `\   said 'Your Honour, who in their right mind parks in the passing |
_o__)lane?'"  -- Steven Wright |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python MAPI

2007-07-23 Thread kyosohma
On Jul 22, 3:00 pm, [EMAIL PROTECTED] wrote:
> > Well, I ran Process Monitor with some filters enabled to only watch
> > Thunderbird and MS Word. Unfortunately, that didn't give me any of the
> > registry edits, so I disabled my filters and ran it without. Now I
> > have a log file with 28,000 entries. It's amazing to see all the stuff
> > that happens in just a few moments, but how am I supposed to parse
> > this mess?
>
> I expect you will find it easier figuring out how to install your app
> in the SendTo menu rather than making your app callable via MAPI. This
> probably involves ShellExtensions but I believe there are utilities
> that can be used to add any arbitrary application to the SendTo menu.
> That may be enough for your application.
>
> You might want to have a look at SpamBayes for an example of an
> Outlook extension written in Python to get an idea of how you can
> interface with Outlook.

We may add it to the Sendto menu, but we have users that want to be
able to use the email functionality from within Office Apps. I've been
planning on reading the SpamBayes source code anyway...however, we're
trying to move away from Outlook. We're currently using Zimbra now and
that's why I'd like to open my Python program with MAPI so I can send
email through our new Zimbra mail server.

I have interfaced with Outlook before using COM, but it's not pretty.

Mike

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


Re: ANN: Snobol 1.0

2007-07-23 Thread Aahz
In article <[EMAIL PROTECTED]>,
greg   wrote:
>Aahz wrote:
>>
>> So adding SNOBOL patterns to another library would be a wonderful
>> gift to the Python community...
>
>I wrote a module for Snobol-style pattern matching a while back, but
>didn't get around to releasing it.  I've just put it on my web page:
>
>http://www.cosc.canterbury.ac.nz/greg.ewing/python/Snobol.tar.gz

Nice!  You have restored my faith in the time machine.  ;-)
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

This is Python.  We don't care much about theory, except where it intersects 
with useful practice.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pure Python equivalent of unix "file" command?

2007-07-23 Thread c james
Take a look at
http://www.demonseed.net/~jp/code/magic.py



W3 wrote:
> Hi all,
> 
> Just a quick one... Is there such a thing?
> 
> Thanks,
> /Walter

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


Re: Need Help with base64

2007-07-23 Thread Diez B. Roggisch
pycraze wrote:

> Hi ,
> 
>   I am currently trying to implement base64 encoding and decoding
> scheme in C . Python has a module , base64 , that will  do the
> encoding and decoding with ease . I am aware of OpenSSL having support
> for base64 encoding and decoding , but i will have to now implement
> both in C without using the openssl libraries .
> 
> I was able to download a code w.r.t. base 64 encoding and
> decoding . I am attaching the code below .
> 
> 
> void encodeblock( unsigned char cin[3], unsigned char cout[4], int
> nlen )
> {
> 
> cout[0] = cb64[ cin[0] >> 2 ];
> cout[1] = cb64[ ((cin[0] & 0x03) << 4) | ((cin[1] & 0xf0) >> 4) ];
> cout[2] = (unsigned char) (nlen > 1 ? cb64[ ((cin[1] & 0x0f) << 2)
> | ((cin[2] & 0xc0) >> 6) ] : '=');
> cout[3] = (unsigned char) (nlen > 2 ? cb64[ cin[2] & 0x3f ] :
> '=');
> }
> 
> 
> void decodeblock( unsigned char cin[4], unsigned char cout[3] )
> {
> cout[ 0 ] = (unsigned char ) (cin[0] << 2 | cin[1] >> 4);
> cout[ 1 ] = (unsigned char ) (cin[1] << 4 | cin[2] >> 2);
> cout[ 2 ] = (unsigned char ) (((cin[2] << 6) & 0xc0) | cin[3]);
> }
> 
> 
> int base641_decodestring(char* pcstr,int size,char** ppcdest)
> {
>   unsigned char cin[4] = {""};
>   unsigned char cout[3] = {""};
>   unsigned char  cv = 0;
>   int ni = 0;
>   int nlen = 0;
>   char* cptr = pcstr;
>   *ppcdest = malloc(sizeof(char)*160);
>   if (!*ppcdest)
> {
> return 1;
> }
>   memset(*ppcdest,0,sizeof(char)*160);
> 
>   char* pcstring = malloc( sizeof(char) * SIZE);
> if (!pcstring)
>   {
>   aps_log("APS_log.txt","\nbae64.c:base64encode:malloc failed
> \n");
>   return 1;
>   }
>   memset(pcstring,'\0',SIZE);
> 
> for( nlen = 0, ni = 0; ni < 4; ni++ )
>   {
> cv = 0;
> while(  cv == 0 )
>   {
> cv = (unsigned char) *cptr;
> cv = (unsigned char) ((cv < 43 || cv > 122) ? 0 :
> cd64[ cv - 43 ]);
> if( cv )
> {
> cv = (unsigned char) ((cv == '$') ? 0 : cv - 61);
> }
> }
> if( cptr++ )
>   {
> nlen++;
> if( cv )
> {
> cin[ ni ] = (unsigned char) (cv - 1);
> }
> }
> else
>   {
> cin[ni] = 0;
> }
> }
> if( nlen )
>   {
> decodeblock( cin, cout );
> 
> }
>   memcpy(*ppcdest,cout,160);
>   return 0;
> }/*end of base64_decode */
> 
> char* base64_encode(char* pcstr)
> {
>   unsigned char cin[3] = {""};
>   unsigned char cout[4] = {""};
>   int ni = 0;
>   int nlen = 0;
>   int flag = 1;
>   char* cptr = pcstr;
>   char* pcstring = malloc( sizeof(char) * SIZE);
> if (!pcstring)
>   {
>   aps_log("APS_log.txt","\nbae64.c:base64encode:malloc failed
> \n");
>   return (void*)0;
>   }
>   memset(pcstring,'\0',SIZE);
>   while( flag )
>   {
> for( ni = 0; ni < 3; ni++ )
> {
>   cin[ni] = (unsigned char)*cptr;
>   if( *++cptr != '\0' )
> nlen++;
>   else
>   {
> cin[ni] = 0;
>   flag = 0;
> break;
>   }
> }
> encodeblock(cin, cout,nlen);
> strcat(pcstring,cout);
>   }
> 
>   return pcstring;
> 
> }/* end of base64_encode */
> 
> 
>   But this code gives different hex values as compared to the
> python base64.encodestring and base64.decodestring respectively .
> 
>  I need some help on this matter . I need some pointers on
> where is the mistake for the above file .

How about posting that in a C-newsgroup? python _has_ base64-encoding
support.

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


Need Help with base64

2007-07-23 Thread pycraze
Hi ,

  I am currently trying to implement base64 encoding and decoding
scheme in C . Python has a module , base64 , that will  do the
encoding and decoding with ease . I am aware of OpenSSL having support
for base64 encoding and decoding , but i will have to now implement
both in C without using the openssl libraries .

I was able to download a code w.r.t. base 64 encoding and
decoding . I am attaching the code below .


void encodeblock( unsigned char cin[3], unsigned char cout[4], int
nlen )
{

cout[0] = cb64[ cin[0] >> 2 ];
cout[1] = cb64[ ((cin[0] & 0x03) << 4) | ((cin[1] & 0xf0) >> 4) ];
cout[2] = (unsigned char) (nlen > 1 ? cb64[ ((cin[1] & 0x0f) << 2)
| ((cin[2] & 0xc0) >> 6) ] : '=');
cout[3] = (unsigned char) (nlen > 2 ? cb64[ cin[2] & 0x3f ] :
'=');
}


void decodeblock( unsigned char cin[4], unsigned char cout[3] )
{
cout[ 0 ] = (unsigned char ) (cin[0] << 2 | cin[1] >> 4);
cout[ 1 ] = (unsigned char ) (cin[1] << 4 | cin[2] >> 2);
cout[ 2 ] = (unsigned char ) (((cin[2] << 6) & 0xc0) | cin[3]);
}


int base641_decodestring(char* pcstr,int size,char** ppcdest)
{
  unsigned char cin[4] = {""};
  unsigned char cout[3] = {""};
  unsigned char  cv = 0;
  int ni = 0;
  int nlen = 0;
  char* cptr = pcstr;
  *ppcdest = malloc(sizeof(char)*160);
  if (!*ppcdest)
{
return 1;
}
  memset(*ppcdest,0,sizeof(char)*160);

  char* pcstring = malloc( sizeof(char) * SIZE);
if (!pcstring)
  {
  aps_log("APS_log.txt","\nbae64.c:base64encode:malloc failed
\n");
  return 1;
  }
  memset(pcstring,'\0',SIZE);

for( nlen = 0, ni = 0; ni < 4; ni++ )
  {
cv = 0;
while(  cv == 0 )
  {
cv = (unsigned char) *cptr;
cv = (unsigned char) ((cv < 43 || cv > 122) ? 0 :
cd64[ cv - 43 ]);
if( cv )
{
cv = (unsigned char) ((cv == '$') ? 0 : cv - 61);
}
}
if( cptr++ )
  {
nlen++;
if( cv )
{
cin[ ni ] = (unsigned char) (cv - 1);
}
}
else
  {
cin[ni] = 0;
}
}
if( nlen )
  {
decodeblock( cin, cout );

}
  memcpy(*ppcdest,cout,160);
  return 0;
}/*end of base64_decode */

char* base64_encode(char* pcstr)
{
  unsigned char cin[3] = {""};
  unsigned char cout[4] = {""};
  int ni = 0;
  int nlen = 0;
  int flag = 1;
  char* cptr = pcstr;
  char* pcstring = malloc( sizeof(char) * SIZE);
if (!pcstring)
  {
  aps_log("APS_log.txt","\nbae64.c:base64encode:malloc failed
\n");
  return (void*)0;
  }
  memset(pcstring,'\0',SIZE);
  while( flag )
  {
for( ni = 0; ni < 3; ni++ )
{
  cin[ni] = (unsigned char)*cptr;
  if( *++cptr != '\0' )
nlen++;
  else
  {
cin[ni] = 0;
  flag = 0;
break;
  }
}
encodeblock(cin, cout,nlen);
strcat(pcstring,cout);
  }

  return pcstring;

}/* end of base64_encode */


  But this code gives different hex values as compared to the
python base64.encodestring and base64.decodestring respectively .

 I need some help on this matter . I need some pointers on
where is the mistake for the above file .

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


Re: Catching a key press

2007-07-23 Thread westymatt
linux primarily still a little lost in how to implementent this,
however I understand what you are saying.

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


Re: decorators tutorials

2007-07-23 Thread james_027
hi bruno,

That seems to be hard to read at all, or I am just very new to python?

With that decorator how do I take advantage of it compare when I just
write a function that could do the same as what the decorator did? I
could translate the could from above into ...

def check_login(msg):
   #...
def my_func(toto, tata):
   #...

#call it like this
check_login('msg')
my_func('toto', 'tata')

Thanks
james
On Jul 23, 6:26 pm, Bruno Desthuilliers  wrote:
> james_027 a écrit :
>
> > Hi all,
>
> > I am having difficulty understanding decorator. The definition was
> > clear for me, but the syntax is not so clear to me.
>
> > will decorators will always have to be in this way
>
> > def check_login(func):
> > def _check_login(*args):
> > print "I am decorator"
> > return func(*args)
> > return _check_login
>
> Sort of... Well, depends...
>
> Basically, a decorator is a callable taking a callable as argument and
> returning a callable. These callable are usually *but* not necessarily
> functions. You may want to read the section about the special method
> __call__ in the  Fine Manual.
>
> Also, you may want to write a 'parameterized' decorator - a decorator
> taking arguments. In this case, you need one more wrapping level:
>
> def check_login(msg):
>def check_login_deco(func):
>  def _check_login(*args, **kw):
>print msg
>return func(*args, **kw)
>  return _check_login
>return check_login_deco
>
> @check_login("I am the decorator")
> def my_func(toto, tata):
>print toto, tata


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

Re: Configure apache to run python scripts

2007-07-23 Thread joe jacob
On Jul 23, 4:42 pm, Bruno Desthuilliers  wrote:
> joe jacob a écrit :
>
> > I need to configure apache to run python scripts. I followed the steps
> > mentioned in this site (http://www.thesitewizard.com/archive/
> > addcgitoapache.shtml). But I am not able to run python scripts from
> > Firefox, I  got a forbidden error "you do not have permission to
> > access the file in the server" when I try to run the script form
> > Firefox browser. Somebody please help me.
>
> http://httpd.apache.org/docs//howto/cgi.html
>
> with 'your_apache_version_here' in 1.3, 2.0, 2.2
>
> FWIW, your problem relates to apache and permissions, not to Python.
>
> HTH

I got it right, I configured the apache incorrectly. Now I can execute
the python scripts. Thanks for the response.

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

Re: Configure apache to run python scripts

2007-07-23 Thread Bruno Desthuilliers
joe jacob a écrit :
> I need to configure apache to run python scripts. I followed the steps
> mentioned in this site (http://www.thesitewizard.com/archive/
> addcgitoapache.shtml). But I am not able to run python scripts from
> Firefox, I  got a forbidden error "you do not have permission to
> access the file in the server" when I try to run the script form
> Firefox browser. Somebody please help me.

http://httpd.apache.org/docs//howto/cgi.html

with 'your_apache_version_here' in 1.3, 2.0, 2.2

FWIW, your problem relates to apache and permissions, not to Python.

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


Returned mail: Data format error

2007-07-23 Thread Post Office
Virus Warning Message (from InterScanVirusWall mbox.infotel.bg)

Found virus WORM_MYDOOM.GEN in file DOCUMENT.SCR (in document.zip)
The uncleanable file is deleted.

If you have questions, contact administrator.

-
The original message was received at Mon, 23 Jul 2007 12:47:19 +0200
from python.org [74.255.151.9]

- The following addresses had permanent fatal errors -





Virus Warning Message (from InterScanVirusWall mbox.infotel.bg)

document.zip is removed from here because it contains a virus.

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

Re: Can a low-level programmer learn OOP?

2007-07-23 Thread Eddie Corns
Wolfgang Strobl <[EMAIL PROTECTED]> writes:
>few of James Gimple's snippets from "Algorithms in SNOBOL4"
>(->http://www.snobol4.org/) as an exercise using that library might help
>to get a better appreciation. Perhaps I'll try, eventually ...

I never noticed them or the PDF of the book there before.  Some Friday
afternoon reading for sure.

Personally I hope to get more to time to look at a combination of Lua and
PEGs (http://en.wikipedia.org/wiki/Parsing_expression_grammar) for my parsing
needs.

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


Re: decorators tutorials

2007-07-23 Thread james_027
Hi all,

I am having difficulty understanding decorator. The definition was
clear for me, but the syntax is not so clear to me.

will decorators will always have to be in this way

def check_login(func):
def _check_login(*args):
print "I am decorator"
return func(*args)
return _check_login



@check_login
def method2(input):
print "I am method TWO. Input %s" % input


james

On Jul 23, 4:41 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> james_027 wrote:
> > Hi,
>
> > I am learning python by learning django, and I stumble upon decorator
> > which is very cool, any beginners resources for python decorators,
> > although I can google it, I just want to get a good tutorial for this
> > topic.
>
> Decorators are just a more concise but less obvious way of calling a
> defined function on another function.
>
> e.g.
> @my_decorator
> def foo():
>...
>
> is the essentially the same as:
>
> def foo():
>...
> foo=my_decorator(foo)


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


Re: Lazy "for line in f" ?

2007-07-23 Thread Duncan Booth
Duncan Booth <[EMAIL PROTECTED]> wrote:

> or even:
> 
>read = f.readline
>while read():
>pass
> 

Oops, I forgot the other obvious variant on this, which has the benefit of 
getting rid of the test I said was 'required' while still leaving the data 
accessible:

for line in iter(f.readline, ''):
pass

Takes 8.89 seconds (best of 3 runs) versus 3.56 (best of 3) for the 
similar:

for line in f:
pass

So readline is 250% slower at best, and only then if you remember the 
obscure use of iter. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lazy "for line in f" ?

2007-07-23 Thread Alexandre Ferrieux
On Jul 23, 12:18 pm, Duncan Booth <[EMAIL PROTECTED]>
wrote:
>
> Whatever, the iterator makes the code both cleaner and faster. It is at
> the expense of not being suitable for interactive sessions, or in some
> cases pipes, but for those situations you can continue to use readline
> and the extra overhead in runtime will not likely be noticable.

But *why* is it so ? If Python calls fgets() which already has
internal buffering, why is the extra buffering gaining so much ?

-Alex

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


Re: decorators tutorials

2007-07-23 Thread Bruno Desthuilliers
james_027 a écrit :
> Hi all,
> 
> I am having difficulty understanding decorator. The definition was
> clear for me, but the syntax is not so clear to me.
> 
> will decorators will always have to be in this way
> 
> def check_login(func):
> def _check_login(*args):
> print "I am decorator"
> return func(*args)
> return _check_login
> 

Sort of... Well, depends...

Basically, a decorator is a callable taking a callable as argument and 
returning a callable. These callable are usually *but* not necessarily 
functions. You may want to read the section about the special method 
__call__ in the  Fine Manual.

Also, you may want to write a 'parameterized' decorator - a decorator 
taking arguments. In this case, you need one more wrapping level:

def check_login(msg):
   def check_login_deco(func):
 def _check_login(*args, **kw):
   print msg
   return func(*args, **kw)
 return _check_login
   return check_login_deco

@check_login("I am the decorator")
def my_func(toto, tata):
   print toto, tata


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


Re: Lazy "for line in f" ?

2007-07-23 Thread Duncan Booth
Alexandre Ferrieux <[EMAIL PROTECTED]> wrote:

> On Jul 23, 10:33 am, Duncan Booth <[EMAIL PROTECTED]>
> wrote:
>>
>> The extra buffering means that iterating over a file is about 3 times
>> faster than repeatedly calling readline.
>>
>> while 1:
>> line = f.readline()
>> if not line:
>> break
>>
>> for line in f:
>> pass
>>
> 
> Surely you'll notice that the comparison is spoilt by the fact that
> the readline version needs an interpreted test each turn around.
> A more interesting test would be the C-implemented iterator, just
> calling fgets() (the thin layer policy) without extra 8k-blocking.
> 
No, I believe the comparison is perfectly fair. You need the extra test 
for the readline version whatever you do, and you don't need it for the 
iterator.

If you insist, you can add an identical 'if not line: break' into the 
iterator version as well: it adds another 10% onto the iterator runtime 
which is still nearly a factor of 3 faster than the readline version, 
but then you aren't comparing equivalent code.

Alternatively you can knock a chunk off the time for the readline loop 
by writing it as:

   while f.readline():
   pass

or even:

   read = f.readline
   while read():
   pass

which gets it down from 10.3 to 9.0 seconds. It's 'fair' in your book 
since it avoids all the extra interpreter overhead of attribute lookup 
and a separate test, but it does make it a touch hard to do anything 
useful with the actual data.

Whatever, the iterator makes the code both cleaner and faster. It is at 
the expense of not being suitable for interactive sessions, or in some 
cases pipes, but for those situations you can continue to use readline 
and the extra overhead in runtime will not likely be noticable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with exec

2007-07-23 Thread vedrandekovic
On 23 srp, 09:19, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> En Sun, 22 Jul 2007 10:36:59 -0300, <[EMAIL PROTECTED]>
> escribió:
>
> >> Since the application is transforming
> >> its input, it could transform braces into indentation. Of course
> >> *Python*
> >> doesn't use braces, but the question was how to write "pseudo-Python"
> >> without using indentation to indicate grouping.
>
> > This previously is exactly what I need can you help me somehow about
> > this
> > code
> > indentation, on any way you know.Plese help I will really appreciate
> > this!!
>
> If you are using the tokenize module as suggested some time ago, try to
> analyze the token sequence you get using { } (or perhaps begin/end pairs
> in your own language, that are easier to distinguish from a dictionary
> display) and the sequence you get from the "real" python code. Then write
> a script to transform one into another:
>
>  from tokenize import generate_tokens
>  from token import tok_name
>  from cStringIO import StringIO
>
> def analyze(source):
>  g = generate_tokens(StringIO(source).readline)
>  for toknum, tokval, _, _, _  in g:
>  print tok_name[toknum], repr(tokval)
>
> I think you basically will have to ignore INDENT, DEDENT, and replace
> NAME+"begin" with INDENT, NAME+"end" with DEDENT.
>
> --
> Gabriel Genellina

Hello,

I know what do you mean and I really need that , but I don't know how
to I do this. Please help me! It's really important to me

 
Regards,
 
Vedran

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

set_proxy in urllib2 is driving my crazy

2007-07-23 Thread est
A simple py script

import urllib2
req=urllib2.Request("http://www.google.com";)
req.set_proxy("127.0.0.1:1","http")
print urllib2.urlopen(req).read()




Here is error:

 "C:\Python25\python.exe" -u "E:\Python\Crawler\test.py"


Traceback (most recent call last):
  File "E:\Python\Crawler\test.py", line 4, in 
print urllib2.urlopen(req).read()
  File "C:\Python25\lib\urllib2.py", line 121, in urlopen
return _opener.open(url, data)
  File "C:\Python25\lib\urllib2.py", line 374, in open
response = self._open(req, data)
  File "C:\Python25\lib\urllib2.py", line 392, in _open
'_open', req)
  File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
  File "C:\Python25\lib\urllib2.py", line 1101, in http_open
return self.do_open(httplib.HTTPConnection, req)
  File "C:\Python25\lib\urllib2.py", line 1076, in do_open
raise URLError(err)
urllib2.URLError: 


I built a proxy with CCproxy 6.3.2 on my own machine, and it's working
absolutely all right, but how can my simple python script go wrong ?

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


Re: Catching a key press

2007-07-23 Thread thebjorn
On Jul 23, 9:05 am, westymatt <[EMAIL PROTECTED]> wrote:
> This is without a gui toolkit.  This is going to be implemented on
> console i/o

If you're on windows, you'll need the kbhit() and getch() functions in
the msvcrt module. The up arrow returns two separate "keyboard-
hits" (with ordinal value 224 and 72).

-- bjorn

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


Re: Lazy "for line in f" ?

2007-07-23 Thread Alexandre Ferrieux
On Jul 23, 10:33 am, Duncan Booth <[EMAIL PROTECTED]>
wrote:
>
> The extra buffering means that iterating over a file is about 3 times
> faster than repeatedly calling readline.
>
> while 1:
> line = f.readline()
> if not line:
> break
>
> for line in f:
> pass
>

Surely you'll notice that the comparison is spoilt by the fact that
the readline version needs an interpreted test each turn around.
A more interesting test would be the C-implemented iterator, just
calling fgets() (the thin layer policy) without extra 8k-blocking.

-Alex

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


Re: decorators tutorials

2007-07-23 Thread Roel Schroeven
james_027 schreef:
> Hi,
> 
> I am learning python by learning django, and I stumble upon decorator
> which is very cool, any beginners resources for python decorators,
> although I can google it, I just want to get a good tutorial for this
> topic.

I like the short explanation on Kent's Korner: 
http://personalpages.tds.net/~kent37/kk/1.html

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

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


python-fam documentation.

2007-07-23 Thread Shriphani
Folks,
I am trying to create an app which stares at a file and when the file
is altered, the script joins a channel on freenode and reports that
the file has been altered.
I found a module called python-fam, unfortunately i have been unable
to find documentation for it. Can someone please help me ?
Thanks,
Shriphani Palakodety.

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


Re: decorators tutorials

2007-07-23 Thread [EMAIL PROTECTED]
james_027 wrote:
> Hi,
>
> I am learning python by learning django, and I stumble upon decorator
> which is very cool, any beginners resources for python decorators,
> although I can google it, I just want to get a good tutorial for this
> topic.

Decorators are just a more concise but less obvious way of calling a
defined function on another function.

e.g.
@my_decorator
def foo():
   ...

is the essentially the same as:

def foo():
   ...
foo=my_decorator(foo)

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


Re: decorators tutorials

2007-07-23 Thread Michele Simionato
On Jul 23, 10:13 am, james_027 <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I am learning python by learning django, and I stumble upon decorator
> which is very cool, any beginners resources for python decorators,
> although I can google it, I just want to get a good tutorial for this
> topic.
>
> Thanks
> james

Look at the decorator page in the Python Wiki. There is also a paper
by
David Mertz on IBM DeveloperWorks. Finally, you may have a look at my
own work http://www.phyast.pitt.edu/~micheles/python/documentation.html

   Michele Simionato

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


Re: Lazy "for line in f" ?

2007-07-23 Thread Duncan Booth
Alexandre Ferrieux <[EMAIL PROTECTED]> wrote:

> On Jul 23, 9:36 am, Paul Rubin  wrote:
>> Alexandre Ferrieux <[EMAIL PROTECTED]> writes:
>> > So I'll reiterate the question: *why* does the Python library add 
that
>> > extra layer of (hard-headed) buffering on top of stdio's ?
>>
>> readline?
> 
> I know readline() doesn't have this problem. I'm asking why the file
> iterator does.
> 
Here's a program which can create a large file and either read it with 
readline or iterate over the lines. Output from various runs should 
answer your question.

The extra buffering means that iterating over a file is about 3 times 
faster than repeatedly calling readline.

C:\Temp>test.py create 100
create file
Time taken=7.28 seconds

C:\Temp>test.py readline
readline
Time taken=1.03 seconds

C:\Temp>test.py iterate
iterate
Time taken=0.38 seconds

C:\Temp>test.py create 1000
create file
Time taken=47.28 seconds

C:\Temp>test.py readline
readline
Time taken=10.39 seconds

C:\Temp>test.py iterate
iterate
Time taken=3.58 seconds


--- test.py 
import time, sys

NLINES = 10
def create():
print "create file"
f = open('testfile.txt', 'w')
for i in range(NLINES):
print >>f, "This is a test file with a lot of lines"
f.close()

def readline():
print "readline"
f = open('testfile.txt', 'r')
while 1:
line = f.readline()
if not line:
break
f.close()

def iterate():
print "iterate"
f = open('testfile.txt', 'r')
for line in f:
pass
f.close()

def doit(fn):
start = time.time()
fn()
end = time.time()
print "Time taken=%0.2f seconds" % (end-start)

if __name__=='__main__':
if len(sys.argv) >= 3:
NLINES = int(sys.argv[2])

if sys.argv[1]=='create':
doit(create)
elif sys.argv[1]=='readline':
doit(readline)
elif sys.argv[1]=='iterate':
doit(iterate)


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


Re: Lazy "for line in f" ?

2007-07-23 Thread Alexandre Ferrieux
On Jul 23, 9:36 am, Paul Rubin  wrote:
> Alexandre Ferrieux <[EMAIL PROTECTED]> writes:
> > So I'll reiterate the question: *why* does the Python library add that
> > extra layer of (hard-headed) buffering on top of stdio's ?
>
> readline?

I know readline() doesn't have this problem. I'm asking why the file
iterator does.

-Alex

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


Re: decorators tutorials

2007-07-23 Thread Bruno Desthuilliers
james_027 a écrit :
> Hi,
> 
> I am learning python by learning django, and I stumble upon decorator
> which is very cool, any beginners resources for python decorators,
> although I can google it, I just want to get a good tutorial for this
> topic.

You should find answers on python.org, and searching this newsgroup.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >