Re: Taking data from a text file to parse html page

2006-08-23 Thread Anthra Norell
DH,
  Could you be more specific describing what you have and what you want? 
You are addressing people, many of whom are good at
stripping useless junk once you tell them what 'useless junk' is.
  Also it helps to post some of you data that you need to process and a 
sample of the same data as it should look once it is
processed.

Frederic

- Original Message -
From: "DH" <[EMAIL PROTECTED]>
Newsgroups: comp.lang.python
To: 
Sent: Thursday, August 24, 2006 2:11 AM
Subject: Taking data from a text file to parse html page


> Hi,
>
> I'm trying to strip the html and other useless junk from a html page..
> Id like to create something like an automated text editor, where it
> takes the keywords from a txt file and removes them from the html page
> (replace the words in the html page with blank space) I'm new to python
> and could use a little push in the right direction, any ideas on how to
> implement this?
>
> Thanks!
>
> --
> http://mail.python.org/mailman/listinfo/python-list

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


Re: how to get file name of the running .py file

2006-08-23 Thread Fredrik Lundh
Larry Bates wrote:

>> How to get the name of the running .py file like the macro _FILE_ in C?

> import os
> import sys
> print sys.argv[0]
> 
> or if you just want the script and not the full path
> 
> print os.path.basename(sys.argv[0])

except that __FILE__ is the name of the current source file, not the 
name of the main program.

the global name __file__ is a better choice; when definied, it points to 
the file from which the current module was loaded (this might be a byte 
code file or a shared library).

also see:

 http://pyref.infogami.com/__file__



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


Re: sum and strings

2006-08-23 Thread Fredrik Lundh
Tim Chase wrote:

>  >>> q3 = q1 + q2
>  >>> q3.n, q3.i, q3.j, q3.k
> (8, 13, 16, 22)
>  >>> sum([q1,q2])
> Traceback (most recent call last):
>File "", line 1, in ?
> TypeError: unsupported operand type(s) for +: 'int' and 'q'
> 
> Just because something is slow or sub-optimal doesn't mean it 
> should be an error.

that's not an error because it would be "slow or sub-optimal" to add 
custom objects, that's an error because you don't understand how "sum" 
works.

(hint: sum != reduce)



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


Re: smtplib needs me to put from/to headers in the message?

2006-08-23 Thread Tim Roberts
tobiah <[EMAIL PROTECTED]> wrote:
>
>In the example at:
>
>   http://docs.python.org/lib/SMTP-example.html
>
>The text of the email message ends up with the From:
>and To: headers in it, and yet the call to sendmail()
>on the server object requires me to specify them again.
>
>Shouldn't smptlib just make the headers for me, given
>the 'from' and 'to' addresses?

No, it shouldn't.

>Perhaps this allows
>me to spoof the 'from' address.  Still, I might as well
>just make all of the headers myself, and pass the message
>as a single argument to sendmail().

E-mail consists of two distict and separate standard.  The standard for how
e-mail is exchanged between systems is SMTP, in RFC 2821 (originally 821).
The standard for the format of a message, including headers and body, is in
RFC 2822 (originally 822).

SMTP needs to know who is sending, and where it going.  That's what the
first two parameters to smtplib.sendmail provide.  The entire contents of
the e-mail message, including the headers and the body, are completely
opaque to SMTP.  The message is nothing but "data".

That's why you need to specify it twice.  The first two parameters are for
SMTP, and are used by the mail server (e.g., sendmail).  That part is
called the "envelope".  The body is only used by the mail reader at the
other end, which never sees the data in the SMTP exchange.

Further, the SMTP protocol doesn't care about To:, Cc:, and Bcc:.  There is
just a list of addresses.  To: and Cc: are just for the convenience of the
person reading at the other end.

If it didn't work that way, you couldn't do Bcc:'s.  When you use a Bcc: in
your mail program, the name gets added to the SmTP

This is how a Bcc: is done.  A Bcc: header is never included in an e-mail
message.  The address gets included in the envelope, but not in the headers
or body.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What do you want in a new web framework?

2006-08-23 Thread Cliff Wells
On Thu, 2006-08-24 at 04:04 +, Tim Roberts wrote:
> Cliff Wells <[EMAIL PROTECTED]> wrote:
> >
> >But there are interesting things in Ruby (and Ruby 2 should take care of
> >lots of warts Ruby 1.8 has) that Python could learn from.  All-in-all,
> >Ruby is mostly as good as Python in most ways and better than Python in
> >a couple key ways.
> 
> ...but you can't READ Ruby code.  

Yeah, that's one of the big reasons I haven't seriously considered
trying it.  It's expressive, got interesting features... and appears
unreadable to me.  I'm usually pretty good at deciphering most
languages, even if I haven't used them before, but Ruby is one of the
exceptions.

> One of the things I like best about
> Python is that, like Cobol, you can read Python code like prose (or poetry
> ;) and, for the most part, know what the code does, even without being a
> Python guru.  I have not had the same experience with Ruby.  There are
> special characters in there that make the program say something I can't
> immediately discern.

There's the line noise aspect, but also some things are just expressed
in what appears (to me) to be rather non-idiomatic ways.  But I suppose
it depends on your background.  A rather brilliant friend of mine with a
Smalltalk background thinks that the Ruby reads like a novel. Shrug. He
also reads Japanese, so maybe that's a factor ;-)

> To be sure, people whose opinions I trust (one of whom is Cliff Wells) have
> said that Ruby is great, so I suppose I need to look again.  I just haven't
> had the same "aha!" experience that I had with Python.

Thanks for the vote of confidence. I have lots of opinions, but even I
only trust a few of them ;-)

I think Ruby has great things and I'm certain it's a great fit for many
people.  But I'm with you 100% on Python's readability.  I just wish we
could have the great things from both.

This brings us back around to the web framework debates.  For many
people Ruby "fits" their brains and for others Python does.  I think
frameworks are similar.  I tried Django and while I thought it was a
great product, it simply didn't "fit" how I think about that problem
domain.  TurboGears on the other hand did, and really, it helped clarify
a few things I had vague notions about.  I think we'll do better not
trying to shoehorn people into one or the other.

Regards,
Cliff
-- 

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


Re: all ip addresses of machines in the local network

2006-08-23 Thread John Bokma
"damacy" <[EMAIL PROTECTED]> wrote:

> hi, sandra.

If you reply like is common on Usenet, there is no need to address 
someone, since the attribution line is just there:

Sandra-24 wrote:
^^^

Google for top posting, and read why it's generally considered bad.

> no, it's not as complicated as that. all i want to do is to load a
> database onto different machines residing in the same network.

if they are all in the xx.yy.zz.ii range, with ii the only number that 
varies, you could ping each ii with a short time out. No reply = nothing 
on it (unless pings are blocked).

-- 
John   MexIT: http://johnbokma.com/mexit/
   personal page:   http://johnbokma.com/
Experienced programmer available: http://castleamber.com/
Happy Customers: http://castleamber.com/testimonials.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: all ip addresses of machines in the local network

2006-08-23 Thread mbstevens
On Wed, 23 Aug 2006 21:46:21 -0700, damacy wrote:

> hi, sandra.
> 
> no, it's not as complicated as that. all i want to do is to load a
> database onto different machines residing in the same network. i hope
> there is a way doing it. or perhaps i have a poor understanding of how
> networks work.

It would not be 'as complicated as that' if we knew the kind of
network you are on --  NFS, Samba, Windows, some hybred network, 
SSH, FTP, telnet, remote X, remote desktops?   Every service has its
own way of doing things.


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


Re: all ip addresses of machines in the local network

2006-08-23 Thread John Bokma
"damacy" <[EMAIL PROTECTED]> wrote:

> hi, there. i have a problem writing a program which can obtain ip
> addresses of machines running in the same local network.
> 
> say, there are 4 machines present in the network; [a], [b], [c] and [d]
> and if i run my program on [a], it should be able to find "host names"
> and "ip addresses" of the other machines; [b], [c] and [d]?
> 
> i have read some threads posted on this group, however, they only work
> for localhost, not the entire network.
> 
> any hints if possible?

google for nmap, don't reinvent the wheel.


-- 
John   MexIT: http://johnbokma.com/mexit/
   personal page:   http://johnbokma.com/
Experienced programmer available: http://castleamber.com/
Happy Customers: http://castleamber.com/testimonials.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: all ip addresses of machines in the local network

2006-08-23 Thread damacy
hi, sandra.

no, it's not as complicated as that. all i want to do is to load a
database onto different machines residing in the same network. i hope
there is a way doing it. or perhaps i have a poor understanding of how
networks work.

regards, damacy

Sandra-24 wrote:
> damacy wrote:
> > hi, there. i have a problem writing a program which can obtain ip
> > addresses of machines running in the same local network.
> >
> > say, there are 4 machines present in the network; [a], [b], [c] and [d]
> > and if i run my program on [a], it should be able to find "host names"
> > and "ip addresses" of the other machines; [b], [c] and [d]?
> >
> > i have read some threads posted on this group, however, they only work
> > for localhost, not the entire network.
> >
> > any hints if possible?
> >
> > thanks for your time.
> >
> > regards, damacy
>
> What is this for? Some kind of high availablity server setup? I don't
> know anything that would be useful to you, but I am curious, and maybe
> it will clarify your intentions for others.
> 
> -Sandra

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


Re: Translating Javascript programs to python.

2006-08-23 Thread Vyz
Yes, this is a trimmed down version of padma, a generic indic
transliteration tool
Thanks for comments though.

Terry Reedy wrote:
> "Vyz" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > Its a module to transliterate from telugu language  written in roman
> > script into native unicode. right now its running in a browser window
> > at www.lekhini.org I Intend to translate it into python so that I can
> > integrate into other tools I have. I am able to pass arguments and get
> > output from the script also would be OK. or how about ways to wrap
> > these javascript functions with python.
>
> Leaving aside the code the manipulated the display and user interaction,
> the code should be pretty straightforward logic (if-else statements) and
> table lookups, so translation to Python should be straightforward also.
>
> I checked parser.js.  I don't know javascript but it looks to me like a
> mixture of C and Python.  The for loop headers have to be rewritten, and
> the switch changed to if-elif.  What looks different is the attachment as
> attributes of method functions to functions rather than classes.
>
> As for 'wrapping': can you get a standard javascript interpreter?  If so,
> you could possibly adjust the js so you can pipe a roman string to the js
> program and have it pipe back the telegu unicode version.
>
> >> > I have a script with hundreds of lines of javascript spread accross 7
> >> > files. Is there any tool out there to automatically or
> >> > semi-automatically translate the code into python.
>
> unicode.js is mostly a few hundred verbose lines like
>
> Unicode.codePoints[Padma.lang_TELUGU].letter_PHA  = "\u0C2B";
>
> that setup the translation dict.  Because the object model is different, I
> suspect that these all need to be changed, but, I also suspect, in a
> mechanical way.
>
> If one were starting in Python, one might either just define a dict more
> compactly like
>   TEL_uni = {letter_PHA:"\u0C2B", ...}
> *or* probably better, use the builtin unicodedata module as much as
> possible.
>
> >>> import unicodedata as u
> >>> pha = u.name(u'\u0c2b')
> >>> pha
> 'TELUGU LETTER PHA'
> >>> u.lookup(pha)
> u'\u0c2b'
>
> I don't know what you do with js statement like this:
> Unicode.toPadma[Unicode.codePoints[Padma.lang_TELUGU].misc_VIRAMA +
> Unicode.codePoints[Padma.lang_TELUGU].letter_KA] = Padma.vattu_KA;
> where a constant seems to be assigned to a sum.  But whatever these do
> might correspond to the u.normalize function.
>
> This appears to be based on a generic Indian-script transliteration program
> (Padma), so there may be functions not really needed for Telegu.  (I am
> familiar with Devanagri but know nothing of Telegu and its script except
> that it is Dravidian rather than Indo-European-Sanskritic.)
> 
> Good luck.
> 
> Terry Jan Reedy

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


Re: how to get file name of the running .py file

