dfa - a trivial finite automaton module

2007-05-05 Thread Ian Zimmerman

I have just uploaded my dfa-0.1 module to PyPi.  I have seen similar
or equivalent code in other packages (e.g. FSM in pexpect) but it
was not as general or just used internally and not documented.

This is my first module and nearly first python code, so please
critique the style and API that I can learn something.  Thanks.

-- 
This line is completely ham.
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: Looping over lists

2007-05-05 Thread Paul Rubin
Tommy Grav [EMAIL PROTECTED] writes:
 In C this would be equivalent to:
 for(i = 0; i  n; i++) {
 for(j=i+1; j  n; j++) {
   print a[i], a[j]

for i in xrange(n):
   for j in xrange(i+1, n):
 print a[i], a[j]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looping over lists

2007-05-05 Thread Peter Otten
prad wrote:

 On Friday 04 May 2007 18:40:53 Tommy Grav wrote:
 Can anyone help me with the right approach for this
 in python?
 
 for each in a:
 for item in a[a.index(each)+1:]:
 print each,item
 
 will produce
 
 1 2
 1 3
 1 4
 1 5
 2 3
 2 4
 2 5
 3 4
 3 5
 4 5
 
 a.index(each) gives the index of the each value in the a list.
 then you just add 1 to it so you start at the index value beside each's
 index.

If there are equal items you may not get what you expect:
 
 items = [1, 2, 1.0]
 for a in items:
... for b in items[items.index(a)+1:]:
... print a, b
...
1 2
1 1.0
2 1.0
1.0 2
1.0 1.0

Peter

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


Re: Looping over lists

2007-05-05 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], prad wrote:

 On Friday 04 May 2007 18:40:53 Tommy Grav wrote:
 Can anyone help me with the right approach for this
 in python?
 
 for each in a:
 for item in a[a.index(each)+1:]:
 print each,item
 
 will produce 
 
 1 2
 1 3
 1 4
 1 5
 2 3
 2 4
 2 5
 3 4
 3 5
 4 5

But only if the elements in the list are unique.  And the runtime is
suboptimal because `index()` is doing a linear search -- the outer loop
becomes slower and slower with each iteration.

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


Re: Do I have to quit python to load a module?

2007-05-05 Thread Peter Otten
wang frank wrote:

 When I edit a module, I have to quit python and then restart python and
 then import the module. Are there any way to avoid quit python to load an
 updated module? When I am debugging a module code, I need to constantly
 make changes. It is not convenient to quit and reload.

There is the reload() function, but it has pitfalls. Objects referenced from
without the module are not updated:

 open(tmp.py, w).write(
... def f(): print version one
... )
 import tmp
 tmp.f()
version one
 g = tmp.f
 open(tmp.py, w).write(
... def f(): print version two
... )
 reload(tmp)
module 'tmp' from 'tmp.py'
 tmp.f()
version two
 g()
version one

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


Re: Python regular expressions just ain't PCRE

2007-05-05 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Wiseman wrote:

 Note: I know there are LALR parser generators/parsers for Python, but
 the very reason why re exists is to provide a much simpler, more
 productive way to parse or validate simple languages and process text.
 (The pyparse/yappy/yapps/insert your favourite Python parser
 generator here argument could have been used to skip regular
 expression support in the language, or to deprecate re. Would you want
 that? And following the same rule, why would we have Python when
 there's C?)

I don't follow your reasoning here.  `re` is useful for matching tokens
for a higher level parser and C is useful for writing parts that need
hardware access or raw speed where pure Python is too slow.

Regular expressions can become very unreadable compared to Python source
code or EBNF grammars but modeling the tokens in EBNF or Python objects
isn't as compact and readable as simple regular expressions.  So both `re`
and higher level parsers are useful together and don't supersede each
other.

The same holds for C and Python.  IMHO.

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


Re: Firefighters at the site of WTC7 Move away the building is going to blow up, get back the building is going to blow up.

2007-05-05 Thread MooseFET
On May 4, 8:19 pm, James Stroud [EMAIL PROTECTED] wrote:
 MooseFET wrote:
  On May 4, 12:32 pm, James Stroud [EMAIL PROTECTED] wrote:
  []

 The Marxist contribution to western thought is that it put everything in
 terms of labor and thus allowed us to quantify the human component of
 economies.

  No the great insight by Marx was in the selling of ducks.  Anybody
  want to buy a duct  has done more to advance economic thinking than
  the works of most economists.

  Economists have a vested interest in preventing people from
  understanding economics.  They are well paid and know that they
  wouldn't be for long if people really understood what was going on.

 You must be an economist because you provide absolutely no
 interpretation of what the hell you were saying in ghe first paragraph
 (as if you actually know what you were trying to say). Duct or duck,
 first of all. Second of all--make a point.

Groucho Marx.


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


Re: How to check if a string is empty in python?

2007-05-05 Thread John Machin
On May 5, 12:19 pm, [EMAIL PROTECTED] (Alex Martelli) wrote:
 Larry Bates [EMAIL PROTECTED] wrote:

...

  Isn't deprecated like depreciated but not quite to zero yet?

 No.  To deprecate comes from a Latin verb meaning to ward off a
 disaster by prayer; when you're saying you deprecate something, you're
 saying you're praying for that something to disappear, go away; in a
 secular context, you're earnestly imploring people to NOT do it.

 To depreciate comes from a Latin verb meaning to reduce the price;
 when you're saying you depreciate something, you're saying you put on
 that something a lower price (and, by extension, a lower value) than it
 has (or, more commonly, used to have).  You're not necessarily saying
 it's worth nothing at all (accountants sometimes deem an asset fully
 depreciated to mean something close to that, but the adverb fully is
 crucial to this meaning), just that it's worth less than before.

Seeing this thread has already deteriorated [another word with Latin
ancestry, not to be conflated with posteriorated] to the level of a
debate about how many angels can stand shoulder-to-shoulder between
the quotes surrounding the repr of an empty string, I presume it's OK
if I remark that a fully depreciated asset is one that has a *book*
value of zero [essentially that the whole of its original cost has
been written off (i.e. claimed as a tax deduction)] , and that this
has absolutely nothing to do with the true worth of the asset.





 The two terms got somewhat entwined, no doubt because their spelling is
 so similar (even though etimology and pronunciation are poles apart),
 but the correct meanings and usage are still well distinct.

 Alex


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


Re: Firefighters at the site of WTC7 Move away the building is going to blow up, get back the building is going to blow up.

2007-05-05 Thread James Stroud
MooseFET wrote:
 On May 4, 8:19 pm, James Stroud [EMAIL PROTECTED] wrote:
 MooseFET wrote:
 On May 4, 12:32 pm, James Stroud [EMAIL PROTECTED] wrote:
 []
 The Marxist contribution to western thought is that it put everything in
 terms of labor and thus allowed us to quantify the human component of
 economies.
 No the great insight by Marx was in the selling of ducks.  Anybody
 want to buy a duct  has done more to advance economic thinking than
 the works of most economists.
 Economists have a vested interest in preventing people from
 understanding economics.  They are well paid and know that they
 wouldn't be for long if people really understood what was going on.
 You must be an economist because you provide absolutely no
 interpretation of what the hell you were saying in ghe first paragraph
 (as if you actually know what you were trying to say). Duct or duck,
 first of all. Second of all--make a point.
 
 Groucho Marx.
 
 

You could have convinced me that Karl Marx was in the duck business 
because I wouldn't think anyone on any of these lists would be banal 
enough to use such a well worn joke.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before?

2007-05-05 Thread Eeyore


quasi wrote:

 Gib Bogle wrote:

 Ah, so the firefighters were in on the conspiracy!

 No, but the firefighters are very much aware that there is more to
 9/11 than has been officially revealed.

 This is even more true at Pentagon. The firefighters there brought
 dogs trained to search for survivors and/or remains

Sounds like good practice.


 and found nothing.

And the significance of this is ?

Graahm

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


Re: Why stay with lisp when there are python and perl?

2007-05-05 Thread kaens
Yes there is.

On 5/3/07, Markus E Leypold
[EMAIL PROTECTED] wrote:

 Xah Lee [EMAIL PROTECTED] writes:

  (if there is some demand, i will add a concrept, little programing

 No. There ain't.

 - M

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

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


Re: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before?

2007-05-05 Thread Tonico
On May 4, 2:08 am, quasi [EMAIL PROTECTED] wrote:
 On Fri, 04 May 2007 09:37:37 +1200, Gib Bogle

 [EMAIL PROTECTED] wrote:
 Ah, so the firefighters were in on the conspiracy!

 No, but the firefighters are very much aware that there is more to
 9/11 than has been officially revealed.

 This is even more true at Pentagon. The firefighters there brought
 dogs trained to search for survivors and/or remains and found nothing.

 quasi

Ah, Quasi, Midex and the other conspiratorers! You're the living proof
that (gullible) idiots don't disappear: there just are new ones every
time.
Regards
Tonio


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


Re: How do I get type methods?

2007-05-05 Thread yavannadil
On May 5, 1:17 am, Fuzzyman [EMAIL PROTECTED] wrote:
 dir(type(localContext))
 Perhaps ?

It gives
['__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__str__']

while

import sys
dir(type(sys.modules))

gives
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__',
'__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__',
'__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
'__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy',
'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys',
'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update',
'values']

so I guess PyUNO extension doesn't provide proper introspection :-(

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


Re: Looping over lists

2007-05-05 Thread kaens
I think the for i in range() is more readable (Maybe because I'm
coming from a c-style syntax language background) -  but what would
the benefits of using enumerate be (other that being more . . .
pythonesque?)

On 5/5/07, Dennis Lee Bieber [EMAIL PROTECTED] wrote:
 On Fri, 4 May 2007 19:26:17 -0700, [EMAIL PROTECTED] (Alex Martelli)
 declaimed the following in comp.lang.python:

  for i in range(n):
  for j in range(i+1, n):
  print a[i], a[j]
 
 Ah, but wouldn't the cleaner Python be something like


  a = [1, 2, 3, 4, 5, 3, 6]   #just to confuse matters
  for pos, val in enumerate(a):
 ... for v2 in a[pos+1:]:
 ... print val, v2
 ...
 1 2
 1 3
 1 4
 1 5
 1 3
 1 6
 2 3
 2 4
 2 5
 2 3
 2 6
 3 4
 3 5
 3 3
 3 6
 4 5
 4 3
 4 6
 5 3
 5 6
 3 6
 
 --
 WulfraedDennis Lee Bieber   KD6MOG
 [EMAIL PROTECTED]   [EMAIL PROTECTED]
 HTTP://wlfraed.home.netcom.com/
 (Bestiaria Support Staff:   [EMAIL PROTECTED])
 HTTP://www.bestiaria.com/
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: How do I get type methods?

2007-05-05 Thread yavannadil
On May 4, 7:13 pm, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:
 The OPs problem is, there is no access to the class or type because
 there is no name.

Exactly :-(

 You can get just instances from a factory function.

Worse, if I call

localContext.ServiceManage

I'll get something with different set of methods, but of the same type
- 'pyuno' :-(

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


Re: My Python annoyances

2007-05-05 Thread Ross Ridge
Ben Collver  [EMAIL PROTECTED] wrote:
It is problem report #1678102.  I understand the problem: that a 32 bit 
number looks different in a 32 bit signed int than in a 64 bit signed 
int.  However, the workaround of dropping a bit seems to defeat the 
purpose of using a CRC.

The workaround doesn't drop any bits, it converts the value to a Python
long and extracts the lower 32 bits.

There's really no good reason for Python to give two different results
here.  It should either return a signed 32-bit CRC value in a Python int,
or return a unsigned 32-bit CRC value in either Python long or a Python
int, if it's big enough.  What it's doing now, returning unsigned value in
a Python int, even when it's not big enough to hold the result, is wrong.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  [EMAIL PROTECTED]
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling Exe from Python

2007-05-05 Thread kaens
I've been using subprocess.call(['name','arg1','arg2']) Works fine.

On 2 May 2007 03:48:19 -0700, M Abbas [EMAIL PROTECTED] wrote:
 Hello Folks,

 This is what i am required to do.
 Call an executable from my python script, and when the executable is
 fininshed running, i should continue with my python script.

 I have tried os.exec() but it calls the executable and never returns
 to the calling python script.
 I tried os.fork it will start an independent process,
 since logic of my program depends on the results of executable.

 I am unable to figure, how to do it.
 Hope you folks would help me.

 ~JinBaba

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

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


progress

2007-05-05 Thread Merrigan
Hi All,

I have posted yesterday about an ftplib issue, this has been resolved.

I actually want to ask something here...

The script that that ftplib error was from...I was wondering - What do
I need to do to print the stats (speed/s, percentage done) of the
upload that is running on the monitor.

This script runs on a Fedora Machine.

Thanx for the help guys!

 -- Merrigan

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


Re: Newbie and Page Re-Loading

2007-05-05 Thread mosscliffe
Miki,

Thank you very much for your helpful reply.  A simple example is the
best way of getting started, I have found.

I have no excuses now - to not get it working.  I recently tried
Visual Studio with Visual Basic.  Nice for five minutes, but then all
the helping bits got in the way, so then you try to do it all yourself
and the logic behind 'viewstate' just seemed to do different things at
different times and my silver surfing brain, just wants to do things,
rather than learn all sorts of exceptions, which I will not remember
tomorrow, never mind the next week or month.

I will try the local server, after I get forms working.

A question for the future.  I am creating several spreadsheets on
google which contain data, I need to search and display on my web
page.  The data is quite large so I need to filter it as opposed to
just looking at the spreadsheet.  Am I right in thinking there is
something called an 'atom' feed, which will supply me the data from
google as a 'cursor' (think it is an SQL term) and I can read the rows
as records in python ?

Thanks again

Richard



On May 4, 10:10 pm, Miki [EMAIL PROTECTED] wrote:
 Hello Richard,

  I do not want to run a framework yet.  I would like to understand
  python at script level, before adding more aspects to learn, like
  frameworks.

 The way CGI works is that your script is called every time the
 corresponding HTML is loaded. You can access all the parameters sent
 to the script using cgi.FieldStorage.

  I think I get your idea about hidden fields and how to alter them.

 Note that hidden fields are passed in plain text format from/to the
 server, don't send anything sensitive in them.

  My single page script should work something like this

  DisplayHTMLHeaderandBodyHeader
  Check if this is a Re-Load (HiddenField would not exist first time I
  am assuming)

 It could be None: cgi.FieldStorage().getvalue(hidden_attribute) ==
 None

  Display SearchSection with previous SearchRequest
  If SearchRequest is True: Get and Display Results
  Display TrailerHTMLandTrailerBody

  . Wait for NewSearch or NextPage

 In CGI you don't wait, the script exists and called again when use
 hits a button/refresh ...

  Does the above make sense or is there a better way ?

 There are many other ways (AJAX, Web frameworks, FastCGI ...). However
 I'd recommend you start with plain CGI which is *simple*.
 Here is a small example:
 #!/usr/local/bin/python

 import cgitb; cgitb.enable() # Show errors in HTML output
 from cgi import FieldStorage

 FUNNY = [ mickey, donald, daisy, minnie, goofy ]

 def main():
 print Content-Type: text/html
 print

 form = FieldStorage()
 query = form.getvalue(query, )

 print '''htmlbody
 h1Disney Search/h1

 form
 input type=text name=query value=%s
 input type=submit value=search
 ''' % query

 if query:
 for someone in FUNNY:
 if query in someone:
 print br /%s % someone

 print /form/body/html

 if __name__ == __main__:
 main()

  How do I get the directory of my modules into the Python Path

 import sys
  sys.path.append(/path/to/my/modules)

 Note that your script directory is automatically added to the path.

  Is there a lightweight Https Server I could run locally (WINXP), which
  would run .py scripts, without lots of installation modifications ?

 http://lighttpd.net.
 Make sure mod_cgi is uncommented, set your document root and set
 right python interpreter in cgi.assign

 HTH,
 --
 Miki [EMAIL PROTECTED]http://pythonwise.blogspot.com


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


Re: Newbie and Page Re-Loading

2007-05-05 Thread mosscliffe
Alex,

Thanks for the help.

Richard

On May 5, 3:42 am, [EMAIL PROTECTED] (Alex Martelli) wrote:
 Miki [EMAIL PROTECTED] wrote:

...

   Is there a lightweight Https Server I could run locally (WINXP), which
   would run .py scripts, without lots of installation modifications ?
 http://lighttpd.net.
  Make sure mod_cgi is uncommented, set your document root and set
  right python interpreter in cgi.assign

 For https, you do need to do substantial homework, though -- no two ways
 about it, since you'll need to get SSL certificates, etc etc.  There are
 reasonably simple instructions for the purpose at
 http://www.cyberciti.biz/tips/how-to-install-ssl-lighttpd-https-configu
 ration.html, but they're for Linux -- I don't know how they change when
 you want to serve https on Xp.

 Alex


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


Re: My Python annoyances

2007-05-05 Thread Ben Collver
Terry Reedy wrote:
 You don't need an invitation to disagree with another person's tracker 
 comment.  I assumed you knew this and took non-response as acquiesence. 
 That (closing no response by item submitter) is a fairly typical pattern , 
 by the way.  I wish it were otherwise.

I (incorrectly) took the comment to support rather than invalidate my 
report, and did not see anything to challenge.  Email is not 100% 
reliable, but I understand you don't have the time to hound submitters. 
  Do you think it might help to ask a question when you expect a 
response from the submitter?  It might act as a prompt.

 That is a different issue.  If, for instance, you think the docs could and 
 should be improved to make people more wary, reopen the item, change the 
 appropriate field to 'documentation' and please give a suggested addition 
 or change.

I trust the experts to take the appropriate action.  It seems equally 
reasonable to ignore the report for its triviality, or to treat the 
checksum as a long, since that is what zlib returns.

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


Re: High resolution sleep (Linux)

2007-05-05 Thread Nick Craig-Wood
John [EMAIL PROTECTED] wrote:
 
  The table below shows the execution time for this code snippet as
  measured by the unix command `time':
 
  for i in range(1000):
   time.sleep(inter)
 
  inter   execution time  ideal
  0 0.02 s0 s
  1e-44.29 s0.1 s
  1e-34.02 s1 s
  2e-34.02 s2 s
  5e-38.02 s5 s
 
  Hence it seems like the 4 s is just overhead and that the time.sleep
  method treats values below approximately 0.001 as 0.

The exact minimum sleep time will be determined by the HZ value that
your kernel was compiled with.  In newer kernels that is typically 250
or 1000, it used to be 100 in older kernels.

If you look at the config file used to build your kernel you can
discover the HZ value.

If you try to sleep for less than a timer tick, then the kernel
performs a yield.

  Is there a standard way (or slick trick) to get higher resolution? If
  it is system dependent it's acceptable but not very nice :)

I assume you are using sleep for timing purposes..  This isn't a
terribly good idea, but here is an idea for you

# 
from time import time, sleep

def hr_sleep(duration):
end = time() + duration
if duration  0.02:
sleep(duration)
while time() - end  0:
sleep(0)

if __name__ == __main__:
from timeit import Timer
for e in range(0,7):
dt = 10**-e
loops = 10**e
t = Timer(hr_sleep(%f) % dt, from __main__ import hr_sleep)
print expected = %.2E actual = %.2E % (dt, t.timeit(loops)/loops)
# 

This prints

expected = 1.00E+00 actual = 1.00E+00
expected = 1.00E-01 actual = 1.00E-01
expected = 1.00E-02 actual = 1.00E-02
expected = 1.00E-03 actual = 1.00E-03
expected = 1.00E-04 actual = 1.02E-04
expected = 1.00E-05 actual = 1.19E-05
expected = 1.00E-06 actual = 2.66E-06

on my 250 HZ machine

You could then do run-time calibration to work out the overhead of the
function on any given machine to make it more accurate.

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


Re: Firefighters at the site of WTC7 Move away the building is going to blow up, get back the building is going to blow up.

2007-05-05 Thread jmfbahciv
In article [EMAIL PROTECTED],
   MooseFET [EMAIL PROTECTED] wrote:
On May 4, 8:19 pm, James Stroud [EMAIL PROTECTED] wrote:
 MooseFET wrote:
  On May 4, 12:32 pm, James Stroud [EMAIL PROTECTED] wrote:
  []

 The Marxist contribution to western thought is that it put everything in
 terms of labor and thus allowed us to quantify the human component of
 economies.

  No the great insight by Marx was in the selling of ducks.  Anybody
  want to buy a duct  has done more to advance economic thinking than
  the works of most economists.

  Economists have a vested interest in preventing people from
  understanding economics.  They are well paid and know that they
  wouldn't be for long if people really understood what was going on.

 You must be an economist because you provide absolutely no
 interpretation of what the hell you were saying in ghe first paragraph
 (as if you actually know what you were trying to say). Duct or duck,
 first of all. Second of all--make a point.

Groucho Marx.

Give that man a cigar.

/BAH

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


Re: Looping over lists

2007-05-05 Thread Dustan
On May 5, 3:15 am, kaens [EMAIL PROTECTED] wrote:
 I think the for i in range() is more readable (Maybe because I'm
 coming from a c-style syntax language background) -  but what would
 the benefits of using enumerate be (other that being more . . .
 pythonesque?)

It doesn't create a whole new list just for iterating.

 On 5/5/07, Dennis Lee Bieber [EMAIL PROTECTED] wrote:

  On Fri, 4 May 2007 19:26:17 -0700, [EMAIL PROTECTED] (Alex Martelli)
  declaimed the following in comp.lang.python:

   for i in range(n):
   for j in range(i+1, n):
   print a[i], a[j]

  Ah, but wouldn't the cleaner Python be something like

   a = [1, 2, 3, 4, 5, 3, 6]   #just to confuse matters
   for pos, val in enumerate(a):
  ... for v2 in a[pos+1:]:
  ... print val, v2
  ...
  1 2
  1 3
  1 4
  1 5
  1 3
  1 6
  2 3
  2 4
  2 5
  2 3
  2 6
  3 4
  3 5
  3 3
  3 6
  4 5
  4 3
  4 6
  5 3
  5 6
  3 6

  --
  WulfraedDennis Lee Bieber   KD6MOG
  [EMAIL PROTECTED]   [EMAIL PROTECTED]
  HTTP://wlfraed.home.netcom.com/
  (Bestiaria Support Staff:   [EMAIL PROTECTED])
  HTTP://www.bestiaria.com/
  --
 http://mail.python.org/mailman/listinfo/python-list


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


Problem with Closing TCP connection

2007-05-05 Thread Madhur
Dear All,

I am currently developing a tool using Python 2.4.2 which will be used
as a sink to pump TCP messages. During which i have observed that the
TCP close interface provided by Python is not closing the connection.
This i confirmed by looking at the ethereal logs, which show proper 3
way FIN ACK Handshake. But the netstat reports TIME_WAIT state for the
TCP connection, which is hindering the messages to be pumped later. I
would like to know whether the problem exists Python close and is
there is turnaround? to the mentioned problem.

Thanks,

Madhur

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


Re: Problems Drawing Over Network

2007-05-05 Thread paul
Andrew schrieb:
 Hello Everyone
[snipped stuff]
Sorry not being helpful, but I suggest you post a minimal sample of your 
code demonstrating your program.

cheers
  Paul


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


Re: Do I have to quit python to load a module?

2007-05-05 Thread Carsten Haese
On Sat, 2007-05-05 at 05:33 +, wang frank wrote:
 Hi,
 
 When I edit a module, I have to quit python and then restart python and 
 then import the module. Are there any way to avoid quit python to load an 
 updated module? When I am debugging a module code, I need to constantly 
 make changes. It is not convenient to quit and reload.

This is a frequently asked question. See
http://www.python.org/doc/faq/ . The answer to your question is at
http://tinyurl.com/2qc7ev .

-Carsten


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


Re: Problem with Closing TCP connection

2007-05-05 Thread malkarouri
On 5 May, 12:18, Madhur [EMAIL PROTECTED] wrote:
[...]
 as a sink to pump TCP messages. During which i have observed that the
 TCP close interface provided by Python is not closing the connection.
 This i confirmed by looking at the ethereal logs, which show proper 3
 way FIN ACK Handshake. But the netstat reports TIME_WAIT state for the
 TCP connection, which is hindering the messages to be pumped later. I
 would like to know whether the problem exists Python close and is
 there is turnaround? to the mentioned problem.

IIRC, this is normal operation of TCP connections. A very short
explanation is here (http://www.unixguide.net/network/socketfaq/
2.7.shtml).
So it is not a problem of Python.
I don't know exactly what you want to do, but I suggest you look at
one of the following options:
- Either get IP messages and filter them, same way as ethereal.
Probably complicated coding.
- Depending on your problem, you may try opening the TCP socket in
Python using the SO_REUSEADDR option.

Regards,
k

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


Re: Non blocking sockets with select.poll() ?

2007-05-05 Thread Maxim Veksler
On 5/4/07, Jean-Paul Calderone [EMAIL PROTECTED] wrote:
 
 #!/usr/bin/env python
 import socket
 import select
 
 class PollingSocket(socket.socket):
 
 
 def __init__(self, port_number):
 self.__poll = select.poll()
 self.tcp_port_number = port_number
 
 socket.socket.__init__(self, socket.AF_INET, socket.SOCK_STREAM)
 self.setblocking(0)
 self.bind(('0.0.0.0', self.tcp_port_number))
 self.listen(5)
 self.__poll.register(self)
 
 def poll(self, timeout = 0):
 return self.__poll.poll(timeout)
 
 def debugPollingSocket(port_num):
 print BIND TO PORT: , port_num
 return PollingSocket(port_num)
 
 all_sockets = map(debugPollingSocket, xrange(1, 19169))
 
 print We have this in stock:
 for nb_active_socket in all_sockets:
 print nb_active_socket.tcp_port_number
 
 while 1:
 for nb_active_socket in all_sockets:
 print Asking, nb_active_socket.tcp_port_number
 if nb_active_socket.poll(0):
 print Found, nb_active_socket.tcp_port_number
 conn, addr = nb_active_socket.accept()
 while 1:
 data = conn.recv(1024)
 if not data: break
 conn.send(data)
 conn.close()
 
 

 This will only handle one connection at a time, of course.  The polling
 it does is also somewhat inefficient.  Perhaps that's fine for your use
 case.  If not, though, I'd suggest this version (untested):


Actually, I'm here to learn. I could have used any number of different
approaches to accomplish this; starting from
http://docs.python.org/lib/module-asyncore.html to twisted to
http://oss.coresecurity.com/projects/pcapy.html.

I would appreciate it if you could elaborate on why my loop is
inefficient, I will try to improve it then (and post back).

Besides, this whole story started from me writing a quick
totalitarian security testing framework. Once I'm done with the
networking part I will start working on the part that kill's all
current processes listening on TCP/IP of the machine. Obviously thats
not meant for production boxes... The simple idea is having the poller
on one side of the firewall connection and the monster on the other
side replying, a kind of primitive and plain firewall testing utility.

   from twisted.internet import pollreactor
   pollreactor.install()

   from twisted.internet import reactor
   from twisted.protocols.wire import Echo
   from twisted.internet.protocol import ServerFactory

   f = ServerFactory()
   f.protocol = Echo
   for i in range(1, 19169):
   reactor.listenTCP(i, f)
   reactor.run()

 This will handle traffic from an arbitrary number of clients at the same
 time and do so more efficiently than the loop in your version.  You can
 also try epollreactor instead of pollreactor, if the version of Linux you
 are using supports epoll, for even better performance.


Thanks!

 Jean-Paul



-- 
Cheers,
Maxim Veksler

Free as in Freedom - Do u GNU ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Firefighters at the site of WTC7 Move away the building is going to blow up, get back the building is going to blow up.

2007-05-05 Thread James Stroud
[EMAIL PROTECTED] wrote:
 In article [EMAIL PROTECTED],
MooseFET [EMAIL PROTECTED] wrote:
 On May 4, 8:19 pm, James Stroud [EMAIL PROTECTED] wrote:
 MooseFET wrote:
 Groucho Marx.
 
 Give that man a cigar.
 
 /BAH
 

Please take note aspiring humorists, we have here an actual example of 
humor.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I get type methods?

2007-05-05 Thread Carsten Haese
On Sat, 2007-05-05 at 01:19 -0700, [EMAIL PROTECTED] wrote:
 On May 4, 7:13 pm, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:
  The OPs problem is, there is no access to the class or type because
  there is no name.
 
 Exactly :-(
 
  You can get just instances from a factory function.
 
 Worse, if I call
 
 localContext.ServiceManage
 
 I'll get something with different set of methods, but of the same type
 - 'pyuno' :-(

'pyuno' objects are proxy objects that represent UNO objects, services,
and interfaces. Since all attribute lookups are handled by the UNO
bridge, the proxy object doesn't actually know what attributes it has,
which is why it won't respond anything useful to the usual dir()
inspection.

To list the methods and properties that the UNO object behind a pyuno
proxy object has, you need to use UNO inspection capabilities. Something
like the following seems to work:

# unodir.py
def unodir(unoobj):
   import uno
   from com.sun.star.beans.MethodConcept import ALL as ALLMETHS
   from com.sun.star.beans.PropertyConcept import ALL as ALLPROPS
   ctx = uno.getComponentContext()
   introspection = ctx.ServiceManager.createInstanceWithContext(
   com.sun.star.beans.Introspection, ctx)
   access = introspection.inspect(unoobj)
   meths = access.getMethods(ALLMETHS)
   props = access.getProperties(ALLPROPS)
   return [ x.getName() for x in meths ] + [ x.Name for x in props ]

 import uno
 from unodir import unodir
 localContext = uno.getComponentContext()
 unodir(localContext)
[u'queryInterface', u'acquire', u'release', u'getValueByName',
u'getServiceManager', u'getElementType', u'hasElements', u'getByName',
u'getElementNames', u'hasByName', u'replaceByName', u'insertByName',
u'removeByName', u'getTypes', u'getImplementationId', u'queryAdapter',
u'dispose', u'addEventListener', u'removeEventListener',
u'ServiceManager', u'ElementType', u'ElementNames', u'Types',
u'ImplementationId']

Hope this helps,

Carsten


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


Re: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before?

2007-05-05 Thread quasi
On Sat, 05 May 2007 07:54:50 +0100, Eeyore
[EMAIL PROTECTED] wrote:



quasi wrote:

 Gib Bogle wrote:

 Ah, so the firefighters were in on the conspiracy!

 No, but the firefighters are very much aware that there is more to
 9/11 than has been officially revealed.

 This is even more true at Pentagon. The firefighters there brought
 dogs trained to search for survivors and/or remains

Sounds like good practice.


 and found nothing.

And the significance of this is ?

The plane was supposed to have passengers.

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


Re: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before?

2007-05-05 Thread Dotan Cohen
I missed the relevancy to Python in this thread. Could someone,
preferably the OP, please quote it? Thanks in advance.

Dotan Cohen

http://lyricslist.com/
http://what-is-what.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looping over lists

2007-05-05 Thread Paul Rubin
Dustan [EMAIL PROTECTED] writes:
  I think the for i in range() is more readable (Maybe because I'm
  coming from a c-style syntax language background) -  but what would
  the benefits of using enumerate be (other that being more . . .
  pythonesque?)
 
 It doesn't create a whole new list just for iterating.

That's what xrange is for.
-- 
http://mail.python.org/mailman/listinfo/python-list


Ezanb.com New Technology Forums - Register Now and Win!!!

2007-05-05 Thread Shaine
Hi there,

We have just launched a new Technology Forums - http://www.ezanb.com.
Our aim is to create such a knowledge base where anybody can find the
solution to any 'technology related problems'. So, in this regard we
are seeking your co-operation. We want you to share your valuable
knowledge with the whole world and also use the knowledge of thousands
of other technical experts. We want to make ezanb.com A Technology
Forum
as Technology Knowledge Sharing Hub and with the help of your
support
we can achieve this aim easily.

Sharing your knowledge online will increase your credibility in
Cyberspace. You can also share your achievements with others by using
ezanb.com. For example if you have written some complex code snippet
then
you can share that code snippet with others.

Besides the benefits mentioned above we also want to encourage you
by running a contest POST and WIN. In this contest we will
distribute a
gadgets to each member on every 50th Post on ezanb.com.

So Go Ahead and Register now at http://www.ezanb.com

Thank you very much

Administrator
http://www.ezanb.com

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


Re: Looping over lists

2007-05-05 Thread Alex Martelli
Dustan [EMAIL PROTECTED] wrote:

 On May 5, 3:15 am, kaens [EMAIL PROTECTED] wrote:
  I think the for i in range() is more readable (Maybe because I'm
  coming from a c-style syntax language background) -  but what would
  the benefits of using enumerate be (other that being more . . .
  pythonesque?)
 
 It doesn't create a whole new list just for iterating.

As the example list was of length 5, that's not all that important in
this case.  In cases where it _is_ crucial, you can use xrange.

The performance of the various ways of looping is substantially the
same:

$ python -mtimeit -s'n=5; a=n*[23]' 'for i in range(n): x=a[i]'
100 loops, best of 3: 1.4 usec per loop
$ python -mtimeit -s'n=5; a=n*[23]' 'for i in xrange(n): x=a[i]'
100 loops, best of 3: 1.18 usec per loop
$ python -mtimeit -s'n=5; a=n*[23]' 'for i,v in enumerate(a): x=v'
100 loops, best of 3: 1.49 usec per loop
$ 

Here, xrange is minutely faster and enumerate slower, but each speed
difference in the noise.  Focusing on clarity is thus well warranted.

for i in range(n):
for j in range(i+1, n):
print a[i], a[j]
 
   Ah, but wouldn't the cleaner Python be something like
 
a = [1, 2, 3, 4, 5, 3, 6]   #just to confuse matters
for pos, val in enumerate(a):
   ... for v2 in a[pos+1:]:
   ... print val, v2

This breaks symmetry, by using enumerate in the outer loop and a slice
in the inner loop; the symmetrical construction of using range in both
loops is a big conceptual/clarity win -- the reader of the code needs to
grasp one fewer concept (locally).  Using xrange in both loops would
be just as good from this POV.


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


Re: What happened to [EMAIL PROTECTED]

2007-05-05 Thread jim-on-linux
On Friday 04 May 2007 22:19, Carsten Haese wrote:
 Hiya,

 I just tried sending an email to
 [EMAIL PROTECTED] to request a website
 change, and the email bounced back with this
 excerpt from the delivery failure report:

 
 Reporting-MTA: dns; bag.python.org
 [...]
 Final-Recipient: rfc822;
 [EMAIL PROTECTED] Original-Recipient:
 rfc822; [EMAIL PROTECTED] Action: failed
 Status: 5.0.0
 Diagnostic-Code: X-Postfix; unknown user:
 webmaster 

 Who should I contact to request the website
 change?

 Thanks,

 Carsten.

I'm not sure but you can try;

[EMAIL PROTECTED]
or
http://mail.python.org/

jim-on-lnux
http://www.inqvista.com


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


Re: Lisp for the C21

2007-05-05 Thread Raffael Cavallaro
On 2007-05-04 11:32:14 -0400, Paul Rubin http://[EMAIL PROTECTED] said:

 Anyone who didn't love lisp in the 20th century has no heart.
 Anyone who still loves it in the 21st, has no head.

By the same logic we should all be conservative Republicans. Given this 
implication, I'll stick with lisp, thanks.

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


Re: Python regular expressions just ain't PCRE

2007-05-05 Thread Wiseman
On May 5, 5:12 am, Terry Reedy [EMAIL PROTECTED] wrote:

 I believe the current Python re module was written to replace the Python
 wrapping of pcre in order to support unicode.

I don't know how PCRE was back then, but right now it supports UTF-8
Unicode patterns and strings, and Unicode character properties. Maybe
it could be reintroduced into Python?

 I don't remember those being in the pcre Python once had.  Perhaps they are
 new.

At least today, PCRE supports recursion and recursion check,
possessive quantifiers and once-only subpatterns (disables
backtracking in a subpattern), callouts (user functions to call at
given points), and other interesting, powerful features.

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


Re: Non blocking sockets with select.poll() ?

2007-05-05 Thread Jean-Paul Calderone
On Sat, 5 May 2007 15:37:31 +0300, Maxim Veksler [EMAIL PROTECTED] wrote:
On 5/4/07, Jean-Paul Calderone [EMAIL PROTECTED] wrote:
 
 #!/usr/bin/env python
 import socket
 import select
 
 class PollingSocket(socket.socket):
 

Usually there's no particularly good reason to subclass socket.  In this
case you did it to add a poll method, it seems.  However...

 
 def __init__(self, port_number):
 self.__poll = select.poll()
 self.tcp_port_number = port_number
 
 socket.socket.__init__(self, socket.AF_INET, socket.SOCK_STREAM)
 self.setblocking(0)
 self.bind(('0.0.0.0', self.tcp_port_number))
 self.listen(5)
 self.__poll.register(self)

Creating one poll object per socket isn't necessary.  You only need one
overall.

 
 def poll(self, timeout = 0):
 return self.__poll.poll(timeout)

Polling with a zero timeout is just busy looping.  You want to poll with a
large (or infinite) timeout, and on more than one socket at a time.

 
 def debugPollingSocket(port_num):
 print BIND TO PORT: , port_num
 return PollingSocket(port_num)
 
 all_sockets = map(debugPollingSocket, xrange(1, 19169))
 
 print We have this in stock:
 for nb_active_socket in all_sockets:
 print nb_active_socket.tcp_port_number
 
 while 1:
 for nb_active_socket in all_sockets:
 print Asking, nb_active_socket.tcp_port_number
 if nb_active_socket.poll(0):
 print Found, nb_active_socket.tcp_port_number
 conn, addr = nb_active_socket.accept()
 while 1:
 data = conn.recv(1024)
 if not data: break
 conn.send(data)
 conn.close()
 
 

Instead of looping over all the sockets repeatedly and asking each one if
it has any data, you want to create one poll object, register every socket
with it, and ask it which sockets have data.  You also want to put the
accepted sockets into non-blocking mode and also poll them, reading from
whichever ones have data when they have data.

Even if you don't want to use Twisted, it might be beneficial to read how
it is implemented to learn how to do this.

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


Re: Python regular expressions just ain't PCRE

2007-05-05 Thread Wiseman
On May 5, 7:19 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:
 In [EMAIL PROTECTED], Wiseman wrote:
  Note: I know there are LALR parser generators/parsers for Python, but
  the very reason why re exists is to provide a much simpler, more
  productive way to parse or validate simple languages and process text.
  (The pyparse/yappy/yapps/insert your favourite Python parser
  generator here argument could have been used to skip regular
  expression support in the language, or to deprecate re. Would you want
  that? And following the same rule, why would we have Python when
  there's C?)

 I don't follow your reasoning here.  `re` is useful for matching tokens
 for a higher level parser and C is useful for writing parts that need
 hardware access or raw speed where pure Python is too slow.

 Regular expressions can become very unreadable compared to Python source
 code or EBNF grammars but modeling the tokens in EBNF or Python objects
 isn't as compact and readable as simple regular expressions.  So both `re`
 and higher level parsers are useful together and don't supersede each
 other.

 The same holds for C and Python.  IMHO.

 Ciao,
 Marc 'BlackJack' Rintsch

Sure, they don't supersede each other and they don't need to. My point
was that the more things you can do with regexes (not really regular
expressions anymore), the better -as long as they are powerful enough
for what you need to accomplish and they don't become a giant Perl-
style hack, of course-, because regular expressions are a built-in,
standard feature of Python, and they are much faster to use and write
than Python code or some LALR parser definition, and they are more
generally known and understood. You aren't going to parse a
programming language with a regex, but you can save a lot of time if
you can parse simple, but not so simple languages with them. Regular
expressions offer a productive alternative to full-fledged parsers for
the cases where you don't need them. So saying if you want feature X
or feature Y in regular expressions you should use a Bison-like parser
sounds a bit like an excuse, because the very reason why regular
expressions like these exist is to avoid using big, complex parsers
for simple cases. As an analogy, I mentioned Python vs. C: you want to
develop high-level languages because they are simpler and more
productive than working with C, even if you can do anything with the
later.

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


File names and file objects [was Re: My Python annoyances]

2007-05-05 Thread Steven D'Aprano
On Fri, 04 May 2007 07:55:25 -0700, Alex Martelli wrote:

 What about the case where I have an array of objects that represent some
 particular binary file format.  If the object is a file, then I want to
 copy its contents.  If the object is a string, then I want to write the
 string.  And so forth.
 
 Type-switching in this way is a rather dubious practice in any
 language (it can't respect the open-closed principle).

What do people think about functions that accept either a file name or a
file object?


def handle_file(obj):
if type(obj) == str:
need_to_close = True
obj = file(obj, 'r')
else: 
need_to_close = False
do_something_with(obj.read())
if need_to_close:
data.close()


Good idea? Bad idea? Just a matter of personal preference?



-- 
Steven.

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


Re: Python regular expressions just ain't PCRE

2007-05-05 Thread dustin
On Sat, May 05, 2007 at 08:52:15AM -0700, Wiseman wrote:
  I believe the current Python re module was written to replace the Python
  wrapping of pcre in order to support unicode.
 
 I don't know how PCRE was back then, but right now it supports UTF-8
 Unicode patterns and strings, and Unicode character properties. Maybe
 it could be reintroduced into Python?

I would say this is a case for rough consensus and working code.  With
something as big and ugly[1] as a regexp library, I think the working
code part will be the hard part.

So, if you have a patch, there's a decent chance such a thing would be
adopted.  

I'm not sure what your skill level is, but I would suggest studying the
code, starting in on a patch for one or more of these features, and then
corresponding with the module's maintainers to improve your patch to the
point where it can be accepted.

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


Re: Object interfaces and capabilities [was Re: File names and file objects [was Re: My Python annoyances]]

2007-05-05 Thread Paul Boddie
Steven D'Aprano wrote:

 What do people think about functions that accept either a file name or a
 file object?


 def handle_file(obj):
 if type(obj) == str:
 need_to_close = True
 obj = file(obj, 'r')
 else:
 need_to_close = False
 do_something_with(obj.read())
 if need_to_close:
 data.close()


 Good idea? Bad idea? Just a matter of personal preference?

I sometimes write functions like this myself. However, the matter of
testing for file-like objects can obviously vary somewhat in terms of
personal preference and correctness. Some would argue that this is a
situation which would benefit from interfaces:

if isinstance(obj, FileLike): # or obj.implements(FileLike), perhaps
do_something_with(obj.read())

In the original example, we can intuitively see that a file-like
object need only support the read and close methods, and in the case
of receiving a file-like object, only the read method need exist on
the object. Consequently, we can write the following:

if hasattr(obj, read):
do_something_with(obj.read())

Some would rightly say that this is ridiculous: you're testing
something which will be discovered straight away. However, there can
be situations where you might want to know in advance whether the
object is suitable, especially if you may perform more than one kind
of operation on the object and where side-effects may occur - the let
the code fail attitude arguably doesn't hold up very well in such
cases.

The problem can then be framed in terms of being able to express the
set of required operations and whether something like interfaces is a
flexible enough means of doing so. We might have something like this:

if test_for_file(obj):
do_something_with(obj) # not the string but the object itself

Now, we have the choice of explicitly phrasing the test ourselves...

def test_for_file(obj):
return hasattr(obj, read) and hasattr(obj, close) # and ...

...or relying on an interface mechanism to do this for us, with the
possible additional overhead of declaring such interface usage when
defining or adopting classes.

It seems to me that there's a gulf between the use of interfaces, with
the cost of introducing declarations in the code and the benefit of
relatively easy verification of object capabilities, and the current
situation where one might like to try and deduce the required
capabilities of an object at any given point in the code. Without
interfaces, such verification is difficult but there's less overhead
for the programmer; with interfaces, verification is easier but the
programmer has to work harder to do most of the work. I can't really
see a good compromise.

Paul

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


Re: change of random state when pyc created??

2007-05-05 Thread Dustan
On May 4, 10:48 pm, Alan Isaac [EMAIL PROTECTED] wrote:
 This may seem very strange, but it is true.
 If I delete a .pyc file, my program executes with a different state!

 In a single directory I have
 module1 and module2.

 module1 imports random and MyClass from module2.
 module2 does not import random.

 module1 sets a seed like this::

 if __name__ == __main__:
 random.seed(314)
 main()

 I execute module1.py from the (Windows) shell.
 I get a result, let's call it result1.
 I execute it again. I get another result, say result2.
 Running it again and again, I get result2.

 Now I delete module2.pyc.
 I execute module1.py from the shell.
 I get result1.
 I execute it again; I get result2.
 From then on I get result2,
 unless I delete module.pyc again,
 in which case I once again get result1.

 Can someone explain this to me?

 Thank you,
 Alan Isaac

I can't imagine why that would be, and I was unable to reproduce that
behavior, using Microsoft Windows XP and Python 2.5:

module1.py
import module2
import random

def main():
for i in range(10): print module2.aRandom()

if __name__ == '__main__':
random.seed(314)
main()
/module1.py

module2.py
import random
print module2 imported

def aRandom():
return random.randrange(100)
/module2.py


C:\Documents and Settings\DUSTAN\Desktop\apackagemodule1.py
module2 imported
196431
111465
2638
628136
234231
207699
546775
449804
633844
179171

C:\Documents and Settings\DUSTAN\Desktop\apackagemodule1.py
module2 imported
196431
111465
2638
628136
234231
207699
546775
449804
633844
179171

C:\Documents and Settings\DUSTAN\Desktop\apackagemodule1.py
module2 imported
196431
111465
2638
628136
234231
207699
546775
449804
633844
179171

C:\Documents and Settings\DUSTAN\Desktop\apackagemodule1.py
module2 imported
196431
111465
2638
628136
234231
207699
546775
449804
633844
179171

I deleted module2.pyc right before that last call.

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


Re: File names and file objects [was Re: My Python annoyances]

2007-05-05 Thread Steven Howe




Steven D'Aprano wrote:

  On Fri, 04 May 2007 07:55:25 -0700, Alex Martelli wrote:

  
  

  What about the case where I have an array of objects that represent some
particular binary file format.  If the object is a file, then I want to
copy its contents.  If the object is a string, then I want to write the
string.  And so forth.
  

"Type-switching" in this way is a rather dubious practice in any
language (it can't respect the "open-closed" principle).

  
  
What do people think about functions that accept either a file name or a
file object?


def handle_file(obj):
if type(obj) == str:
need_to_close = True
obj = file(obj, 'r')
else: 
need_to_close = False
do_something_with(obj.read())
if need_to_close:
data.close()


Good idea? Bad idea? Just a matter of personal preference?



  

The first question to ask is why are you using an array to hold
multiple 
unidentified objects? Why not use a dictionary instead. You could add
items using the object as key and type as data element.
import types
dictOfObjects = {}
aString = 'abcde'
fobj = open('filename', 'w')
fout = open('anotherFilename','r')
dictOfObject[aString] = [types.StringType]
dictOfObjects [fobj] = [types.FileType, 'w']
dictOfOjbect[fout] = [types.FileType,'r']

Then you can iterate over the dictionary; selection/action by type.

The question seems kind of bogus anyway. The only language
feature that stores different elements in a single body are similar to
'C/C++' structures. At which point one has to ask... why not use the 
struct module? Ah ... perhaps the questioner didn't know about them?

Well I'd suggest, before more 'annoyances' postings to review the
top level of the module
index @ http://docs.python.org/modindex.html.
I find it a great place to start looking for python language features
that
my programs need, but I don't know, yet.

sph

-- 
HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0



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

How do I use the config parser?

2007-05-05 Thread noagbodjivictor
Hi,
I need a specific example. I have seen the docs, but I don't all the
stuffs there.

So basically, I need my config file to be created and read by my
script.

Here is a snippet

# read old actions
from ConfigParser import ConfigParser

fp = open(makepath('App\qt_actions.conf'))
configdict = ConfigParser()
configdict.readfp(fp)


Now I want to know how to read a section, a section attribute's value,
and to write thoses back after reading.

Thanks

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


Re: OT somewhat: Do you telecommute? What do you wish the boss understood about it?

2007-05-05 Thread estherschindler
Oh! what a lovely response -- and I agree with almost all of it.

I just handed in the article, and hadn't seen your message, but you'll
be glad to know that I ended up with a whole sidebar about the costs
that a telecommuter may bear. That didn't include the travel and hotel
outlay, though it might have, since I just spent $400 on plane tickets
to Boston for next month, and I won't  be reimbursed for them until
after the trip. (The devil's advocate piece of that, however, is that
I don't pay for gas to commute to-and-from the office, either, which
never is reimbursed. One side effect of telecommuting is that I have
to put fuel in the car only once a month.)

Anyway, my sidebar focused on the more direct questions of what does
the company cover? Many of them don't have right or wrong answers,
but there ought to be a policy in place before either the telecommuter
or the accounting department have a fit. (If a telecommuter wears out
her office chair, who pays for it? The usual answer is the
telecommuter but is that really fair? If I had a cube in the office,
they'd get me a chair. Maybe a junky one, but there would be a
facilities budget to cover it.)

I think you can tell that I liked what you wrote. I'll be sure to let
you know when the article is published.

Esther

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


Re: What happened to [EMAIL PROTECTED]

2007-05-05 Thread Aahz
In article [EMAIL PROTECTED],
Carsten Haese  [EMAIL PROTECTED] wrote:

I just tried sending an email to [EMAIL PROTECTED] to request a
website change, and the email bounced back with this excerpt from the
delivery failure report:

Oops!  I've informed the appropriate people.

For now, either hang on to your request or send it directly to me.

Thanks for letting us know!
-- 
Aahz ([EMAIL PROTECTED])   * http://www.pythoncraft.com/

Look, it's your affair if you want to play with five people, but don't
go calling it doubles.  --John Cleese anticipates Usenet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python regular expressions just ain't PCRE

2007-05-05 Thread Martin v. Löwis
 Are there any plans to support these features in re? 

This question is impossible to answer. I don't have such
plans, and I don't know of any, but how could I speak for
the hundreds of contributors to Python world-wide, including
those future contributors which haven't contributed *yet*.

Do you have plans for such features in re?

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


Python Binding

2007-05-05 Thread Georg Grabler
Hello everybody.

There's a C library which i'd like to have python bindings for. I havn't
known anything before about how to write python bindings for a C library.

I succeeded now by using distutils to write the first bindings for functions
and similar.

Now, it seems as something is blocking my brain. For the library, i
need custom types, so types defined in this library (structures),
including pointers and similar.

I've been thinking about what i will need to represent this lists in python.
I thought about creating an external python object, providing information
i get from the list in C structures which can be converted.

Basically, it are list of packages, which have several attributes (next,
prev, etc). But i don't know how to supply a proper list from the binding /
object written in C.

Any suggestions or hints about this?

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


Re: behavior difference for mutable and immutable variable in function definition

2007-05-05 Thread jianbing . chen
On May 4, 5:14 pm, Carsten Haese [EMAIL PROTECTED] wrote:
 On Fri, 2007-05-04 at 14:30 -0700, [EMAIL PROTECTED] wrote:
  Hi,

  Can anyone explain the following:

  Python 2.5 (r25:51908, Apr  9 2007, 11:27:23)
  [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2
  Type help, copyright, credits or license for more information.
   def foo():
  ... x = 2
  ...
   foo()
   def bar():
  ... x[2] = 2
  ...

   bar()
  Traceback (most recent call last):
File stdin, line 1, in module
File stdin, line 2, in bar
  NameError: global name 'x' is not defined

 x = 2 binds the name 'x' in foo's local namespace to the object '2'.
 For this, it doesn't matter whether the name 'x' was previously bound to
 anything.

 x[2] = 2 is a shorthand notation for the method call
 x.__setitem__(2,2). This requires the name 'x' to be bound to some
 object that has a __setitem__ method.

 -Carsten

This makes sense.

Thank you.

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


Re: How do I use the config parser?

2007-05-05 Thread Rob Williscroft
 wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

 Hi,
 I need a specific example. I have seen the docs, but I don't all the
 stuffs there.
 

 from ConfigParser import ConfigParser

 
 Now I want to know how to read a section, a section attribute's value,
 and to write thoses back after reading.
 

ConfigParser is derived from RawConfigParser, so you need
to look at RawConfigParser's docs here:

http://docs.python.org/lib/RawConfigParser-objects.html


Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I use the config parser?

2007-05-05 Thread Fuzzyman
On May 5, 8:13 pm, [EMAIL PROTECTED] wrote:
 Hi,
 I need a specific example. I have seen the docs, but I don't all the
 stuffs there.

 So basically, I need my config file to be created and read by my
 script.

 Here is a snippet

 # read old actions
 from ConfigParser import ConfigParser

 fp = open(makepath('App\qt_actions.conf'))
 configdict = ConfigParser()
 configdict.readfp(fp)

 Now I want to know how to read a section, a section attribute's value,
 and to write thoses back after reading.


You could do it simply with ConfigObj ( 
http://www.voidspace.org.uk/python/configobj.html
):

from configobj import ConfigObj

config = ConfigObj(filename)
section = config['Section Name']
value = section['value']



section['value'] = newValue
config.write()

All the best,


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


 Thanks


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


Re: Python regular expressions just ain't PCRE

2007-05-05 Thread [EMAIL PROTECTED]
Wiseman wrote:
 I'm kind of disappointed with the re regular expressions module. In
 particular, the lack of support for recursion ( (?R) or (?n) ) is a
 major drawback to me. There are so many great things that can be
 accomplished with regular expressions this way, such as validating a
 mathematical expression or parsing a language with nested parens,
 quoting or expressions.

-1 on this from me.  In the past 10 years as a professional
programmer, I've used the wierd extended regex features maybe 5
times total, whether it be in Perl or Python.  In contrast, I've had
to work around the slowness of PCRE-style engines by forking off  a
grep() or something similar practically every other month.  I think
it'd be far more valuable for most programmers if Python moved toward
dropping the extended semantics so that something one of the efficient
regex libraries (linked in a recent thread here on comp.lang.python)
could work with, and then added a parsing library to the standard
library for more complex jobs.  Alternatively, if the additional
memory used isn't huge we could consider having more intelligence in
the re compiler and having it choose between a smarter PCRE engine or
a faster regex engine based on the input.  The latter is something I'm
playing with a patch for that I hope to get into a useful state for
discussion soon.

But regexes are one area where speed very often makes the difference
between whether they're usable or not, and that's far more often been
a limitation for me--and I'd think for most programmers--than any lack
in their current Python semantics.  So I'd rather see  that attacked
first.

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


Re: progress

2007-05-05 Thread half . italian
On May 5, 1:46 am, Merrigan [EMAIL PROTECTED] wrote:
 Hi All,

 I have posted yesterday about an ftplib issue, this has been resolved.

 I actually want to ask something here...

 The script that that ftplib error was from...I was wondering - What do
 I need to do to print the stats (speed/s, percentage done) of the
 upload that is running on the monitor.

 This script runs on a Fedora Machine.

 Thanx for the help guys!

  -- Merrigan

Looks like all you've got on the Python side is the size() method.
You could start a timer when the transfer begins, and then compare the
size on the server versus the size locally to get progress.

~Sean

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


Re: My newbie annoyances so far

2007-05-05 Thread igouy2
On Apr 27, 9:07 am, John Nagle [EMAIL PROTECTED] wrote:
 The CPython implementation is unreasonably slow compared
 to good implementations of other dynamic languages such
 as LISP and JavaScript.

Why do you say CPython is slower than JavaScript? Please provide
examples.

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


Re: Python regular expressions just ain't PCRE

2007-05-05 Thread John Machin
On May 6, 1:52 am, Wiseman [EMAIL PROTECTED] wrote:
 On May 5, 5:12 am, Terry Reedy [EMAIL PROTECTED] wrote:

  I believe the current Python re module was written to replace the Python
  wrapping of pcre in order to support unicode.

 I don't know how PCRE was back then, but right now it supports UTF-8
 Unicode patterns and strings, and Unicode character properties. Maybe
 it could be reintroduced into Python?

UTF-8 Unicode is meaningless. Python has internal unicode string
objects, with comprehensive support for converting to/from str (8-bit)
string objects. The re module supports unicode patterns and strings.
PCRE supports patterns and strings which are encoded in UTF-8. This
is quite different, a kludge, incomparable. Operations which inspect/
modify UTF-8-encoded data are of interest only to folk who are
constrained to use a language which has nothing resembling a proper
unicode datatype.


 At least today, PCRE supports recursion and recursion check,
 possessive quantifiers and once-only subpatterns (disables
 backtracking in a subpattern), callouts (user functions to call at
 given points), and other interesting, powerful features.

The more features are put into a regular expression module, the more
difficult it is to maintain and the more the patterns look like line
noise.

There's also the YAGNI factor; most folk would restrict using regular
expressions to simple grep-like functionality and data validation --
e.g. re.match([A-Z][A-Z]?[0-9]{6}[0-9A]$, idno). The few who want to
recognise yet another little language tend to reach for parsers, using
regular expressions only in the lexing phase.

If you really want to have PCRE functionality in Python, you have a
few options:
(1) create a wrapper for PCRE using e.g. SWIG or pyrex or hand-
crafting
(2) write a PEP, get it agreed, and add the functionality to the re
module
(3) wait until someone does (1) or (2) for free
(4) fund someone to do (1) or (2)

HTH,
John

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


Re: Cannot execute Windows commands via Python in 64-bit

2007-05-05 Thread Tim Roberts
minitotoro [EMAIL PROTECTED] wrote:

Upon further investigation it turned out to be a windohs 64-bit issue
(which is what I was afraid of). I did however find an asinine work
around.

Make a copy of defrag.exe from the system32 folder and paste it in the
same directory as the python script. Voila! It now works. Piece of
junk windohs... :-S

If you are using a 32-bit Python, then all references you make to
\windows\system32 are automatically rewritten to \windows\syswow64.  If
defrag.exe is not present in \windows\syswow64, that could explain it.

Unbelievable but true.  Although we were all smart enough to handle the
transition from \windows\system in Win16 to \windows\system32 in Win32,
Microsoft apparently believes programmers have all grown too stupid to
handle the transition to Win64 on our own.

Some registry references are also silently rewritten.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza  Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: change of random state when pyc created??

2007-05-05 Thread Alan Isaac
I have documented this behavior
 on two completely different systems
(Win 2000 and Win XP SP2), using Python 2.5.1.

It two modules where this happens,
as described before.
If it should not happen, there is a bug.
I am looking for potential explanation,
since I realize that finding bugs is unlikely.

Alan Isaac


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


Re: change of random state when pyc created??

2007-05-05 Thread John Machin
On May 6, 9:00 am, Alan Isaac [EMAIL PROTECTED] wrote:
 I have documented this behavior
  on two completely different systems
 (Win 2000 and Win XP SP2), using Python 2.5.1.

You can't say that you have documented the behaviour when you
haven't published  files that exhibit the alleged behaviour.

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


FIXED: [EMAIL PROTECTED]

2007-05-05 Thread Aahz
In article [EMAIL PROTECTED], Aahz [EMAIL PROTECTED] wrote:
In article [EMAIL PROTECTED],
Carsten Haese  [EMAIL PROTECTED] wrote:

I just tried sending an email to [EMAIL PROTECTED] to request a
website change, and the email bounced back with this excerpt from the
delivery failure report:

Oops!  I've informed the appropriate people.
For now, either hang on to your request or send it directly to me.
Thanks for letting us know!

Okay, anyone who was trying to send e-mail to the webmasters should try
again.
-- 
Aahz ([EMAIL PROTECTED])   * http://www.pythoncraft.com/

Look, it's your affair if you want to play with five people, but don't
go calling it doubles.  --John Cleese anticipates Usenet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with py2exe and microsoft speech SDK 5.1

2007-05-05 Thread [EMAIL PROTECTED]
Hi Dave,

I can't help you but  maybe  you'll have more luck if you try also the
dedicated py2exe mailing list:

https://lists.sourceforge.net/lists/listinfo/py2exe-users

francois

On May 4, 7:36 am, Dave Lim [EMAIL PROTECTED] wrote:
 On May 3, 1:29 pm, Dave Lim diband... at yahoo.com
 wrote:
  Hello, this is my first time in the mailing list so
  bear with me.

  Basically what I did was I followed this

 site:http://surguy.net/articles/speechrecognition.xml



  So I installed microsoft speech SDK 5.1 and then
 used
  pythonwin COM MakePy utility for it and it worked
 out
  fine. However, I need to compile my program into a
  .exe and I have no idea how to make this work. I
 tried
  using py2exe but I get the error:

  Traceback (most recent call last):
File simple-speech-recognition.py, line 57, in
 ?
  TypeError: Error when calling the metaclass bases
  cannot create 'NoneType' instances

  If anybody knows a good solution to this problem I
  would very much appreciate it if you can guide me
 to
  the right path / solution.

  Thank you very much!
  -Dave Lim

  __
  Do You Yahoo!?
  Tired of spam?  Yahoo! Mail has the best spam

 protection aroundhttp://mail.yahoo.com

 I've never done this, but I want to at some point, so
 I went and
 grabbed some good links on packaging up Python apps:

 http://davidf.sjsoft.com/mirrors/mcmillan-inc/install1.html
 http://www.pharscape.org/content/view/33/51/
 http://wiki.python.org/moin/Py2Exe
 http://www.py2exe.org/index.cgi/Tutorial

 There's also growth in using Python Eggs:

 http://peak.telecommunity.com/DevCenter/PythonEggs



 Mike

 Thanks for the links. But I already have compiled it
 successfully into an executable my only problem is i
 still have that error. I still have the same error:

  Traceback (most recent call last):
File simple-speech-recognition.py, line 57, in ?
  TypeError: Error when calling the metaclass bases
  cannot create 'NoneType' instances

 I used py2exe and I also added typelibs in the options
 however that didn't seem to fix my problem. Below is
 my setup.py, can anyone tell me what I'm lacking or
 doing wrong here?

 setup.py

 from distutils.core import setup
 import py2exe

 setup(options = {py2exe: {typelibs:
 [('{C866CA3A-32F7-11D2-9602-00C04F8EE628}',0,5,0)]}},
 console = [simple.py])

 Dave

 __
 Do You Yahoo!?
 Tired of spam?  Yahoo! Mail has the best spam protection 
 aroundhttp://mail.yahoo.com


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


Init style output with python?

2007-05-05 Thread Maxim Veksler
Hi list,

I'm working on writing sanity check script, and for aesthetic reasons
I would like the output be in the formatted like the gentoo init
script output, that is:

Check for something .. [OK]
Check for something else ..[FAIL]


Is there are frame work or something in python that would allow me to
do this (quickly) ?
If not, ideas how I should I be getting this boring task of:
1. get screen width
2. get output string length
3. get out status length
4. calculate space
5. print string, print space, print status, print newline

what happens if user changes textual terminal resolution ?

p.s.
I would also like to OK and FAIL output to be colored. I haven't
found anything for python to would allow to to output to ansi (linux,
rxvt, xterm). Here's a quick class I've written (in the hope it proves
to be useful to the next guy).


#!/usr/bin/env python
 This stuff is under GPL, as always

class ColorTerm:
def __init__(self, Mono = False):
pass

def __get_tput_color_value__(colorcode):
from commands import getoutput
return getoutput('tput setaf ' + colorcode)

BLACK_FG =  __get_tput_color_value__('0')
RED_FG =__get_tput_color_value__('1')
GREEN_FG =  __get_tput_color_value__('2')
YELLOW_FG = __get_tput_color_value__('3')
BLUE_FG =   __get_tput_color_value__('4')
MAGENTA_FG =__get_tput_color_value__('5')
CYAN_FG =   __get_tput_color_value__('6')
WHITE_FG =  __get_tput_color_value__('7')

def black(self, msg):
return self.BLACK_FG + msg + self.BLACK_FG

def red(self, msg):
return self.RED_FG + msg + self.BLACK_FG

def green(self, msg):
return self.GREEN_FG + msg + self.BLACK_FG

def yellow(self, msg):
return self.YELLOW_FG + msg + self.BLACK_FG

def blue(self, msg):
return self.BLUE_FG + msg + self.BLACK_FG

def magenta(self, msg):
return self.MAGENTA_FG + msg + self.BLACK_FG

def cyan(self, msg):
return self.CYAN_FG + msg + self.BLACK_FG

def white(self, msg):
return self.WHITE_FG + msg + self.BLACK_FG


cc = ColorTerm()
print cc.red('Cool!') + cc.yellow('?'), cc.green('Sure is!!!')
print Now setting your terminal text color to blue + cc.BLUE_FG
print well don't be blue about this, here let me set it back for you
print cc.BLACK_FG + see, nothing to worry about


-- 
Cheers,
Maxim Veksler

Free as in Freedom - Do u GNU ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: change of random state when pyc created??

2007-05-05 Thread Alan Isaac
John Machin [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 You can't say that you have documented the behaviour when you
 haven't published  files that exhibit the alleged behaviour.

Fine.  I have observed this behavior.
The files are not appropriate for posting.
I do not yet have a minimum case.
But surely I am not the first to notice this!
Alan Isaac
PS I'll send you the files off list.


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


Re: change of random state when pyc created??

2007-05-05 Thread John Machin
On May 5, 1:48 pm, Alan Isaac [EMAIL PROTECTED] wrote:
 This may seem very strange, but it is true.
 If I delete a .pyc file, my program executes with a different state!

 In a single directory I have
 module1 and module2.

 module1 imports random and MyClass from module2.

That's rather ambiguous. Do you mean
(a) module1 imports random and (MyClass from module2)
or
(b) module1 imports (random and MyClass) from module2

 module2 does not import random.

This statement would *appear* to rule out option (b) but appearances
can be deceptive :-)

It's a bit of a worry that you call the first file module1 and not
the_script. Does module2 import module1, directly or indirectly?


 module1 sets a seed like this::

 if __name__ == __main__:
 random.seed(314)
 main()

 I execute module1.py from the (Windows) shell.
 I get a result, let's call it result1.
 I execute it again. I get another result, say result2.
 Running it again and again, I get result2.

Stop right there. Never mind what happens when you delete module2.pyc.
Should you not expect to get the same result each time? Is that not
the point of setting a constant seed each time you run the script?
 Problem 1.


 Now I delete module2.pyc.
 I execute module1.py from the shell.
 I get result1.
 I execute it again; I get result2.
 From then on I get result2,
 unless I delete module.pyc again,
 in which case I once again get result1.

 Can someone explain this to me?

 Thank you,
 Alan Isaac

Compiling module2 is causing code to be executed that probably
shouldn't be executed. === Problem 2.

With all due respect to your powers of description :-) no, it can't be
explained properly, without seeing the contents of the source files. I
strongly suggest that if you continue to experience Problem1 and/or
Problem 2, you cut your two files down to the bare minima and post
them here.

Meanwhile,  my deja-vu detector is kicking in ...

uh-huh (1), from 25 April:
===
%  test2.py  %
from random import seed
seed(314)
class Trivial:
pass
===
Is module2 (still) doing that?
Is module1 importing itself (directly or indirectly)?

uh-huh (2), the long thread about relative imports allegedly being
broken ...

It appears to me that you need to divorce the two concepts module
and script in your mind.

Modules when executed should produce only exportables: classes,
functions, NAMED_CONSTANTS, etc. It is OK to do things like process
the easier-to-create
_ds = \
foo 1
bar 42
zot 666
into the easier-to-use
USEFUL_DICT = {'foo': 1, 'bar': 42, zot: 666}
but not to change global state.

Scripts which use functions etc from a module or package should be
independent of the module/package such that they don't need anything
more complicated than simple importing of the module/package. The
notion of inspecting the script's path to derive the module/package
path and then stuffing that into sys.paths is mind boggling. Are
module1/script1 and module2 parts of a package?

Here's a suggestion for how you should structure scripts:

def main():
# All productive code is inside a function to take advantage
# of access to locals being faster than access to globals
import mymodule
mymodule.do_something()
if __name__ == __main__:
main()
else:
raise Exception(Attempt to import script containing nothing
importable)

and your modules should *start* with:
if __name__ == __main__:
raise Exception(Attempt to execute hopefully-pure module as a
script)

HTH,
John

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


Re: High resolution sleep (Linux)

2007-05-05 Thread Tim Roberts
John [EMAIL PROTECTED] wrote:

The table below shows the execution time for this code snippet as
measured by the unix command `time':

for i in range(1000):
   time.sleep(inter)

inter   execution time  ideal
0 0.02 s0 s
1e-44.29 s0.1 s
1e-34.02 s1 s
2e-34.02 s2 s
5e-38.02 s5 s

Hence it seems like the 4 s is just overhead and that the time.sleep
method treats values below approximately 0.001 as 0.

Is there a standard way (or slick trick) to get higher resolution? If
it is system dependent it's acceptable but not very nice :)

Consider what you're asking here.  The operating system can only age the
timer list and re-evaluate process ready states when a process goes into
kernel mode, either by releasing the CPU or hitting the end of its time
slice.  In order to know that a process has reached the end of its time
slice, it has to be interrupted by something, typically the timer
interrupt.

In order to provide 10us sleep resolution, the timer interrupt would have
to fire every 10us.  The overhead of handling the timer interrupt and
rescheduling that often is quite significant.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza  Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Init style output with python?

2007-05-05 Thread John Machin
On May 6, 9:27 am, Maxim Veksler [EMAIL PROTECTED] wrote:
 Hi list,

 I'm working on writing sanity check script, and for aesthetic reasons
 I would like the output be in the formatted like the gentoo init
 script output, that is:
 
 Check for something .. [OK]
 Check for something else ..[FAIL]
 

 Is there are frame work or something in python that would allow me to
 do this (quickly) ?
 If not, ideas how I should I be getting this boring task of:
 1. get screen width

Is it not (a) safe (b) sensible to assume a minimum width (say 79) and
avoid the whole question of determining the terminal width?

 2. get output string length
 3. get out status length
 4. calculate space
 5. print string, print space, print status, print newline

Surely you don't need assistance with steps 2 - 5 ...

 what happens if user changes textual terminal resolution ?

Something rather unaesthetic, I imagine.

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


Re: FIXED: [EMAIL PROTECTED]

2007-05-05 Thread John Machin
On 6/05/2007 9:11 AM, Aahz wrote:
 In article [EMAIL PROTECTED], Aahz [EMAIL PROTECTED] wrote:
 In article [EMAIL PROTECTED],
 Carsten Haese  [EMAIL PROTECTED] wrote:
 I just tried sending an email to [EMAIL PROTECTED] to request a
 website change, and the email bounced back with this excerpt from the
 delivery failure report:
 Oops!  I've informed the appropriate people.
 For now, either hang on to your request or send it directly to me.
 Thanks for letting us know!
 
 Okay, anyone who was trying to send e-mail to the webmasters should try
 again.

uh-huh, but PyPI search doesn't return,
and PyPI browse cops this:

Error...

There's been a problem with your request

psycopg.ProgrammingError: ERROR:  could not serialize access due to 
concurrent update

delete from browse_tally

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


Re: change of random state when pyc created??

2007-05-05 Thread Alan Isaac
John Machin [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 (a) module1 imports random and (MyClass from module2)

Right.

 It's a bit of a worry that you call the first file module1 and not
 the_script. Does module2 import module1, directly or indirectly?

No.
I call a module any file meant to be imported by others.
Many of my modules include a main function,
which allow the module to be executed as a script.
I do not think this is unusual, even as terminology.


 Should you not expect to get the same result each time? Is that not
 the point of setting a constant seed each time you run the script?

Yes.  That is the problem.
If I delete module2.pyc,
I do not get the same result.

 With all due respect to your powers of description :-) no, it can't be
 explained properly, without seeing the contents of the source files.

I sent them to you.
What behavior did you see?
 from random import seed
 seed(314)
 class Trivial:
 pass
 ===
 Is module2 ... doing that?
 Is module1 importing itself (directly or indirectly)?

No.

Separate issue
==

 Here's a suggestion for how you should structure scripts:

 def main():
 # All productive code is inside a function to take advantage
 # of access to locals being faster than access to globals
 import mymodule
 mymodule.do_something()
 if __name__ == __main__:
 main()
 else:
 raise Exception(Attempt to import script containing nothing
 importable)

 and your modules should *start* with:
 if __name__ == __main__:
 raise Exception(Attempt to execute hopefully-pure module as a
 script)

I'm not going to call this a bad practice, since it has clear virtues.
I will say that it does not seem to be a common practice, although that
may be my lack of exposure to other's code.  And it still does not
address the common need of playing with a package in progress
or a package under consideration without installing it.

Cheers,
Alan Isaac



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


module console

2007-05-05 Thread castironpi
Can I get the console to behave like it's in a module?

So far I have inspect.getsource() working by setting the filename and
linenumbers of the return from compiler.parse().  I'm looking too.  -me

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


Re: Problem with inspect.getfile

2007-05-05 Thread Gabriel Genellina
En Wed, 02 May 2007 11:46:29 -0300, elventear [EMAIL PROTECTED]  
escribió:

 On May 2, 1:12 am, Gabriel Genellina [EMAIL PROTECTED] wrote:
 En Wed, 02 May 2007 02:53:55 -0300, elventear [EMAIL PROTECTED]
 escribió:

  Found the offending code. I was importing between files that were at
  the same level of the hierarchy without using absolute references.
  Coded worked fine, but inspect didn't. Was this gaffe on my part? Or
  was inspect supposed to handle it?

 Could you provide an example?

 Simple example

 My PYTHONPATH points to /python

 I have the following:

 /python/packages
 __init.py__
 /containers
 __init.py__
 module1.py
 module2.py

 So basically module2 depends on module1. So within module2.py I was I
 was doing import module1 instead of import
 packages.containers.module1. My code ran ok, but the functions in
 the inspect module weren't able to handle it (getfile was the source
 of the problem).

I tried it with Python 2.5 on Windows XP and couldn't make it fail.  
Perhaps it is specific to the Mac, or perhaps it depends on other details  
like __init__.py contents, order of imports, or how specifically you  
import things.

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


Re: change of random state when pyc created??

2007-05-05 Thread Dustan
On May 5, 6:30 pm, Alan Isaac [EMAIL PROTECTED] wrote:
 John Machin [EMAIL PROTECTED] wrote in message

 news:[EMAIL PROTECTED]

  You can't say that you have documented the behaviour when you
  haven't published  files that exhibit the alleged behaviour.

 Fine.  I have observed this behavior.
 The files are not appropriate for posting.
 I do not yet have a minimum case.
 But surely I am not the first to notice this!
 Alan Isaac
 PS I'll send you the files off list.

I got the files and tested them, and indeed got different results
depending on whether or not there was a pyc file. I haven't looked at
the source files in great detail yet, but I will. I would certainly
agree that there's a bug going on here; we just need to narrow down
the problem (ie come up with a minimum case).

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


Re: module console

2007-05-05 Thread castironpi
On May 5, 7:29 pm, [EMAIL PROTECTED] wrote:
 Can I get the console to behave like it's in a module?

 So far I have inspect.getsource() working by setting the filename and
 linenumbers of the return from compiler.parse().  I'm looking too.  -me

This at least gets a instance loaded; we'll see.
import imp
m=imp.new_module('aname')
class A: pass

m.A=A

from pickle import *
m.A.__module__='aname'
import sys
sys.modules['aname']=m
a=m.A()
loads(dumps(a))
#fb: aname.A instance at 0x00B4F148

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


Re: Python regular expressions just ain't PCRE

2007-05-05 Thread Wiseman
On May 5, 6:28 pm, [EMAIL PROTECTED] wrote:

 I'm not sure what your skill level is, but I would suggest studying the
 code, starting in on a patch for one or more of these features, and then
 corresponding with the module's maintainers to improve your patch to the
 point where it can be accepted.

I'll consider creating a new PCRE module for Python that uses the
latest version PCRE library. It'll depend on my time availability, but
I can write Python extensions, and I haven't used PCRE in a long time,
and I recall it was a bit of a hassle, but I could get it done.

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


Re: Python regular expressions just ain't PCRE

2007-05-05 Thread Wiseman
On May 5, 10:06 pm, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 -1 on this from me.  In the past 10 years as a professional
 programmer, I've used the wierd extended regex features maybe 5
 times total, whether it be in Perl or Python.  In contrast, I've had
 to work around the slowness of PCRE-style engines by forking off  a
 grep() or something similar practically every other month.

I use these complex features every month on my job, and performance is
rarely an issue, at least for our particular application of PCRE.

By the way, if you're concerned about performance, you should be
interested on once-only subpatterns.


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


Re: Python regular expressions just ain't PCRE

2007-05-05 Thread Wiseman
On May 5, 10:44 pm, John Machin [EMAIL PROTECTED] wrote:
 UTF-8 Unicode is meaningless. Python has internal unicode string
 objects, with comprehensive support for converting to/from str (8-bit)
 string objects. The re module supports unicode patterns and strings.
 PCRE supports patterns and strings which are encoded in UTF-8. This
 is quite different, a kludge, incomparable. Operations which inspect/
 modify UTF-8-encoded data are of interest only to folk who are
 constrained to use a language which has nothing resembling a proper
 unicode datatype.

Sure, I know it's a mediocre support for Unicode for an application,
but we're not talking an application here. If I get the PCRE module
done, I'll just PyArg_ParseTuple(args, et#, utf-8, str, len),
which will be fine for Python's Unicode support and what PCRE does,
and I won't have to deal with this string at all so I couldn't care
less how it's encoded and if I have proper Unicode support in C or
not. (I'm unsure of how Pyrex or SWIG would treat this so I'll just
hand-craft it. It's not like it would be complex; most of the magic
will be pure C, dealing with PCRE's API.)

 There's also the YAGNI factor; most folk would restrict using regular
 expressions to simple grep-like functionality and data validation --
 e.g. re.match([A-Z][A-Z]?[0-9]{6}[0-9A]$, idno). The few who want to
 recognise yet another little language tend to reach for parsers, using
 regular expressions only in the lexing phase.

Well, I find these features very useful. I've used a complex, LALR
parser to parse complex grammars, but I've solved many problems with
just the PCRE lib. Either way seeing nobody's interested on these
features, I'll see if I can expose PCRE to Python myself; it sounds
like the fairest solution because it doesn't even deal with the re
module - you can do whatever you want with it (though I'd rather have
it stay as it is or enhance it), and I'll still have PCRE. That's if I
find the time to do it though, even having no life.

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


Re: File names and file objects [was Re: My Python annoyances]

2007-05-05 Thread Alex Martelli
Steven D'Aprano [EMAIL PROTECTED] wrote:
   ...
 What do people think about functions that accept either a file name or a
 file object?
 
 def handle_file(obj):
 if type(obj) == str:
 need_to_close = True
 obj = file(obj, 'r')
 else: 
 need_to_close = False
 do_something_with(obj.read())
 if need_to_close:
 data.close()
 
 Good idea? Bad idea? Just a matter of personal preference?

Acceptable as an idea, but a disaster in terms of this specific
implementation (as coded, it would reject a Unicode string, or any other
string-like object, for example).  Also, if all you're going to do with
the file is .read() it in one big gulp, there's no real advantage to
this approach, either.

Assuming the way you're going to use the file-like object is subtler
(e.g., loop line by line so that huge files can be processed without
overwhelming memory), then a better implementation may be warranted:

def handle_file(file_or_path):
try:
f = open(file_or_path)
finis = f.close
except TypeError:
f = file_or_path
def finis(): pass
try:
for line in f:
...
finally:
finis()

This version accepts anything that open is happy with, or else any
sequence of lines, including but not limited to a file or file-like
object open for reading.  Now this, it seems to me, is a helpful
approach to polymorphism.


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


Weekly Python Patch/Bug Summary

2007-05-05 Thread Kurt B. Kaiser
Patch / Bug Summary
___

Patches :  360 open ( +4) /  3760 closed ( +4) /  4120 total ( +8)
Bugs:  971 open ( +3) /  6683 closed (+10) /  7654 total (+13)
RFE :  257 open ( +3) /   282 closed ( +0) /   539 total ( +3)

New / Reopened Patches
__

test_1686475 of test_os  pagefile.sys   (2007-04-28)
   http://python.org/sf/1709112  opened by  A.B., Khalid

run test_1565150(test_os.py) only on NTFS  (2007-04-29)
   http://python.org/sf/1709599  opened by  Hirokazu Yamamoto

Update locale.__all__  (2007-04-30)
CLOSED http://python.org/sf/1710352  opened by  Humberto Diógenes

PEP 318 -- add resolution and XRef  (2007-05-01)
CLOSED http://python.org/sf/1710853  opened by  Jim Jewett

PEP 3132: extended unpacking  (2007-05-02)
   http://python.org/sf/1711529  opened by  Georg Brandl

syslog syscall support for SysLogLogger  (2007-05-02)
   http://python.org/sf/1711603  opened by  Luke-Jr

fix for bug 1712742  (2007-05-04)
   http://python.org/sf/1713041  opened by  Raghuram Devarakonda

Fix warnings related to PyLong_FromVoidPtr  (2007-05-05)
   http://python.org/sf/1713234  opened by  Hirokazu Yamamoto

Patches Closed
__

Picky floats  (2006-04-28)
   http://python.org/sf/1478364  closed by  loewis

Update locale.__all__  (2007-05-01)
   http://python.org/sf/1710352  closed by  gbrandl

Use MoveFileEx() to implement os.rename() on windows  (2007-04-20)
   http://python.org/sf/1704547  closed by  loewis

PEP 318 -- add resolution and XRef  (2007-05-01)
   http://python.org/sf/1710853  closed by  gbrandl

New / Reopened Bugs
___

test_1686475 fails when pagefile.sys does not exist  (2007-04-28)
CLOSED http://python.org/sf/1709282  opened by  Calvin Spealman

test_1686475 fails because pagefile.sys does not exist  (2007-04-28)
   http://python.org/sf/1709284  opened by  Calvin Spealman

struct.calcsize() incorrect  (2007-04-29)
CLOSED http://python.org/sf/1709506  opened by  JoelBondurant

Tutorial - Section 8.3 - type 'instance'  (2007-04-30)
CLOSED http://python.org/sf/1710295  opened by  elrond79

zipfile.ZipFile behavior inconsistent.  (2007-05-01)
   http://python.org/sf/1710703  opened by  Mark Flacy

Ctrl+Shift block marking by words  (2007-05-01)
   http://python.org/sf/1710718  opened by  zorkin

subprocess must escape redirection characters under win32  (2007-05-01)
CLOSED http://python.org/sf/1710802  opened by  Patrick Mézard

CGIHttpServer leaves traces of previous requests in env  (2007-05-03)
   http://python.org/sf/1711605  opened by  Steve Cassidy

CGIHttpServer fails if python exe has spaces  (2007-05-03)
   http://python.org/sf/1711608  opened by  Steve Cassidy

SequenceMatcher bug with insert/delete block after replace  (2007-05-03)
   http://python.org/sf/1711800  opened by  Christian Hammond

__getslice__ changes integer arguments  (2007-05-03)
   http://python.org/sf/1712236  opened by  Imri Goldberg

Cannot use dict with unicode keys as keyword arguments  (2007-05-04)
   http://python.org/sf/1712419  opened by  Viktor Ferenczi

urllib.quote throws exception on Unicode URL  (2007-05-04)
   http://python.org/sf/1712522  opened by  John Nagle

pprint handles depth argument incorrectly  (2007-05-04)
   http://python.org/sf/1712742  opened by  Dmitrii Tisnek

character set in Japanese on Ubuntu distribution  (2007-05-04)
   http://python.org/sf/1713252  opened by  Christopher Grell

Error inside logging module's documentation  (2007-05-05)
CLOSED http://python.org/sf/1713535  opened by  billiejoex

Bugs Closed
___

TimedRotatingFileHandler's doRollover opens file in w mode  (2007-04-27)
   http://python.org/sf/1708538  closed by  vsajip

test_1686475 fails when pagefile.sys does not exist  (2007-04-28)
   http://python.org/sf/1709282  deleted by  ironfroggy

struct.calcsize() incorrect  (2007-04-29)
   http://python.org/sf/1709506  closed by  loewis

Tutorial - Section 8.3 - type 'instance'  (2007-04-30)
   http://python.org/sf/1710295  closed by  gbrandl

Portability issue: os.rename behaves differently on win32  (2007-04-03)
   http://python.org/sf/1693753  closed by  loewis

subprocess must escape redirection characters under win32  (2007-05-01)
   http://python.org/sf/1710802  closed by  astrand

Bypassing __dict__ readonlyness  (2005-09-24)
   http://python.org/sf/1303614  closed by  arigo

subclassing ModuleType and another built-in type  (2005-04-01)
   http://python.org/sf/1174712  closed by  arigo

Error inside logging module documentation  (2007-05-05)
   http://python.org/sf/1713535  closed by  gbrandl

New / Reopened RFE
__

commands module  (2007-05-05)
   http://python.org/sf/1713624  opened by  Joseph Armbruster

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


Emacs and pdb after upgrading to Ubuntu Feisty

2007-05-05 Thread levander
I've been using pdb under emacs on an Ubuntu box to debug python
programs.  I just upgraded from Ubuntu Edgy to Feisty and this combo
has stopped working.  Python is at 2.5.1 now, and emacs is at 21.41.1.

It used to be I could just M-x pdb RET pdb script-name RET and be
presented with a prompt where I could debug my script, as well as an
arrow in another source code buffer indicating where I am in the
source code.

Now however, when I do M-x pdb RET pdb ~/grabbers/npr-grabber.py -s
WESUN, I get this is in a buffer called *gud*:

Current directory is /home/levander/grabbers/

No prompt or anything follows it, just that one line.  It doesn't pop
up an arrow in the other buffer either.  None of the regular commands
like 'n', 's', or 'l' do anything here.  So, I did a 'Ctrl-C' and got:

 /home/levander/grabbers/npr-grabber.py(24)module()
- 
(Pdb)  /home/levander/grabbers/npr-grabber.py(30)module()
- import getopt
(Pdb) Traceback (most recent call last):
  File /usr/bin/pdb, line 1213, in main
pdb._runscript(mainpyfile)
  File /usr/bin/pdb, line 1138, in _runscript
self.run(statement, globals=globals_, locals=locals_)
  File bdb.py, line 366, in run
exec cmd in globals, locals
  File string, line 1, in module
  File /home/levander/grabbers/npr-grabber.py, line 30, in module
import getopt
  File /home/levander/grabbers/npr-grabber.py, line 30, in module
import getopt
  File bdb.py, line 48, in trace_dispatch
return self.dispatch_line(frame)
  File bdb.py, line 66, in dispatch_line
self.user_line(frame)
  File /usr/bin/pdb, line 144, in user_line
self.interaction(frame, None)
  File /usr/bin/pdb, line 187, in interaction
self.cmdloop()
  File cmd.py, line 130, in cmdloop
line = raw_input(self.prompt)
KeyboardInterrupt
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
 /home/levander/grabbers/cmd.py(151)cmdloop()
- pass
(Pdb)

It's wierd because at the bottom of that call stack, it does look like
it's wating for input, but no input works...  And, after I hit Ctrl-C
I do get a prompt as you see at the bottom of that listing just
above.  Now I type quit and get:

Post mortem debugger finished. The /home/cponder/grabbers/npr-
grabber.py will be restarted

Anybody can tell me who to get pdb working under emacs on Ubuntu
Feisty?

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


Re: My newbie annoyances so far

2007-05-05 Thread John Nagle
[EMAIL PROTECTED] wrote:
 On Apr 27, 9:07 am, John Nagle [EMAIL PROTECTED] wrote:
 
The CPython implementation is unreasonably slow compared
to good implementations of other dynamic languages such
as LISP and JavaScript.
 
 
 Why do you say CPython is slower than JavaScript? Please provide
 examples.

See

http://www.mozilla.org/projects/tamarin/faq.html

Tamarin is a just-in-time compiler for Javascript.

Franz LISP at one time held the speed record for LISP
implementations, being only slightly slower than C.

Python is generally considered to be about 60x slower
than C, which is about par for the course for a naive
byte code interpreter.

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


Re: change of random state when pyc created??

2007-05-05 Thread Steven D'Aprano
On Sun, 06 May 2007 00:20:04 +, Alan Isaac wrote:

 Should you not expect to get the same result each time? Is that not
 the point of setting a constant seed each time you run the script?
 
 Yes.  That is the problem.
 If I delete module2.pyc,
 I do not get the same result.


I think you have missed what John Machin is pointing out. According to
your original description, you get different results even if you DON'T
delete module2.pyc.

According to your original post, you get the _same_ behaviour the first
time you run the script, regardless of the pyc file being deleted or not.
You wrote:

[quote]
module1 sets a seed like this::

if __name__ == __main__:
random.seed(314)
main()

I execute module1.py from the (Windows) shell.
I get a result, let's call it result1.
I execute it again. I get another result, say result2.
Running it again and again, I get result2.
[end quote]

So, with module2.pyc file existing, you get result1 the first time you
execute module1.py, and then you get result2 every time from then onwards.

How is that different from what you wrote next?

[quote]
Now I delete module2.pyc.
I execute module1.py from the shell.
I get result1.
I execute it again; I get result2.
From then on I get result2,
unless I delete module.pyc again,
in which case I once again get result1.
[end quote]

You get the same behaviour with or without module2.pyc: the first run of
the script gives different results from subsequent runs. You can reset
that first run by deleting module2.pyc.

I'm still perplexed how this is possible, but now I'm more perplexed.

If you want to send me the modules, I will have a look at them as well.
Many eyes make for shallow bugs...



-- 
Steven.

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


[ python-Bugs-1713535 ] Error inside logging module's documentation

2007-05-05 Thread SourceForge.net
Bugs item #1713535, was opened at 2007-05-05 20:01
Message generated for change (Tracker Item Submitted) made by Item Submitter
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1713535group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: None
Group: None
Status: Open
Resolution: None
Priority: 5
Private: No
Submitted By: billiejoex (billiejoex)
Assigned to: Nobody/Anonymous (nobody)
Summary: Error inside logging module's documentation

Initial Comment:
http://docs.python.org/lib/module-logging.html

Inside the explanation of logging.debug an example code is showed:

 FORMAT = %(asctime)-15s %(clientip)s %(user)-8s %(message)s
 logging.basicConfig(format=FORMAT)
 dict = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
 logging.warning(Protocol problem: %s, connection reset, extra=d)


In the code dict is created but never used. 
When logging.warning is called the author use the argument 'd' instead of 
'dict' and no reference to 'd' exists:

 logging.warning(Protocol problem: %s, connection reset, extra=d)

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1713535group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1713535 ] Error inside logging module documentation

2007-05-05 Thread SourceForge.net
Bugs item #1713535, was opened at 2007-05-05 20:01
Message generated for change (Settings changed) made by billiejoex
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1713535group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: None
Group: None
Status: Open
Resolution: None
Priority: 1
Private: No
Submitted By: billiejoex (billiejoex)
Assigned to: Nobody/Anonymous (nobody)
Summary: Error inside logging module documentation

Initial Comment:
http://docs.python.org/lib/module-logging.html

Inside the explanation of logging.debug an example code is showed:

 FORMAT = %(asctime)-15s %(clientip)s %(user)-8s %(message)s
 logging.basicConfig(format=FORMAT)
 dict = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
 logging.warning(Protocol problem: %s, connection reset, extra=d)


In the code dict is created but never used. 
When logging.warning is called the author use the argument 'd' instead of 
'dict' and no reference to 'd' exists:

 logging.warning(Protocol problem: %s, connection reset, extra=d)

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1713535group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1713535 ] Error inside logging module documentation

2007-05-05 Thread SourceForge.net
Bugs item #1713535, was opened at 2007-05-05 20:01
Message generated for change (Settings changed) made by billiejoex
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1713535group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: None
Group: None
Status: Open
Resolution: None
Priority: 5
Private: No
Submitted By: billiejoex (billiejoex)
Assigned to: Nobody/Anonymous (nobody)
Summary: Error inside logging module documentation

Initial Comment:
http://docs.python.org/lib/module-logging.html

Inside the explanation of logging.debug an example code is showed:

 FORMAT = %(asctime)-15s %(clientip)s %(user)-8s %(message)s
 logging.basicConfig(format=FORMAT)
 dict = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
 logging.warning(Protocol problem: %s, connection reset, extra=d)


In the code dict is created but never used. 
When logging.warning is called the author use the argument 'd' instead of 
'dict' and no reference to 'd' exists:

 logging.warning(Protocol problem: %s, connection reset, extra=d)

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1713535group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1566331 ] Bad behaviour in ossaudio audio device.obuf*

