ANN: HarvestMan 1.4.5 a2

2005-07-22 Thread Anand
I am glad to announce that the second alpha release of HarvestMan 1.4.5
version is available for download. The first alpha of version 1.4.5 was
released on May 27 2005.

 HarvestMan [http://harvestman.freezope.org] is a multithreaded web
crawler program written entirely in Python. It has many features which
allows you to highly customize your www crawling/offline downloading.
HarvestMan features as much as 60+ configuration options. Options are
configured using a custom XML configuration file.

Here are some changes for this release.

o Use of collections.deque data structure in critical places. This
  improves the performance of the program when run with Python 2.4 .
o Improved HTTP redirect handler to take care of redirect handling
  that requires cookies.
o A number of bug fixes to reduce invalid url (HTTP 404) errors.
o Code cleanup to rewrite exception handlers.
o Obsolte modules removed.

Complete changelog at http://harvestman.freezope.org
/files/Changelog.txt .

WWW: http://harvestman.freezope.org .

-Anand

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

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


SCF 1.2b1 released

2005-07-22 Thread Philippe C. Martin

I am very please to announce the release of SCF 1.2b1 a Smart Card
development system designed in Python:

Two major features are being introduced: 

1) Support for BasicCard DES/3/DES/AES secure messaging (Beta release 1) .

2) COM Support: access the power of SCF from Visual Basic or your favorite
Windows® language! SCF COM extension is provided as source code so
extensions can be applied by the programers.


SCF is available on www.snakecard.com for download and free testing. 
You may also browse the reference guide online.


Best regards,


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

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


PyGTK or wxPython (not a flame war) on Windows

2005-07-22 Thread TPJ
GUI's etc: PyGtk on Windows
(...) So if someone develops mainly for X and just wants to make sure
that it is not impossible to run on Windows, you can use PyGTK. (...),
July 2nd, 1999

pyGTK on Windows
(...)
 can i use pyGTK under
 Windows???

It's probably doable (...) but not worthy in my oppinion (...). A much
better choice is wxPython (...)

(...)even if it is made to work under windows, pygtk would not have a
windows look and feel.  wxPython is probably your best bet (...)

pygtk vs. wxPython
4. (...) If you want cross-platform capabilities (...) then go
wxWindows. May 17 2002

7. (...) The pygtk (and gtk port in general) does not yet support
threading on windows. (...) GTK 2.0 is supposed to fix it but support
isn't available *yet*. (...) May 17 2002

PyGTK vs. wxPython
7. (...) wxPython would indeed be a better choice if your applications
are only to run on a certain infamous legacy operating system from the
Pacific Northwest.  The PyGTK is a better choice if you are writing for
Linux and want your application to also be able to run on windows.
(...) Apr 25

11. (...) I'm using wxPython because GTK for windows wasn't ready
three years ago when I initially had to write my first Windows
application.  If I evaluated both of them again today, I might choose
GTK, and I might not. Apr 27



In the nearest future I will have to decide what to use: PyGTK or
wxPython. I like those both APIs. wxPython has more widgets, but PyGTK
seems to be faster. I can use them both for free (it's very important).
My only concern is that although I'm doing development on Linux, I'd
like to make my application runnable on Windows as well (Py2Exe). I'd
like to choose PyGTK (because of its rich documentation), but I'm not
sure if PyGTK is stable on Windows... For now I know that wxPython runs
well on Windows.

For now I haven't experienced any problems with wxPython on Linux
(Slackware, Aurox /Polish RH-like distro/). I used wxPython on Linux,
but I stopped because of its poor documentation (mainly C++ docs, not
Python docs). But recently I noticed this documentation got better
(*much* better!).

How well does PyGTK run on Windows (98, 2K, XP)? How stable is it? Will
I be able to make an executable (using Py2Exe) of an application that
uses PyGTK?

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


Re: PEP on path module for standard library

2005-07-22 Thread mkent
I really love Jason's 'path' module.  Sadly, I've encountered a serious
problem with using it.  When you try to 'freeze' an application module,
and Jason's 'path' module is present in any of the directories that are
looked at by freeze's module finder (your app doesn't have to import
it), freeze goes into an infinite loop of imports, eventually getting a
'maximum recursion depth' exception.  This seems to be related to
freeze getting confused between 'os.path' and Jason's 'path'.

I encountered this using Jason's latest 'path' module and Python 2.3.2.
 I was able to solve it for my use by renaming path.py to newpath.py
and using 'from newpath import path' in my modules.

I've just notified Jason about this.  I presume a solution like mine
will be used, and look forward to seeing Jason's module in stdlib.

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


Re: PyGTK or wxPython (not a flame war) on Windows

2005-07-22 Thread Sybren Stuvel
TPJ enlightened us with:
 I'd like to choose PyGTK (because of its rich documentation), but
 I'm not sure if PyGTK is stable on Windows... For now I know that
 wxPython runs well on Windows.

Don't forget that wxPython looks like Mac on a Mac. That's important
too :)

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython Fedora Core 4

2005-07-22 Thread Christophe Lambin
linuxfreak [EMAIL PROTECTED] wrote:

   Has anyone installed wxPython on Fedora Core 4. Apparently it need
 the libstdc++.so.5 file while Fedora installs the newer libstdc++.so.6
 file. I tried installing the libstdc rpm from fedora core 3

You can install compat-libstdc++-33 (part of FC4), which has
libstdc++.so.5.  However, since your wxPython package wasn't built for
FC4, you may run into other problems.

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


Re: PEP on path module for standard library

2005-07-22 Thread Stefan Rank
on 22.07.2005 00:21 Michael Hoffman said the following:
 Reinhold Birkenfeld wrote:
 
John Roth wrote:


Why did Guido want a PEP?

He said,


Whoa! Do we really need a completely different mechanism for doing the
same stuff we can already do? The path module seems mostly useful for
folks coming from Java who are used to the Java Path class.
   
 
 What is this Java Path class? I have been STFWing and have found nothing 
 on it in the. Indeed if you search for Java Path class (with quotes) 
 almost half of the pages are this message from Guido. ;)
 
 Any Java hackers here want to tell us of the wonders of the Java Path 
 class?

no such thing exists.

there is only the `File` class that incorporates a little bit of the 
`path` functionality and some of the python built-in `file` functionality.

my little self would actually propose to make *path* a built-in type as 
an intermediate between file and basestring/str/unicode (the latter is 
probably needed).

*ducks*

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


Re: Detecting computers on network

2005-07-22 Thread Sybren Stuvel
linuxfreak enlightened us with:
 How about sending an ICMP echo packet to your broadcast address and
 checking which hosts send a reply

Won't work on all boxes. Windows boxes ignore broadcast pings, for
example.

I'd go for a call to nmap -sP instead, and filter it's output.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython Fedora Core 4

2005-07-22 Thread Sybren Stuvel
linuxfreak enlightened us with:
 Has anyone installed wxPython on Fedora Core 4. Apparently it need
 the libstdc++.so.5 file while Fedora installs the newer
 libstdc++.so.6 [...] Fedora does not allow multiple versions of the
 same file.

Try Ubuntu Linux, which does allow having libstdc++.so.5 and .6
installed, on the same system, using the package manager.

Fedora _does_ allow multiple versions of that library, but apparently
not via it's package manager. Nobody is stopping you from getting the
file and putting it on your system.

You could also recompile the wxPython RPMs, so they link to your
version of the library.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Centering text in a wx.ListBox w/ wxPython

2005-07-22 Thread Franz Steinhaeusler
On 26 Jun 2005 22:34:31 -0700, fo [EMAIL PROTECTED] wrote:

How do I center each item in the ListBox widget?

Hm, I don't think, this is possilble.

Also, is it possible to change the color of the selected item? right
now it uses the OSes color. I would like it to be consistant on every
machine.
for example:
listbox.SetForegroundColour(wx.BLUE)

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


Re: Help with regexp please

2005-07-22 Thread Felix Collins
Christopher Subich wrote:
 Scott David Daniels wrote:
Thanks to you both.  Wow!  what a quick response!

 string.rsplit('.',1)[0]

Clever Python!  ;-)


Sorry, I mainly code in C so I'm not very Pythonic in my thinking.
Thanks again...

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


Re: Returning histogram-like data for items in a list

2005-07-22 Thread David Isaac