2006-08-23 Thread Bill Pursell

Jason Jiang wrote:
> Hi,
>
> How to get the name of the running .py file like the macro _FILE_ in C?

There are many ways--IMO the easiest is with __file__:

>>> print __file__
/home/bill/.pystart
>>>
[tmp]$ cat foo.py
#!/usr/bin/env python

print "The name of the file is:%s"%__file__
[tmp]$ ./foo.py
The name of the file is:./foo.py

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


Re: all ip addresses of machines in the local network

2006-08-23 Thread Sandra-24
damacy wrote:
> hi, there. i have a problem writing a program which can obtain ip
> addresses of machines running in the same local network.
>
> say, there are 4 machines present in the network; [a], [b], [c] and [d]
> and if i run my program on [a], it should be able to find "host names"
> and "ip addresses" of the other machines; [b], [c] and [d]?
>
> i have read some threads posted on this group, however, they only work
> for localhost, not the entire network.
>
> any hints if possible?
>
> thanks for your time.
>
> regards, damacy

What is this for? Some kind of high availablity server setup? I don't
know anything that would be useful to you, but I am curious, and maybe
it will clarify your intentions for others.

-Sandra

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


Re: What do you want in a new web framework?

2006-08-23 Thread Tim Roberts
Cliff Wells <[EMAIL PROTECTED]> wrote:
>
>But there are interesting things in Ruby (and Ruby 2 should take care of
>lots of warts Ruby 1.8 has) that Python could learn from.  All-in-all,
>Ruby is mostly as good as Python in most ways and better than Python in
>a couple key ways.

...but you can't READ Ruby code.  One of the things I like best about
Python is that, like Cobol, you can read Python code like prose (or poetry
;) and, for the most part, know what the code does, even without being a
Python guru.  I have not had the same experience with Ruby.  There are
special characters in there that make the program say something I can't
immediately discern.

To be sure, people whose opinions I trust (one of whom is Cliff Wells) have
said that Ruby is great, so I suppose I need to look again.  I just haven't
had the same "aha!" experience that I had with Python.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: smtplib needs me to put from/to headers in the message?

2006-08-23 Thread Tobiah
Thank you for the valuable clarification, and the pointers.
I will look into the RFC's.  I wonder though, whether that
will solve my main question, which is why the python.org
example mandates that I specify 'from' and 'to' twice.

Thanks,

Tobiah