2007-05-05 Thread SourceForge.net
Bugs item #1566331, was opened at 2006-09-27 13:19
Message generated for change (Comment added) made by rluse
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1566331group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Extension Modules
Group: Python 2.4
Status: Open
Resolution: None
Priority: 5
Private: No
Submitted By: Sam Dennis (samdennis)
Assigned to: Greg Ward (gward)
Summary: Bad behaviour in ossaudio audio device.obuf*

Initial Comment:
The _ssize() function in ossaudiodev.c (2.4.3, but it's
the same in svn) calls SNDCTL_SET_CHANNELS with
channels=0 as part of an attempt to determine the total
number of samples per second for the current
configuration of the audio device, but as far as I can
tell this is not guaranteed to act as a query and at
least two implementations treat it as a request for a
monaural format (the ALSA pcm-oss module and the
alsa-oss library).

What this can safely be replaced with I don't know;
both Linux's OSS drivers and ALSA support
SOUND_PCM_READ_CHANNELS but this is not standard to the
best of my knowledge.  Storing the value returned when
the program calls .setfmt or .setparameters may be an
option.

--

Comment By: Bob Luse (rluse)
Date: 2007-05-06 03:41

Message:
Logged In: YES 
user_id=1688601
Originator: NO

I just wanted to confirm that this is  problem for me as well when I run
this.  I am writing an application where I need to get buffer information
when I am running with 2 channels.  This is a quite normal situation these
days.  I assume that the change is made to mono because in OSS mono is the
default, so that it will work with what is now quite ancient hardware. 
But, requesting the buffer size should not cause such a dramatic error.  I
don't understand why this is such a problem.  Could there be a parameter
for number of channels since you cannot request the buffer size unless you
have already setup the hardware giving the number of channels?  So even if
the System cannot figure out the number of channels, your application knows
it and can tell it.  Granted, it is a kluge, but it is a kluge that can
work whereas currently whenever you request buffer information the speed of
your sound is cut in half making the obuf commands unusable.  Possibly
another solution would be to remove these commands until they work.  I did
notice that the program does reference SOUND_PCM_WRITE_CHANNELS.  Is
SOUND_PCM_WRITE_CHANNELS standard and SOUND_PCM_READ_CHANNELS not standard?
 I don't know that that is not true, but it does seem strange.  

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1566331group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1707768 ] os.path.normpath changes path (chops of trailing slash)