Ric Deez [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 I have a list:
 L1 = [1,1,1,2,2,3]
 How can I easily turn this into a list of tuples where the first element
 is the list element and the second is the number of times it occurs in
 the list (I think that this is referred to as a histogram):

For ease of reading (but not efficiency) I like:
hist = [(x,L1.count(x)) for x in set(L1)]
See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277600

Alan Isaac


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


Re: Software needed

2005-07-22 Thread David Isaac

niXin [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 Can anyone direct me to where I can find free software to do the
following:
 Document Management Software
 ---
 1. Written in PHP or Python
 2. scanning feature - where I can scan a document


http://furius.ca/nabu/ ?


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


wxPython Fedora Core 4

2005-07-22 Thread linuxfreak
Hi guys,

  Has anyone installed wxPython on Fedora Core 4. Apparently it need
the libstdc++.so.5 file while Fedora installs the newer libstdc++.so.6
file. I tried installing the libstdc rpm from fedora core 3 which would
have installed the required file but Fedora does not allow multiple
versions of the same file . Man   this is frustrating. Help desparately
required..


Thanks

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


Re: PEP on path module for standard library

2005-07-22 Thread Andrew Dalke
Michael Hoffman wrote:
 Having path descend from str/unicode is extremely useful since I can 
 then pass a path object to any function someone else wrote without 
 having to worry about whether they were checking for basestring. I think 
 there is a widely used pattern of accepting either a basestring[1] or a 
 file-like object as a function argument, and using isinstance() to 
 figure out which it is.

Reinhold Birkenfeld wrote:
 Where do you see that pattern? IIRC it's not in the stdlib.

Here's the first place that comes to mind for me

xml.sax.saxutils

def prepare_input_source(source, base = ):
This function takes an InputSource and an optional base URL and
returns a fully resolved InputSource object ready for reading.

if type(source) in _StringTypes:
source = xmlreader.InputSource(source)
elif hasattr(source, read):
f = source
source = xmlreader.InputSource()
source.setByteStream(f)
if hasattr(f, name):
source.setSystemId(f.name)


and xml.dom.pulldom

def parse(stream_or_string, parser=None, bufsize=None):
if bufsize is None:
bufsize = default_bufsize
if type(stream_or_string) in _StringTypes:
stream = open(stream_or_string)
else:
stream = stream_or_string
if not parser:
parser = xml.sax.make_parser()
return DOMEventStream(stream, parser, bufsize)

Using the power of grep

aifc.py
def __init__(self, f):
if type(f) == type(''):
f = __builtin__.open(f, 'rb')
# else, assume it is an open file object already
self.initfp(f)

binhex.py
class HexBin:
def __init__(self, ifp):
if type(ifp) == type(''):
ifp = open(ifp)

imghdr.py
if type(file) == type(''):
f = open(file, 'rb')
h = f.read(32)
else:
location = file.tell()
h = file.read(32)
file.seek(location)
f = None

mimify.py
if type(infile) == type(''):
ifile = open(infile)
if type(outfile) == type('') and infile == outfile:
import os
d, f = os.path.split(infile)
os.rename(infile, os.path.join(d, ',' + f))
else:
ifile = infile

wave.py
def __init__(self, f):
self._i_opened_the_file = None
if type(f) == type(''):
f = __builtin__.open(f, 'rb')
self._i_opened_the_file = f
# else, assume it is an open file object already
self.initfp(f)


compiler/transformer.py:

if type(file) == type(''):
file = open(file)
return self.parsesuite(file.read())

plat-mac/applesingle.py
if type(input) == type(''):
input = open(input, 'rb')
# Should we also test for FSSpecs or FSRefs?
header = input.read(AS_HEADER_LENGTH)

site-packages/ZODB/ExportImport.py
if file is None: file=TemporaryFile()
elif type(file) is StringType: file=open(file,'w+b')


site-packages/numarray/ndarray.py
if type(file) == type():
name = 1
file = open(file, 'wb')


site-packages/kiva/imaging/GdImageFile.py
if type(fp) == type():
import __builtin__
filename = fp
fp = __builtin__.open(fp, rb)
else:
filename = 

site-packages/reportlab/graphics/renderPM.py
   if type(image.path) is type(''):
im = _getImage().open(image.path).convert('RGB')
   else:
im = image.path.convert('RGB')


site-packages/twisted/protocols/irc.py
def __init__(self, file):
if type(file) is types.StringType:
self.file = open(file, 'r')

(hmm, that last one looks buggy.  It should
have a else: self.file = file afterwards.)


Used in the std. lib and used by many different
people.  (I excluded the Biopython libraries
in this list, btw, because I may have influenced
the use of this sort of type check.)

Andrew
[EMAIL PROTECTED]

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


Re: Help with regexp please

2005-07-22 Thread Christopher Subich
Scott David Daniels wrote:
 Felix Collins wrote:
 I have an outline number system like
 1
 1.2
 1.2.3
 I want to parse an outline number and return the parent.
 
 Seems to me regex is not the way to go:
 def parent(string):
 return string[: string.rindex('.')]

Absolutely, regex is the wrong solution for this problem.  I'd suggest 
using rsplit, though, since that will Do The Right Thing when a 
top-level outline number is passed:
def parent(string):
return string.rsplit('.',1)[0]

Your solution will throw an exception, which may or may not be the right 
behaviour.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Detecting computers on network

2005-07-22 Thread linuxfreak
How about sending an ICMP echo packet to your broadcast address and
checking which hosts send a reply

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


Re: How to limit the uploading file size in python?

2005-07-22 Thread Tim Roberts
praba kar [EMAIL PROTECTED] wrote:

   In Php we can limit the uploading file size
by php.ini configuration file. But In python what
way we can limit the file uploading size.
kindly let me know.

Unlike PHP, Python is a general-purpose language that is not targetted
specifically at the web, so it has no native concept of uploading.

You can do this by using the LimitRequestBody directive in your Apache
configuration or .htaccess file.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza  Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Stupid question: Making scripts python-scripts

2005-07-22 Thread bruno modulix
Jan Danielsson wrote:
 Hello all,
 
How do I make a python script actually a _python_ in unix:ish
 environments?
 
 I know about adding:
 #!/bin/sh
 
..as the first row in a shell script, but when I installed python on
 a NetBSD system, I didn't get a python executable; only a python2.4
 executable.
 
Adding #!/usr/pkg/bin/python2.4 as the first row in the script
 would probably work, but that would be too specific for the system I'm
 using, imho.

What about:

ln /usr/pkg/bin/python2.4 /usr/bin/python

then
#!/usr/bin/python

in your script, and you should be done (dont forget to chmod +x your
script of course)

Or I'm I missing something specific to xxxBSD ?

I saw someone using #!/usr/bin/env python, but that failed on the
 system I'm using, 

How do you execute the python interpreter ? If you need to type
python2.4 (not just python), then obviously 'usr/bin/env python'
syntax shouldn't work either.

My 2 cents
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Difference between and '

2005-07-22 Thread Michael Hoffman
Steven D'Aprano wrote:
 Michael Hoffman wrote:
 
 John Machin wrote:

 [EMAIL PROTECTED] wrote:

 Can someone tell me the difference between single quote and double
 quote?

   ord(') - ord('')
 5

 Very zen.
 
 But unfortunately incorrect, since the original poster didn't ask for 
 the difference between the ordinal values of the single quote and double 
 quote characters, but for the difference between the characters themselves.

It reminded me of a zen koan, because although it was a joke at the 
expense of original poster, the true answer was still contained within 
when the answerer had to use different kinds of quoting to quote single 
and double quotes.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web-Forms

2005-07-22 Thread Fuzzyman


Mike Meyer wrote:
 Mathias Waack [EMAIL PROTECTED] writes:

  Hi,
 
  I need to access some information from a web site which are only accessible
  through a form. Thus for each bucket of data you have to fill out the form,
  submit it and wait for an answer. Very easy - if you don't have to check
  some hundred times. Of course this site requires cookies, it is not
  directly accessible by URL and so on. All that nice stuff used to make a
  web site more professional;)
 
  But now the question: how can this be solved by using Python?

 urllib2 (in the standard library) for reading the data from the
 website. BeautifulSoup URL:
 http://www.crummy.com/software/BeautifulSoup/ for extracting data
 from the pages.



Adding ClientForm for automatically handling the forms and
ClientCookie/cookielib for automatic cookie handling.

Best Regards,

Fuzzy
http://www.voidspace.org.uk/python

mike

 --
 Mike Meyer [EMAIL PROTECTED]
 http://www.mired.org/home/mwm/
 Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

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


Re: PEP on path module for standard library

2005-07-22 Thread Michael Hoffman
Stefan Rank wrote:
 on 22.07.2005 00:21 Michael Hoffman said the following:
 Any Java hackers here want to tell us of the wonders of the Java Path 
 class?
 
 no such thing exists.
 
 there is only the `File` class that incorporates a little bit of the 
 `path` functionality and some of the python built-in `file` functionality.

Ah, here it is:

http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPythin installation woes

2005-07-22 Thread Martin Franklin
linuxfreak wrote:
 Hi all,
 
 Was working with python 2.3 in a fedora core 3 machine. I upgraded it
 to Fedora Core 4 with a clean install. So now I have python 2.4
 installed. But when I try to install wxPython for python 2.4 using an
 rpm file i downloaded from the wxpython web site i get dependencies
 errors. Turns out that  libstdc++.so.5 is needed but I checked and i
 see that libstdc++.so.6 is installed on my system. Help needed guys and
 needed pronto. Thanks a ton once again :)
 


I have fedora core 4 and a yum list wx* produces this:-

wxGTK.i386   2.4.2-12   extras
wxGTK-common.i3862.4.2-12   extras
wxGTK-common-devel.i386  2.4.2-12   extras
wxGTK-devel.i386 2.4.2-12   extras
wxGTK-gl.i3862.4.2-12   extras
wxGTK-stc.i386   2.4.2-12   extras
wxGTK-xrc.i386   2.4.2-12   extras
wxGTK2.i386  2.4.2-12   extras
wxGTK2-devel.i3862.4.2-12   extras
wxGTK2-gl.i386   2.4.2-12   extras
wxGTK2-stc.i386  2.4.2-12   extras
wxGTK2-xrc.i386  2.4.2-12   extras
wxPythonGTK2.i3862.4.2.4-7  extras


So I assume a

yum install wxPythonGTK2

will get you wxPython installed.

  *I havn't done that since I only use Tkinter*

Martin



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


Re: Lots of pdf files

2005-07-22 Thread Richie Hindle

[Duncan]
 a mere $29.90, except it is GPL'd so I'm not sure what the money is for

Tech support [...] free forever for registered users.

But I've often wondered whether you could charge for mass-market GPL software
simply because your ordinary punter doesn't know what the GPL is, and doesn't
mind paying a small amount of money for decent software.  Whether it's
ethical, given that presumably the thing is GPL because it inherits GPL code
from other developers, I don't know.  Certainly the GPL itself has no
objection to charging for binaries provided you ship the source as well.

-- 
Richie Hindle
[EMAIL PROTECTED]

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


Re: is this pythonic?

2005-07-22 Thread Caleb Hattingh
Terry

Yes, I must agree with you that it is something I should know.  I do try  
to keep with things but there are always some things that slip through the  
cracks, like enumerate, in this case.  That is why I am extremely grateful  
the for the activity, generosity and pure knowledge on this newsgroup to  
fill in the blanks for me.   It is guys like you who are willing to take  
the time to give responses that make it what it is.   In another  
newsgroup, I could have been flamed for letting Simon know he helped more  
than just the OP with his post :)