Ben Finney wrote:
> tobiah <[EMAIL PROTECTED]> writes:
> 
> 
>>In the example at:
>>  http://docs.python.org/lib/SMTP-example.html
>>
>>The text of the email message ends up with the From: and To: headers
>>in it, and yet the call to sendmail() on the server object requires
>>me to specify them again.
> 
> 
> [Pet hate issue: Every RFC 2822 email message has exactly *one* body
> and *one* header. 

-- 
Posted via a free Usenet account from http://www.teranews.com

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


all ip addresses of machines in the local network

2006-08-23 Thread damacy
hi, there. i have a problem writing a program which can obtain ip
addresses of machines running in the same local network.

say, there are 4 machines present in the network; [a], [b], [c] and [d]
and if i run my program on [a], it should be able to find "host names"
and "ip addresses" of the other machines; [b], [c] and [d]?

i have read some threads posted on this group, however, they only work
for localhost, not the entire network.

any hints if possible?

thanks for your time.

regards, damacy

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


Re: Regex help...pretty please?

2006-08-23 Thread vbgunz
MooMaster Wrote:
> I'm trying to develop a little script that does some string
> manipulation. I have some few hundred strings that currently look like
> this:
> cond(a,b,c)
> and I want them to look like this:
> cond(c,a,b)

I zoned out on your question and created a very simple flipper.
Although it will not solve your problem maybe someone looking for a
simpler version may find it useful as a starting point. I hope it
proves useful. I'll post my simple flipper here:

s = 'cond(1,savv(grave(3,2,1),y,x),maxx(c,b,a),0)'
def argFlipper(s):
''' take a string of arguments and reverse'em e.g.
>>> cond(1,savv(grave(3,2,1),y,x),maxx(c,b,a),0)
 -> cond(0,maxx(a,b,c),savv(x,y,grave(1,2,3)),1)

'''

count = 0
keyholder = {}
while 1:
if s.find('(') > 0:
count += 1
value = '%sph' + '%d' % count
tempstring = [x for x in s]
startindex = s.rfind('(')
limitindex = s.find(')', startindex)
argtarget = s[startindex + 1:limitindex].split(',')
argreversed = ','.join(reversed(argtarget))
keyholder[value] = '(' + argreversed + ')'
tempstring[startindex:limitindex + 1] = value
s = ''.join(tempstring)
else:
while count and keyholder:
s = s.replace(value, keyholder[value])
count -= 1
value = '%sph' + '%d' % count
return s  

print argFlipper(s)

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


Can Python do Perl's print <

2006-08-23 Thread yichun . wei
Perl has the ability to do the following:

  print > QSUB.stdin, qsubcmds
  (or Popen.communicate(qsubcmds))

the "rm -f " was not executed in my case.

The corresponding perl script runs fine:

  open(QSUB, "| $qsubcmds -") || die "kao";
  print QSUB 

Re: Accessing application data portably

2006-08-23 Thread Steve Holden
Tom E H wrote:
> My Python application includes some data files that need to be accessed by
> modules I distribute with it.
> 
> Where can I put them, and how should I arrange my code, so that it works
> across platforms?
> 
> On Linux, I could install the data to "/usr/lib/myprogram/datafile", and
> on Windows to "datafile" relative to where the executable (made by
> py2exe) is installed.  Then I could detect the operating system, and choose
> appropriately.
> 
> To be that explicit seems undesirable.  Any cleverer ideas?
> 
> Tom
> 
> (Please CC me on replies: I'm not subscribed.  The From address is munged)
> 
If you aren't ubscribed then the only person who is going to copy you on 
email is someone complaining about your presumptuousness in assuming 
they'd happily want to spend time trimming your email address just so 
you won't be bothered by the spam plagie.

Sorry, the question seems to have completely gone out of my head ...

regards
  Steeve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Accessing application data portably

2006-08-23 Thread Steve Holden
Tom E H wrote:
> My Python application includes some data files that need to be accessed by
> modules I distribute with it.
> 
> Where can I put them, and how should I arrange my code, so that it works
> across platforms?
> 
> On Linux, I could install the data to "/usr/lib/myprogram/datafile", and
> on Windows to "datafile" relative to where the executable (made by
> py2exe) is installed.  Then I could detect the operating system, and choose
> appropriately.
> 
> To be that explicit seems undesirable.  Any cleverer ideas?
> 
> Tom
> 
> (Please CC me on replies: I'm not subscribed.  The From address is munged)
> 
If you aren't ubscribed then the only person who is going to copy you on 
email is someone complaining about your presumptuousness in assuming 
they'd happily want to spend time trimming your email address just so 
you won't be bothered by the spam plagie.

Sorry, the question seems to have completely gone out of my head ...

regards
  Steeve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: range of int() type.

2006-08-23 Thread Felipe Almeida Lessa
23 Aug 2006 17:28:48 -0700, KraftDiner <[EMAIL PROTECTED]>:
> This is obvious... but how do I crop off the high order bits if
> necessary?
> a[0]&0x ?

min(a[0], 0x) ?

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


Re: Dr. Dobb's Python-URL! - weekly Python news and links (Aug 23)

2006-08-23 Thread Steve Holden
John Salerno wrote:
> Jack Diederich wrote:
> 
> 
>>David Wahler is no longer out of the office.
>>http://groups.google.com/groups/search?q=David+Wahler+out+of+office
> 
> 
> LOL. That's the best part this week! :)

Can anyone remember when David Wahler got back?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Translating Javascript programs to python.

2006-08-23 Thread Terry Reedy

"Vyz" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Its a module to transliterate from telugu language  written in roman
> script into native unicode. right now its running in a browser window
> at www.lekhini.org I Intend to translate it into python so that I can
> integrate into other tools I have. I am able to pass arguments and get
> output from the script also would be OK. or how about ways to wrap
> these javascript functions with python.

Leaving aside the code the manipulated the display and user interaction, 
the code should be pretty straightforward logic (if-else statements) and 
table lookups, so translation to Python should be straightforward also.

I checked parser.js.  I don't know javascript but it looks to me like a 
mixture of C and Python.  The for loop headers have to be rewritten, and 
the switch changed to if-elif.  What looks different is the attachment as 
attributes of method functions to functions rather than classes.

As for 'wrapping': can you get a standard javascript interpreter?  If so, 
you could possibly adjust the js so you can pipe a roman string to the js 
program and have it pipe back the telegu unicode version.

>> > I have a script with hundreds of lines of javascript spread accross 7
>> > files. Is there any tool out there to automatically or
>> > semi-automatically translate the code into python.

unicode.js is mostly a few hundred verbose lines like

Unicode.codePoints[Padma.lang_TELUGU].letter_PHA  = "\u0C2B";

that setup the translation dict.  Because the object model is different, I 
suspect that these all need to be changed, but, I also suspect, in a 
mechanical way.

If one were starting in Python, one might either just define a dict more 
compactly like
  TEL_uni = {letter_PHA:"\u0C2B", ...}
*or* probably better, use the builtin unicodedata module as much as 
possible.

>>> import unicodedata as u
>>> pha = u.name(u'\u0c2b')
>>> pha
'TELUGU LETTER PHA'
>>> u.lookup(pha)
u'\u0c2b'

I don't know what you do with js statement like this:
Unicode.toPadma[Unicode.codePoints[Padma.lang_TELUGU].misc_VIRAMA + 
Unicode.codePoints[Padma.lang_TELUGU].letter_KA] = Padma.vattu_KA;
where a constant seems to be assigned to a sum.  But whatever these do 
might correspond to the u.normalize function.

This appears to be based on a generic Indian-script transliteration program 
(Padma), so there may be functions not really needed for Telegu.  (I am 
familiar with Devanagri but know nothing of Telegu and its script except 
that it is Dravidian rather than Indo-European-Sanskritic.)

Good luck.

Terry Jan Reedy




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


Re: how to get file name of the running .py file

2006-08-23 Thread Jason Jiang
Thank you guys.

Jason

"Simon Forman" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Larry Bates wrote:
>> Jason Jiang wrote:
>> > Hi,
>> >
>> > How to get the name of the running .py file like the macro _FILE_ in C?
>> >
>> > Thanks.
>> > Jason
>> >
>> >
>> >
>> import os
>> import sys
>> print sys.argv[0]
>>
>> or if you just want the script and not the full path
>>
>> print os.path.basename(sys.argv[0])
>>
>> -Larry Bates
>
> Also, check out:
> http://groups.google.ca/group/comp.lang.python/browse_frm/thread/712572b3c2f2cb13
>
> Peace,
> ~Simon
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 



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


Re: Regex help...pretty please?

2006-08-23 Thread Paul McGuire
"MooMaster" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> I'm trying to develop a little script that does some string
> manipulation. I have some few hundred strings that currently look like
> this:
>
> cond(a,b,c)
>
> and I want them to look like this:
>
> cond(c,a,b)



Pyparsing makes this a fairly tractable problem.  The hardest part is
defining the valid contents of a relational and arithmetic expression, which
may be found within the arguments of your cond(a,b,c) constructs.

Not guaranteeing this 100%, but it did convert your pathologically nested
example on the first try.

-- Paul

--
from pyparsing import *

ident = ~Literal("cond") + Word(alphas)
number = Combine(Optional("-") + Word(nums) + Optional("." + Word(nums)))

arithExpr = Forward()
funcCall = ident+"("+delimitedList(arithExpr)+")"
operand = number | funcCall | ident
binop = oneOf("+ - * /")
arithExpr << ( ( operand + ZeroOrMore( binop + operand ) ) | ("(" +
arithExpr + ")" ) )
relop = oneOf("< > == <= >= != <>")

condDef = Forward()
simpleCondExpr = arithExpr + ZeroOrMore( relop + arithExpr ) | condDef
multCondExpr = simpleCondExpr + "*" + arithExpr
condExpr = Forward()
condExpr << ( simpleCondExpr | multCondExpr | "(" + condExpr + ")" )

def reorderArgs(t):
return "cond(" + ",".join(["".join(t.arg3), "".join(t.arg1),
"".join(t.arg2)]) + ")"

condDef << ( Literal("cond") + "(" + Group(condExpr).setResultsName("arg1")
+ "," +
 Group(condExpr).setResultsName("arg2")
+ "," +
 Group(condExpr).setResultsName("arg3")
+ ")" ).setParseAction( reorderArgs )

tests = [
"cond(a,b,c)",
"cond(1>2,b,c)",
"cond(-1,1,f)*((float(e)*(2**4))+(float(d)*8)+(float(c)*4)+(float(b)*2)+floa
t(a))",
"cond(a,b,(abs(c) >= d))",
"cond(0,cond(c,cond(e,cond(g,h,(a",condExpr.transformString(t)
--
Prints:
cond(a,b,c) -> cond(c,a,b)
cond(1>2,b,c) -> cond(c,1>2,b)
cond(-1,1,f)*((float(e)*(2**4))+(float(d)*8)+(float(c)*4)+(float(b)*2)+float
(a)) ->
cond(f,-1,1)*((float(e)*(2**4))+(float(d)*8)+(float(c)*4)+(float(b)*2)+float
(a))
cond(a,b,(abs(c) >= d)) -> cond((abs(c)>=d),a,b)
cond(0,cond(c,cond(e,cond(g,h,(a
cond((a<1),0,cond((ahttp://mail.python.org/mailman/listinfo/python-list


Re: range of int() type.

2006-08-23 Thread KraftDiner

Terry Reedy wrote:
> "KraftDiner" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> >
> > So what type / class should one use to represent a 16 bit integers
> > (signed or unsigned)?
>
> For most purposes, Python just has integers, with 'small' ones (depending
> on the machine) handled more efficiently.  For special purposes, you may
> want to use the array or struct modules.
>
> tjr

Ok so the bottom line is..
if I have two arrays...

a = array.array('L')
a.append(65536L)
b = array.array('H')
b.append(a[0])

I will get the error:
  File "", line 1, in ?
OverflowError: unsigned short is greater than maximum

This is obvious... but how do I crop off the high order bits if
necessary?
a[0]&0x ?

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


Taking data from a text file to parse html page

2006-08-23 Thread DH
Hi,

I'm trying to strip the html and other useless junk from a html page..
Id like to create something like an automated text editor, where it
takes the keywords from a txt file and removes them from the html page
(replace the words in the html page with blank space) I'm new to python
and could use a little push in the right direction, any ideas on how to
implement this?

Thanks!

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


Re: setting a breakpoint in the module

2006-08-23 Thread Simon Forman
Jason Jiang wrote:
> Great! It's working now. Thank you so much.
> 
> Jason

You're welcome, it's a pleasure!  :-D

~Simon

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


Re: how to get file name of the running .py file

2006-08-23 Thread Simon Forman
Larry Bates wrote:
> Jason Jiang wrote:
> > Hi,
> >
> > How to get the name of the running .py file like the macro _FILE_ in C?
> >
> > Thanks.
> > Jason
> >
> >
> >
> import os
> import sys
> print sys.argv[0]
>
> or if you just want the script and not the full path
>
> print os.path.basename(sys.argv[0])
>
> -Larry Bates

Also, check out:
http://groups.google.ca/group/comp.lang.python/browse_frm/thread/712572b3c2f2cb13

Peace,
~Simon

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


Re: radio buttons in curses

2006-08-23 Thread Steve Holden
Fabian Braennstroem wrote:
> Sorry, me again...
> Does nobody have an idea or is it to stupid?
> 
> * Fabian Braennstroem <[EMAIL PROTECTED]> wrote:
> 
>>Hi,
>>
>>I want to add some radio and check buttons to my curses
>>script. As I understand it, there are no buttons in the
>>'basic' curses module. Now, I found the curses-extra module,
>>but I not able to download and install it.
>>
>>Does anybody have an idea, where I can download the module
>>or, even better, how I can create radio and check buttons
>>with the 'ordinary' curses module? Would be nice...
>>
>>Greetings!
>> Fabian
>>
>>-- 
>>http://mail.python.org/mailman/listinfo/python-list
>>
> 
> 
> Greetings!
>  Fabian
> 
Sounding a bit like a "no", looks like. Did you Google much?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Problem of function calls from map()

2006-08-23 Thread Steve Holden
Fredrik Lundh wrote:
> Sion Arrowsmith wrote:
> 
> 
>>>(you cannot really use "profile" to *benchmark* things written in Python 
>>>either; the
>>>profiler tells you where a given program spends the time, not how fast it is 
>>>in com-
>>>parision with other programs)
>>
>>Hmm. Playing around with timeit suggests that although split() *is*
>>faster than split("\t"), it's fractional, rather than the OP's four
>>times faster. Is the overhead of profile keeping track of calls in
>>Python getting in the way?
> 
> 
> correct.
> 
> 
>>And why can map() keep everything at the C level when the list com-
> 
>  > prehension can't?
> 
> map is called with two Python objects (the str.split callable and the 
> sequence object), while the list comprehension is turned into a byte-
> code loop that evaluates s.split for each item in the sequence; compare 
> and contrast:
> 
>  >>> def func(a):
>  return map(str.split, a)
> 
>  >>> dis.dis(func)
>2   0 LOAD_GLOBAL  0 (map)
>3 LOAD_GLOBAL  1 (str)
>6 LOAD_ATTR2 (split)
>9 LOAD_FAST0 (a)
>   12 CALL_FUNCTION2
>   15 RETURN_VALUE
> 
>  >>> def func(a):
>  return [s.split() for s in a]
> 
>  >>> dis.dis(func)
>2   0 BUILD_LIST   0
>3 DUP_TOP
>4 STORE_FAST   1 (_[1])
>7 LOAD_FAST0 (a)
>   10 GET_ITER
>  >>   11 FOR_ITER19 (to 33)
>   14 STORE_FAST   2 (s)
>   17 LOAD_FAST1 (_[1])
>   20 LOAD_FAST2 (s)
>   23 LOAD_ATTR0 (split)
>   26 CALL_FUNCTION0
>   29 LIST_APPEND
>   30 JUMP_ABSOLUTE   11
>  >>   33 DELETE_FAST  1 (_[1])
>   36 RETURN_VALUE
> 
> (LOAD_GLOBAL and LOAD_ATTR does full name lookups, while LOAD_FAST loads 
> a local variable using an integer index)
> 
> 
> 
Well I guess if people wanted to argue for keeping the functionals this 
should be on the list ...

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: smtplib needs me to put from/to headers in the message?

2006-08-23 Thread Ben Finney
tobiah <[EMAIL PROTECTED]> writes:

> In the example at:
>   http://docs.python.org/lib/SMTP-example.html
> 
> The text of the email message ends up with the From: and To: headers
> in it, and yet the call to sendmail() on the server object requires
> me to specify them again.

[Pet hate issue: Every RFC 2822 email message has exactly *one* body
and *one* header. The header contains multiple fields. Most library
terminology, including the 'smtplib' and 'email' modules, gets this
wrong.]

The smtplib does no processing or parsing of the message data,
correct. You should have the from and to addresses parameterised, use
the 'email' module to create the message and 'smtplib' to send it:

http://docs.python.org/lib/module-email.html>
http://docs.python.org/lib/node597.html>

-- 
 \  "Puritanism: The haunting fear that someone, somewhere, may be |
  `\  happy."  -- Henry L. Mencken |
_o__)  |
Ben Finney

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


Re: Accessing application data portably

2006-08-23 Thread Tom E H
Larry Bates wrote:
>> Well that's great, but how do you access the ini file portably?
> 
> From my original post:
> 
> Then I use ConfigParser in my application...

Thanks, but where in the directory structure do you put the ini file on
different platforms?  Presumably you have to hard-code that into the source
and then do operating system type detection?

i.e. if I make my config parser:

import ConfigParser
config = ConfigParser.ConfigParser()
config.read(filename)

What do you use for filename on Windows?  What on Linux?  OSX? etc.  How do
you detect which operating system you are running on?

Tom

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


Re: Dr. Dobb's Python-URL! - weekly Python news and links (Aug 23)

2006-08-23 Thread Georg Brandl
Jack Diederich wrote:
> QOTW:  "Because there's no chance that the original request is sane." - Georg
> Brandl (responding to a question involving a Banana)

Looks like I'm trying to fulfil my bot duties from time to time ;)

> "this is one of your last chances to test the new code in 2.5 before the final
> release. *Please* try this release out and let us know about any problems you
> find" - Anthony Baxter, Python Release Manager
> 
> 
> sum() is for numbers.  It doesn't work with strings for your protection.
> 
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/e782a88bf5b2f911/
>   
> Parsing valid email addresses is hard.
> 
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/dfb305247edd7c6c/
>   
> Q: How do I make my code python 3000 compatible?
> A: Wait for python 3000.
> 
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/8aee8423747c094d/
>   
> The C++ STL can't match python's speed in some applications.
> 
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/94fed9a76015a5e4/
>   
> David Wahler is no longer out of the office.
> http://groups.google.com/groups/search?q=David+Wahler+out+of+office

Thanks for pointing that out, Jack ;)

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


Re: setting a breakpoint in the module

2006-08-23 Thread David M. Cooke
"Jason Jiang" <[EMAIL PROTECTED]> writes:

> Hi,
>
> I have two modules: a.py and b.py. In a.py, I have a function called
> aFunc(). I'm calling aFunc() from b.py (of course I import module a first).
> The question is how to directly set a breakpoint in aFunc().
>
> The way I'm doing now is to set a breakpoint in b.py at the line to call
> aFunc(), 'c' to it, then 's' to step in, then set the breakpoint inside
> aFunc() by 'b lineNumber'. It's too cumbersome.

You can also add in your source

import pdb; pdb.set_trace()

at the point you want the debugger to stop. Useful if you want to
break after some failing condition, for instance.

-- 
|>|\/|<
/--\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca
-- 
http://mail.python.org/mailman/listinfo/python-list


smtplib needs me to put from/to headers in the message?

2006-08-23 Thread tobiah
In the example at:

http://docs.python.org/lib/SMTP-example.html

The text of the email message ends up with the From:
and To: headers in it, and yet the call to sendmail()
on the server object requires me to specify them again.

Shouldn't smptlib just make the headers for me, given
the 'from' and 'to' addresses?  Perhaps this allows
me to spoof the 'from' address.  Still, I might as well
just make all of the headers myself, and pass the message
as a single argument to sendmail().

Or perhaps I'm missing it altogether.

Thanks,

Tobiah

-- 
Posted via a free Usenet account from http://www.teranews.com

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


Re: Accessing application data portably

2006-08-23 Thread Larry Bates
Tom E H wrote:
> Larry Bates wrote:
>> Tom E H wrote:
>>> My Python application includes some data files that need to be accessed
>>> by modules I distribute with it.
>>>
>>> Where can I put them, and how should I arrange my code, so that it works
>>> across platforms?
>>>
>> I almost always send along an application.ini file and put the location
>> of where my data is to be stored in that file instead of imbedding (or
>> worse, hard-coding) it in the application program itself.
> 
>> Something like:
>>
>> [init]
>> debug=0
>> quiet=0
>> datafilepath=/usr/lib/myprogram/datafile
> 
> Well that's great, but how do you access the ini file portably?
> 
> Tom

>From my original post:

Then I use ConfigParser in my application...

for help on ConfigParser you can do:

import ConfigParser
help(ConfigParser)

-Larry Bates

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


Re: how to get file name of the running .py file

2006-08-23 Thread Larry Bates
Jason Jiang wrote:
> Hi,
> 
> How to get the name of the running .py file like the macro _FILE_ in C?
> 
> Thanks.
> Jason 
> 
> 
> 
import os
import sys
print sys.argv[0]

or if you just want the script and not the full path

print os.path.basename(sys.argv[0])

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


how to get file name of the running .py file

2006-08-23 Thread Jason Jiang
Hi,

How to get the name of the running .py file like the macro _FILE_ in C?

Thanks.
Jason 



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


Re: Class instantiation

2006-08-23 Thread Colin J. Williams
Fredrik Lundh wrote:
> Colin J. Williams wrote:
> 
>> In the example below, with the disassembly following that, we run into 
>> trouble with the line:
>> self.connect(fileID, mode= 'r')   # open sheet in the read mode
>>
>> the traceback is:
>> Traceback (most recent call last):
>>File "C:\Documents and Settings\cjw\My Documents\OODev\tArray.py", 
>> line 26, in __init__
>>  self.connect(fileID, mode= 'r')   # open sheet in the read mode
>> NameError: global name 'fileID' is not defined
>>
>> At line 26, location 31, why is LOAD_GLOBAL generated for fileId, when 
>> LOAD_FAST has done the job at locations 0 and 20?
> 
> hint: Python is case-sensitive.
> 
> 
> 
Thanks to those who responded.  Paul McNett sums it up - DOH!

Colin W.

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


Re: range of int() type.

2006-08-23 Thread Terry Reedy

"KraftDiner" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> So what type / class should one use to represent a 16 bit integers
> (signed or unsigned)?

For most purposes, Python just has integers, with 'small' ones (depending 
on the machine) handled more efficiently.  For special purposes, you may 
want to use the array or struct modules.

tjr



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


Re: Python and STL efficiency

2006-08-23 Thread Neil Cerutti
On 2006-08-23, Amanjit Gill <[EMAIL PROTECTED]> wrote:
> you should also include  for ostream_operator.

, actually.

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


Re: callable to disappear?

2006-08-23 Thread Terry Reedy

"faulkner" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> what's wrong with hasattr(obj, '__call__')?

I have the impression that this is not currently true for all callables . 
If not, this may be improved in the future.

>> Antoon Pardon
>> Is there a chance this will be reconsidered?

The items in PEP 3100 have different levels of certainly.  Some may even 
get changed after experience with the alpha versions.  Guido is allowing a 
year from first alpha (early 2007?) to final release, instead of the 
current 4-5 months.

There has been recent discussion since of iscallable and some other 
is()s.  The points you mentioned were raised and considered.  I don't 
remember if there was a decision for the present.

Two of the bigger negatives for 'iscallable':
1. You cannot know for sure until you call and get a return.
2. It does not say if the candidate is callable with any particular number 
or set of parameters.

Terry Jan Reedy



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


Re: in-memory-only file object from string

2006-08-23 Thread bobrik
> See the standard modules: StringIO and cStringIO
Thank you!

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


Re: Best way to construct an email - attach a html file and send

2006-08-23 Thread a
hey larry thanks
Larry Bates wrote:
> a wrote:
> > What is the best way to construct an email in python and also attach a
> > html file
> >
> > the html file to be attached is not on disk, but should be dynamically
> > constructed in the python script
> >
> > I want to attach the django debug error to an email and mail it to
> > myself whenever there is an error in the application
> >
> > thanks a lot
> > py
> >
> Here is a link to a class that will allow you to attach files.  You
> can either write the HTML to a tempfile and attach or modify a
> little to accept a string or cstringIO object instead.  Hope it
> helps.
> 
> -Larry Bates

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


Re: Translating Javascript programs to python.

2006-08-23 Thread Vyz
Its a module to transliterate from telugu language  written in roman
script into native unicode. right now its running in a browser window
at www.lekhini.org I Intend to translate it into python so that I can
integrate into other tools I have. I am able to pass arguments and get
output from the script also would be OK. or how about ways to wrap
these javascript functions with python.

Thanks
Vyz

supercoder wrote:
> Vyz wrote:
> > Hi,
> > I have a script with hundreds of lines of javascript spread accross 7
> > files. Is there any tool out there to automatically or
> > semi-automatically translate the code into python.
> >
> > Thanks
> > Vyz
>
> Not a tool, but assuming the javascript is not too complex you could
> interpret some of it using python and the CGI module.
> 
> But really, what would be the use?

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


Re: range of int() type.

2006-08-23 Thread Gabriel Genellina

At Wednesday 23/8/2006 18:53, KraftDiner wrote:


> |>> import sys
> |>> sys.maxint
> 2147483647
>

So what type / class should one use to represent a 16 bit integers
(signed or unsigned)?


Plain int.
If you need the overflow at 32K/64K, try: x & 0x



Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


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

Re: in-memory-only file object from string

2006-08-23 Thread Gabriel Genellina

At Wednesday 23/8/2006 18:56, bobrik wrote:


how to create a file object whose contents I initialize from a string
and which is purely in memory?


See the standard modules: StringIO and cStringIO



Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


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

RE: in-memory-only file object from string

2006-08-23 Thread Caolan
Title: in-memory-only file object from string






The mmap module should do 
what you are looking for. It allows you to store data in memory (hence the name 
memory map) and treat it as both a string and a file.


From: 
[EMAIL PROTECTED] on behalf of 
bobrikSent: Wed 8/23/2006 2:56 PMTo: 
python-list@python.orgSubject: in-memory-only file object from 
string

Hello,how to create a file object whose contents I 
initialize from a stringand which is purely in memory?I can make a 
workaround like this:filecontents = "Very interesting stuff ... 
"file = os.tmpfile ()file.write (filecontents)file.seek 
(0)procedure (fileobject = file)but this creates a file on harddisk. 
Instead I would like to usesomething like:filecontents = "Very 
interesting stuff ... "file = stringfile (filecontents)procedure 
(fileobject = file)Is this possible somehow? I appreciate any 
help.--http://mail.python.org/mailman/listinfo/python-list


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

Re: text editor suggestion?

2006-08-23 Thread Ravi Teja

John Salerno wrote:
> Ravi Teja wrote:
>
> > ???
> >
> > In the same file, near the top.
> >
> > keywordclass.python=and assert break class continue def del elif \
> > else except exec finally for from global if import in is lambda None \
> > not or pass print raise return try while yield
> >
> > I could add my own keywords to it.
> >
>
> But I don't want all my keywords to be highlighted in the same way. I
> have different colors for Python keywords, functions and methods,
> exceptions, other words like 'self', etc. and there's no way to do this
> without rewriting the lexer file (which is in C++) and recompiling Scite
> to build the changes into it.

I don't know if SciTE somehow supports function highlighting but the
properties file for php will perhaps give you some ideas on having
seperate groups with different highlight properties. I recall
repurposing something similar when I used to use Spyce for web apps.

http://mailman.lyra.org/pipermail/scite-interest/attachments/20050912/c9d5e51b/html-0001.obj

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


in-memory-only file object from string

2006-08-23 Thread bobrik
Hello,

how to create a file object whose contents I initialize from a string
and which is purely in memory?
I can make a workaround like this:

filecontents = "Very interesting stuff ... "
file = os.tmpfile ()
file.write (filecontents)
file.seek (0)
procedure (fileobject = file)

but this creates a file on harddisk. Instead I would like to use
something like:

filecontents = "Very interesting stuff ... "
file = stringfile (filecontents)
procedure (fileobject = file)

Is this possible somehow? I appreciate any help.

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


Re: range of int() type.

2006-08-23 Thread KraftDiner

Simon Forman wrote:
> KraftDiner wrote:
> > What is the range of a variable of type int()
> >
> > eg:
> > i = int()
> > print i.max()  # 0x
> > print i.min() # 0x
> >
> > is it a signed 16 bit or 32 bit or is it unsigned 16 or 32...
> > I've noticed that it can be incremented into a new class of type
> > long...
>
> |>> import sys
> |>> sys.maxint
> 2147483647
>

So what type / class should one use to represent a 16 bit integers
(signed or unsigned)?




> >From the sys module docs:
> maxint
> The largest positive integer supported by Python's regular integer
> type. This is at least 2**31-1. The largest negative integer is
> -maxint-1 -- the asymmetry results from the use of 2's complement
> binary arithmetic.
> 
> Peace,
> ~Simon
> 
> P.S. ints and longs are becoming unified soon.

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


Re: Problem with tokenize module and indents

2006-08-23 Thread Simon Forman
Tim wrote:
> I ran into a problem with a script i was playing with to check code
> indents and need some direction.  It seems to depend on if tabsize is
> set to 4 in editor and spaces and tabs indents are mixed on consecutive
> lines.  Works fine when editors tabsize was 8 regardless if indents are
> mixed.
>
> Below are how the 3 test files are laid out, the sample code and output
> I get.
> Any help on how to detect this correctly would be appreciated.
>
>
> # nano -T4 tabspacing_4.py
> class Test:
> """triple quote"""  #indent is 1 tab
> def __init__(self, msg):#indent is 4 spaces   <<
> this gets reported as a dedent when there is no change in indent level
> self.msg = msg#indent is 2 tabs
>
> #nano -T8 tabspacing_8A.py
> class Test:
> """triple quote"""  #indent is 1 tab
> def __init__(self, msg):#indent is 8 spaces<< no
> indent change reported
> self.msg = msg#indent is 1 tab + 4 spaces
>
> #nano -T8 tabspacing_8B.py
> class Test:
> """triple quote"""  #indent is 1 tab
> def __init__(self, msg):#indent is 1 tab  <<
> no indent change reported
> self.msg = msg#indent is 1 tab + 4 spaces
>
>
>
> My script
>
> #!/usr/bin/env python
>
> import tokenize
> from sys import argv
>
> indent_lvl = 0
> line_number = 0
> lines = file(argv[1]).readlines()
> done = False
>
> def parse():
>
> def feed():
>
> global line_number, lines
>
> if line_number < len(lines):
> txt = lines[line_number]
> line_number += 1
> else:
> txt = ''
>
> return txt
>
> def indents(type, token, start, end, line):
>
> global indent_lvl, done
>
> if type == tokenize.DEDENT:
> indent_lvl -= 1
> elif type == tokenize.INDENT:
> indent_lvl += 1
> elif type == tokenize.ENDMARKER:
> done = True
> return
> else:
> return
>
> print "token=%s, line_number=%i, indent_lvl=%i" %
> (tokenize.tok_name[type], start[0], indent_lvl), line.strip()
>
> while not done:
> tokenize.tokenize(feed, indents)
>
> parse()
>
>
> $ ./sample.py tabspacing_4.py
> token=INDENT, line_number=3, indent_lvl=1 """triple quote"""
> #indent is 1 tab
> token=DEDENT, line_number=4, indent_lvl=0 def __init__(self, msg):
> #indent is 4 spaces  <-- PROBLEM HERE
> token=INDENT, line_number=5, indent_lvl=1 self.msg = msg
> #indent is 2 tabs
> token=DEDENT, line_number=8, indent_lvl=0
>
> $ ./sample.py tabspacing_8A.py
> token=INDENT, line_number=3, indent_lvl=1 """triple quote"""
> #indent is 1 tab
> token=INDENT, line_number=5, indent_lvl=2 self.msg = msg
> #indent is 1 tab + 4 spaces
> token=DEDENT, line_number=8, indent_lvl=1
> token=DEDENT, line_number=8, indent_lvl=0
>
> $ ./sample.py tabspacing_8B.py
> token=INDENT, line_number=3, indent_lvl=1 """triple quote"""
> #indent is 1 tab
> token=INDENT, line_number=5, indent_lvl=2 self.msg = msg
> #indent is 1 tab + 4 spaces
> token=DEDENT, line_number=8, indent_lvl=1
> token=DEDENT, line_number=8, indent_lvl=0

Well, the simple answer is "Don't mix tabs and spaces."   But if that's
unhelpful  ;-) , check out the tabnanny script (now in the standard
library) and also the expandtabs() method of strings.

http://docs.python.org/lib/module-tabnanny.html

Peace,
~Simon

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


Re: What do you want in a new web framework?

2006-08-23 Thread Cliff Wells
On Wed, 2006-08-23 at 22:13 +0200, Peter Maas wrote:
> Alex Martelli wrote:
> > Indeed, it has been truthfully observed that Python's the only language
> > with more web frameworks than keywords.
> > 
> > I have already suggested to the BDFL that he can remedy this situation
> > in Py3k: all he has to do, of course, is to add a LOT more keywords.
> 
> Here is another remedy: he adds one of the frameworks to the standard
> library :)

That didn't help Tk maintain a monopoly on Python GUI toolkits.

Cliff

-- 

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


Re: What do you want in a new web framework?

2006-08-23 Thread Cliff Wells
On Wed, 2006-08-23 at 02:28 -0700, Paul Boddie wrote:
> Cliff Wells wrote:

> > No, the reason Rails is successful is due to being a decent, focused
> > product with *great* marketing (screencasts, anyone?).
> 
> Screencasts? Perhaps, like a great showman, they draw in the punters
> effectively enough, but I'd rather developers concentrate on writing
> decent documentation than stuffing the pipes of the Internet up with
> multi-megabyte proprietary blobs showing some individual developing
> "hello world" (and still having to practise slight-of-hand in order to
> make it "slick" enough).

Well, I think screencasts are pretty great for this type of thing.
Think about the primary complaint: "Which one do I choose?".  It can
take a while to wade through the various documentation (or lack of),
install, do some basic tests, etc and the whole process can be pretty
wearing on a newcomer.  A screencast on the other hand lets you lazily
sip coffee while you get a small feel for the framework.  I think it
also shows what someone who *knows* the framework can do (which can be
nearly impossible to know when you're testing it yourself).  The "20
minute wiki" screencast would be the "2 day trial and error" for someone
new to the framework. 

> 
> [...]
> 
> > Also the fact that Ruby doesn't suck isn't hurting Rails any either.  If
> > GvR wants to improve Python's status against Ruby, I suggest looking at
> > what people are *really* raving about in the Ruby world (despite how
> > they got there) and address those issues rather than getting sidetracked
> > with this nonsense.
> 
> First of all, I'd take the raving from the Ruby scene with a pinch of
> salt, given the tendency of the blog personalities doing the raving to
> breathlessly declare some kind of victory at every turn - as Steve
> Holden once said, these people are good at the "don't mention the
> weaknesses" style of marketing, and that's probably something various
> Python Web framework developers have picked up quite effectively. 

Oh sure.  And you have to also remind yourself that most of these guys
are coming from PHP where practically nothing sucks by comparison (and
there are *lots* of PHP people to convert).  

But there are interesting things in Ruby (and Ruby 2 should take care of
lots of warts Ruby 1.8 has) that Python could learn from.  All-in-all,
Ruby is mostly as good as Python in most ways and better than Python in
a couple key ways.  Add marketing to that (whatever kind it happens to
be) and you've got the recipe for success. 

When I suggest using Python to customers they tend to get nervous as if
it's some esoteric language that might disappear off the map next
weekend and is only known to 12 people.  I shouldn't need to reassure
people that it is what it is: one of the most popular languages in use
today.  That's the other kind of bad marketing that Python should avoid.

> I'd rather the Python core developers stopped chasing shadows and looked at
> the Python distribution in its entirety. Hopefully, the Python 3000
> exercise will see its focus shift into really removing the artifacts of
> legacy decisions in both the language and the library rather than
> shoehorning more wishlist items into the language.

My single wishlist item (which will probably never happen) is actually
the *removal* of a single "feature": the distinction between statements
and expressions.  Forget list comprehensions, ternary operators, etc.
You get them with no additional syntax in expression-based languages.  I
played with Logix a bit (but sadly the project appears dead) and the
expression-based Python syntax it provides gives me goose-bumps.

At this point in my life, inertia keeps me with Python (it's "good
enough" and I lack the time and energy to convert to another language),
but there's little doubt in my mind that this distinction will
eventually force me elsewhere *wipes away tear*.  


Regards,
Cliff

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


Re: setting a breakpoint in the module

2006-08-23 Thread Jason Jiang
Great! It's working now. Thank you so much.

Jason

"Simon Forman" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Jason Jiang wrote:
>> "Simon Forman" <[EMAIL PROTECTED]> wrote in message
>> news:[EMAIL PROTECTED]
>> > Jason Jiang wrote:
>> >> Hi,
>> >>
>> >> I have two modules: a.py and b.py. In a.py, I have a function called
>> >> aFunc(). I'm calling aFunc() from b.py (of course I import module a
>> >> first).
>> >> The question is how to directly set a breakpoint in aFunc().
>> >>
>> >> The way I'm doing now is to set a breakpoint in b.py at the line to 
>> >> call
>> >> aFunc(), 'c' to it, then 's' to step in, then set the breakpoint 
>> >> inside
>> >> aFunc() by 'b lineNumber'. It's too cumbersome.
>> >>
>> >> Thanks.
>> >> Jason
>> >
>> > What debugger are you using?
>>
>> I'm using Python pdb module pdb.py.
>>
>
> So, can't you just issue the command:
>
> (Pdb) b a.py:aFunc
>
> or
>
> (Pdb) b a.py:lineNumber
>
> where "lineNumber" is a line number in a.py within aFunc()?
>
>
> http://docs.python.org/lib/debugger-commands.html
>
> Peace,
> ~Simon
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 



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


Re: Accessing application data portably

2006-08-23 Thread Tom E H
Larry Bates wrote:
> Tom E H wrote:
>> My Python application includes some data files that need to be accessed
>> by modules I distribute with it.
>> 
>> Where can I put them, and how should I arrange my code, so that it works
>> across platforms?
>>
> I almost always send along an application.ini file and put the location
> of where my data is to be stored in that file instead of imbedding (or
> worse, hard-coding) it in the application program itself.

> Something like:
> 
> [init]
> debug=0
> quiet=0
> datafilepath=/usr/lib/myprogram/datafile

Well that's great, but how do you access the ini file portably?

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


Re: range of int() type.

2006-08-23 Thread Simon Forman
KraftDiner wrote:
> What is the range of a variable of type int()
>
> eg:
> i = int()
> print i.max()  # 0x
> print i.min() # 0x
>
> is it a signed 16 bit or 32 bit or is it unsigned 16 or 32...
> I've noticed that it can be incremented into a new class of type
> long...

|>> import sys
|>> sys.maxint
2147483647

>From the sys module docs:
maxint
The largest positive integer supported by Python's regular integer
type. This is at least 2**31-1. The largest negative integer is
-maxint-1 -- the asymmetry results from the use of 2's complement
binary arithmetic.

Peace,
~Simon

P.S. ints and longs are becoming unified soon.

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


Problem with tokenize module and indents

2006-08-23 Thread Tim
I ran into a problem with a script i was playing with to check code 
indents and need some direction.  It seems to depend on if tabsize is 
set to 4 in editor and spaces and tabs indents are mixed on consecutive 
lines.  Works fine when editors tabsize was 8 regardless if indents are 
mixed.

Below are how the 3 test files are laid out, the sample code and output 
I get. 
Any help on how to detect this correctly would be appreciated.


# nano -T4 tabspacing_4.py
class Test:
"""triple quote"""  #indent is 1 tab
def __init__(self, msg):#indent is 4 spaces   << 
this gets reported as a dedent when there is no change in indent level
self.msg = msg#indent is 2 tabs

#nano -T8 tabspacing_8A.py
class Test:
"""triple quote"""  #indent is 1 tab
def __init__(self, msg):#indent is 8 spaces<< no 
indent change reported
self.msg = msg#indent is 1 tab + 4 spaces

#nano -T8 tabspacing_8B.py
class Test:
"""triple quote"""  #indent is 1 tab
def __init__(self, msg):#indent is 1 tab  << 
no indent change reported
self.msg = msg#indent is 1 tab + 4 spaces



My script

#!/usr/bin/env python

import tokenize
from sys import argv

indent_lvl = 0
line_number = 0
lines = file(argv[1]).readlines()
done = False

def parse():

def feed():

global line_number, lines

if line_number < len(lines):
txt = lines[line_number]
line_number += 1
else:
txt = ''

return txt

def indents(type, token, start, end, line):

global indent_lvl, done

if type == tokenize.DEDENT:
indent_lvl -= 1
elif type == tokenize.INDENT:
indent_lvl += 1
elif type == tokenize.ENDMARKER:
done = True
return
else:
return

print "token=%s, line_number=%i, indent_lvl=%i" % 
(tokenize.tok_name[type], start[0], indent_lvl), line.strip()

while not done:
tokenize.tokenize(feed, indents)

parse()


$ ./sample.py tabspacing_4.py  
token=INDENT, line_number=3, indent_lvl=1 """triple quote"""  
#indent is 1 tab
token=DEDENT, line_number=4, indent_lvl=0 def __init__(self, msg):
#indent is 4 spaces  <-- PROBLEM HERE
token=INDENT, line_number=5, indent_lvl=1 self.msg = msg  
#indent is 2 tabs
token=DEDENT, line_number=8, indent_lvl=0

$ ./sample.py tabspacing_8A.py 
token=INDENT, line_number=3, indent_lvl=1 """triple quote"""  
#indent is 1 tab
token=INDENT, line_number=5, indent_lvl=2 self.msg = msg  
#indent is 1 tab + 4 spaces
token=DEDENT, line_number=8, indent_lvl=1
token=DEDENT, line_number=8, indent_lvl=0

$ ./sample.py tabspacing_8B.py 
token=INDENT, line_number=3, indent_lvl=1 """triple quote"""  
#indent is 1 tab
token=INDENT, line_number=5, indent_lvl=2 self.msg = msg  
#indent is 1 tab + 4 spaces
token=DEDENT, line_number=8, indent_lvl=1
token=DEDENT, line_number=8, indent_lvl=0



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


Re: setting a breakpoint in the module

2006-08-23 Thread Simon Forman
Jason Jiang wrote:
> "Simon Forman" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > Jason Jiang wrote:
> >> Hi,
> >>
> >> I have two modules: a.py and b.py. In a.py, I have a function called
> >> aFunc(). I'm calling aFunc() from b.py (of course I import module a
> >> first).
> >> The question is how to directly set a breakpoint in aFunc().
> >>
> >> The way I'm doing now is to set a breakpoint in b.py at the line to call
> >> aFunc(), 'c' to it, then 's' to step in, then set the breakpoint inside
> >> aFunc() by 'b lineNumber'. It's too cumbersome.
> >>
> >> Thanks.
> >> Jason
> >
> > What debugger are you using?
>
> I'm using Python pdb module pdb.py.
>

So, can't you just issue the command:

(Pdb) b a.py:aFunc

or

(Pdb) b a.py:lineNumber

where "lineNumber" is a line number in a.py within aFunc()?


http://docs.python.org/lib/debugger-commands.html

Peace,
~Simon

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


range of int() type.

2006-08-23 Thread KraftDiner
What is the range of a variable of type int()

eg:
i = int()
print i.max()  # 0x
print i.min() # 0x

is it a signed 16 bit or 32 bit or is it unsigned 16 or 32...
I've noticed that it can be incremented into a new class of type
long...

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


Re: Python and STL efficiency

2006-08-23 Thread Mc Osten
Ray <[EMAIL PROTECTED]> wrote:

> Great to know that my model of how the world works is still correct!
> (at least in relation to Python and C++!) :)

So please explain my results. I loop the same number of times.

-- 
blog:  http://www.akropolix.net/rik0/blogs | Uccidete i filosofi,
site:  http://www.akropolix.net/rik0/  | tenetevi riso e
forum: http://www.akropolix.net/forum/ | bacchette per voi.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and STL efficiency

2006-08-23 Thread Mc Osten
Tim N. van der Leeuw <[EMAIL PROTECTED]> wrote:

> I have to admit to a stupid mistake, for which I feel quite ashamed - I
> got the loop-size wrong in the Python code. So all Python results
> posted by me were off by a factor of 10 :-(
> I feel quite bad about that!

Well, this makes *my* results quite surprising.
I checked it threetimes. I loop 100 times in both Python and C++,
and Python here is faster.

-- 
blog:  http://www.akropolix.net/rik0/blogs | Uccidete i filosofi,
site:  http://www.akropolix.net/rik0/  | tenetevi riso e
forum: http://www.akropolix.net/forum/ | bacchette per voi.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum and strings

2006-08-23 Thread Tim Chase
> Maybe he's just insisting on the principle of least surprise?
> Personally, I'd rather expect sum() to work for strings and Python to
> issue a warning instead of raising a type error. That warning might
> also be appropriate when using sum() on other builtin sequence types.

In its own way, it makes good sense to not be surprising:

 >>> # using regular number
 >>> n1 = 1
 >>> n2 = 2
 >>> sum([n1,n2])
3

 >>> # using complex numbers
 >>> c1 = 1+2j
 >>> c2 = 5+11j
 >>> sum([c1,c2])
(6+13j)

 >>> # using quaternion-ish objects
 >>> class Q(object):
... def __init__(self, n, i,j,k):
... self.n = n
... self.i = i
... self.j = j
... self.k = k
... def __add__(self, other):
... return Q(self.n+other.n,
... self.i+other.i,
... self.j+other.j,
... self.k+other.k)
...
 >>> q1 = Q(1,2,3,5)
 >>> q2 = Q(7,11,13,17)
 >>> q3 = q1 + q2
 >>> q3.n, q3.i, q3.j, q3.k
(8, 13, 16, 22)
 >>> sum([q1,q2])
Traceback (most recent call last):
   File "", line 1, in ?
TypeError: unsupported operand type(s) for +: 'int' and 'q'


Just because something is slow or sub-optimal doesn't mean it 
should be an error.  Otherwise calls to time.sleep() should throw 
an error...

 >>> time.sleep(1000)
Traceback (most recent call last):
   File "", line 1, in ?
InefficentError: call takes more than 1 second to complete


[scratches head]

+1 regarding principle of least surprise on sum()

-tkc



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


Re: Python and STL efficiency

2006-08-23 Thread Amanjit Gill
> Hi, I'm learning STL and I wrote some simple code to compare the
> efficiency of python and STL.

Hi, you are benching heap allocations and of course heap fragmentation.
this is what devpartner c++ profiler had to say:

Method   %in % with Called Average Real Name Method Children
-
RtlFreeHeap 52,8 52,8 81.034 7,6 7,7
RtlAllocateHeap 19,8 19,8 81.089 2,9 2,9
main 16,9 89,7 1 198083,2 1052376,0
ExitProcess 10,3 10,3 1 120616,8 120641,3
 ...

So on linux its a lot better than that, because - I think - ptmalloc is
used which is based on dmalloc which is efficient for those small size
allocs (which malloc() and free() were never designed for).

on win32, activate the low fragmenting heap or write a custom stl
allocator.

 _set_sbh_threshold(128);   // method 1

  ULONG HeapFragValue = 2;
  HeapSetInformation((HANDLE)_get_heap_handle(),  // method 2
 HeapCompatibilityInformation,
 &HeapFragValue,
 sizeof(HeapFragValue));

last non-python message from me :)

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


Re: Best way to construct an email - attach a html file and send

2006-08-23 Thread Larry Bates
a wrote:
> where is the link
> thanks a lot for your kind help
> Larry Bates wrote:
>> a wrote:
>>> What is the best way to construct an email in python and also attach a
>>> html file
>>>
>>> the html file to be attached is not on disk, but should be dynamically
>>> constructed in the python script
>>>
>>> I want to attach the django debug error to an email and mail it to
>>> myself whenever there is an error in the application
>>>
>>> thanks a lot
>>> py
>>>
>> Here is a link to a class that will allow you to attach files.  You
>> can either write the HTML to a tempfile and attach or modify a
>> little to accept a string or cstringIO object instead.  Hope it
>> helps.
>>
>> -Larry Bates
> 
Sorry, Left off the link:

http://motion.sourceforge.net/related/send_jpg.py
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: setting a breakpoint in the module

2006-08-23 Thread Jason Jiang
I'm using Python pdb module pdb.py.

"Simon Forman" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Jason Jiang wrote:
>> Hi,
>>
>> I have two modules: a.py and b.py. In a.py, I have a function called
>> aFunc(). I'm calling aFunc() from b.py (of course I import module a 
>> first).
>> The question is how to directly set a breakpoint in aFunc().
>>
>> The way I'm doing now is to set a breakpoint in b.py at the line to call
>> aFunc(), 'c' to it, then 's' to step in, then set the breakpoint inside
>> aFunc() by 'b lineNumber'. It's too cumbersome.
>>
>> Thanks.
>> Jason
>
> What debugger are you using?
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 



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


Re: CONSTRUCT - Module Attributes and Execution Environment

2006-08-23 Thread Larry Bates
Georg Brandl wrote:
> Larry Bates wrote:
>> lazaridis_com wrote:
>>> I would like to change the construct:
>>>
>>> if __name__ == '__main__':
>>>
>>> to something like:
>>>
>>> if exec.isMain():
>>>
>>> My (OO thought) is to place a class in an separate code module and to
>>> instantiate an singleton instance which would keep th something like
>>> this:
>>>
>>> class ExecutionEnv:
>>> def isMain(self)
>>> if CALLING_MODULE.__name__ == '__main__':
>>> return true
>>> else
>>> return false
>>>
>>> exec = ExecutionEnv()
>>>
>>> How to I get access to the CALLING_MODULE ?
>>>
>>> -
>>>
>>> Are ther alternative constructs/mechanism available, which could be
>>> used to add this functionality possiby directly to a code-module?
>>>
>> Two thoughts:
>>
>> 1) Don't call a class instance exec, it will mask the built-in
>> exec statement.
> 
> He won't be able to ;)
> 
> Georg

You are correct exec is a reserved word and can't be used as a
variable name.  Thanks for pointing that out.

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


Re: setting a breakpoint in the module

2006-08-23 Thread Simon Forman
Jason Jiang wrote:
> Hi,
>
> I have two modules: a.py and b.py. In a.py, I have a function called
> aFunc(). I'm calling aFunc() from b.py (of course I import module a first).
> The question is how to directly set a breakpoint in aFunc().
>
> The way I'm doing now is to set a breakpoint in b.py at the line to call
> aFunc(), 'c' to it, then 's' to step in, then set the breakpoint inside
> aFunc() by 'b lineNumber'. It's too cumbersome.
> 
> Thanks.
> Jason

What debugger are you using?

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


Re: Accessing application data portably

2006-08-23 Thread Larry Bates
Tom E H wrote:
> My Python application includes some data files that need to be accessed by
> modules I distribute with it.
> 
> Where can I put them, and how should I arrange my code, so that it works
> across platforms?
> 
> On Linux, I could install the data to "/usr/lib/myprogram/datafile", and
> on Windows to "datafile" relative to where the executable (made by
> py2exe) is installed.  Then I could detect the operating system, and choose
> appropriately.
> 
> To be that explicit seems undesirable.  Any cleverer ideas?
> 
> Tom
> 
> (Please CC me on replies: I'm not subscribed.  The From address is munged)
> 
I almost always send along an application.ini file and put the location
of where my data is to be stored in that file instead of imbedding (or
worse, hard-coding) it in the application program itself.  I also put
other parameters that the user might want to change that will change
the behavior of my program (debugging, logging, etc.) there also.  Then
during installation I modify the option in this file with the install
script.

Something like:

[init]
debug=0
quiet=0
datafilepath=/usr/lib/myprogram/datafile

or

[init]
debug=0
quiet=0
datafilepath=C:\Program Files\myprogram\datafile

Then I use ConfigParser in my application to read this file and
extract the parameters.  Makes it easy for more experienced users
(and me) to be able to easily relocate the datafile if they
desire.

On Windows I use Inno Installer and it can modify these options inside the
.ini file during the installation so that datafilepath points to where
my data actually will live.  Works perfectly for me.

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


Re: Regex help...pretty please?

2006-08-23 Thread Simon Forman
MooMaster wrote:
> I'm trying to develop a little script that does some string
> manipulation. I have some few hundred strings that currently look like
> this:
>
> cond(a,b,c)
>
> and I want them to look like this:
>
> cond(c,a,b)
>
> but it gets a little more complicated because the conds themselves may
> have conds within, like the following:
>
> cond(0,cond(c,cond(e,cond(g,h,(a
> What I want to do in this case is move the last parameter to the front
> and then work backwards all the way out (if you're thinking recursion
> too, I'm vindicated) so that it ends up looking like this:
>
> cond((a<1), 0, cond((a
> futhermore, the conds may be multiplied by an expression, such as the
> following:
>
> cond(-1,1,f)*((float(e)*(2**4))+(float(d)*8)+(float(c)*4)+(float(b)*2)+float(a))
>
> Here, all I want to do is switch the parameters of the conds without
> touching the expression, like so:
>
> cond(f,-1,1)*((float(e)*(2**4))+(float(d)*8)+(float(c)*4)+(float(b)*2)+float(a))
>
> So that's the gist of my problem statement. I immediately thought that
> regular expressions would provide an elegant solution. I would go
> through the string by conds, stripping them & the () off, until I got
> to the lowest level, then move the parameters and work backwards. That
> thought process became this:
> -CODE
> import re
>
> def swap(left, middle, right):
> left = left.replace("(", "")
> right = right.replace(")", "")
> temp = left
> left = right
> right = temp
> temp = middle
> middle = right
> right = temp
> whole = 'cond(' + left + ',' + middle + ',' + right + ')'
> return whole
>
> def condReplacer(string):
>  #regex = re.compile(r'cond\(.*,.*,.+\)')
>  regex = re.compile(r'cond\(.*,.*,.+?\)')
>  if not regex.search(string):
>   print "whole string is: " + string
>   [left, middle, right] = string.split(',')
>   right = right.replace('\'', ' ')
>   string = swap(left.strip(), middle.strip(), right.strip())
>   print "the new string is:" + string
>   return string
>  else:
>   more_conds = regex.search(string)
>   temp_string = more_conds.group()
>   firstParen = temp_string.find('(')
>   temp_string = temp_string[firstParen:]
>   print "there are more conditionals!" + temp_string
>   condReplacer(temp_string)
> def lineReader(file):
>  for line in file:
>  regex = r'cond\(.*,.*,.+\)?'
>  if re.search(regex,line,re.DOTALL):
> condReplacer(line)
>
> if __name__ == "__main__":
>input_file = open("only_conds2.txt", 'r')
>lineReader(input_file)
> -CODE
>
> I think my problem lies in my regular expression... If I use the one
> commented out I do a greedy search and in my test case where I have a
> conditional * an expression, I grab the expression too, like so:
>
> INPUT:
>
> cond(-1,1,f)*((float(e)*(2**4))+(float(d)*8)+(float(c)*4)+(float(b)*2)+float(a))
> OUTPUT:
> whole string is:
> (-1,1,f)*((float(e)*(2**4))+(float(d)*8)+(float(c)*4)+(float(b)*2)+float
> (a))
> the new string
> is:cond(f*((float(e*(2**4+(float(d*8+(float(c*4+(float(b*2+float
> (a,-1,1)
>
> when all I really want to do is grab the part associated with the cond.
> But if I do a non-greedy search I avoid that problem but stop too early
> when I have an expression like this:
>
> INPUT:
> cond(a,b,(abs(c) >= d))
> OUTPUT:
> whole string is: (a,b,(abs(c)
> the new string is:cond((abs(c,a,b)
>
> Can anyone help me with the regular expression? Is this even the best
> approach to take? Anyone have any thoughts?
>
> Thanks for your time!

You're gonna want a parser for this.  pyparsing or spark would suffice.
 However, since it looks like your source strings are valid python you
could get some traction out of the tokenize standard library module:

from tokenize import generate_tokens
from StringIO import StringIO

s =
'cond(-1,1,f)*((float(e)*(2**4))+(float(d)*8)+(float(c)*4)+(float(b)*2)+float(a))'

for t in generate_tokens(StringIO(s).readline):
print t[1],


Prints:
cond ( - 1 , 1 , f ) * ( ( float ( e ) * ( 2 ** 4 ) ) + ( float ( d ) *
8 ) + ( float ( c ) * 4 ) + ( float ( b ) * 2 ) + float ( a ) )

Once you've got that far the rest should be easy.  :)

Peace,
~Simon

http://pyparsing.wikispaces.com/
http://pages.cpsc.ucalgary.ca/~aycock/spark/
http://docs.python.org/lib/module-tokenize.html

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


Re: Python and STL efficiency

2006-08-23 Thread Amanjit Gill

> I was using VC++.net and IDLE, respectively. I had expected C++ to be
> way faster. However, while the python code gave the result almost

- This code runs amortized 100ms on my machien (vc.net 2003 pro,
dinkumware stl, p4m 2.2GHz thinkpad, windows 2003 server), (10 loops in
1000ms)
- with STLPort 5.2, this code runs in 39-43ms (10 loops in 390ms ->
430ms).

a. did you compile in release mode? and if yes, vc.net _standard_
edition has no optimizing compiler in release mode, you need vc.net pro
or enterprise. or did you use  vc.net 2005 ?

you should also include  for ostream_operator.

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


Re: How to download a web page just like a web browser do ?

2006-08-23 Thread Andre Meyer
You get websucker.py in the standard Python installation. On Win look at C:\Python24\Tools\webchecker or similar.regardsAndre
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: sum and strings

2006-08-23 Thread neophyte
Fredrik Lundh wrote:
> do you often write programs that "sums" various kinds of data types, and
> for which performance issues are irrelevant?
>
> or are you just stuck in a "I have this idea" loop?

Maybe he's just insisting on the principle of least surprise?
Personally, I'd rather expect sum() to work for strings and Python to
issue a warning instead of raising a type error. That warning might
also be appropriate when using sum() on other builtin sequence types.

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


Re: Help don't know what problem is Newbie

2006-08-23 Thread Peter Otten
len wrote:


> Have the following code:

Short variable names increase the likelihood of name clashes:

> c = db.cursor()

> c = ''

> c = csz[0]

> c = csz[0] + ' ' + csz[1]
> c.execute("insert into Producer \
> (Producer_Sid, Producerno, Company, Street, Suitepo, City,
> State, Zip, \
> Phone, Taxid, Fax) \
> values (" + orec + ")")

Peter

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


Re: What do you want in a new web framework?

2006-08-23 Thread Peter Maas
Alex Martelli wrote:
> Indeed, it has been truthfully observed that Python's the only language
> with more web frameworks than keywords.
> 
> I have already suggested to the BDFL that he can remedy this situation
> in Py3k: all he has to do, of course, is to add a LOT more keywords.

Here is another remedy: he adds one of the frameworks to the standard
library :)

Peter Maas, Aachen
-- 
http://mail.python.org/mailman/listinfo/python-list


Help don't know what problem is Newbie

2006-08-23 Thread len
Have the following code:

import os
import csv
import re
import mx.ODBC
import mx.ODBC.Windows

currdir = os.getcwd()
db = mx.ODBC.Windows.DriverConnect('dsn=UICPS Test')
c = db.cursor()
sid = 315

matchstr = re.compile(r'\(*\)*-*,*')
reader = csv.reader(open(currdir + r'\\IBI Brokers List 8-21-06.csv'))

for rec in reader:
if rec[0] != '' or rec[1] != '':
if rec[0] == 'Name:':
orec = ''
orec = orec + rec[12] + ',' + rec[2]
elif rec[1] == 'Address1':
orec = orec + ',' + rec[4]
elif rec[1] == 'Address2':
orec = orec + ',' + rec[4]
elif rec[1] == 'City, State, ZIP':
csz = matchstr.sub('', rec[4]).split()
if len(csz) == 0:
c = ''
s = ''
z = ''
elif len(csz) == 3:
c = csz[0]
s = csz[1]
z = csz[2]
elif len(csz) == 4:
c = csz[0] + ' ' + csz[1]
s = csz[2]
z = csz[3]
orec = orec + ',' + c + ',' + s + ',' + z + ',' +
matchstr.sub('', rec[13])
elif rec[1] == 'Tax ID':
orec = orec + ',' + rec[4].replace('-', '') + ',' +
matchstr.sub('', rec[12])
sid += 1
orec = str(sid) + ',' + orec
print orec
c.execute("insert into Producer \
(Producer_Sid, Producerno, Company, Street, Suitepo, City,
State, Zip, \
Phone, Taxid, Fax) \
values (" + orec + ")")

Below is a listing of the orec which I printed along with the python
error:

[DEBUG ON]
>>>
316,001,#001 Insurance Brokers of Indiana,400 Camby Court,P O Box
190,Greenwood,IN,46142,3178882593 ,351539405,3178857011

Traceback (most recent call last):
  File "C:\UICPS\IBIagent.py", line 44, in -toplevel-
c.execute("insert into Producer \
AttributeError: 'str' object has no attribute 'execute'

Thanks
Len Sumnler

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


Re: Dr. Dobb's Python-URL! - weekly Python news and links (Aug 23)

2006-08-23 Thread John Salerno
Jack Diederich wrote:

> David Wahler is no longer out of the office.
> http://groups.google.com/groups/search?q=David+Wahler+out+of+office

LOL. That's the best part this week! :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python-like C++ library

2006-08-23 Thread Simon Forman
Will McGugan wrote:
> Hi folks,
>
> I'm forced to use C++ and STL at work, and consequently miss the ease
> of use of Python. I was wondering if there was a C++ library that
> implemented the fundamental objects of Python as close as possible,
> perhaps using STL underneath the hood.
>
> Too clarify, Im not looking to interface C++ with Python in any way,
> just to emulate the strings / containers / slicing etc. I did google
> for it but my search terms were too vague...
>
> Thanks in advance,
>
> Will McGugan
> --
> http://www.willmcgugan.com

Forgive me if this is stupid, but python's written in C..  couldn't you
use python itself or parts of it as a library?

I know you said you're not "looking to interface C++ with Python in any
way", but why emulate if you could include?  (Again, if this is stupid,
sorry! :) )

Peace,
~Simon

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


setting a breakpoint in the module

2006-08-23 Thread Jason Jiang
Hi,

I have two modules: a.py and b.py. In a.py, I have a function called
aFunc(). I'm calling aFunc() from b.py (of course I import module a first).
The question is how to directly set a breakpoint in aFunc().

The way I'm doing now is to set a breakpoint in b.py at the line to call
aFunc(), 'c' to it, then 's' to step in, then set the breakpoint inside
aFunc() by 'b lineNumber'. It's too cumbersome.

Thanks.
Jason 



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


Re: Class instantiation

2006-08-23 Thread Fredrik Lundh
Colin J. Williams wrote:

> In the example below, with the disassembly following that, we run into 
> trouble with the line:
> self.connect(fileID, mode= 'r')   # open sheet in the read mode
> 
> the traceback is:
> Traceback (most recent call last):
>File "C:\Documents and Settings\cjw\My Documents\OODev\tArray.py", 
> line 26, in __init__
>  self.connect(fileID, mode= 'r')   # open sheet in the read mode
> NameError: global name 'fileID' is not defined
> 
> At line 26, location 31, why is LOAD_GLOBAL generated for fileId, when 
> LOAD_FAST has done the job at locations 0 and 20?

hint: Python is case-sensitive.



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


Re: Class instantiation

2006-08-23 Thread Paul McNett
Colin J. Williams wrote:
> class arSpread(object):
>def __init__(self, fileId= None, ar= None):
>  if fileId:
>if ar is not None:
>  print fileId
>  self.connect(fileID, mode= 'r')   # open sheet in the read mode
>else:
>  self.connect(fileID, mode= 'w')   # open the sheet in the 

'dOH! . Change to self.connect(fileId, ...)

:)


-- 
Paul McNett
http://paulmcnett.com
http://dabodev.com

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


Re: Class instantiation

2006-08-23 Thread Gabriel Genellina

At Wednesday 23/8/2006 16:21, Colin J. Williams wrote:


In the example below, with the disassembly following that, we run into
trouble with the line:
NameError: global name 'fileID' is not defined

At line 26, location 31, why is LOAD_GLOBAL generated for fileId, when
LOAD_FAST has done the job at locations 0 and 20?


Don't blame the code generator... fileId != fileID



Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


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

Re: running windows 'start' cmd using spawnl

2006-08-23 Thread Michel Claveau
Hi!

You can use (exemple) :

 "cmd /cSTART notepad"

-- 
@-salutations

Michel Claveau


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


setting a breakpoint in the function of my module

2006-08-23 Thread Jason Jiang
Hi,

I have two modules: a.py and b.py. In a.py, I have a function called 
aFunc(). I'm calling aFunc() from b.py (of course I import module a first). 
The question is how to directly set a breakpoint in aFunc().

The way I'm doing now is to set a breakpoint in b.py at the line to call 
aFunc(), 'c' to it, then 's' to step in, then set the breakpoint inside 
aFunc() by 'b lineNumber'. It's too cumbersome.

Thanks.
Jason 



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


Re: swapping numeric items in a list

2006-08-23 Thread Jiang Nutao
Thanks. But the thing I need to swap is [0x12, 0x34, 0x56, 0x78], not 
[0x1234, 0x5678].

- Original Message - 
From: "Gabriel Genellina" <[EMAIL PROTECTED]>
To: "Jiang Nutao" <[EMAIL PROTECTED]>
Cc: "Gabriel Genellina" <[EMAIL PROTECTED]>; 
Sent: Wednesday, August 23, 2006 12:19 PM
Subject: Re: swapping numeric items in a list


> At Wednesday 23/8/2006 15:32, Jiang Nutao wrote:
>
>>This is what I got in the debugger:
>>
>>(Pdb) aa=array('b', [126, 55, 71, 112])
>>(Pdb) aa
>>array('b', [126, 55, 71, 112])
>>(Pdb) aa.byteswap()
>>(Pdb) aa
>>array('b', [126, 55, 71, 112])
>
> Oh, sorry, to swap by two bytes "H" was the right typecode. But your input 
> array should be:
 aa = array('H', [0x1234, 0x5678])
> which should give:
> array('H', [0x3412, 0x7856])
>
>
>
> Gabriel Genellina
> Softlab SRL
>
>
>
>
> __
> Preguntá. Respondé. Descubrí.
> Todo lo que querías saber, y lo que ni imaginabas,
> está en Yahoo! Respuestas (Beta).
> ¡Probalo ya! http://www.yahoo.com.ar/respuestas
>
> 

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


Class instantiation

2006-08-23 Thread Colin J. Williams
In the example below, with the disassembly following that, we run into 
trouble with the line:
self.connect(fileID, mode= 'r')   # open sheet in the read mode

the traceback is:
Traceback (most recent call last):
   File "C:\Documents and Settings\cjw\My Documents\OODev\tArray.py", 
line 26, in __init__
 self.connect(fileID, mode= 'r')   # open sheet in the read mode
NameError: global name 'fileID' is not defined

At line 26, location 31, why is LOAD_GLOBAL generated for fileId, when 
LOAD_FAST has done the job at locations 0 and 20?

I would appreciate advice.

Colin W.

class arSpread(object):
   def __init__(self, fileId= None, ar= None):
 if fileId:
   if ar is not None:
 print fileId
 self.connect(fileID, mode= 'r')   # open sheet in the read mode
   else:
 self.connect(fileID, mode= 'w')   # open the sheet in the 
write mode
 if ar is not None:
   self.setArray(ar)



[Dbg]>>> dis.disassemble(arSpread.__init__.im_func.func_code)
  23   0 LOAD_FAST1 (fileId)
   3 JUMP_IF_FALSE   64 (to 70)
   6 POP_TOP

  24   7 LOAD_FAST2 (ar)
  10 LOAD_GLOBAL  2 (None)
  13 COMPARE_OP   9 (is not)
  16 JUMP_IF_FALSE   28 (to 47)
  19 POP_TOP

  25  20 LOAD_FAST1 (fileId)
  23 PRINT_ITEM
  24 PRINT_NEWLINE

  26  25 LOAD_FAST0 (self)
  28 LOAD_ATTR4 (connect)
  31 LOAD_GLOBAL  5 (fileID)
  34 LOAD_CONST   1 ('mode')
  37 LOAD_CONST   2 ('r')
  40 CALL_FUNCTION  257
  43 POP_TOP
  44 JUMP_ABSOLUTE   71
 >>   47 POP_TOP

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


Re: swapping numeric items in a list

2006-08-23 Thread Gabriel Genellina

At Wednesday 23/8/2006 15:32, Jiang Nutao wrote:


This is what I got in the debugger:

(Pdb) aa=array('b', [126, 55, 71, 112])
(Pdb) aa
array('b', [126, 55, 71, 112])
(Pdb) aa.byteswap()
(Pdb) aa
array('b', [126, 55, 71, 112])


Oh, sorry, to swap by two bytes "H" was the right typecode. But your 
input array should be:

aa = array('H', [0x1234, 0x5678])

which should give:
array('H', [0x3412, 0x7856])



Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


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

Re: Regex help...pretty please?

2006-08-23 Thread Tim Chase
> cond(a,b,c)
> 
> and I want them to look like this:
> 
> cond(c,a,b)
> 
> but it gets a little more complicated because the conds themselves may
> have conds within, like the following:
> 
> cond(0,cond(c,cond(e,cond(g,h,(ahttp://mail.python.org/mailman/listinfo/python-list


Re: swapping numeric items in a list

2006-08-23 Thread Fredrik Lundh
Jiang Nutao wrote:

> array.byteswap() won't work for me easily. I tried this before my 1st post. 
> I defined
> 
> aa = array('H', [0x12, 0x34, 0x56, 0x78])
> 
> Then did byteswap aa.byteswap(). The result was
> 
> array('H', [0x1200, 0x3400, 0x5600, 0x7800])
> 
> You can see it byteswapped within each item.

you need to do things in the right order; first convert to bytes, then 
build a 16-bit array, and then byteswap that array.

from array import array

# convert data array to 8-bit byte buffer
buf = array("B", [0x12, 0x34, 0x56, 0x78]).tostring()

# treat byte buffer as list of 16-bit integers
buf = array("H", buf)
buf.byteswap()

buf = buf.tostring() # convert back to bytes

[hex(ord(c)) for c in buf]
-> ['0x34', '0x12', '0x78', '0x56']



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


Re: Python + Java Integration

2006-08-23 Thread Fredrik Lundh
Ben Sizer wrote:

> Java itself never deserved to be the 'next' anything anyway.

I've had a lot of developers come up to me and
say, "I haven't had this much fun in a long time.
It sure beats writing Cobol" -- James Gosling



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


Dr. Dobb's Python-URL! - weekly Python news and links (Aug 23)

2006-08-23 Thread Jack Diederich
QOTW:  "Because there's no chance that the original request is sane." - Georg
Brandl (responding to a question involving a Banana)

"this is one of your last chances to test the new code in 2.5 before the final
release. *Please* try this release out and let us know about any problems you
find" - Anthony Baxter, Python Release Manager


sum() is for numbers.  It doesn't work with strings for your protection.

http://groups.google.com/group/comp.lang.python/browse_thread/thread/e782a88bf5b2f911/
  
Parsing valid email addresses is hard.

http://groups.google.com/group/comp.lang.python/browse_thread/thread/dfb305247edd7c6c/
  
Q: How do I make my code python 3000 compatible?
A: Wait for python 3000.

http://groups.google.com/group/comp.lang.python/browse_thread/thread/8aee8423747c094d/
  
The C++ STL can't match python's speed in some applications.

http://groups.google.com/group/comp.lang.python/browse_thread/thread/94fed9a76015a5e4/
  
David Wahler is no longer out of the office.
http://groups.google.com/groups/search?q=David+Wahler+out+of+office
  
  Releases of Note
Python 2.5 Release Candidate 1
See 
http://www.python.org/2.5/
  
byteplay - a python bytecode assembler/disassembler
http://wiki.python.org/moin/ByteplayDoc
  
ratfun-2.3 Polynomials and Ration Function library
http://calcrpnpy.sourceforge.net/ratfun.html
  
PyYAML-3.04 YAML parser and emitter for Python
http://pyyaml.org/wiki/PyYAML
  
  Upcoming Community Events
Plone Conference 2006, October 25-27 (Seattle, Washington)
http://plone.org/events/conferences/seattle-2006
  
Open Source Developers Conference Dec 5-8 (Melbourne, Australia)
http://www.osdc.com.au/
  


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.

For far, FAR more Python reading than any one mind should
absorb, much of it quite interesting, several pages index
much of the universe of Pybloggers.
http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog
http://www.planetpython.org/
http://mechanicalcat.net/pyblagg.html

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, Tim Lesher, and Tony Meyer continue the marvelous
tradition early borne by Andrew Kuchling, Michael Hudson and Brett
Cannon 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/python/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/Python


Re: how do you get the name of a dictionary?

2006-08-23 Thread Fredrik Lundh
Steve Holden wrote:

> Right. Plus it's fun to imagine the effbot hitting itself as hard as 
> some people would obviously have liked to hit it in the past :-)

you mean the guy who's spent the last six months downrating every single 
post I've made on this list over at googlegroups ?  I'd say it's safe to 
ignore him; he's a certified nutcase.



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


Re: running windows 'start' cmd using spawnl

2006-08-23 Thread Fredrik Lundh
Tor Erik wrote:

> I need to start a program in a new cmd-window. To do this I need to 
> execute: start [command]
> With os.system this is straight-forward.
> But I need to do it with spawnl and P_NOWAIT. I.e, asynchronously.
> The problem is that I need to know the path where start resides,
> which I'm unable to find.

os.startfile(command) could work.




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


Re: how do you get the name of a dictionary?

2006-08-23 Thread Fredrik Lundh
jojoba wrote:

>> the fact that despite all attempts to explain how things work, you're
>> still haven't realized that if you want the names of things, you should
>> pass *namespaces* to your object viewer, not individual objects.
> 
> And what im saying is that isnt it silly that we need pass an entire
> namespace

namespaces are objects too, you know.  passing "an entire namespace" is 
no harder than passing any other object.



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


Regex help...pretty please?

2006-08-23 Thread MooMaster
I'm trying to develop a little script that does some string
manipulation. I have some few hundred strings that currently look like
this:

cond(a,b,c)

and I want them to look like this:

cond(c,a,b)

but it gets a little more complicated because the conds themselves may
have conds within, like the following:

cond(0,cond(c,cond(e,cond(g,h,(a= d))
OUTPUT:
whole string is: (a,b,(abs(c)
the new string is:cond((abs(c,a,b)

Can anyone help me with the regular expression? Is this even the best
approach to take? Anyone have any thoughts? 

Thanks for your time!

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


Re: swapping numeric items in a list

2006-08-23 Thread Jiang Nutao
This is what I got in the debugger:

(Pdb) aa=array('b', [126, 55, 71, 112])
(Pdb) aa
array('b', [126, 55, 71, 112])
(Pdb) aa.byteswap()
(Pdb) aa
array('b', [126, 55, 71, 112])

- Original Message - 
From: "Gabriel Genellina" <[EMAIL PROTECTED]>
To: "Jiang Nutao" <[EMAIL PROTECTED]>
Cc: 
Sent: Wednesday, August 23, 2006 11:28 AM
Subject: Re: swapping numeric items in a list


> At Wednesday 23/8/2006 14:44, Jiang Nutao wrote:
>
>>array.byteswap() won't work for me easily. I tried this before my 1st 
>>post.
>>I defined
>>
>> aa = array('H', [0x12, 0x34, 0x56, 0x78])
>>
>>Then did byteswap aa.byteswap(). The result was
>>
>> array('H', [0x1200, 0x3400, 0x5600, 0x7800])
>>
>>You can see it byteswapped within each item.
>
> Use array('b') or 'B'. 'H' are two-byes integers.
>
>
>
> Gabriel Genellina
> Softlab SRL
>
>
>
>
> __
> Preguntá. Respondé. Descubrí.
> Todo lo que querías saber, y lo que ni imaginabas,
> está en Yahoo! Respuestas (Beta).
> ¡Probalo ya! http://www.yahoo.com.ar/respuestas
>
> 

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


Re: swapping numeric items in a list

2006-08-23 Thread Gabriel Genellina

At Wednesday 23/8/2006 14:44, Jiang Nutao wrote:


array.byteswap() won't work for me easily. I tried this before my 1st post.
I defined

aa = array('H', [0x12, 0x34, 0x56, 0x78])

Then did byteswap aa.byteswap(). The result was

array('H', [0x1200, 0x3400, 0x5600, 0x7800])

You can see it byteswapped within each item.


Use array('b') or 'B'. 'H' are two-byes integers.



Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


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

Re: running windows 'start' cmd using spawnl

2006-08-23 Thread Gabriel Genellina

At Wednesday 23/8/2006 14:22, Tor Erik wrote:


I need to start a program in a new cmd-window. To do this I need to
execute: start [command]
With os.system this is straight-forward.
But I need to do it with spawnl and P_NOWAIT. I.e, asynchronously.
The problem is that I need to know the path where start resides,
which I'm unable to find.


On Windows NT, XP, 2003 and others, there is no "start.exe" 
executable; it's an internal command. It only exists on 95, 98, maybe ME.

Try the subprocess module.


Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


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

Re: callable to disappear?

2006-08-23 Thread faulkner
what's wrong with hasattr(obj, '__call__')?

Antoon Pardon wrote:
> I have been reading http://www.python.org/dev/peps/pep-3100/
> en there is written:
>
>   To be removed:
>  ...
>
>  callable(): just call the object and catch the exception
>
>  ...
>
> But that doesn't seem to be a generally available option.
> The place where you want to check if something is callable
> doens't need to be the place where you actually want to call
> it. Removing callable will mean that you can't check whether
> or not something is callable without incurring the side-effects
> of calling it.
>
> I also think code will become more ugly
>
> How do you suggest I would code the following:
>
> if callable(func):
> for i, el in lst:
> lst[i] = func(el)
>   othercode()
>
>
> I can code as follows:
>
> try:
> for i, el in lst:
>   lst[i] = func(el)
>   othercode()
> except TypeError:
> pass
>
>
> But this has the problem that othercode could throw a TypeError:
>
> So it seems I would need at least two try statements
>
> try:
> for i, el in lst:
>   try:
>   lst[i] = func(el)
>   except TypeError
>   raise LoopBreak
>   othercode()
> except LoopBreak:
> pass
>
> And this still has problems because the TypeError could be
> raised because lst is an unsubscriptable object.
>
>
> Is there a chance this will be reconsidered?
> 
> -- 
> Antoon Pardon

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


Re: swapping numeric items in a list

2006-08-23 Thread Jiang Nutao
Thank you all guys for the help. Guess I'm gonna pick bearophile's way. It's 
fast, neat, and easy to read.

array.byteswap() won't work for me easily. I tried this before my 1st post. 
I defined

aa = array('H', [0x12, 0x34, 0x56, 0x78])

Then did byteswap aa.byteswap(). The result was

array('H', [0x1200, 0x3400, 0x5600, 0x7800])

You can see it byteswapped within each item.

Jason

"Marc 'BlackJack' Rintsch" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> In <[EMAIL PROTECTED]>, Jiang Nutao
> wrote:
>
>> To convert list
>> aa = [0x12, 0x34, 0x56, 0x78]
>> into
>> [0x34, 0x12, 0x78, 0x56]
>>
>> How to do it fast? My real list is huge.
>
> Use the `array` module and the `array.byteswap()` method.
>
> Ciao,
> Marc 'BlackJack' Rintsch
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 



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


  1   2   >