2007-05-05 Thread SourceForge.net
Bugs item #1707768, was opened at 2007-04-26 01:44
Message generated for change (Comment added) made by siemer
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1707768group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Python Library
Group: Python 2.5
Status: Open
Resolution: None
Priority: 5
Private: No
Submitted By: Robert Siemer (siemer)
Assigned to: Nobody/Anonymous (nobody)
Summary: os.path.normpath changes path (chops of trailing slash)

Initial Comment:
Hello everybody!

 os.path.normpath('/etc/passwd')
'/etc/passwd'


I don't know any environment at all where

a) '/etc/passwd/'
b) '/etc/passwd'

are treated the same. It clearly does not apply for the path part of http urls 
(this is left as an exercise for the reader).

But it also does not apply for (e.g.) Linux either:
an open() on path a) return ENOTDIR while it succeeds with b).

(assuming /etc/passwd is a file)

This is definitively not a documentation bug, as normpath should normalize a 
path and not fuck it up.


Robert

--

Comment By: Robert Siemer (siemer)
Date: 2007-05-06 06:15

Message:
Logged In: YES 
user_id=150699
Originator: YES

1) I (submitter) didn't specify what I expected to see:

os.path.normpath('/etc/passwd/') -- '/etc/passwd/'

So, I agree with the latest consensus, but definitely not with the
/etc/passwd/. version...