Thanks
Caleb


On Wed, 20 Jul 2005 23:41:36 +0200, Terry Reedy [EMAIL PROTECTED] wrote:


 Wow, I didn't know about enumerate.

 It is listed and explained in Lib Ref Manual, Chapter 2, on builtin
 functions and types and their methods.  Everyone should read at least  
 that
 much of the Lib manual.

 Terry J. Reedy




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


Re: Difference between and '

2005-07-22 Thread John Machin
[EMAIL PROTECTED] wrote:
 Hi,
 
 Can someone tell me the difference between single quote and double
 quote?


  ord(') - ord('')
5

or ask a meaningful question ...



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


Re: PEP on path module for standard library

2005-07-22 Thread Michael Hoffman
Reinhold Birkenfeld wrote:
 FYI: I modified the path module a bit so that it fits many of the suggestions
 from python-dev, and put the result in the Python CVS tree under
 nondist/sandbox/path.
 
 Most prominent change is that it doesn't inherit from str/unicode anymore.
 I found this distinction important, because as a str subclass the Path object
 has many methods that don't make sense for it.

Having path descend from str/unicode is extremely useful since I can 
then pass a path object to any function someone else wrote without 
having to worry about whether they were checking for basestring. I think 
there is a widely used pattern of accepting either a basestring[1] or a 
file-like object as a function argument, and using isinstance() to 
figure out which it is.

What do you gain from removing these methods? A smaller dir()?

[1] Probably str in actuality.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP on path module for standard library

2005-07-22 Thread Reinhold Birkenfeld
Michael Hoffman wrote:
 Reinhold Birkenfeld wrote:
 FYI: I modified the path module a bit so that it fits many of the suggestions
 from python-dev, and put the result in the Python CVS tree under
 nondist/sandbox/path.
 
 Most prominent change is that it doesn't inherit from str/unicode anymore.
 I found this distinction important, because as a str subclass the Path object
 has many methods that don't make sense for it.
 
 Having path descend from str/unicode is extremely useful since I can 
 then pass a path object to any function someone else wrote without 
 having to worry about whether they were checking for basestring. I think 
 there is a widely used pattern of accepting either a basestring[1] or a 
 file-like object as a function argument, and using isinstance() to 
 figure out which it is.

Where do you see that pattern? IIRC it's not in the stdlib.

 What do you gain from removing these methods? A smaller dir()?

It made sense to me at the time I changed this, although at the moment
I can't exactly recall the reasons.

Probably as Terry said: a path is both a list and a string.

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


Re: PEP on path module for standard library

2005-07-22 Thread Reinhold Birkenfeld
Michael Hoffman wrote:
 [EMAIL PROTECTED] wrote:
 I really love Jason's 'path' module.  Sadly, I've encountered a serious
 problem with using it.  When you try to 'freeze' an application module,
 and Jason's 'path' module is present in any of the directories that are
 looked at by freeze's module finder (your app doesn't have to import
 it), freeze goes into an infinite loop of imports, eventually getting a
 'maximum recursion depth' exception.  This seems to be related to
 freeze getting confused between 'os.path' and Jason's 'path'.
 
 I encountered this using Jason's latest 'path' module and Python 2.3.2.
  I was able to solve it for my use by renaming path.py to newpath.py
 and using 'from newpath import path' in my modules.
 
 I've just notified Jason about this.  I presume a solution like mine
 will be used, and look forward to seeing Jason's module in stdlib.
 
 This sounds like a bug in freeze rather than something that should be 
 worked around in the standard library. Although there have already been 
 people opposed to naming it path because the duplication with os.path 
 might confuse humans.

As the most likely placement will be a class named Path inside the os.path
module, that bug with freeze won't apply to the stdlib version of Path.

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


Re: PEP on path module for standard library

2005-07-22 Thread Reinhold Birkenfeld
John Roth wrote:
 Michael Hoffman [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]
 Many of you are familiar with Jason Orendorff's path module 
 http://www.jorendorff.com/articles/python/path/, which is frequently 
 recommended here on c.l.p. I submitted an RFE to add it to the Python 
 standard library, and Reinhold Birkenfeld started a discussion on it in 
 python-dev 
 http://mail.python.org/pipermail/python-dev/2005-June/054438.html.

 The upshot of the discussion was that many python-dev'ers wanted path 
 added to the stdlib, but Guido was not convinced and said it must have a 
 PEP.
 
 Why did Guido want a PEP? Is it because he likes the idea but
 feels the feature set needs to be examined a bit more by the wider
 community, or is it some other reason?

He said,


Whoa! Do we really need a completely different mechanism for doing the
same stuff we can already do? The path module seems mostly useful for
folks coming from Java who are used to the Java Path class. With the
massive duplication of functionality we should also consider what to
recommend for the future: will the old os.path module be deprecated,
or are we going to maintain both alternatives forever? (And what about
all the duplication with the os module itself, like the cwd()
constructor?) Remember TOOWTDI.


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


dictionary that discards old items

2005-07-22 Thread Will McGugan
Hi folks,

I need a collection class that behaves like a dictionary but when it 
reaches 'n' items it discards the oldest item so that the length never 
goes above 'n'. (Its for caching search results)

I have a vague memory of a module that does this, but I cant remember 
where I read about it. Can anyone enlighten me?


Regards,

Will McGugan

-- 
http://www.willmcgugan.com
.join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in 
jvyy*jvyyzpthtna^pbz)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dictionary that discards old items

2005-07-22 Thread Michael Hoffman
Will McGugan wrote:

 I need a collection class that behaves like a dictionary but when it 
 reaches 'n' items it discards the oldest item so that the length never 
 goes above 'n'. (Its for caching search results)
 
 I have a vague memory of a module that does this, but I cant remember 
 where I read about it. Can anyone enlighten me?

You want a Least Recently Used, or LRU, cache. Here's one:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252524

Google for LRU python to find others.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Couple quick questions from a Python Noob

2005-07-22 Thread digitalsubjunctive
Thanks you to.

Oh, and it is .pyw, you're right.

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


problem with string

2005-07-22 Thread Tzanko Tzanev
hi :)
I need some help for this script
I have

cursor = conn.cursor()
cursor.execute(select * from playlist limit 5)
result = cursor.fetchall()
# iterate through resultset
playlist_txt = ''
for record in result:
mp3id = record[0]
mp3_title = record[1]
mp3_artist = record[2]
playlist_txt += mp3id + mp3_title + mp3_artist
#print mp3id ,  - , mp3_title , ' - ', mp3_artist , br /
cursor.close()
conn.close()
--
#and want to print this out of for record in result:
print playlist_txt

#but there is an error in
playlist_txt += mp3id + mp3_title + mp3_artist

10x in advance :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: goto

2005-07-22 Thread Mike Meyer
Rocco Moretti [EMAIL PROTECTED] writes:

 My favorite infinte loop with while is:
i = 0
while i  20:
  do_process(i)
 Note the prominent *lack* of any change to i here?
 Oh, for:
 from i = 0
 invariant 0 = i = 20
 variant 21 - i
 until i  19
 loop
 do_process(i)
 which throws an exception at the beginning of the second loop.

 What language is that from?

Eiffel.

 I take it the exception is from the 21-i not changing as it goes
 around the loop, right? (But why can't variant i work just as well?)

Because that's the way variant is defined. You actually want the
variant to move in a specific direction, so that you don't wind up
incrementing it when you should be decrementing it. Eiffel chose down,
so you you need -i at the very least. It also insists that the
invariant be positive. I'm not sure why; it makes the variant more
complicated, resulting in exceptions from bugs in the variant as well
as bugs in the loop.

  mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating images with text in them

2005-07-22 Thread Mike Meyer
[EMAIL PROTECTED] (phil hunt) writes:
 On Thu, 21 Jul 2005 02:44:03 -0500, Terry Hancock [EMAIL PROTECTED] wrote:
While bitmap font files are not copyrightable, there are license issues
with most of the nicer fonts you are probably talking about.

 Oh? I can understand them being copyrighted; but if they are not 
 copywritable, what licnese issues are there? In any case, there 
 presumably are not license issues with the fonts that come with a 
 standard GNU/Linux distribution such as SuSE 9.1, which is what I am 
 using.

I haven't looked in a while; the situation may have changed.

The font files per se are copyrightable, and you may have licensing
issues if you want to give those away. The *output* from the font
files - the bitmaps that Terry mentions - are not copyrightable. You
are free to do whatever you want with the images you get from them,
including scan them all in and create a bitmapped font file, or scan
them in in multipe sizes and cons up a competing font.

 mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Returning histogram-like data for items in a list

2005-07-22 Thread Michael Hoffman
Ric Deez wrote:
 Hi there,
 
 I have a list:
 L1 = [1,1,1,2,2,3]
 
 How can I easily turn this into a list of tuples where the first element 
 is the list element and the second is the number of times it occurs in 
 the list (I think that this is referred to as a histogram):
 
 i.e.:
 
 L2 = [(1,3),(2,2),(3,1)]

  import itertools
  L1 = [1,1,1,2,2,3]
  L2 = [(key, len(list(group))) for key, group in itertools.groupby(L1)]
  L2
[(1, 3), (2, 2), (3, 1)]
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with string

2005-07-22 Thread John Machin
Tzanko Tzanev wrote:
 hi :)
 I need some help for this script
 I have
 
 cursor = conn.cursor()
 cursor.execute(select * from playlist limit 5)
 result = cursor.fetchall()
 # iterate through resultset
 playlist_txt = ''
 for record in result:
 mp3id = record[0]
 mp3_title = record[1]
 mp3_artist = record[2]
 playlist_txt += mp3id + mp3_title + mp3_artist
 #print mp3id ,  - , mp3_title , ' - ', mp3_artist , br /
 cursor.close()
 conn.close()
 --
 #and want to print this out of for record in result:
 print playlist_txt
 
 #but there is an error in
 playlist_txt += mp3id + mp3_title + mp3_artist

Have you considered doing print record at the appropriate place?

Care to tell us what the error message is, or is it a state secret that 
can be obtained only by hanging you by your extremities and inserting 
laxatives into your ears with firehoses?

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


Re: Returning histogram-like data for items in a list

2005-07-22 Thread George Sakkis
Michael Hoffman [EMAIL PROTECTED] wrote:

 Ric Deez wrote:
  Hi there,
 
  I have a list:
  L1 = [1,1,1,2,2,3]
 
  How can I easily turn this into a list of tuples where the first element
  is the list element and the second is the number of times it occurs in
  the list (I think that this is referred to as a histogram):
 
  i.e.:
 
  L2 = [(1,3),(2,2),(3,1)]

   import itertools
   L1 = [1,1,1,2,2,3]
   L2 = [(key, len(list(group))) for key, group in itertools.groupby(L1)]
   L2
 [(1, 3), (2, 2), (3, 1)]
 -- 
 Michael Hoffman

This is correct if the original list items are grouped together; to be on the 
safe side, sort it
first:
L2 = [(key, len(list(group))) for key, group in itertools.groupby(sorted(L1))]

Or if you care about performance rather than number of lines, use this:

def hist(seq):
h = {}
for i in seq:
try: h[i] += 1
except KeyError: h[i] = 1
return h.items()


George


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


Re: Stupid question: Making scripts python-scripts

2005-07-22 Thread Mike Meyer
Bill Mill [EMAIL PROTECTED] writes:

 On 7/21/05, Jan Danielsson [EMAIL PROTECTED] wrote:
 Hello all,
 
How do I make a python script actually a _python_ in unix:ish
 environments?
 
 I know about adding:
 #!/bin/sh
 
..as the first row in a shell script, but when I installed python on
 a NetBSD system, I didn't get a python executable; only a python2.4
 executable.
 
Adding #!/usr/pkg/bin/python2.4 as the first row in the script
 would probably work, but that would be too specific for the system I'm
 using, imho.
 
I saw someone using #!/usr/bin/env python, but that failed on the
 system I'm using, so I assume that's something specific too (or is the
 installation broken?).

 The env program [1], which usually exists at least on a linux system,
 executes the program given as its argument. Thus, /usr/bin/env
 python tries to executes python, which bash will then use to run the
 python script. As long as env exists, and python is somewhere in the
 PATH, this is a fairly portable way to run python scripts.

env doesn't invoke the shell, it uses execvp, which duplicates the
actions of the shell in searching for an executable. Further, he's on
NetBSD - he may not have bash installed. My FreeBSD box certainly
doesn't.

 Does BSD really not come with the env program? I bet there's an
 equivalent you could symlink to it. Unfortunately, I've never BSDed,
 so I can't help you find it. To get a workable subset of the normal
 env functionality, you could try (assuming you use bash):

NetBSD comes with an env. His env is failing because he doesn't have a
python command installed.

This appears to be wart(?) in the NetBSD packaging system. To allow
multiple versions of FreeBSD to coexist, it doesn't install a python
command at all, but instead leaves the versioned one around.

Two solutions: have your scripts use #!/usr/pkg/bin/python2.4. That
way, when you install a new python, they will keep using the old
one. That will insure they won't break when you upgrade.

However, such breakage is pretty rare in practice. I'd pick a favorite
bin directory and symlink from python there to /usr/pkg/bin/python2.4,
then use #!/usr/bin/env python in your scripts.

While I'm on the topic, I think I'll share my favorite cool trick.

  #!/usr/opt/bin/mypythonscript

Doesn't work because Unix won't let you use an interpreted script as
the interpreter (is this true for all variants?). However,

#!/usr/bin/env mypythonscript

works like a charm.

  mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP on path module for standard library