2) I can't draw any explicit normalization rules from the excerpts of the
POSIX standard posted by iszegedi. Saying that dir/ should be treated as
dir/. doesn't mean that it is the normalized version of the first one. -
I actually read implicitly that the first one is the habitual one that
needs interpretation.

And I think everybody agrees that - beeing the same or not - dir/. is
unusual.

3) I don't know what this is good for in the proposal:
path = path.rstrip()

It removes significant whitespace from the path, what must be avoided.

--

Comment By: Istvan Szegedi (iszegedi)
Date: 2007-05-01 20:05

Message:
Logged In: YES 
user_id=1772412
Originator: NO

I must admit that josm's comments make sense: in fact, I quickly tried out
how mkdir command from a bash shell would behave and it does the same:

# mkdir hello
# rmdir hello/. 
Invalid argument

whereas
# rmdir hello/

works fine. I also wrote a small C program using mkdir() and rmdir()
functions and they behave exactly the same as mkdir/rmdir from bash (well,
no real suprise).

My suggestion to get the original issue fixed was based on POSIX standard
and apparently the Linux commands are not fully POSIX compliant, either...
Or do I misunderstand the quotes from the standard?  Anyway, it is pretty
easy to modify my fix to be inline with Linux commands and C functions -
everything could be the same, apart from the last line where I added /. 
-- this should be only /.  So the entire function could look like this:

-- clip --


def normpath(path):
Normalize path, eliminating double slashes, etc.
if path == '':
return '.'
initial_slashes = path.startswith('/')
# The next two lines were added by iszegedi
path = path.rstrip()
trailing_slash = path.endswith('/')
# POSIX allows one or two initial slashes, but treats three or more
# as single slash.
if (initial_slashes and
path.startswith('//') and not path.startswith('///')):
initial_slashes = 2
comps = path.split('/')
new_comps = []
for comp in comps:
if comp in ('', '.'):
continue
if (comp != '..' or (not initial_slashes and not new_comps) or
 (new_comps and new_comps[-1] == '..')):
new_comps.append(comp)
elif new_comps:
new_comps.pop()
comps = new_comps
path = '/'.join(comps)
if initial_slashes:
path = '/'*initial_slashes + path
# The next two lines were added by iszegedi
if trailing_slash:
path = path + '/'
return path or '.'


-- clip --

Nevertheless, I would really appreciate to receive some comments from
POSIX gurus, how they see this problem.


--

Comment By: jos (josm)
Date: 2007-04-30 08:48

Message:
Logged In: YES 
user_id=1776568
Originator: NO

I think we should be careful enough to tackle on this.
iszegedi's patch seems to work correctly,
but XBD's spec itself has some defect.
http://www.opengroup.org/austin/mailarchives/ag-review/msg01722.html

What do you think of the follow behavior?
 os.mkdir('dir/')
 os.mkdir('dir2/')
 os.rmdir(os.path.normpath('dir'))
 os.rmdir(os.path.normpath('dir2/'))
Traceback (most recent call last):
  File stdin, line 1, in module
OSError: [Errno 22] Invalid argument: 'dir2/.'