2005-07-22 Thread Neil Hodgson
Reinhold Birkenfeld:

 And it is much more Pythonic in my eyes. Though that word may be inaccurate
 when it comes from someone else that Guido, I feel that endless chains of
 '[os.path.join(os.path.join(z, a), x) for x in 
 os.path.listdir(os.path.join(z, a) if os.path.isfile(os.path.join(
 are not qualified as being Pythonic.

I like Path but the above is trying too hard to be poor code. 
os.path.join takes more than 2 arguments, so that should be
[os.path.join(z, a, x) for x in os.path.listdir(os.path.join(z, a) 
if os.path.isfile(os.path.join(

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


Returning histogram-like data for items in a list

2005-07-22 Thread Ric Deez
Hi there,

I have a list:
L1 = [1,1,1,2,2,3]

How can I easily turn this into a list of tuples where the first element 
is the list element and the second is the number of times it occurs in 
the list (I think that this is referred to as a histogram):

i.e.:

L2 = [(1,3),(2,2),(3,1)]

I was doing something like:

myDict = {}
for i in L1:
myDict.setdefault(i,[]).append(i)

then doing this:

L2 = []
for k, v in myDict.iteritems():
L2.append((k, len(v)))

This works but I sort of feel like there ought to be an easier way, 
rather than to have to store the list elements, when all I want is a 
count of them. Would anyone care to comment?

I also tried this trick, where locals()['_[1]'] refers to the list 
comprehension itself as it gets built, but it gave me unexpected results:

  L2 = [(i, len(i)) for i in L2 if not i in locals()['_[1]']]
  L2
[((1, 3), 2), ((2, 2), 2), ((3, 1), 2)]

i.e. I don't understand why each tuple is being counted as well.

Regards,

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


Re: PEP on path module for standard library

2005-07-22 Thread George Sakkis
John Roth [EMAIL PROTECTED] wrote:

 Reinhold Birkenfeld [EMAIL PROTECTED] wrote
  He said,
 
  
  Whoa! Do we really need a completely different mechanism for doing the
  same stuff we can already do? The path module seems mostly useful for
  folks coming from Java who are used to the Java Path class. With the
  massive duplication of functionality we should also consider what to
  recommend for the future: will the old os.path module be deprecated,
  or are we going to maintain both alternatives forever? (And what about
  all the duplication with the os module itself, like the cwd()
  constructor?) Remember TOOWTDI.
  

 Read literally, this says (at least to me) I don't want to fix it because
 I don't think it's broke.

Or rather I prefer a single existing mediocre solution than two solutions 
(even if the second was
better).

George


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


Re: problem with string

2005-07-22 Thread Bruno Desthuilliers
Tzanko Tzanev a écrit :
 hi :)
 I need some help for this script
 I have

please take care of indentation when posting code.

 
 cursor = conn.cursor()
 cursor.execute(select * from playlist limit 5)
 result = cursor.fetchall()
 # iterate through resultset
 playlist_txt = ''
 for record in result:
 mp3id = record[0]
 mp3_title = record[1]
 mp3_artist = record[2]
 playlist_txt += mp3id + mp3_title + mp3_artist

Err... what about:
  print br /\n.join([ - .join(record[:3]) for record in result])

or :
  for record in result:
print %s - %s - %s br / % tuple(record[:3])

Anyway, avoid string concatenation in loop, prefer appending to a list 
and then str.join():

  playlist = []
  for record in result:
playlist.append(record[0] + record[1] + record[2])
  print  \n.join(playlist)

Note that this is a very strange and complicated way to write:
  print \n.join([''.join(rec) for rec[:3] in result])

And, finally, if you just want to check what's in your resultset:
  print result

 #print mp3id ,  - , mp3_title , ' - ', mp3_artist , br /
 cursor.close()
 conn.close()

Since you're doing a fetchall(), you could (and should if you don't use 
em again) free your resources as soon as you've retrieved the resultset:

  cursor = conn.cursor()
  cursor.execute(select * from playlist limit 5)
  result = cursor.fetchall()
  cursor.close()
  conn.close()
  # now use the resultset...


 --
 #and want to print this out of for record in result:
 print playlist_txt
 
 #but there is an error in
 playlist_txt += mp3id + mp3_title + mp3_artist

Are we supposed to guess what the error is ? Sorry, I'm not psychic 
enough. Please post the full traceback.

(wild guess: mp3id is an integer ?)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Returning histogram-like data for items in a list

2005-07-22 Thread jeethu_rao
Adding to George's reply, if you want slightly more performance, you
can avoid the exception with something like

def hist(seq):
h = {}
for i in seq:
h[i] = h.get(i,0)+1
return h.items()

Jeethu Rao

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


Re: Difference between and '

2005-07-22 Thread Erik Max Francis
[EMAIL PROTECTED] wrote:

 Can someone tell me the difference between single quote and double
 quote?

One has double the fun.

-- 
Erik Max Francis  [EMAIL PROTECTED]  http://www.alcyone.com/max/
San Jose, CA, USA  37 20 N 121 53 W  AIM erikmaxfrancis
   Forgive your enemies, but never forget their names.
   -- John F. Kennedy
-- 
http://mail.python.org/mailman/listinfo/python-list


Help with regexp please

2005-07-22 Thread Felix Collins
Hi,
  I'm not a regexp expert and had a bit of trouble with the following 
search.

I have an outline number system like

1
1.2
1.2.3
1.3
2
3
3.1

etc.

I want to parse an outline number and return the parent.

So for example...

parent(1.2.3.4) returns 1.2.3

The only way I can figure is to do two searches feeding the output of 
the first into the input of the second.

Here is the code fragment...

m = re.compile(r'(\d+\.)+').match(1.2.3.4)
n = re.compile(r'\d+(\.\d+)+').match(m.string[m.start():m.end()])
parentoutlinenumber = n.string[n.start():n.end()]

parentoutlinenumber
1.2.3

How do I get that into one regexp?

Thanks for any help...

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


Re: dictionary that discards old items

2005-07-22 Thread Raymond Hettinger
[Will McGugan]
 I need a collection class that behaves like a dictionary but when it
 reaches 'n' items it discards the oldest item so that the length never
 goes above 'n'. (Its for caching search results)


import collections

class Cache(dict):
def __init__(self, n, *args, **kwds):
self.n = n
self.queue = collections.deque()
dict.__init__(self, *args, **kwds)
def __setitem__(self, k, v):
self.queue.append(k)
dict.__setitem__(self, k, v)
if len(self)  self.n:
oldk = self.queue.popleft()
del self[oldk]

#  . . .
# make similar modifications to setdefault, __delitem__, fromkeys
# and other mutating methods as needed

# Example
c = Cache(3)
for w in 'the quick brown fox jumped over the lazy dog'.split():
c[w] = w[:1].upper()
print repr(c)

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


Re: Help with regexp please

2005-07-22 Thread Scott David Daniels
Felix Collins wrote:
 Hi,
  I'm not a regexp expert and had a bit of trouble with the following search.
 I have an outline number system like
 1
 1.2
 1.2.3
 I want to parse an outline number and return the parent.

Seems to me regex is not the way to go:
 def parent(string):
 return string[: string.rindex('.')]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP on path module for standard library

2005-07-22 Thread Duncan Booth
George Sakkis wrote:

 Read literally, this says (at least to me) I don't want to fix it
 because I don't think it's broke.
 
 Or rather I prefer a single existing mediocre solution than two
 solutions (even if the second was better).
 
Except that he is open to persuasion, so the PEP has to demonstrate that 
the duplication is worth the benefit.

Personally I think the concept of a specific path type is a good one, but 
subclassing string just cries out to me as the wrong thing to do. In other 
words, to me a path represents something in a filesystem, the fact that it 
has one, or indeed several string representations does not mean that the 
path itself is simply a more specific type of string.

You should need an explicit call to convert a path to a string and that 
forces you when passing the path to something that requires a string to 
think whether you wanted the string relative, absolute, UNC, uri etc.

It may even be that we need a hierarchy of path classes: URLs need similar 
but not identical manipulations to file paths, so if we want to address the 
failings of os.path perhaps we should also look at the failings of urlparse 
at the same time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with string

2005-07-22 Thread Michael Hoffman
Tzanko Tzanev wrote:

 #but there is an error in
 playlist_txt += mp3id + mp3_title + mp3_artist

It'd be a lot easier to help if you'd say what the error was.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP on path module for standard library

2005-07-22 Thread Michael Hoffman
Duncan Booth wrote:

 You should need an explicit call to convert a path to a string and that 
 forces you when passing the path to something that requires a string to 
 think whether you wanted the string relative, absolute, UNC, uri etc.

Egad. I'm not sure if that will really make people's lives easier.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RegUnloadkey access denied

2005-07-22 Thread future_retro
I've worked out that I can open and close the key fine if I don't open
a subkey.  I've tried adding flush and close statements after opening
the key and still get access denied when trying to unload.

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


Re: httplib/HTTPS Post Problem

2005-07-22 Thread michaelparkin
Thanks for the replies, Andreas and Peter.

Andreas Kostyrka wrote:

snip

 Just a curious guess: Are you behind a proxy? If so, it's a known and
 never fixed bug from Python 1.5 times ;)

No, I'm not behind a proxy - the server is on the same PC as my client
(while I'm testing!).

 You might also try to use PyCurl.

I've quickly read about PyCurl, but it only seems to allow HTTP HEAD,
GET, POST and PUT methods - though please correct me if I'm wrong.

I'd like to use httpLib in Python as I also need the DELETE method and
the possibility of adding some extra headers and extra methods (I'm
working on something like this : http://sw.nokia.com/uriqa/URIQA.html
that allows MGET, MPUT, MPOST, etc.).

I've done some more testing and still can't work out why Python
operates differently to other http clients... any ideas?

Thanks,

Michael.

snip

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


Multithreaded class with queues

2005-07-22 Thread Antal Rutz
Hi!

I wrote a little class to make multihreading easier. It's based on one
of aahz's threading example scripts. What it does:

It spawns up number of CollectorThreads and one ProcessThread. The
CollectorThreads listen on one queue (inputqueue), read, process the
data (with colfunc), put the result onto the outputqueue. The
ProcessThread listens on the outputqueue, reads, processes (with
prfunc). end. (more details in the attached file)

it seems to work with test functions but when I use a network-intensive
function (snmp-queries) it just gets slower with maxThreads set to more
than 1.

Any help?
Thanks.
see the class attached.
ps. Maybe I basically don't understand something...

-- 


--arutz
#!/usr/local/bin/python


Multithreaded class for the task: multiple collector - one dataprocessor

Usage: 

collector = Collector(data, colfunc, prfunc, maxThreads)
collector.run()

Internals:

Collector spawns up the CollectorThreads and a ProcessThread and puts
the data onto the inputQueue. The CollectorThread reads the data from
inputQueue and processes it through 'colfunc()'.  Then puts
the result onto the outputQueue.  The ProcessThread only listens on the
outputQueue (blocks on it) and feeds the data to `prfunc()`.

Thread shutdown: collectorthreads: inputQueue.put(shutdown=True)
 processthread: outputQueue.put(shutdown=True)


import threading
import Queue
#from operator import truth as _truth

#def _xor(a,b):
#return _truth(a) ^ _truth(b)

class _Token:
def __init__(self, data=None, shutdown=None):
#if not _xor(data, shutdown):
#raise Tsk, tsk, need to set either URL or shutdown (not both)
self.data = data
self.shutdown = shutdown

class _CollectorThread(threading.Thread):
Worker thread blocking on inputQueue.
   The result goes to outputQueue after processed by self.func.


def __init__(self, inQueue, outQueue, func):
threading.Thread.__init__(self)
self.inQ = inQueue
self.outQ = outQueue
self.func = func

def run(self):
while True:
token = self.inQ.get()
if token.shutdown is not None:
break
else:
#collect data from the routers
#print token.data
result = self.func(token.data)
self.outQ.put_nowait(_Token(data=result))

class _ProcessThread(threading.Thread):
'Reader-only' thread processing outputQueue.

def __init__(self, outQueue, func):
threading.Thread.__init__(self)
self.outQ = outQueue
self.func = func

def run(self):
while True:
token = self.outQ.get()
if token.shutdown is not None:
break
else:
#insert into db or do anything
self.func(token.data)

class Collector:
Spawns up the threadpool (worker and processthreads)
   and puts tha data onto the inputQueue of the worker threads.
   Then shuts them down.

def __init__(self, data, colfunc, prfunc, maxThreads=5):
Parameters:
- data: data for collectfunc (type of sequence)
- colfunc: function to process inputQueue into outputQueue
- prfunc: function to process outputQueue
- maxThreads: MAX_THREADS


self.data = data
self.inputQueue = Queue.Queue()
self.outputQueue = Queue.Queue()
self.threadPool = []

#Start the worker threads
for i in range(maxThreads):
collector = _CollectorThread(self.inputQueue,
 self.outputQueue,
 colfunc)
collector.start()
self.threadPool.append(collector)

#Start the db thread
self.processthread = _ProcessThread(self.outputQueue, prfunc)
self.processthread.start()

def run(self):
Queue the data and shutdown the threads.
self._queueData()
self._shutdown()

def _queueData(self):
Put data onto the inputQueue.
for d in self.data:
self.inputQueue.put_nowait(_Token(data=d))

def _shutdown(self):
for i in self.threadPool:
self.inputQueue.put(_Token(shutdown=True))
for thread in self.threadPool:
thread.join()
self.outputQueue.put(_Token(shutdown=True))
self.processthread.join()

if __name__ == '__main__':
def myprint(s):
print s

def hashdata(a):
return a + ': OK'

MAX_THREADS = 5

data = ['1', '2', 'asd', 'qwe']
collect = Collector(data=data, colfunc=hashdata, prfunc=myprint, 
maxThreads=MAX_THREADS)
collect.run()

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

Re: PEP on path module for standard library

2005-07-22 Thread Thomas Heller
[EMAIL PROTECTED] writes:

 I really love Jason's 'path' module.  Sadly, I've encountered a serious
 problem with using it.  When you try to 'freeze' an application module,
 and Jason's 'path' module is present in any of the directories that are
 looked at by freeze's module finder (your app doesn't have to import
 it), freeze goes into an infinite loop of imports, eventually getting a
 'maximum recursion depth' exception.  This seems to be related to
 freeze getting confused between 'os.path' and Jason's 'path'.

 I encountered this using Jason's latest 'path' module and Python 2.3.2.
  I was able to solve it for my use by renaming path.py to newpath.py
 and using 'from newpath import path' in my modules.

 I've just notified Jason about this.  I presume a solution like mine
 will be used, and look forward to seeing Jason's module in stdlib.

That was a bug in modulefinder, which was fixed in Python 2.4 and 2.3.4.
See http://www.python.org/sf/876278.

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


Re: Web-Forms

2005-07-22 Thread Michele Simionato
Use twill:http://www.idyll.org/~t/www-tools/twill.html

Michele Simionato

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


Re: Detecting computers on network

2005-07-22 Thread Peter Tillotson
You could use a sniffer in promiscuous mode. pypcap -- or something 
like. This will record every packet seen by your network card. Whether 
is will work depends on whether you are on a true braodcast network.

if a box is on and completely inactive you'll never see it, but most 
boxes do something. Windows boxes positively shout about there presence :-)

baically this is pasive nmap, nmap will try to open a tcp or udp 
connection on every  machine. your going to generat a lot of traffic.

If you've got access to the boxes enabling ICMP and using that is the 
proper way.

Sandeep Arya wrote:
 Hello dear
 
 I had sent my earlier queries regarding same topic. However just to be 
 more specific this time..
 
 I just wann try to detect that if there are some ip address in a list of 
 some ip address alive or not.
 
 How can i do this?
 
 Shall i try to connect them and check that my connection is working or 
 not? If working than means alive  (connection based)
 
 SHalle i send some buffer value (whatever) to socket using sendto(...) 
 and then checking for return value? (Connectionless)
 
 Well for me it doesnot matter that i should have connection or 
 connectionless.. I just wannn  know who are alive in my LAN?
 
 This application will be for my computers in lan. not for maganetwork.
 
 LAN will have just some bridges and computers.
 
 i need to detect tham all..
 
 however i doesnot matter that all of them replies or not. I just wann 
 know that atleast some of them reply. Rest i will take care of...
 
 
 Sandeep
 
 _
 NRIs, does your family in India need money urgently? 
 http://creative.mediaturf.net/creatives/icicibank/ICICI_NRI_ERA.htm Open 
 an ICICI Bank NRI savings A/c
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Get directory from http web site

2005-07-22 Thread rock69
Hi all :)

I was wondering if there's some neat and easy way to get the entire
contents of a directory at a specific web url address.

I have the following link:

http://www.infomedia.it/immagini/riviste/covers/cp

and as you can see it's just a list containing all the files (images)
that I need. Is it possible to retrieve this list (not the physical
files) and have it stored in a variable of type list or something?

And, if so, what would be the easiest and most efficient way?

Thank you so much in advance.

Rock

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


Web frame systems vs. pure Python

2005-07-22 Thread Lad
I am thinking about a new project and I do not know if I should use
Python with HTML code only or use a web frame such as Cherry or a
similar ( which one then??) and a template system.
Can you please explain what I will get / lose if I use a web frame
system? 
Thanks a lot 
La.

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


Re: dictionary that discards old items

2005-07-22 Thread Tim Williams (gmail)
On 7/21/05, Michael Hoffman [EMAIL PROTECTED] wrote:
 Will McGugan wrote:
 
  I need a collection class that behaves like a dictionary but when it
  reaches 'n' items it discards the oldest item so that the length never
  goes above 'n'. (Its for caching search results)
 
  I have a vague memory of a module that does this, but I cant remember
  where I read about it. Can anyone enlighten me?
 
 You want a Least Recently Used, or LRU, cache. Here's one:
 
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252524
 

http://py.vaults.ca/apyllo.py/514463245.769244789.92554878
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RegUnloadkey access denied

2005-07-22 Thread future_retro
solved it!

I need to close the key first

import ntsecuritycon
import win32security
import win32api
import _winreg
import win32con

flags = ntsecuritycon.TOKEN_ADJUST_PRIVILEGES |
ntsecuritycon.TOKEN_QUERY
htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(),
flags)
Loadid = win32security.LookupPrivilegeValue(None, 'SeRestorePrivilege')
Saveid = win32security.LookupPrivilegeValue(None, 'SeBackupPrivilege')
LoadPrivilege = [(Loadid, ntsecuritycon.SE_PRIVILEGE_ENABLED)]
SavePrivilege = [(Saveid, ntsecuritycon.SE_PRIVILEGE_ENABLED)]
win32security.AdjustTokenPrivileges(htoken, 0, LoadPrivilege)
win32security.AdjustTokenPrivileges(htoken, 0, SavePrivilege)

key = _winreg.HKEY_USERS
hkey = win32api.RegLoadKey(key,'Marc','c:\\ntuser.dat')
okey = win32api.RegOpenKeyEx(key,'Marc\\test',0,win32con.KEY_SET_VALUE)
win32api.RegSetValueEx(okey,'test',0,_winreg.REG_DWORD,0)
win32api.RegCloseKey(okey)
win32api.RegUnLoadKey(key,'Marc')

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


find a specified dictionary in a list

2005-07-22 Thread Odd-R.
I have this list:

[{'i': 'milk', 'oid': 1}, {'i': 'butter', 'oid': 2},{'i':'cake','oid':3}]

All the dictionaries of this list are of the same form, and all the oids
are distinct. If I have an oid and the list, how is the simplest way of
getting the dictionary that holds this oid?


Thanks in advance



-- 
Har du et kjøleskap, har du en TV
så har du alt du trenger for å leve

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


Re: PEP on path module for standard library

2005-07-22 Thread Harald Armin Massa
 When you try to 'freeze' an application module,
and Jason's 'path' module is present in any of the directories that are
looked at by freeze's module finder (your app doesn't have to import
it), freeze goes into an infinite loop of imports, eventually getting a
'maximum recursion depth' exception.  This seems to be related to
freeze getting confused between 'os.path' and Jason's 'path'.

This is a bug in distutils. Thomas Hellers py2exe encounters the same
bug. As much as I remember our conversation, he submitted a patch to
distutils.

In the meanwhile I renamed path.py to jpath.py, usings Jason's first
letter in a motion of honour while circumventing this bug.

Harald

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


Re: Cursor navigation

2005-07-22 Thread TA

Andy Dustman [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]

 This is untrue: cursor.scroll() is an optional DB-API 2.0 extension.

 http://www.python.org/peps/pep-0249.html

 MySQLdb supports this, but I do not know about your case.


Yes 'cursor.scroll()' is optional and pySqlite supports it too, but pyPgSQL
does not.

Thanks for replying.

--
TA


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


Re: PEP on path module for standard library

2005-07-22 Thread Harald Armin Massa
Having path descend from str/unicode is extremely useful since I can
then pass a path object to any function someone else wrote without
having to worry about whether they were checking for basestring.
I use path.py from Jason to encapsulate a lot of the windows plattform
specialities of path dealing.
Being able to use path-opjects at every place where I would use str or
unicode is very essential, because I often use Python to tame Excel and
Word. To open files within these programms needs some plain str as
PATH for the file. (which, of course, can also be down by ways to
convert PATH to STRING.

Harald

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


Re: find a specified dictionary in a list

2005-07-22 Thread John Machin
Odd-R. wrote:
 I have this list:
 
 [{'i': 'milk', 'oid': 1}, {'i': 'butter', 'oid': 2},{'i':'cake','oid':3}]
 
 All the dictionaries of this list are of the same form, and all the oids
 are distinct. If I have an oid and the list, how is the simplest way of
 getting the dictionary that holds this oid?
 

Something like this:

def oidfinder(an_oid, the_list):
 for d in the_list:
if d['oid'] == an_oid:
 return d
 return None
 # These are not the oids you are looking for.



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


Re: Web frame systems vs. pure Python

2005-07-22 Thread Rob Cowie
I don't know what your project is, but a web framework might make your
system more scalable and maintainable if it gets larger. They often
provide useful mechanisms for maintaining state and persistance.

Template systems IMHO should be considered separately from App
frameworks (although they may be integrated). If you will frequently be
rendering web pages that are predominantly static but augmented with
dynamically generated/retrieved data, templates are a good way to go.
However, they can confuse if your system is only simple. In that case,
I wouldn't go for a full blown templating engine but 'roll my own'
using python dictionaries and 'string interpolation' (a daft name as it
isn't really interpolation).

Furthermore, app frameworks are sometimes a pain to install on a
webserver, particularly if you do not have control of it.

It all depends on your project size, your willingness to spend some
serious time climbing the learning curve associated with a framework,
and the server you wish to deploy on.

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


Separation of Code in CGI App

2005-07-22 Thread Rob Cowie
Hi,

I need to create a planner/calendar system using python cgi scripts. It
is my first CGI app (beyond a few tutorial examples).

I wish to separate the code according to function. For instance, the
code to handle the DB connection, SQL querying, HTML form variable
retrieval, rendering of HTML via some sort of template system etc. Each
will be a class instantiated when the CGI app is called.

To do this, do I just create each of these classes in one, monolithic
.cgi file? or is it possible to separate these out into different
scripts and have a 'controller' script call them and pass the relevant
parameters/data? I guess I could also store the python code in text
files and use the 'execfile()' function, although it seems to me that
would be an uneccasary performance hit.

If that is possible, is that the right way to go? If not, suggestions
would be gratefully recieved!

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


Re: Building Python with Tcl/Tk on Cygwin_NT-5.1

2005-07-22 Thread Dean N. Williams


Hi Jason,

I downloaded your new Cygwin from http://cygwin.com and tried to 
build install Python/CDAT again. It appears to have built properly, but 
when I try to execute, it receive a sock error. How do I get around this 
problem?

When I built Cygwin, I instructed it to install everything.

Thanks in advance for your help and best regards,
Dean


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


Re: wxPython Fedora Core 4

2005-07-22 Thread Sybren Stuvel
Christophe Lambin enlightened us with:
 However, since your wxPython package wasn't built for FC4, you may
 run into other problems.

That should be solved by recompiling the wxPython RPMs.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get directory from http web site

2005-07-22 Thread Sybren Stuvel
rock69 enlightened us with:
 I was wondering if there's some neat and easy way to get the entire
 contents of a directory at a specific web url address. [...] Is it
 possible to retrieve this list (not the physical files) and have it
 stored in a variable of type list or something?

Check out the chapter on HTML parsing at
http://www.diveintopython.org/

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: find a specified dictionary in a list

2005-07-22 Thread John Machin
John Machin wrote:
 Odd-R. wrote:
 
 I have this list:

 [{'i': 'milk', 'oid': 1}, {'i': 'butter', 'oid': 2},{'i':'cake','oid':3}]

 All the dictionaries of this list are of the same form, and all the oids
 are distinct. If I have an oid and the list, how is the simplest way of
 getting the dictionary that holds this oid?

 
 Something like this:
 
 def oidfinder(an_oid, the_list):
 for d in the_list:
 if d['oid'] == an_oid:
Better indented as:
  if d['oid'] == an_oid:
 return d
 return None
 # These are not the oids you are looking for.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python on a public library computer

2005-07-22 Thread Anton Vredegoor

This is about how to start a Python interpreter on a very locked down
library computer.

Some time ago I started a thread about it.(Google won't let me reply to
older topics so I'm starting a new topic with the same title) A few
days ago I found a Jython console applet that can be run from a
webpage:

http://tams-www.informatik.uni-hamburg.de/applets/jython/primacheck.html

This opens a webpage (well, maybe after some editing, I can't get
google to display this link on the same line) which after some time aks
the user to sign an applet which then turns out to be a complete Jython
editor and interpreter!

I'm looking for the sourcecode of a project like this so that I can
host such a page myself and include more modules. Can anyone reach the
author or has anyone written something like it and is willing to share
the code? Alternatively can someone give me some tips about how to
write it myself? Currently I'm at the stage where I can compile and run
the examples (and the applets!) on the Jython homepage. I'm still
wondering about how to sign applets.

Maybe the interpreter could be done by using the code.py module from
Jython itself and just redirect stdin and stdout to an applet?

Anton

p.s. John Lee: You remembered correctly, such a thing exists.

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


Re: find a specified dictionary in a list

2005-07-22 Thread Odd-R.
On 2005-07-22, John Machin [EMAIL PROTECTED] wrote:
 Odd-R. wrote:
 I have this list:
 
 [{'i': 'milk', 'oid': 1}, {'i': 'butter', 'oid': 2},{'i':'cake','oid':3}]
 
 All the dictionaries of this list are of the same form, and all the oids
 are distinct. If I have an oid and the list, how is the simplest way of
 getting the dictionary that holds this oid?
 

 Something like this:

 def oidfinder(an_oid, the_list):
  for d in the_list:
   if d['oid'] == an_oid:
  return d
  return None
  # These are not the oids you are looking for.

Thank you for your help, but I was hoping for an even simpler
solution, as I am suppose to use it in a
tal:block tal:define=p python: sentence.

Is there a simpler way of doing it? What if I assume that the
oid I'm searching for really exists?

Thanks again


-- 
Har du et kjøleskap, har du en TV
så har du alt du trenger for å leve

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


Re: Difference between and '

2005-07-22 Thread Peter Hansen
Steven D'Aprano wrote:
 It may shock some people to learn that difference in the sense of 
 mathematical subtraction is not the only meaning of the word, but there 
 it is. One wouldn't, I hope, misunderstand What is the difference 
 between spaghetti marinara and spaghetti pescatora? and attempt to 
 subtract one from the other, since subtraction is not defined for 
 foodstuffs.

  sum(ord(c) for c in 'spaghetti marinara') - sum(ord(c) for c in 
spaghetti pescatora)
-119

Works for me... ;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: Spyce 2.0.3

2005-07-22 Thread Jonathan Ellis
Spyce 2.0.3 released

Spyce is a python web application server, combining features of
popular frameworks such as ASP.NET and JSP with Pythonic elegance.
Spyce may be deployed as a standalone server, proxied behind
Apache, under mod_python, FastCGI, or CGI.

Spyce 2.0 includes features unique to Python web frameworks such as
  Active Handlers
- reusable components without the leaky abstractions seen in
  ASP.NET et al.
- http://spyce.sourceforge.net/docs/doc-lang_handlers.html
  Active Tag compiler
- http://spyce.sourceforge.net/docs/doc-tag_new2.html

2.0.3 is a bugfix and documentation-improvement release.
The installation section of the manual has received particular
attention.  There is also the new section on starting your first
project (http://spyce.sourceforge.net/docs/doc-conf_next.html),
which answers the FAQ, how do I organize my Spyce files.

Demos and downloads are available at http://spyce.sourceforge.net/.

Changelog is at http://svn-hosting.com/svn/spyce/trunk/spyce/CHANGES.

Jonathan Ellis
http://spyced.blogspot.com

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


Re: find a specified dictionary in a list

2005-07-22 Thread John Machin




Odd-R. Hogstad wrote (in private e-mail, with scarcely private
contents):

  In comp.lang.python, you wrote:
  
  
Odd-R. wrote:


  I have this list:

[{'i': 'milk', 'oid': 1}, {'i': 'butter', 'oid': 2},{'i':'cake','oid':3}]

All the dictionaries of this list are of the same form, and all the oids
are distinct. If I have an oid and the list, how is the simplest way of
getting the dictionary that holds this oid?

  

Something like this:

def oidfinder(an_oid, the_list):
 for d in the_list:
	if d['oid'] == an_oid:
 return d
 return None
 # These are not the oids you are looking for.

  
  
Thank you, however I was hoping for something even simpler,
as I am to use it in a tal:block tal:define="d python:
  

Sorry, I don't know what tal:block etc etc means.

And I don't know what "even simpler" could mean. Once you have the list
and have defined the function, you can simply deploy it wherever you
need the value.
current_oid = whatever
...
current_dict = oidfinder(current_oid, the_list)

  
Is this the only way to do it? What if I know that the oid
I am looking for is pressent?


  

Answering the 2nd question first: ignore the possiblility that the
oidfinder() will return None i.e. just chill out.

Other ways:
(a) use a list comprehension inline: 

current_dict = [d for d in the_list if d['oid'] == current_oid][0]
# this is a tad ugly and will blow up if the sought oid is not present
-- but that can't happen, can it ? :-)

(b) preprocess the weird/baroque/byzantine list that you have got. 

the_dict = {}
for d in the_list:
 the_dict[d['oid']] = d

then you do this:

current_dict = the_dict[current_oid]
# Simpler than that it cannot be.

Now a couple of questions for you:

(1) Have you contemplated that an oid can appear more than once in the
list?
(2) What in tarnation is an "oid"?

Cheers,
John


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

Re: Python on a public library computer

2005-07-22 Thread Sybren Stuvel
Anton Vredegoor enlightened us with:
 Some time ago I started a thread about it.(Google won't let me reply
 to older topics so I'm starting a new topic with the same title)

Why not use a proper Usenet client?

 A few days ago I found a Jython console applet that can be run from
 a webpage:

Nice! For giggles, try raise SystemExit() ;-)

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


tuple to string?

2005-07-22 Thread Francois De Serres
hiho,

what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) to 
the string 'spam'?

TIA,
Francois
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python on a public library computer

2005-07-22 Thread Robert Kern
Sybren Stuvel wrote:
 Anton Vredegoor enlightened us with:
 
Some time ago I started a thread about it.(Google won't let me reply
to older topics so I'm starting a new topic with the same title)
 
 Why not use a proper Usenet client?

Because he's on a public computer without one installed?

-- 
Robert Kern
[EMAIL PROTECTED]

In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die.
   -- Richard Harter

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


Re: Difference between and '

2005-07-22 Thread François Pinard
[EMAIL PROTECTED]

 Can someone tell me the difference between single quote and double
 quote?

There is no strong reason to use one and avoid the other.  Yet, while
representing strings, Python itself has a _preference_ for single
quotes.  Programmers can put this duality to good use, by adopting
reasonable conventions, which are nothing more than conventions! :-)

I would guess many people choose one over the other for minimizing the
amount of backslash escape needed.  Some people keep double quotes for
strings that would later undergo formatting, maybe because in most
shells and some other languages, double quotes allow for substitution
and single quotes prevent it.  But in my opinion, while not dismissing
a lot of wisdom developed within other languages, it may be foolish
letting other languages blindly dictate what is best Python style.

Personally, I keep single quotes for computer strings, and double
quotes for human strings.  To segregate between computer and human
character for a string, I merely ask myself: If I wanted to use this
program in another language, would I want this particular string
translated or not?.  Yes means double quotes, no means single quotes.
As single quotes are often use within human text, as apostrophes, this
was a wise choice as far as shell escaping goes.

This is extendable to triple-quoted strings.  I use triple-double quotes
for doc strings meant to hold documentation, which is the usual case.
If doc strings are used for BNF snippets, like with SPARK, or any other
machine data, triple-single quotes are mandatory by my own convention.

-- 
François Pinard   http://pinard.progiciels-bpi.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


command line argument passing

2005-07-22 Thread Hayri ERDENER
hi to all,
is it possible in python to pass arguments by using command prompt in
windows 2000 and XP ?
for example:
sourceCode.py  factorial  4
 gives me the factorial of 4 namely 24. 
best regards
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Difference between and '

2005-07-22 Thread François Pinard
[Robert Kern]

 One habit that seems to crop up, though, is that I will use '' for
 internal strings and  for strings that will eventually get seen by
 the user.  Don't ask me why.

One sure thing is that it would help, later, if you ever want to
internationalise a Python program.  Not that it occurs that often! :-)

-- 
François Pinard   http://pinard.progiciels-bpi.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuple to string?

2005-07-22 Thread Jason Drew
''.join((chr(e) for e in (0x73, 0x70, 0x61, 0x6D)))

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


Re: tuple to string?

2005-07-22 Thread Robert Kern
Francois De Serres wrote:
 hiho,
 
 what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) to 
 the string 'spam'?

In [1]: t = (0x73, 0x70, 0x61, 0x6D)

In [2]: ''.join(chr(x) for x in t)
Out[2]: 'spam'

-- 
Robert Kern
[EMAIL PROTECTED]

In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die.
   -- Richard Harter

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


Re: PEP on path module for standard library

2005-07-22 Thread Peter Hansen
Duncan Booth wrote:
 Personally I think the concept of a specific path type is a good one, but 
 subclassing string just cries out to me as the wrong thing to do. In other 
 words, to me a path represents something in a filesystem, the fact that it 
 has one, or indeed several string representations does not mean that the 
 path itself is simply a more specific type of string.
 
 You should need an explicit call to convert a path to a string and that 
 forces you when passing the path to something that requires a string to 
 think whether you wanted the string relative, absolute, UNC, uri etc.

Duncan, are you another formerly non-user of path who has this opinion, 
or have you already attempted to use path extensively in your code?

I'm not saying I dismiss the opinions of those who haven't actually 
tried working with a string-based path object, but it's worth 
considering that you might adopt a different opinion after using it for 
a while.

I did.

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


Re: tuple to string?

2005-07-22 Thread Peter Hansen
Francois De Serres wrote:
 hiho,
 
 what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) to 
 the string 'spam'?

  mytuple = (0x73, 0x70, 0x61, 0x6D)
  ''.join(chr(v) for v in mytuple)
'spam'

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


Re: tuple to string?

2005-07-22 Thread deelan
Francois De Serres wrote:
 hiho,
 
 what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) to 
 the string 'spam'?

one way is to use a list expression:

  ''.join([chr(c) for c in (0x73, 0x70, 0x61, 0x6D)])
'spam'

another is to use map:

  ''.join(map(chr, (0x73, 0x70, 0x61, 0x6D)))
'spam'

HTH,
deelan.

-- 
deelan, #1 fan of adriana lima!
http://www.deelan.com/




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


Re: command line argument passing

2005-07-22 Thread Peter Hansen
Hayri ERDENER wrote:
 hi to all,
 is it possible in python to pass arguments by using command prompt in
 windows 2000 and XP ?
 for example:
 sourceCode.py  factorial  4
  gives me the factorial of 4 namely 24. 

Yes, the arguments are available as a list in sys.argv .

Remember that you need to import sys before you can access that, and 
that the values will be returned as strings, so if they should be 
treated as numbers it's up to you to convert them.

Use of the getopt or optparse modules is recommended to work with 
command line arguments more effectively.

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


Re: command line argument passing

2005-07-22 Thread gene tani
just remember: sys.argv[0] == script name


http://www.artima.com/weblogs/viewpost.jsp?thread=4829

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


Re: command line argument passing

2005-07-22 Thread Dennis Benzinger
Hayri ERDENER schrieb:
 hi to all,
 is it possible in python to pass arguments by using command prompt in
 windows 2000 and XP ?
 for example:
 sourceCode.py  factorial  4
  gives me the factorial of 4 namely 24. 
 best regards

import sys

print sys.argv


Or use the optparse module. Docs:
http://www.python.org/doc/2.4.1/lib/module-optparse.html

Bye,
Dennis
-- 
http://mail.python.org/mailman/listinfo/python-list


broken links

2005-07-22 Thread rbt
How can I find broken links (links that point to files that do not
exist) in a directory and remove them using Python? I'm working on RHEL4

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


Re: find a specified dictionary in a list

2005-07-22 Thread Christopher Subich


Odd-R. wrote:
 On 2005-07-22, John Machin [EMAIL PROTECTED] wrote:
  Odd-R. wrote:
  I have this list:
 
  [{'i': 'milk', 'oid': 1}, {'i': 'butter', 'oid': 2},{'i':'cake','oid':3}]
 
  All the dictionaries of this list are of the same form, and all the oids
  are distinct. If I have an oid and the list, how is the simplest way of
  getting the dictionary that holds this oid?
 
 
  Something like this:
 
  def oidfinder(an_oid, the_list):
   for d in the_list:
  if d['oid'] == an_oid:
   return d
   return None
   # These are not the oids you are looking for.

 Thank you for your help, but I was hoping for an even simpler
 solution, as I am suppose to use it in a
 tal:block tal:define=p python: sentence.

 Is there a simpler way of doing it? What if I assume that the
 oid I'm searching for really exists?

If you really, really, really don't care about proper error handling,
both of these expressions should work: (warning, untested since I'm at
work)
right_oid = [d for d in dictlist if d['oid']==the_oid][0]
right_oid = (d for d in dictlist if d['oid']==the_oid).next()

The last one more efficient as a generator expression, but requires
Python2.4.  Both of these error in Really Bad Ways (range error and
StopIteration exceptions, respectively) if the right dictionary isn't
in the list.

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


is this possible?

2005-07-22 Thread scrimp
Is it possible to print a PDF file using python without having acrobat
reader installed on the machine??

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


Re: Difference between and '

2005-07-22 Thread John Machin
Peter Hansen wrote:
 Steven D'Aprano wrote:
 
 It may shock some people to learn that difference in the sense of 
 mathematical subtraction is not the only meaning of the word, but 
 there it is. One wouldn't, I hope, misunderstand What is the 
 difference between spaghetti marinara and spaghetti pescatora? and 
 attempt to subtract one from the other, since subtraction is not 
 defined for foodstuffs.
 
 
   sum(ord(c) for c in 'spaghetti marinara') - sum(ord(c) for c in 
 spaghetti pescatora)
 -119
 
 Works for me... ;-)

Works for me too:

C:\junkpython --fuzzy --punt
Python 9.4.1 (#165, Mar 30 3005, 09:13:57) [MSC v.13109 1024 bit 
(Intel)] on win1024
Type help, copyright, credits or license for more information.
  a = foodstuff('spaghetti marinara')
  b = foodstuff('spaghetti pescatora')
  a - b
0
  explain
a.base is b.base
a.topping != b.topping
but
 fuzzy mode selected
 a.topping isa salty_smelly_stuff
 b.topping isa salty_smelly_stuff
 punt mode selected
 prob(customer_knows_difference) = 0.01
 PSF interdiction
 all your operator are belong to us
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: broken links

2005-07-22 Thread rbt
I found it:

os.path.exists(path)


On Fri, 2005-07-22 at 09:22 -0400, rbt wrote:
 How can I find broken links (links that point to files that do not
 exist) in a directory and remove them using Python? I'm working on RHEL4
 
 Thanks,
 rbt
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dictionary that discards old items

2005-07-22 Thread Michael Hoffman
Will McGugan wrote:

 You want a Least Recently Used, or LRU, cache. Here's one:

 Thanks. I found the one I saw originally in the Python Cookbook. Only 
 they call it a FIFO cache.

A FIFO cache is different, as gene tani points out. You need to consider 
  which one it is you want.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


time.time() under load between two machines

2005-07-22 Thread kwharrigan
I am working on some code using python and a distributed system.  Some
particular message is sent on one machine (with a timestamp logged) and
after the message is received, a timestamp is made.  I am having
problems with negative latencies happening under intense CPU load.
There is ntp sync happening so the machines should be very well in
sync.  Example:

machine1


sendTime = time.time()
Call to send message

machine2
---

Got a message
recvTime = time.time()

Latency = recvTime-sendTime is NEGATIVE

Is it possible that the CPU load is affecting the accuracy of the
time.time() call, or that the relative difference in CPU load between
the machines is causing this delta inaccuracy?  Any help would be
appreciated.

Kyle Harrigan

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


Re: time.time() under load between two machines

2005-07-22 Thread Michael Hoffman
[EMAIL PROTECTED] wrote:
 I am working on some code using python and a distributed system.  Some
 particular message is sent on one machine (with a timestamp logged) and
 after the message is received, a timestamp is made.  I am having
 problems with negative latencies happening under intense CPU load.

How negative are we talking about? What platforms are you using?
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >