cx_Freeze 4.0

2008-09-02 Thread Anthony Tuininga
What is cx_Freeze?

cx_Freeze is a set of scripts and modules for freezing Python scripts
into executables in much the same way that py2exe and py2app do. It
requires Python 2.3 or higher since it makes use of the zip import
facility which was introduced in that version.


Where do I get it?

http://cx-freeze.sourceforge.net


What's new?

This release marks a significant change in functionality. Any feedback
is appreciated.

Changes from 4.0b1 to 4.0
1) Added support for copying files to the target directory.
2) Added support for a hook that runs when a module is missing.
3) Added support for binary path includes as well as excludes; use
sequences rather than dictionaries as a more convenient API; exclude
the standard locations for 32-bit and 64-bit libaries in
multi-architecture systems.
4) Added support for searching zip files (egg files) for modules.
5) Added support for handling system exit exceptions similarly to what
Python does itself as requested by Sylvain.
6) Added code to wait for threads to shut down like the normal Python
interpreter does. Thanks to Mariano Disanzo for discovering this
discrepancy.
7) Hooks added or modified based on feedback from many people.
8) Don't include the version name in the display name of the MSI.
9) Use the OS dependent path normalization routines rather than simply
use the lowercase value as on Unix case is important; thanks to Artie
Eoff for pointing this out.
10) Include a version attribute in the cx_Freeze package and display
it in the output for the --version option to the script.
11) Include build instructions as requested by Norbert Sebok.
12) Add support for copying files when modules are included which
require data files to operate properly; add support for copying the
necessary files for the Tkinter and matplotlib modules.
13) Handle deferred imports recursively as needed; ensure that from
lists do not automatically indicate that they are part of the module
or the deferred import processing doesn't actually work!
14) Handle the situation where a module imports everything from a
package and the __all__ variable has been defined but the package has
not actually imported everything in the __all__ variable during
initialization.
15) Modified license text to more closely match the Python Software
Foundation license as was intended.
16) Added sample script for freezing an application using matplotlib.
17) Renamed freeze to cxfreeze to avoid conflict with another package
that uses that executable as requested by Siegfried Gevatter.

Changes from 3.0.3 to 4.0b1
1) Added support for placing modules in library.zip or in a separate
zip file for each executable that is produced.
2) Added support for copying binary dependent files (DLLs and shared libraries)
3) Added support for including all submodules in a package
4) Added support for including icons in Windows executables
5) Added support for constants module which can be used for
determining certain build constants at runtime
6) Added support for relative imports available in Python 2.5 and up
7) Added support for building Windows installers (Python 2.5 and up)
and RPM packages
8) Added support for distutils configuration scripts
9) Added support for hooks which can force inclusion or exclusion of
modules when certain modules are included
10) Added documentation and samples
11) Added setup.py for building the cx_Freeze package instead of a
script used to build only the frozen bases
12) FreezePython renamed to a script called freeze in the Python distribution
13) On Linux and other platforms that support it set LD_RUN_PATH to
include the directory in which the executable is located
--
http://mail.python.org/mailman/listinfo/python-announce-list

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


ANN: Leo 4.5 final released

2008-09-02 Thread Edward K Ream
Leo 4.5 final is now available at:
http://sourceforge.net/project/showfiles.php?group_id=3458package_id=29106

Leo is a text editor, data organizer, project manager and much more. See:
http://webpages.charter.net/edreamleo/intro.html

The highlights of Leo 4.5:
--

- Full support for @shadow files in Leo's core.
- Major improvements to Leo's key binding code.
- The beginning of usable vim-like bindings.
- uA's may now be associated with vnodes in @thin and @shadow files.
- Several magor reorganizations of Leo's code:
  including sax-based parsing, support for the Graph world (unified nodes),
  and simplified drawing code.
- Leo is now an installable package.
- Prepared code to be ready for Python 3.0.
- Many small improvements and bug fixes.

Quote of the month:
---
Squeak and Leo have been two of the most significant technologies to
redefine my personal computer experience and the ideas behind computing.

Links:
--
Leo:  http://webpages.charter.net/edreamleo/front.html
Forum:http://groups.google.com/group/leo-editor
Download: http://sourceforge.net/project/showfiles.php?group_id=3458
Bzr:  http://code.launchpad.net/leo-editor/
Quotes:   http://webpages.charter.net/edreamleo/testimonials.html


Edward K. Ream   email:  [EMAIL PROTECTED]
Leo: http://webpages.charter.net/edreamleo/front.html


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

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


Python-URL! - weekly Python news and links (Sep 2)

2008-09-02 Thread Gabriel Genellina
QOTW:  Information outlives technology. - Tim Bray
http://www.tbray.org/ongoing/When/200x/2003/03/24/XMLisOK, but notice
all the offspring of this meme any simple search makes apparent


Thoughts about the various forms of the import statement:

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

Looking for an atomic increment operation:

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

Comparing unicode and byte strings:

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

Alternatives eval() in unsafe environments:

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

An algorithmic problem (identify where good data starts inside a
sequence) as an excuse to post many creative solutions (including
generators and even regular expressions):

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

Enumerating all the currently installed Python modules:

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

When to use try/except:

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

str.downer? str.downcase? str.lowercase is the *obvious* name, isn't it?

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



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

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

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily

Just beginning with Python?  This page is a great place to start:
http://wiki.python.org/moin/BeginnersGuide/Programmers

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

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

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.
http://groups.google.com/group/comp.lang.python.announce/topics

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

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

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

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

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

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

The Summary of Python Tracker Issues is an automatically generated
report summarizing new bugs, closed ones, and patch submissions. 

http://search.gmane.org/?author=status%40bugs.python.orggroup=gmane.comp.python.develsort=date

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

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

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://code.activestate.com/recipes/langs/python/

Many Python conferences around the world are in preparation.
Watch this space for links to them.

Among several Python-oriented RSS/RDF feeds available, see:
http://www.python.org/channews.rdf
For more, see:
http://www.syndic8.com/feedlist.php?ShowMatch=pythonShowStatus=all
The old Python To-Do List now lives principally in a
SourceForge reincarnation.
http://sourceforge.net/tracker/?atid=355470group_id=5470func=browse
http://www.python.org/dev/peps/pep-0042/

del.icio.us presents an intriguing approach to reference commentary.
It already 

pyArkansas on October 4th

2008-09-02 Thread Greg Lindstrom
We are pleased to announce that pyArkansas will be held on the campus of
University of Central Arkansas  (www.uca.edu) on October 4th.  Scheduled
classes in the morning include Python 101 taught by Dr. Bernard Chen
(incoming faculty at UCA but having taught the course at Georgia State
University), Python 201 taught by Jeff Rush (Dallas Python Users Group)
and Python for Unix/Linux Administration (Noah Gift teaching on his -- and
Jeremy Jones' -- newly released OReilly title).  The afternoon features
talks and a panel discussion along with lots of great give aways and swag.

Due to limitations of physical space we must close registration at 100
participants (in honor of my first OS, SunOS, we may go to 110).  Check out
our wiki at http://pycamp.python.org/Arkansas/HomePage.  There's no
registration fee, so if you're in the area stop on by...we are looking
forward to a great day.

Greg Lindstrom
Python Artists of Arkansas (PyAR^2)
--
http://mail.python.org/mailman/listinfo/python-announce-list

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


Re: python mechanize/libxml2dom question

2008-09-02 Thread Stefan Behnel
bruce wrote:
 i've got the following situation, with the following test url:
 http://schedule.psu.edu/soc/fall/Alloz/a-c/acctg.html#;.
 
 i can generate a list of the tables i want for the courses on the page.
 however, when i try to create the xpath query, and plug it into the xpath
 within python, i'm missing something. if i have a parent xpath query, that
 generates a list of results/nodes... how can i then use the individual
 parent node, and trigger off of it, to get further information.
[code example stripped]

You should really use lxml. It has callable XPath objects that feel like
Python functions, and its Element objects have a getparent() method that gets
you to the parent of the node. Plus, text strings that you get back from an
XPath evaluation also have a getparent() method that returns the Element
object that holds the text. I think that's what you were looking for.

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


Re: Put the output from all my programs in one place

2008-09-02 Thread alex23
On Sep 2, 6:30 am, Jesse Aldridge [EMAIL PROTECTED] wrote:
 I want to put all the output from all of my python programs in one
 place.

Have you considered using the python logging module?

http://docs.python.org/lib/module-logging.html
http://www.onlamp.com/pub/a/python/2005/06/02/logging.html

You can define handlers within a program or via a config file. Then
you just need to specify that they all log to the same location, which
you could define via an environment variable...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Numeric literal syntax (was: Py 2.6 changes)

2008-09-02 Thread Steven D'Aprano
On Tue, 02 Sep 2008 11:13:27 +1000, Ben Finney wrote:

 [EMAIL PROTECTED] writes:
 
 For Python 2.7/3.1 I'd now like to write a PEP regarding the
 underscores into the number literals, like: 0b_0101_, 268_435_456
 etc.
 
 +1 on such a capability.
 
 -1 on underscore as the separator.
 
 When you proposed this last year, the counter-proposal was made
 URL:http://groups.google.com/group/comp.lang.python/
msg/18123d100bba63b8?dmode=source
 to instead use white space for the separator, exactly as one can now do
 with string literals.
 
 I don't see any good reason (other than your familiarity with the D
 language) to use underscores for this purpose, and much more reason
 (readability, consistency, fewer arbitrary differences in syntax,
 perhaps simpler implementation) to use whitespace just as with string
 literals.

At the risk of bike-shedding, I think that allowing arbitrary whitespace 
between string literals is fine, because it aids readability to write 
this:

do_something(
first part of the string
another part of the string
yet more of the string
and a bit more
and so on...
)

but I'm not sure that it is desirable to allow this:

do_something(
142325
93.8012
7113
)


-1/2 on arbitrary whitespace, +1/2 on a single space, and +0 on 
underscores. If semi-colons didn't already have a use, I'd propose using 
them to break up numeric literals:

14;232;593.801;271;13



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


Re: Getting an objetcs dict?

2008-09-02 Thread alex23
On Sep 2, 4:31 am, ssecorp [EMAIL PROTECTED] wrote:
 X.__dict__() and ngot a dict of its variables.

 Now i get errors doing this. what am i doing wrong?

The immediate problem is you're not reading the error messages.

 X.__dict__()
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: 'dict' object is not callable

The not callable is the big tip-off. As it states, __dict__ is a
dictionary object, -not- a method of your class.

 X.__dict__
{'__module__': '__main__', '__doc__': None}

The larger problem is you're not reading the docs  are using this
list to teach you Python. Are you aware of the python-tutor list?

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

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


Re: Numeric literal syntax

2008-09-02 Thread Steven D'Aprano
On Mon, 01 Sep 2008 22:11:13 -0700, Dennis Lee Bieber wrote:

 On Tue, 02 Sep 2008 13:51:16 +1000, Ben Finney
 [EMAIL PROTECTED] declaimed the following in
 comp.lang.python:
 
 This is no more the case than for literal strings:
 
 a = spam eggs ham
 
 a = spam, eggs, ham

  But... Literal string still have the  (or ') delimiters around the
 components. Such does not exist for you example with integers.
 
   Consider
 
 a = spam, eggs, ham
 vs
 a = spam, eggs ham


Quite frankly, I think that it's a stretch to say that leaving out a 
tuple delimiter is a problem with whitespace inside numeric literals. 
That's hardly unique to whitespace:

atuple = 5,6,7,8
vs
atuple = 5,67,8

Look Ma, no whitespace!


But even if allowing whitespace inside numeric literals did create a new 
avenue for errors which never existed before, it is a mistake to only 
consider the downside without the upside. In my opinion, that would be 
rather like declaring that the syntax for attribute access is a mistake 
because you might do this:

x = MyClass()
xy = 4

instead of this:

x = MyClass()
x.y = 4

At some point the programmer has to take responsibility for typos instead 
of blaming the syntax of the language. I agree that we should avoid 
syntax that *encourages* typos, but I don't believe that allowing 
whitespace inside numeric literals does that.



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


Changing the (codec) error handler for the stdout/stderr streams in Python 3.0

2008-09-02 Thread Jukka Aho
Just a tip for those who are only just cutting their teeth on Python 3.0 
and might have encountered the same problem as I did:


When a Python (3.x) program is run on a terminal that only supports a 
legacy character encoding - such as Latin 1 or Codepage 437 - all 
characters printed to stdout will be automatically converted from the 
interpreter's internal Unicode representation to this legacy character 
set.


This is a nice feature to have, of course, but if the original Unicode 
string contains characters for which there is no equivalent in the 
terminal's legacy character set, you will get the dreaded 
UnicodeEncodeError exception.


In other words, the sys.stdout stream - as well as the sys.stderr 
stream - have both been hardwired to do their character encoding magic, 
by default, using the 'strict' error handling scheme:


--- 8 ---

 import sys
 sys.stdout.errors
'strict'
 sys.stderr.errors
'strict'

--- 8 ---

So, essentially, printing out anything but ASCII to stdout is not really 
safe in Python... unless you know beforehand, for sure, what characters 
the terminal will support - which at least in my mind kind of defeats 
the whole purpose of those automatic, implicit conversions.


Now, I have written a more flexible custom error handler myself and 
registered it with Python's codec system, using the 
codecs.register_error() function. When the handler encounters a 
problematic codepoint, it will either suggest a similar-enough Latin 1 
or ASCII substitution for it, or if there is none available in its 
internal conversion table, it will simply print it out using the U+ 
notation. The UnicodeEncodeError exception will never occur with it.


Instead of creating a custom error handler from scratch one could also 
make use of one of Python's built-in, less restrictive error handlers, 
such as 'ignore', 'replace', 'xmlcharrefreplace', or 'backslashreplace'.


But in order to make things work as transparently and smoothly as 
possible, I needed a way to make both the sys.stdio and sys.stderr 
streams actually _use_ my custom error handler, instead of the default 
one.


Unfortunately, the current implementation of io.TextIOWrapper (in Python 
3.0b2, at least) does not yet offer a public, documented interface for 
changing the codec error handler - or, indeed, the target encoding 
itself - for streams that have already been opened, and this means you 
can't officially change it for the stdout or stderr streams, 
either. (The need for this functionality is acknowledged in PEP-3116, 
but has apparently not been implemented yet. [1])


So, after examining io.py and scratching my head a bit, here's how one 
can currently hack one's way around this limitation:


--- 8 ---

import sys
sys.stdout._errors = 'backslashreplace'
sys.stdout._get_encoder()
sys.stderr._errors = 'backslashreplace'
sys.stderr._get_encoder()

--- 8 ---

Issuing these commands makes printing out Unicode strings to a legacy 
terminal a safe procedure again and you're not going get unexpected 
UnicodeEncodeErrors thrown in your face any longer. (Note: 
'backslashreplace' is just an example here; you could substitute the 
error handler of your choice for it.)


The downside of this solution is, of course, that it will break down if 
the private implementation of io.TextIOWrapper in io.py changes in the 
future. But as a workaround, I feel it is sufficient for now, while 
waiting for the real support to appear in the library.


(If there's a cleaner and more future-proof way of doing the same thing 
right now, I'd of course love to hear about it...)


_

1. http://mail.python.org/pipermail/python-3000/2008-April/013366.html

--
znark

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


Re: Enhanced property decorator

2008-09-02 Thread Gabriel Genellina
En Mon, 25 Aug 2008 22:45:36 -0300, Daniel [EMAIL PROTECTED] escribió:

 I've often been frustrated by the inability of the built-in property
 descriptor to handle anything other than a read-only property when
 used as a decorator. Furthermore, read/write/delete properties take
 their doc-string and property definition at a non-intuitive and
 awkward place (after the getter/setter/delter functions). The
 following are three possible solutions to this problem (inspired by
 message http://groups.google.com/group/comp.lang.python/msg/9a56da7ca8ceb7c7).
 I don't like the solution in that thread because it uses apply() which
 will go away in Python 3.

 Solution 1: new built-in function/descriptor

 def prop(func):
 funcs = dict(enumerate(func()))
 return property(funcs[0], funcs[1], funcs.get(2), func.__doc__)

 class Test(object):
 @prop
 def test():
 test doc string
 def fget(self):
 return self._test
 def fset(self, value):
 self._test = value
 def fdel(self):
 del self._test
 return fget, fset, fdel

 Of course the name (prop) could be changed... I couldn't think of
 anything more concise.

 Pros:
 (1) encapsulation of property logic inside function namespace,
 preventing clutter in class namespace.
 (2) doc string appears in a more natural place, before getter/setter/
 delter logic, as in classes and functions.

 Cons:
 (1) additional built-in name.
 (2) duplication/boilerplate in return line (DRY violation).

(Some days late, sorry...) I like the variant below, based on your code. It 
avoids issue (2) by using locals(). Works with Python 3.0 too - and don't use 
tricks like sys._getframe or sys.settrace:

def defproperty(func):
   impls = func()
   return property(doc=func.__doc__, **impls)

class Test(object):
   @defproperty
   def test():
   test doc string
   def fget(self):
   return self._test
   def fset(self, value):
   self._test = value
   def fdel(self):
   del self._test
   return locals()

-- 
Gabriel Genellina

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


python 3k, when will it be mainstream?

2008-09-02 Thread Almar Klein
Hi,

I read that python 3k is now in its final beta version. I was wondering
when we can expect the major packages to make a 3.0 branch.

I am myself quite new to python, and would like to make the
transition as soon as possible, simply because it would save me
porting code later, and I can focus on learning just the python 3.0.

However, I am a former Matlab user and depend on packages like
numpy, scipy, matplotlib. wxPython I use as well.

So to get to the point:
When can we expect these (and other) packages to release their
python 3k versions? And when will the majority of people make the
transition to py3k?

I am looking forward to your thoughts on this,

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

Re: (in memory) database

2008-09-02 Thread Paul Boddie
On 2 Sep, 04:46, Zentrader [EMAIL PROTECTED] wrote:
 On Ubuntu you want to install something like python-sqlite (a search
 for python should turn up everything).  There are 2 parts to this,
 SQLite and the python bindings to SQLite.  So you seem to have SQLite
 installed but not the Python bindings.  Also, on some systems you have
 to have python-sqlite installed, and then build python in order to use
 it.

The python-sqlite and python-sqlite2 packages were needed for Python
2.4 - it was possibly python2.4-sqlite or python2.4-sqlite2 if you go
back a few versions - but Python 2.5 should depend on the sqlite
libraries and pull them in automatically:

http://packages.ubuntu.com/hardy/python2.5

I don't understand why Cameron has a different version of Python which
doesn't seem to have sqlite support enabled.

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


Re: How to print first(national) char from unicode string encoded inutf-8?

2008-09-02 Thread sniipe
On 2 Wrz, 06:05, Mark Tolonen [EMAIL PROTECTED] wrote:
 Marco Bizzarri [EMAIL PROTECTED] wrote in message

 news:[EMAIL PROTECTED]



  On Mon, Sep 1, 2008 at 3:25 PM,  [EMAIL PROTECTED] wrote:

  When I do ${urllib.unquote(c.user.firstName)} without encoding to
  latin-1 I got different chars than I will get: no Ùukasz but Å ukasz
  --
 http://mail.python.org/mailman/listinfo/python-list

  That's crazy. string.encode('latin1') gives you a latin1 encoded
  string; latin1 is a single byte encoding, therefore taking the first
  byte should be no problem.

  Have you tried:

  urlib.unquote(c.user.firstName)[0].encode('latin1') or

  urlib.unquote(c.user.firstName)[0].encode('utf8')

  I'm assuming here that the urlib.unquote(c.user.firstName) returns an
  encodable string (which I'm absolutely not sure), but if it does, this
  should take the first 'character'.

 The OP stated that the original string was encoded in UTF-8 and
 urllib.quote(), so after urllib.unquote the string is in UTF-8 format.
 This must be decoded into a Unicode string before removing the first
 character:

 urllib.unquote(c.user.firstName).decode('utf-8')[0]

 The next problem is that the character in the OP's example string 'Ù' is not
 present in the latin-1 encoding, but using utf-8 encoding demonstrates that
 the full two-byte UTF-8 encoded character is collected:

  import urllib
  name = urllib.quote(u'Ùukasz'.encode('utf-8'))
  name
 '%C5%81ukasz'
  urllib.unquote(name).decode('utf-8')[0].encode('utf-8')
 '\xc5\x81'

 -Mark

@Mark, when I tried urllib.unquote(c.user.firstName).decode('utf-8')
[0].encode('utf-8'), I received this message:

  return render('/reports/create_report_step2.mako')
Module pylons.templating:344 in render
  **cache_args)
return pylons.buffet.render(template_name=template,
fragment=fragment,
format=format, namespace=kargs,
**cache_args)

  format=format, namespace=kargs, **cache_args)
Module pylons.templating:229 in render
  log.debug(Rendering template %s with engine %s,
full_path, engine_name)
return engine_config['engine'].render(namespace,
template=full_path,
**options)  **options)
Module mako.ext.turbogears:49 in render
  info.update(self.extra_vars_func())

return template.render(**info)
  return template.render(**info)
Module mako.template:114 in render
  declared by this template's internal rendering method are
also pulled from the given *args, **data
members.members.
return runtime._render(self, self.callable_, args, data)

def render_unicode(self, *args, **data):  return
runtime._render(self, self.callable_, args, data)
Module mako.runtime:287 in _render
  context = Context(buf, **data)
context._with_template = template
_render_context(template, callable_, context, *args,
**_kwargs_for_callable(callable_, data))
return context.pop_buffer().getvalue()
_render_context(template, callable_, context, *args,
**_kwargs_for_callable(callable_, data))
Module mako.runtime:304 in _render_context
  # if main render method, call from the base of the
inheritance stack
(inherit, lclcontext) = _populate_self_namespace(context,
tmpl)
_exec_template(inherit, lclcontext, args=args,
kwargs=kwargs)
else:
# otherwise, call the actual rendering method specified
_exec_template(inherit, lclcontext, args=args, kwargs=kwargs)
Module mako.runtime:337 in _exec_template
  error_template.render_context(context,
error=error)
else:
callable_(context, *args, **kwargs)  callable_(context,
*args, **kwargs)
Module _reports_create_report_step2_mako:57 in render_body

context.write(filters.decode.utf8(urllib.unquote(str(c.period.end
context.write(u' + ')
 
context.write(filters.decode.utf8(urllib.unquote(c.user.firstName).decode('utf-8')
[0].encode('utf-8')))
 
context.write(filters.decode.utf8(urllib.unquote(str(c.user.secondName)
[0:1])))
context.write(u'/h3\r\ninput type=hidden
name=works[] value=')
context.write(filters.decode.utf8(urllib.unquote(c.user.firstName).decode('utf-8')
[0].encode('utf-8')))
Module encodings.utf_8:16 in decode

def decode(input, errors='strict'):
return codecs.utf_8_decode(input, errors, True)

class IncrementalEncoder(codecs.IncrementalEncoder):  return
codecs.utf_8_decode(input, errors, True)
type 'exceptions.UnicodeEncodeError': 'ascii' codec can't encode
characters in position 0-1: ordinal not in range(128)
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to print first(national) char from unicode string encoded inutf-8?

2008-09-02 Thread sniipe
On 2 Wrz, 10:17, [EMAIL PROTECTED] wrote:
 On 2 Wrz, 06:05, Mark Tolonen [EMAIL PROTECTED] wrote:



  Marco Bizzarri [EMAIL PROTECTED] wrote in message

 news:[EMAIL PROTECTED]

   On Mon, Sep 1, 2008 at 3:25 PM,  [EMAIL PROTECTED] wrote:

   When I do ${urllib.unquote(c.user.firstName)} without encoding to
   latin-1 I got different chars than I will get: no Ùukasz but Å ukasz
   --
  http://mail.python.org/mailman/listinfo/python-list

   That's crazy. string.encode('latin1') gives you a latin1 encoded
   string; latin1 is a single byte encoding, therefore taking the first
   byte should be no problem.

   Have you tried:

   urlib.unquote(c.user.firstName)[0].encode('latin1') or

   urlib.unquote(c.user.firstName)[0].encode('utf8')

   I'm assuming here that the urlib.unquote(c.user.firstName) returns an
   encodable string (which I'm absolutely not sure), but if it does, this
   should take the first 'character'.

  The OP stated that the original string was encoded in UTF-8 and
  urllib.quote(), so after urllib.unquote the string is in UTF-8 format.
  This must be decoded into a Unicode string before removing the first
  character:

  urllib.unquote(c.user.firstName).decode('utf-8')[0]

  The next problem is that the character in the OP's example string 'Ù' is not
  present in the latin-1 encoding, but using utf-8 encoding demonstrates that
  the full two-byte UTF-8 encoded character is collected:

   import urllib
   name = urllib.quote(u'Ùukasz'.encode('utf-8'))
   name
  '%C5%81ukasz'
   urllib.unquote(name).decode('utf-8')[0].encode('utf-8')
  '\xc5\x81'

  -Mark

 @Mark, when I tried urllib.unquote(c.user.firstName).decode('utf-8')
 [0].encode('utf-8'), I received this message:

   return render('/reports/create_report_step2.mako')

 Module pylons.templating:344 in render
   **cache_args)
 return pylons.buffet.render(template_name=template,
 fragment=fragment,
 format=format, namespace=kargs,
 **cache_args)

   format=format, namespace=kargs, **cache_args)
 Module pylons.templating:229 in render
   log.debug(Rendering template %s with engine %s,
 full_path, engine_name)
 return engine_config['engine'].render(namespace,
 template=full_path,
 **options)  **options)
 Module mako.ext.turbogears:49 in render
   info.update(self.extra_vars_func())

 return template.render(**info)
   return template.render(**info)
 Module mako.template:114 in render
   declared by this template's internal rendering method are
 also pulled from the given *args, **data
 members.members.
 return runtime._render(self, self.callable_, args, data)

 def render_unicode(self, *args, **data):  return
 runtime._render(self, self.callable_, args, data)
 Module mako.runtime:287 in _render
   context = Context(buf, **data)
 context._with_template = template
 _render_context(template, callable_, context, *args,
 **_kwargs_for_callable(callable_, data))
 return context.pop_buffer().getvalue()
 _render_context(template, callable_, context, *args,
 **_kwargs_for_callable(callable_, data))
 Module mako.runtime:304 in _render_context
   # if main render method, call from the base of the
 inheritance stack
 (inherit, lclcontext) = _populate_self_namespace(context,
 tmpl)
 _exec_template(inherit, lclcontext, args=args,
 kwargs=kwargs)
 else:
 # otherwise, call the actual rendering method specified
 _exec_template(inherit, lclcontext, args=args, kwargs=kwargs)
 Module mako.runtime:337 in _exec_template
   error_template.render_context(context,
 error=error)
 else:
 callable_(context, *args, **kwargs)  callable_(context,
 *args, **kwargs)
 Module _reports_create_report_step2_mako:57 in render_body
 
 context.write(filters.decode.utf8(urllib.unquote(str(c.period.end
 context.write(u' + ')

 context.write(filters.decode.utf8(urllib.unquote(c.user.firstName).decode('utf-8')
 [0].encode('utf-8')))

 context.write(filters.decode.utf8(urllib.unquote(str(c.user.secondName)
 [0:1])))
 context.write(u'/h3\r\ninput type=hidden
 name=works[] value=')
 context.write(filters.decode.utf8(urllib.unquote(c.user.firstName).decode('utf-8')
 [0].encode('utf-8')))
 Module encodings.utf_8:16 in decode
 
 def decode(input, errors='strict'):
 return codecs.utf_8_decode(input, errors, True)

 class IncrementalEncoder(codecs.IncrementalEncoder):  return
 codecs.utf_8_decode(input, errors, True)
 type 'exceptions.UnicodeEncodeError': 'ascii' codec can't encode
 characters in position 0-1: ordinal not in range(128)

ok, I resolved this problem $
{urllib.unquote(str(c.user.firstName)).decode('utf-8')[0]}

Could anyone explain me why this code works?
--

Re: Inquiry regarding the name of subprocess.Popen class

2008-09-02 Thread Gabriel Genellina
En Mon, 01 Sep 2008 04:23:38 -0300, Jeremy Banks [EMAIL PROTECTED] escribió:

 Hi. I wondered if anyone knew the rationale behind the naming of the
 Popen class in the subprocess module. Popen sounds like the a suitable
 name for a function that created a subprocess, but the object itself is
 a subprocess, not a popen. It seems that it would be more accurate to
 just name the class Subprocess, can anyone explain why this is not the
 case?

I have no idea - but I agree, Subprocess would have been a better name.

-- 
Gabriel Genellina

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


Re: Inquiry regarding the name of subprocess.Popen class

2008-09-02 Thread Gabriel Genellina
En Mon, 01 Sep 2008 04:23:38 -0300, Jeremy Banks [EMAIL PROTECTED] escribió:

 Hi. I wondered if anyone knew the rationale behind the naming of the
 Popen class in the subprocess module. Popen sounds like the a suitable
 name for a function that created a subprocess, but the object itself is
 a subprocess, not a popen. It seems that it would be more accurate to
 just name the class Subprocess, can anyone explain why this is not the
 case?

I have no idea - but I agree, Subprocess would have been a better name.

-- 
Gabriel Genellina

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


Re: python mechanize/libxml2dom question

2008-09-02 Thread Paul Boddie
On 2 Sep, 05:35, bruce [EMAIL PROTECTED] wrote:

 i've got the following situation, with the following test url:
 http://schedule.psu.edu/soc/fall/Alloz/a-c/acctg.html#;.

 i can generate a list of the tables i want for the courses on the page.
 however, when i try to create the xpath query, and plug it into the xpath
 within python, i'm missing something. if i have a parent xpath query, that
 generates a list of results/nodes... how can i then use the individual
 parent node, and trigger off of it, to get further information.

You can always use the parentNode property on the nodes you get as
results from the XPath query, but I guess what you want to do is to
rewind and issue queries relative to some ancestor of the result
nodes.

[...]

 #  course names

 cpath='//table[position()0]/descendant::td[position()[EMAIL 
 PROTECTED]85%]/../td[1]/font/a[2]/text()'

This obviously gets you right down to the hyperlink text within a part
of the table. However, it may be easier to break this query up in
order to get a more manageable overview of the process. My
understanding of the above query is that it can first be rewritten as
the following:

cpath = //table//td[position()=2 and @width='85%']/../td[1]/font/a[2]/
text()

Or even this:

cpath = //table[.//td[position()=2 and @width='85%']]//td[1]/font/
a[2]/text()

But what you could do is to obtain the important tables first:

tables = d.xpath(//table[.//td[position()=2 and @width='85%']])

Here, we use the bracketed term to ensure that the table is the right
one, but we don't actually descend inside the table.

You could, from this, get the name by doing a query from each of these
tables:

for table in tables:
cnames = table.xpath(.//td[1]/font/a[2]/text()) # list of text
nodes

You might want to consider a slightly safer approach when getting the
text:

cnames = table.xpath(.//td[1]/font/a[2]) # list of nodes, should
be one
name = cnames[0].textContent # all the text from the link

When looking for the details, you can then write your query relative
to these tables, rather than having to figure out the location of the
details from the text nodes you've just extracted.

details = table.xpath(following-sibling::table[1]) # list of max
1 node

 i'm assuming that there's a libxml2node method that will do what i need that
 i'm missing...

You should be able to issue XPath queries from any node. There have
been issues with libxml2dom and attribute nodes obtained from XPath,
but these were fixed in recent changesets.

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


python glibc error

2008-09-02 Thread anand nalya
I'm getting the following errors while trying to run a python script:

*** glibc detected *** python: free(): invalid next size (normal):
0x0d2da210 ***

*** glibc detected *** python: malloc(): memory corruption:
0x1b81da60 ***

Is this a bug in my script or python or gllbc?

Relevent version numbers are:
#uname -a
Linux myserver 2.6.18-92.1.10.el5 #1 SMP Tue Aug 5 07:42:41 EDT 2008 x86_64
x86_64 x86_64 GNU/Linux
# python -V
Python 2.4.3
/lib/libc.so.6 | head -1
GNU C Library stable release version 2.5, by Roland McGrath et al.

The same script is running fine of fedora 4:
On Fedora:
uname -a
Linux onyomo.com 2.6.11-1.1369_FC4smp #1 SMP Thu Jun 2 23:08:39 EDT 2005
i686 i686 i386 GNU/Linux
python -V
Python 2.4.1
/lib/libc.so.6 | head -1
GNU C Library development release version 2.3.5, by Roland McGrath et al.

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

Re: Relative imports and import X as Y

2008-09-02 Thread Gabriel Genellina
En Sun, 31 Aug 2008 07:27:12 -0300, Wojtek Walczak [EMAIL PROTECTED] escribió:

 On Sun, 31 Aug 2008 06:40:35 GMT, OKB (not okblacke) wrote:

 Download the latest beta for your system and give it a try.

  Thanks for the advice, but I'd really rather not deal with
 installing the entire thing alongside my existing version, possibly
 causing conflicts in who knows what ways.

 Then you can download tar.gz package, compile it, and try it
 without installing :-)

Or use a virtual machine, or a live CD.

-- 
Gabriel Genellina

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


Re: The Importance of Terminology's Quality

2008-09-02 Thread RedGrittyBrick


George Neuner wrote:

On Mon, 1 Sep 2008 21:03:44 + (UTC), Martin Gregorie
[EMAIL PROTECTED] wrote:


On Mon, 01 Sep 2008 12:04:05 -0700, Robert Maas, http://tinyurl.com/uh3t
wrote:


From: George Neuner [EMAIL PROTECTED] A friend of mine had an
early 8080 micros that was programmed through the front panel using
knife switches

When you say knife switches, do you mean the kind that are shaped like
flat paddles? 


Pedantic correction:

Knife switch is the wrong term. These are high current switches, 
typically used in the sort of heavy duty circuit where the wiring hums 
when power is on or in school electrical circuits so even the back of the 
class can see whether the switch is open or closed. In these a copper 
'blade' closes the contact by being pushed down into a 
narrow, sprung U terminal that makes a close contact with both sides of 
the blade. Like this: http://www.science-city.com/knifeswitch.html


What you're talking is a flat handle on a SPST or DPST toggle switch. It 
is often called a paddle switch and mounted with the flats on the handle 
horizontal. Like this, but often with a longer handle: 
http://www.pixmania.co.uk/uk/uk/1382717/art/radioshack/spdt-panel-mount-

paddle-s.html


I don't know the correct term, but what I was talking about was a tiny
switch with a 1/2 inch metal handle that looks like a longish grain of
rice.  We used to call them knife switches because after hours
flipping them they would feel like they were cutting into your
fingers.



That must be a toggle switch (as MG suggested) just not the paddle type.

e.g.
http://cpc.farnell.com/SW02861/components-spares/product.us0?sku=multicomp-1m31t1b1m1qe
http://tinyurl.com/64a8ld


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


Re: Python 3.0b2 cannot map '\u12b'

2008-09-02 Thread Jukka Aho

Terry Reedy wrote:


If the terminal expects cp437 then displaying utf-8 might give some
problems.



My screen displays whatever Windows tells the graphics card to tell
the screen to display.  In OpenOffice, I can select a unicode font
that displays at least everything in the BasicMultilingualPlane (BMP).


It would appear that the Windows port of Python is probably just not 
forcing the Win32 console into the Unicode mode or using the Unicode 
APIs. (If this holds true, it could be a leftover from the Windows 
95/98/ME days, I suppose...)


http://en.wikipedia.org/wiki/Win32_console

As a workaround - for the time being - you might want to try something 
similar as described in the thread Changing the (codec) error handler 
for the stdout/stderr streams in Python 3.0.


The approach described in there will not let you print characters 
outside the codepage 437 repertoaire - any such characters will still 
need to be substituted with something else - but at least this 
substitution should happen automatically; i.e. you can keep using the 
normal print() function the normal way - even for the fancier 
characters - and your program will no longer crash.


It would be nice to see proper Unicode Win32 console support in Python, 
of course, if at all possible.


--
znark

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


Re: The Importance of Terminology's Quality

2008-09-02 Thread Martin Gregorie
On Mon, 01 Sep 2008 20:48:23 -0400, George Neuner wrote:

 I don't know the correct term, but what I was talking about was a tiny
 switch with a 1/2 inch metal handle that looks like a longish grain of
 rice.  We used to call them knife switches because after hours
 flipping them they would feel like they were cutting into your fingers.

That sounds like a sub-minature SPDT toggle switch with a normal handle. 
Cheap as chips, which is probably why they were used on that front panel. 
Like this by any chance?

http://www.maplin.co.uk/images/300/fh00a_ff70m.jpg




-- 
martin@   | Martin Gregorie
gregorie. | Essex, UK
org   |
--
http://mail.python.org/mailman/listinfo/python-list


Re: Numeric literal syntax (was: Py 2.6 changes)

2008-09-02 Thread Nick Craig-Wood
[EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
  Ben Finney:
  I don't see any good reason (other than your familiarity with the D
  language) to use underscores for this purpose, and much more reason
  (readability, consistency, fewer arbitrary differences in syntax,
  perhaps simpler implementation) to use whitespace just as with string
  literals.
 
  It's not just my familiarity, Ada language too uses underscore for
  that purpose, I think, so there's a precedent, and Ada is a language
  designed to always minimize programming errors, simple code mistakes
  too.

And perl also

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


Re: Inquiry regarding the name of subprocess.Popen class

2008-09-02 Thread Nicola Musatti
On Sep 1, 9:23 am, Jeremy Banks [EMAIL PROTECTED] wrote:
 Hi. I wondered if anyone knew the rationale behind the naming of the
 Popen class in the subprocess module. Popen sounds like the a suitable
 name for a function that created a subprocess, but the object itself is
 a subprocess, not a popen. It seems that it would be more accurate to
 just name the class Subprocess, can anyone explain why this is not the
 case?

The Python class is a generalization of the standard Posix function of
(almost) the same name: http://opengroup.org/onlinepubs/007908775/xsh/popen.html

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


Re: Inquiry regarding the name of subprocess.Popen class

2008-09-02 Thread Marc 'BlackJack' Rintsch
On Tue, 02 Sep 2008 05:02:07 -0700, Nicola Musatti wrote:

 On Sep 1, 9:23 am, Jeremy Banks [EMAIL PROTECTED] wrote:
 Hi. I wondered if anyone knew the rationale behind the naming of the
 Popen class in the subprocess module. Popen sounds like the a suitable
 name for a function that created a subprocess, but the object itself is
 a subprocess, not a popen. It seems that it would be more accurate to
 just name the class Subprocess, can anyone explain why this is not the
 case?
 
 The Python class is a generalization of the standard Posix function of
 (almost) the same name:
 http://opengroup.org/onlinepubs/007908775/xsh/popen.html

So it's a name of a *function* and it's a little bit unsuitable for a 
*class*.  As Jeremy wrote: the instances represent *processes* not 
popens, whatever that may be.

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


Re: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp

2008-09-02 Thread Guilherme Polo
On Tue, Sep 2, 2008 at 12:44 AM, akineko [EMAIL PROTECTED] wrote:
 On Sep 1, 8:28 pm, Guilherme Polo [EMAIL PROTECTED] wrote:
 Can you clarify what is this sticky behavior ? Are you referring to
 a toggle button ? If yes, then you might be after a simple
 Checkbutton:

 checkbutton = Tkinter.Checkbutton(indicatoron=False, text='test')

 I wouldn't spend days to create a custom widget to mimick the
 Checkbutton ;-)

 I don't need to describe the detail but once the button was pressed
 for a bit while, a command is sent through communication.
 The button is left being ButtonDown (sticky) until an
 acknowledgement is sent back through communication.
 This is a way to let the user know the action was acknowledged at
 another end.

 I think probably very few people needs such widget.

Did you even try creating a checkbutton with indicatoron=False ? You
could get surprised.


 Aki-

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




-- 
-- Guilherme H. Polo Goncalves
--
http://mail.python.org/mailman/listinfo/python-list


about downloading the selected information

2008-09-02 Thread woaibeiyang
I have a problem to download the information from url 
http://www.ncbi.nlm.nih.gov/sites/entrez. Because it is impossible for me to 
add searching material to the url to construct a new url and then visit the 
website.
I have the searching material, however I could not find the way to deal with 
this problem. I want to know how can I do this problem with python and which 
part of knowledge should I view first? Thanks! 


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


Algorithm used by difflib.get_close_match

2008-09-02 Thread Guillermo

Hi all,

Does anyone know whether this function uses edit distance? If not,
which algorithm is it using?

Regards,

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


what's the difference between f(a) and f(*a)

2008-09-02 Thread qxyuestc
def sum1(*a): return(sum(i*i for i in a))
def sum2(a): return(sum(i*i for i in a))

a=[1,2,3]
print(sum1(*a), sum2(a))

showed above: the result from sum1() and sum2() is the same. So, what
is the difference between f(a) and f(*a)
--
http://mail.python.org/mailman/listinfo/python-list


How do I adjust the font size on IDLE when running on Mac OS 10.5.4? TIA.

2008-09-02 Thread Malcolm Lewis

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

Re: Inquiry regarding the name of subprocess.Popen class

2008-09-02 Thread Derek Martin
On Tue, Sep 02, 2008 at 12:27:49PM +, Marc 'BlackJack' Rintsch wrote:
  The Python class is a generalization of the standard Posix function of
  (almost) the same name:
  http://opengroup.org/onlinepubs/007908775/xsh/popen.html
 
 So it's a name of a *function* and it's a little bit unsuitable for a 
 *class*.  As Jeremy wrote: the instances represent *processes* not 
 popens, whatever that may be.

I would argue that they don't represent processes at all; the object
is a set of files which connect the standard I/O streams of a
subprocess to its parent, and methods to operate on those files.  The
C library's popen() function, on which this class is based, provides a
means to open a file and connect it to the standard steams of a
subprocess, making it more closely analogous to what the Popen class
does/provides.  As such, Popen is a better name to describe this
object than subprocess would be.  

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



pgpR91MGDIrTx.pgp
Description: PGP signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: Algorithm used by difflib.get_close_match

2008-09-02 Thread Jon Clements
On Sep 2, 2:17 pm, Guillermo [EMAIL PROTECTED] wrote:
 Hi all,

 Does anyone know whether this function uses edit distance? If not,
 which algorithm is it using?

 Regards,

 Guillermo

help(difflib.get_close_matches) will give you your first clue...
--
http://mail.python.org/mailman/listinfo/python-list


What is module initialization?

2008-09-02 Thread dudeja . rajat
Hi,

I found on the net that there is something called module
initialization. Unfortunately, there is not much information for this.
However, small the information I found module initialization can be of
use to me in my project.

I'm currently messing with a problem where I'm keeping my global
variables ( or symbols) in a module and the other mdoules in the
project acess these global variables.

However, there is one case when a module updates one such global
variable but the variable is not getting updated in the module
containing global symbols ( variables). This happen only at the start
of the program and at rest of the places in the program that global
variable is not accessed.

So, I thought of using this module initialization where I will
intialize the module only once to update that variable. Ans in the
rest of the program where ever this module is imported I shall be able
to easily access the update value of the variable.

Could some one provide me a sample code of module intialization? And
how can I ensure that module initialization is done only once?

Thanks and regards,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list


Re: Algorithm used by difflib.get_close_match

2008-09-02 Thread Wojtek Walczak
On Tue, 2 Sep 2008 06:17:37 -0700 (PDT), Guillermo wrote:

 Does anyone know whether this function uses edit distance? If not,
 which algorithm is it using?

The following passage comes from difflib.py:

SequenceMatcher is a flexible class for comparing pairs of sequences of
any type, so long as the sequence elements are hashable.  The basic
algorithm predates, and is a little fancier than, an algorithm
published in the late 1980's by Ratcliff and Obershelp under the
hyperbolic name gestalt pattern matching.  The basic idea is to find
the longest contiguous matching subsequence that contains no junk
elements (R-O doesn't address junk).  The same idea is then applied
recursively to the pieces of the sequences to the left and to the right
of the matching subsequence.  This does not yield minimal edit
sequences, but does tend to yield matches that look right to
people.

HTH.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is module initialization?

2008-09-02 Thread Marc 'BlackJack' Rintsch
On Tue, 02 Sep 2008 14:32:30 +0100, dudeja.rajat wrote:

 I found on the net that there is something called module initialization.
 Unfortunately, there is not much information for this. However, small
 the information I found module initialization can be of use to me in my
 project.

Module initialization is what happens when you import a module the 
first time.  In pure Python modules the module level code is executed and 
in extension modules a special initializing function may be called.

 However, there is one case when a module updates one such global
 variable but the variable is not getting updated in the module
 containing global symbols ( variables).

Sounds unlikely if you *really* update the attribute of the module and 
not just rebind a local name that was bound to the object in the global 
module before.  Example:

from spam import egg

egg = 42  # This does *not* change `spam.egg` but just the local binding!


 Could some one provide me a sample code of module intialization? And how
 can I ensure that module initialization is done only once?

Module initialization is only done once, there's nothing to ensure.

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


Re: what's the difference between f(a) and f(*a)

2008-09-02 Thread Marc 'BlackJack' Rintsch
On Tue, 02 Sep 2008 06:24:21 -0700, qxyuestc wrote:

 showed above: the result from sum1() and sum2() is the same. So, what is
 the difference between f(a) and f(*a)

f(a) - f([1, 2, 3])
f(*a) - f(1, 2, 3)

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


Re: Inquiry regarding the name of subprocess.Popen class

2008-09-02 Thread Marc 'BlackJack' Rintsch
On Tue, 02 Sep 2008 09:28:42 -0400, Derek Martin wrote:

 On Tue, Sep 02, 2008 at 12:27:49PM +, Marc 'BlackJack' Rintsch
 wrote:
  The Python class is a generalization of the standard Posix function
  of (almost) the same name:
  http://opengroup.org/onlinepubs/007908775/xsh/popen.html
 
 So it's a name of a *function* and it's a little bit unsuitable for a
 *class*.  As Jeremy wrote: the instances represent *processes* not
 popens, whatever that may be.
 
 I would argue that they don't represent processes at all; the object is
 a set of files which connect the standard I/O streams of a subprocess to
 its parent, and methods to operate on those files.

And the process' ID, an attribute with the process' return code, a method 
to wait until the process is finished and file objects to communicate 
with the process.

 The C library's popen() function, on which this class is based,
 provides a means to open a file and connect it to the standard steams
 of a subprocess, making it more closely analogous to what the Popen
 class does/provides.  As such, Popen is a better name to describe
 this object than subprocess would be.

Is strongly disagree.  The class provides an interface to start and 
communicate with a `Subprocess`.  Instances stand for processes.

With your reasoning the `file` type should be called `open`.

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


Re: How can we get to the end of a quote inside a string

2008-09-02 Thread Antoon Pardon
On 2008-08-31, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 Hi all,
 Suppose I have a string which contains quotes inside quotes -
 single and double quotes interchangeably -
  s = a1' b1  c1' d1 ' c2 b2 'a2
  I need to start at b1 and end at b2 - i.e. I have to parse the
 single quote strings from inside s.

  Is there an existing string quote parser which I can use or
 should I write a parser myself?

  If somebody could help me on this I would be much obliged.

You could use a combination of split and join in this case.

#use a single quote as a seperator to split the string is a list of substrings
ls = s.split(')

#remove what comes before the first and after the last single quote
ls = ls[1:-1]

#reassemble the string between the outermost single quotes.
s = '.join(ls)

#strip spaces in front and after if you wish
s = s.strip()

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


Python IDEs with F5 or hotkey shell interaction

2008-09-02 Thread mmm
I am looking for advice on Python Editors and IDEs

I have read other posts and threads on the subject and my two
questions at this time are mainly about the IDLE-like F5-run
facilities.  While I am fairly happy using IDLE, the debugger is
unintuitive to me and I wanted a project manager and a better variable/
class browser and also the potential to edit/run other languages such
as R and Tex/Latex. Windows and LINUX compatibility is desired too.

I found numerous editor candidates from reading posts to this Python
users group list  and also documents such as   
http://wiki.python.org/moin/PythonEditors
but few if any alternatives seem to have all of the  ‘interactive’
power of IDLE—- not only a run program in a python shell hotkey but a
persistent, after-a-run memory state can be accessed for interactive
coding and exploration--  i.e. how IDLE works !

*** My first questions is what other editor/IDE have IDLE-like
interactive features.  Or to put it another way, is my appraisal below
of the editors  IDEs I tried right (note some where looked at as much
as a year ago).

Python specific
 IDLEF5 run  Full shell interaction
 PythonWin   F5 run  Full shell interaction, MS Windows only
 PyScripter  F9 run  shell interaction,
 but script created variables are not persistent
(???!)
 PyPEF5 run, but not an interactive shell
 DrPythonF5 run, but not an interactive shell in MS Windows (maybe
in Linux)
 SPE (Stani) Could not get it to run in MS Windows (???!)

PyScripter, PyPe and drPython all had nice features but interaction
quirks.

My second question is based on a belief that I should move to a more
general IDE or editor to get  LINUX compatibility and the ability to
also edit R and LaTex programs.  I have explored these
   Vim
   Cream/Vim
   UliPad
   SciTe
   Jext
   Editra
   Komodo Editor
But none are close to being as interactive friendly as IDLE.

I might look at
  Eclypse with pydev
  Jedit
And these commercial/professional IDEs
  Wing
  Komodo IDE
  Zeus

But before doing so I wanted to know form experienced users:

** How hard is it to configure any of the general editors/IDEs to run
a Python shell using a hotkey (such as IDLEs F5) and whether any can
be set up for full interactivity.

I understand and appreciate  the difficulties to get full IDLE-like
interactivity, but what comes closest?
--
http://mail.python.org/mailman/listinfo/python-list


Leo 4.5 final released

2008-09-02 Thread Edward K Ream
Leo 4.5 final is now available at:
http://sourceforge.net/project/showfiles.php?group_id=3458package_id=29106

Leo is a text editor, data organizer, project manager and much more. See:
http://webpages.charter.net/edreamleo/intro.html

The highlights of Leo 4.5:
--

- Full support for @shadow files in Leo's core.
- Major improvements to Leo's key binding code.
- The beginning of usable vim-like bindings.
- uA's may now be associated with vnodes in @thin and @shadow files.
- Several magor reorganizations of Leo's code:
  including sax-based parsing, support for the Graph world (unified nodes),
  and simplified drawing code.
- Leo is now an installable package.
- Prepared code to be ready for Python 3.0.
- Many small improvements and bug fixes.

Quote of the month:
---
Squeak and Leo have been two of the most significant technologies to
redefine my personal computer experience and the ideas behind computing.

Links:
--
Leo:  http://webpages.charter.net/edreamleo/front.html
Forum:http://groups.google.com/group/leo-editor
Download: http://sourceforge.net/project/showfiles.php?group_id=3458
Bzr:  http://code.launchpad.net/leo-editor/
Quotes:   http://webpages.charter.net/edreamleo/testimonials.html


Edward K. Ream   email:  [EMAIL PROTECTED]
Leo: http://webpages.charter.net/edreamleo/front.html



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


Re: What is module initialization?

2008-09-02 Thread Bruno Desthuilliers

[EMAIL PROTECTED] a écrit :

Hi,

I found on the net that there is something called module
initialization.


The Python C api has a module init function for C-coded modules. There's 
no need for such a thing in pure Python modules since all the top-level 
code is executed when the module is loaded (as a main script or the 
first time the module is imported).



Unfortunately, there is not much information for this.
However, small the information I found module initialization can be of
use to me in my project.

I'm currently messing with a problem where I'm keeping my global
variables ( or symbols) in a module and the other mdoules in the
project acess these global variables.


remember that there's no such thing as a truely global namespace in 
Python. global really means module level.



However, there is one case when a module updates one such global
variable


While this is technically legal, you should restrain yourself from doing 
such a thing, unless you *really* know what you're doing and why.



but the variable is not getting updated in the module
containing global symbols ( variables).


I suspect you didn't use a qualified name when importing. You have to do 
it this way :


# myglobals.py:
answer = 42

# question.py
import myglobals
myglobals.answer = WTF ?


So, I thought of using this module initialization where I will
intialize the module only once to update that variable. Ans in the
rest of the program where ever this module is imported I shall be able
to easily access the update value of the variable.

Could some one provide me a sample code of module intialization?


All statements at the top-level of a module are executed when the module 
is loaded. That's all it takes wrt/ module initialization.



And
how can I ensure that module initialization is done only once?


Unless you're doing weird things with __import__ or the imp module, you 
shouldn't have to worry. import do two things : locate, load *and cache* 
the module *if* it isn't already in cache, and bind names into the 
importing namespace.

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


Re: what's the difference between f(a) and f(*a)

2008-09-02 Thread Bruno Desthuilliers

[EMAIL PROTECTED] a écrit :

def sum1(*a): return(sum(i*i for i in a))
def sum2(a): return(sum(i*i for i in a))

a=[1,2,3]
print(sum1(*a), sum2(a))

showed above: the result from sum1() and sum2() is the same. So, what
is the difference between f(a) and f(*a)


try this:

sum1(a)
sum2(*a)

Then re-read the FineManual(tm):
http://docs.python.org/tut/node6.html#SECTION00673

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


Re: SQL package

2008-09-02 Thread Diez B. Roggisch

Juan schrieb:

Hi

I am trying to write a little a script that can be configurable. This
script should access to a database, that can be of any type (MySQL,
Postgres, SQLite, MS, etc).It has only to perform 2 or 3 simple plain
SQL queries. Hi have tested SQLAlchemy, and it is great, but too much
for my requirements, and I don't have any object relation with the
database tables. All I need is to access any database type in the same
way (mysql://user:[EMAIL PROTECTED]/database, pgsqll://user:[EMAIL 
PROTECTED]/database,
...) and run some basic queries. I have searched for this, but I have
not found any solution. Could you help me please?

If not, how can I run a simple query in SQLAlchemy? And iter the
results? I have tried this without success:

engine = create_engine('postgres://user:[EMAIL PROTECTED]/database',
echo=True)
results = engine.execute(SELECT * FROM TABLE)
for result in results:
print result


sqlalchemy is the way to go, and you should consider actually reading 
the documentation - the above clearly shows that you didn't.


http://www.sqlalchemy.org/docs/05/sqlexpression.html

Here you can see what is needed:
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is module initialization?

2008-09-02 Thread dudeja . rajat
 While this is technically legal, you should restrain yourself from doing
 such a thing, unless you *really* know what you're doing and why.

 but the variable is not getting updated in the module
 containing global symbols ( variables).

 I suspect you didn't use a qualified name when importing. You have to do it
 this way :

 # myglobals.py:
 answer = 42

 # question.py
 import myglobals
 myglobals.answer = WTF ?


But if I do :-
#question.py
from myglobals import *
myglobals.answer = WTF ?

will this work?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Storing Subprocess Results

2008-09-02 Thread Wojtek Walczak
On Tue, 2 Sep 2008 07:16:21 -0700 (PDT), topazcode wrote:
 I am using the subprocess module to run some shell commands on a Linux
 system:

 import subprocess
 output = subprocess.call('''ssh server1 uptime''', shell=True)

 The above assigns the output variable with a return code, i.e. 0 in
 this case.  How can I actually capture the data returned from
 subprocess.call, rather than just the return code?

Use subprocess.Popen instead of call.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Storing Subprocess Results

2008-09-02 Thread Benjamin Kaplan
On Tue, Sep 2, 2008 at 10:16 AM, topazcode [EMAIL PROTECTED] wrote:

 I am using the subprocess module to run some shell commands on a Linux
 system:

 import subprocess
 output = subprocess.call('''ssh server1 uptime''', shell=True)

 The above assigns the output variable with a return code, i.e. 0 in
 this case.  How can I actually capture the data returned from
 subprocess.call, rather than just the return code?  I'd like to have
 the output variable contain the uptime string in this case.  Any help
 is appreciated.  Thanks.
 --
 http://mail.python.org/mailman/listinfo/python-list



http://docs.python.org/lib/node532.html
--
http://mail.python.org/mailman/listinfo/python-list

Re: Using NLTK in Java

2008-09-02 Thread hussainsaiger
On 1 Sep, 16:21, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  On 1 Sep, 11:55, Diez B. Roggisch [EMAIL PROTECTED] wrote:
  [EMAIL PROTECTED] schrieb:

   I am trying to convert a python module (that contains the use of
   NLTK.Corpus) by jythonc. It is not able to include nltk dependencies
   within the java class it creates. So when i use this class in java, it
   fails to recognize nltk. Can anyone please let me know how should i
   use nltk in python/jython modules so i can use in Java.

  If there are any binary dependencies, you are out of luck. It won't
  work. You would need to write a RPC-Server then, with technologies such
  as XMLRPC or CORBA.

  Diez

  So does that mean that Jython does not support nltk uptil now. I ask
  this because when I try to import nltk in Jython (which is assumed to
  replace Python), i get the same error. Its just nltk that I am not
  able to use. The rest of the jython functions and libraries work fine
  within Java.

 I don't know for sure - how about you post the error-message? Otherwise we
 can't assess the problem.

 Diez- Hide quoted text -

 - Show quoted text -

Hi,

What i did was create a python file as:

import nltk
from java.util import Random

class NLPPresentation(Random):
def nextDouble(self):
return 1
def TagByBrown(self,sent):
@sig public String[] TagByBrown(String sent)
brown_a = nltk.corpus.brown.tagged_sents(categories='a')
bigram_tagger = nltk.BigramTagger(brown_a, cutoff=0)
lst = bigram_tagger.tag(sent.split())
return lst

I processed the following code through jythonc compiler to form a JAR
file. I then imported this jar
file into java ide (Java Builder). I then wrote the following program
in java to access this python class:

import org.python.core.PyException;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
import java.util.Random;
import org.nltk.*;
import org.nltk.mallet.*;
public class SimpleEmbedded extends NLPPresentation{
public static void main(String[] args) throws PyException {
SimpleEmbedded so = new SimpleEmbedded();
String s = he is a boy;
so.Call(s);
}
public void Call(String s)
{
String[] arr = TagByBrown(s);
System.out.println(arr[1]);
}
}

When i compile the above java code, i get the following error:

Exception in thread main Traceback (innermost last):
  File C:\jython2.2.1\NLPPresentation.py, line 0, in main
ImportError: no module named nltk

Your comments are highly appreciated.
--
http://mail.python.org/mailman/listinfo/python-list


Re: configure kdevelop for python

2008-09-02 Thread John Fabiani
Sindhu wrote:

 am a newbie to python language and kdevelop, so i would like to know
 how to configure kdevelop for python programming? complete with a
 debugger?

I have not used python and kdevelop but I do know it requires qt and the
link below has several video's of a developer using python qt and
qtdesigner.
http://tv.dgplug.org/devel-inside.html

I hope this helps.

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


Re: What is module initialization?

2008-09-02 Thread Wojtek Walczak
On Tue, 2 Sep 2008 15:32:07 +0100, [EMAIL PROTECTED] wrote:

 But if I do :-
#question.py
 from myglobals import *
 myglobals.answer = WTF ?

 will this work?

Why won't you try? In this case you should receive NameError.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: How can we get to the end of a quote inside a string

2008-09-02 Thread Paul McGuire
On Aug 31, 9:29 am, [EMAIL PROTECTED] wrote:
 Hi all,
     Suppose I have a string which contains quotes inside quotes -
 single and double quotes interchangeably -
  s = a1' b1  c1' d1 ' c2 b2 'a2
      I need to start at b1 and end at b2 - i.e. I have to parse the
 single quote strings from inside s.


Pyparsing defines a helper method called nestedExpr - typically it is
used to find nesting of ()'s, or []'s, etc., but I was interested to
see if I could use nestedExpr to match nested ()'s, []'s, AND {}'s all
in the same string (like we used to do in our algebra class to show
nesting of higher levels than parens - something like {[a + 3*(b-c)]
+ 7} - that is, ()'s nest within []'s, and []'s nest within {}'s).
This IS possible, but it uses some advanced pyparsing methods.  I
adapted this example to map to your case - this was much simpler, as
s nest within ''s, and ''s nest within s.  I still keep a stack of
previous nesting, but I'm not sure this was absolutely necessary.
Here is the working code with your example:

from pyparsing import Forward, oneOf, NoMatch, Literal, CharsNotIn,
nestedExpr

# define special subclass of Forward, that saves previous contained
# expressions in a stack
class ForwardStack(Forward):
def __init__(self):
super(ForwardStack,self).__init__()
self.exprStack = []
self  NoMatch()
def __lshift__(self,expr):
self.exprStack.append(self.expr)
super(ForwardStack,self).__lshift__(expr)
return self
def pop(self):
self.expr = self.exprStack.pop()

# define the grammar
opening = ForwardStack()
closing = ForwardStack()
opening  oneOf([', ''])
closing  NoMatch()
matchedNesting = nestedExpr(opening, closing, CharsNotIn('\''),
ignoreExpr=None)

# define parse-time callbacks
alternate = {'':', ':''}
def pushAlternate(t):
# closing expression should match the current opening quote char
closing  Literal( t[0] )
# if we find the other opening quote char, it is the beginning of
# a nested quote
opening  Literal( alternate[ t[0] ] )
def popClosing():
closing.pop()
opening.pop()
# when these expressions match, the parse action will be called
opening.setParseAction(pushAlternate)
closing.setParseAction(popClosing)

# parse the test string
s =  a1' b1  c1' d1 ' c2 b2 'a2 

print matchedNesting.parseString(s)[0]


Prints:

['a1', [' b1 ', [' c1', [' d1 '], ' c2'], ' b2 '], 'a2']


-- Paul


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


dict.update

2008-09-02 Thread Mike P
Hi All,

I have two dictionaries e.g
dict1 = {123:3,234:5,456:3}
dict2 = {123:4,157:2,234:5,456:3,567:2}

I want to merge these two dictionaries together so i have a resultant
dictionary of:

dict3 = {123:[4,3],157:[2,0],234:[5,5],456:[3,3],567:[2,0]}

As later on i want to write a csv file that would have the form

id  var1  var2
123 4  3
157 2  0

i looks like the dict.update looks almost there but i can't get it to
work properly, can anyone offer any advise?

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


Re: dict.update

2008-09-02 Thread Diez B. Roggisch

Mike P schrieb:

Hi All,

I have two dictionaries e.g
dict1 = {123:3,234:5,456:3}
dict2 = {123:4,157:2,234:5,456:3,567:2}

I want to merge these two dictionaries together so i have a resultant
dictionary of:

dict3 = {123:[4,3],157:[2,0],234:[5,5],456:[3,3],567:[2,0]}

As later on i want to write a csv file that would have the form

id  var1  var2
123 4  3
157 2  0

i looks like the dict.update looks almost there but i can't get it to
work properly, can anyone offer any advise?



res = {}
for d in dict1, dict2:
for key, value in d.iteritems():
res.setdefault(key, []).append(value)


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


Re: dict.update

2008-09-02 Thread Raymond Hettinger
On Sep 2, 8:04 am, Mike P [EMAIL PROTECTED] wrote:
 Hi All,

 I have two dictionaries e.g
 dict1 = {123:3,234:5,456:3}
 dict2 = {123:4,157:2,234:5,456:3,567:2}

 I want to merge these two dictionaries together so i have a resultant
 dictionary of:

 dict3 = {123:[4,3],157:[2,0],234:[5,5],456:[3,3],567:[2,0]}

 As later on i want to write a csv file that would have the form

 id      var1  var2
 123     4      3
 157     2      0

 i looks like the dict.update looks almost there but i can't get it to
 work properly, can anyone offer any advise?

The update() method is not quite right for your purposes.
But a simple generator expression will do the trick:


 dict((k, [v, dict1.get(k, 0)]) for k, v in dict2.items())
{456: [3, 3], 234: [5, 5], 123: [4, 3], 157: [2, 0], 567: [2, 0]}


Raymond

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


Re: Using NLTK in Java

2008-09-02 Thread bearophileHUGS
On Sep 1, 12:30 pm, [EMAIL PROTECTED]:
in Jython (which is assumed to replace Python),

I don't think so.

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


Re: dict.update

2008-09-02 Thread Mike P
Thanks Diez,

This is almost perfect!

Is there a way to ensure each list has two elements, even if one of
them is blank?

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


Re: dict.update

2008-09-02 Thread Mike P
Thanks Raymond,

That's a neat trick, i'll look into learning more about this

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


Re: Inquiry regarding the name of subprocess.Popen class

2008-09-02 Thread Derek Martin
On Tue, Sep 02, 2008 at 01:57:26PM +, Marc 'BlackJack' Rintsch wrote:
  I would argue that they don't represent processes at all; the object is
  a set of files which connect the standard I/O streams of a subprocess to
  its parent, and methods to operate on those files.
 
 And the process' ID, an attribute with the process' return code, a method 
 to wait until the process is finished and file objects to communicate 
 with the process.

The name popen is an abbreviation of pipe open -- the function, and
the class, open pipes to communicate with another process.  What you
said is correct; however there are numerous other ways to open
subprocesses.  The focus of popen is the communication aspect -- the
opening and control of the pipes -- not the subprocess.  That's the
key difference between popen() and all the other methods of starting a
subprocess.

  The C library's popen() function, on which this class is based,
  provides a means to open a file and connect it to the standard steams
  of a subprocess, making it more closely analogous to what the Popen
  class does/provides.  As such, Popen is a better name to describe
  this object than subprocess would be.
 
 Is strongly disagree.  The class provides an interface to start and 
 communicate with a `Subprocess`.  Instances stand for processes.

There's more than one way to look at it.  You can disagree all you
like, but your interpretation disagrees with the historical intent of
popen.

 With your reasoning the `file` type should be called `open`.

In this case, the file is a pipe, and the 'p' in popen represents the
pipe.  Unix, by and large, doesn't care that it's a pipe -- file I/O
is intended to work the same way regardless of whether it's a pipe, a
socket, a file on disk, a special device file, or any other file-like
object you can imagine.  That's why I said file instead of pipe in
my explanation.

Note that in all of these links that talk about popen, the focus is on
opening pipes or file objects, not on subprocesses:

http://www.opengroup.org/onlinepubs/009695399/functions/popen.html
http://docs.python.org/lib/os-newstreams.html
http://us3.php.net/popen
http://docs.hp.com/en/B9106-90010/popen.3S.html
http://www.faqs.org/docs/artu/ch07s02.html

The Linux man page unfortunately copies (verbatim) the FreeBSD man
page, which gets it wrong.  You can not open a process, but you can
definitely open a pipe.

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



pgpmN360qDTwf.pgp
Description: PGP signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp

2008-09-02 Thread akineko
On Sep 2, 5:46 am, Guilherme Polo [EMAIL PROTECTED] wrote:
 Did you even try creating a checkbutton with indicatoron=False ? You
 could get surprised.

I didn't. My perception of checkbutton was a button with a check.
So, I tried as you suggested.
Yes, you are right. It is almost what I wanted (sticky behaviour).
By ignoring the ButtonRelease and Leave events, yes, it can perfectly
meet my requirements.
As checkbutton has deselect() method, this is a better approach, I
have to admit.

Thank you for showing me the correct way to implement.

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


Re: (in memory) database

2008-09-02 Thread Zentrader
 I don't understand why Cameron has a different version of Python which
 doesn't seem to have sqlite support enabled.

Agreed, but won't the package manager tell him if python-sqlite is
installed?  That would be the next step since it appears that SQLite
intself is already installed.  Since Ubuntu uses precompied binaries,
Python should be configured for SQLite which again leaves no python-
sqlite as the only possibility (yeah right).  BTW Python is easy to
install manually.

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


Re: dict.update

2008-09-02 Thread Tino Wildenhain

Mike P wrote:

Hi All,

I have two dictionaries e.g
dict1 = {123:3,234:5,456:3}
dict2 = {123:4,157:2,234:5,456:3,567:2}

I want to merge these two dictionaries together so i have a resultant
dictionary of:

dict3 = {123:[4,3],157:[2,0],234:[5,5],456:[3,3],567:[2,0]}

As later on i want to write a csv file that would have the form

id  var1  var2
123 4  3
157 2  0

i looks like the dict.update looks almost there but i can't get it to
work properly, can anyone offer any advise?


result=dict((key,(dict1.get(key,None),
   dict2.get(key,None)))
  for key in set(dict1.keys()+dict2.keys())
 )

(untested)

should provide you with a resulting dictonary with tuples
where [0] is var1 and [1] is var2, None for values not
in one of the dictionaries (you can put in 0 if you prefer).

You can use it like so to generate your output:

allitems=result.items()
allitems.sort() # sort based on keys as first tuple element

for (key,(var1,var2)) in allitems:
print key,var1,var2

HTH
Tino



smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: [ctypes-users] ctypes - loading 'librsvg-2-2.dll'

2008-09-02 Thread Tim Grove
Thanks Martin (and others) for your advice. No, this solution didn't 
quite work either. Well, the extremely annoying thing is that it DOES 
work on another home pc, but on my laptop which I use for work, it 
doesn't want to know!!! Both are running WinXP Pro. All the dependencies 
and paths seem to be okay, but there must still be something that I'm 
missing.


Tim


Martin (gzlist) wrote:

On 26/08/2008, Tim Grove [EMAIL PROTECTED] wrote:
  

Any ideas why a particular dll won't load on Windows XP Pro using
 ctypes?



I'm going to take a stab in the dark here and suggest it's because you
have multiple (different) copies of iconv.dll on your PATH.

  

 l=CDLL(r'D:\SILSign\librsvg-2-2.dll')
 Traceback (most recent call last):
  File input, line 1, in module
  File C:\PYTHON25\LIB\ctypes\__init__.py, line 349, in __init__
self._handle = _dlopen(self._name, mode)
 WindowsError: [Error 127] The specified procedure could not be found



I get this on my current setup, where I've been messing around trying
to recompile lynx against iconv. I also get a popup saying The
procedure entry point libiconv_set_relocation_prefix could not be
located in the dynamic link library iconv.dll.

Doing this worked for me:

C:\set PATH=C:\Program Files\Common Files\GTK\2.0\bin
C:\C:\Python24\python.exe -c import ctypes; print
ctypes.CDLL('librsvg-2-2')
CDLL 'librsvg-2-2', handle 68e4 at bd9b50

Change the paths to your equivalents and try it, see if you have the
same or a similar dependency problem.

Martin

  

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


source for the property function

2008-09-02 Thread Rowland Smith
Anyone know where the source code for the built-in property function  
is located in a python distribution?


I would like to see how it works - mainly, how does it know which  
class it is being called from?


Thanks,
Rowland

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


Re: Numeric literal syntax (was: Py 2.6 changes)

2008-09-02 Thread Peter Pearson
On 02 Sep 2008 06:10:51 GMT, Steven D'Aprano wrote:
 At the risk of bike-shedding, 
[snip]

(startled noises) It is a delight to find a reference to
that half-century-old essay (High Finance) by the wonderful
C. Northcote Parkinson, but how many readers will catch the
allusion?

-- 
To email me, substitute nowhere-spamcop, invalid-net.
--
http://mail.python.org/mailman/listinfo/python-list


email.Message problem

2008-09-02 Thread Corrado Gioannini
Hi all,
i know i'm probably going to ask a very silly question, but i
can't figure out where i'm doing wrong just reading the docs.

trying to build and send a mail message using the email.* modules
(with python 2.5).

a simplified version of my script that breaks is this:

mailtest.py
--
# coding: ISO-8859-15

import os, mimetypes, smtplib, base64, StringIO
import email.message, email.header, email.generator

messg = email.message.Message()
messg.set_charset('ISO-8859-15')

messg['To'] = '[EMAIL PROTECTED]'
messg['From'] = '[EMAIL PROTECTED]'
messg['Subject'] = email.header.Header(This is a test., 'ISO-8859-15')
messg[Message-ID] = email.Utils.make_msgid()
messg[Content-type] = Multipart/mixed
messg.preamble = Mime test\n

pl = email.Message.Message()
pl.add_header(Content-type, text/plain; charset=ISO-8859-15)
pl.add_header(Content-transfer-encoding, 8bit)
pl.set_payload(Body text goes here.\n, 'ISO-8859-15')
messg.attach(pl)

messg.as_string()
--

running it gives:

Traceback (most recent call last):
  File mailtest.py, line 22, in module
messg.as_string()
  File /usr/lib/python2.5/email/message.py, line 131, in as_string
g.flatten(self, unixfrom=unixfrom)
  File /usr/lib/python2.5/email/generator.py, line 84, in flatten
self._write(msg)
  File /usr/lib/python2.5/email/generator.py, line 109, in _write
self._dispatch(msg)
  File /usr/lib/python2.5/email/generator.py, line 135, in _dispatch
meth(msg)
  File /usr/lib/python2.5/email/generator.py, line 175, in
_handle_text
raise TypeError('string payload expected: %s' % type(payload))
TypeError: string payload expected: type 'list'



the real case is just a little more complex: i have to attach some
files and then send the message with smtplib to a list of recipients.

no problems when attaching files etc., but when i try to get the
message value 'flattened' to pass it to smtplib i always get an error
as above.

it seems to work only if i don't use .attach but just .set_payload in
the main message, but in this case i cannot attach the extra files
(or maybe i'm wrong in this?)


any help (or pointers to docs/examples etc) are very appreciated :-)

10x,
C.
-- 
Quando l'infanzia muore i suoi cadaveri sono chiamati adulti.
 (B. Aldiss)

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


Re: Changing the (codec) error handler for the stdout/stderr streams in Python 3.0

2008-09-02 Thread John Nagle

Jukka Aho wrote:
Just a tip for those who are only just cutting their teeth on Python 3.0 
and might have encountered the same problem as I did:


When a Python (3.x) program is run on a terminal that only supports a 
legacy character encoding - such as Latin 1 or Codepage 437 - all 
characters printed to stdout will be automatically converted from the 
interpreter's internal Unicode representation to this legacy character set.


   Python 5 is even stricter.  Only ASCII (chars 0..127) can be sent
to standard output by default.

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


pyparsing: match empty line

2008-09-02 Thread Marek Kubica
Hi,

I am trying to get this stuff working, but I still fail.

I have a format which consists of three elements:
\d{4}M?-\d (4 numbers, optional M, dash, another number)
EMPTY (the EMPTY token)
[Empty line] (the PAGEBREAK token. The line may contain whitespaces, 
but nothing else)

While the ``watchname`` and ``leaveempty`` were trivial, I cannot get 
``pagebreak`` to work properly.

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from pyparsing import (Word, Literal, Optional, Group, OneOrMore, Regex,
Combine, ParserElement, nums, LineStart, LineEnd, White,
replaceWith)

ParserElement.setDefaultWhitespaceChars(' \t\r')

watchseries = Word(nums, exact=4)
watchrev = Word(nums, exact=1)

watchname = Combine(watchseries + Optional('M') + '-' + watchrev)

leaveempty = Literal('EMPTY')

def breaks(s, loc, tokens):
print repr(tokens[0])
#return ['PAGEBREAK' for token in tokens[0]]
return ['PAGEBREAK']

#pagebreak = Regex('^\s*$').setParseAction(breaks)
pagebreak = LineStart() + LineEnd().setParseAction(replaceWith
('PAGEBREAK'))

parser = OneOrMore(watchname ^ pagebreak ^ leaveempty)

tests = [
2134M-2,
3245-3
3456M-5,
3256-4

4563-4,
4562M-6
 EMPTY
3246-5
]

for test in tests:
print parser.parseString(test)

The output should be:
['2134M-2']
['3245-3', '3456M-5']
['3256-4', 'PAGEBREAK' '4563-4']
['4562M-6', 'EMPTY', '3246-5']

Thanks in advance!
regards,
Marek
--
http://mail.python.org/mailman/listinfo/python-list


Large amount of files to parse/organize, tips on algorithm?

2008-09-02 Thread cnb
I have a bunch of files consisting of moviereviews.

For each file I construct a list of reviews and then for each new file
I merge the reviews so that in the end have a list of reviewers and
for each reviewer all their reviews.

What is the fastest way to do this?

1. Create one file with reviews, open next file an for each review see
if the reviewer exists, then add the review else create new reviewer.

2. create all the separate files with reviews then mergesort them?

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


Re: source for the property function

2008-09-02 Thread Diez B. Roggisch

Rowland Smith schrieb:
Anyone know where the source code for the built-in property function is 
located in a python distribution?


I would like to see how it works - mainly, how does it know which class 
it is being called from?



Google the descriptor protocol for new-style classes. That explains it.

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


Re: Changing the (codec) error handler for the stdout/stderr streams in Python 3.0

2008-09-02 Thread Steven D'Aprano
On Tue, 02 Sep 2008 09:57:05 -0700, John Nagle wrote:

 Jukka Aho wrote:
 Just a tip for those who are only just cutting their teeth on Python
 3.0 and might have encountered the same problem as I did:
 
 When a Python (3.x) program is run on a terminal that only supports a
 legacy character encoding - such as Latin 1 or Codepage 437 - all
 characters printed to stdout will be automatically converted from the
 interpreter's internal Unicode representation to this legacy character
 set.
 
 Python 5 is even stricter.  Only ASCII (chars 0..127) can be sent
 to standard output by default.


Python 5??? Is this the time machine again?



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


How to write verbose scripts

2008-09-02 Thread Steven D'Aprano
I find myself writing command line tools in Python where I wish to 
include verbose output to stdout.

I start with a helper function:


def print_(obj, level=0):
if _verbosity = level:
print obj


And then I end up with functions or methods looking like this:


def parrot(x)
print_(precondition, level=2)
do_something()
print_(status is good..., level=1)
print_(parrot is squawking strongly now, level=2)
do_something_else()
print_(squawk squawk squawk, level=3)
do_more()
print_(postcondition, level=1)
return something


That often means that my functions end up with more message printing code 
than actual code. The whole thing seems messy and hard to manage for all 
but the smallest scripts.

Worst of all, sometimes the messages I wish to print may be expensive to 
compute, and I don't want to waste time computing them if they aren't 
going to be printed because the verbosity is too low. But nor do I wish 
to fill my code with this:

if _verbosity = 3:
x = calculate_complicated_thing()
print_(x, level=3)



Is there a better way of doing this than the way I am going about it?



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


Re: How to write verbose scripts

2008-09-02 Thread Joe Riopel
On Tue, Sep 2, 2008 at 12:55 PM, Steven D'Aprano
[EMAIL PROTECTED] wrote:
 Is there a better way of doing this than the way I am going about it?

Would the logging module help, and just print the output to the stdout
(or a file) instead?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Large amount of files to parse/organize, tips on algorithm?

2008-09-02 Thread Steven D'Aprano
On Tue, 02 Sep 2008 09:48:32 -0700, cnb wrote:

 I have a bunch of files consisting of moviereviews.
 
 For each file I construct a list of reviews and then for each new file I
 merge the reviews so that in the end have a list of reviewers and for
 each reviewer all their reviews.
 
 What is the fastest way to do this?

Use the timeit module to find out.


 1. Create one file with reviews, open next file an for each review see
 if the reviewer exists, then add the review else create new reviewer.
 
 2. create all the separate files with reviews then mergesort them?

The answer will depend on whether you have three reviews or three 
million, whether each review is twenty words or twenty thousand words, 
and whether you have to do the merging once only or over and over again.


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


Re: (in memory) database

2008-09-02 Thread Peter Otten
Zentrader wrote:

 I don't understand why Cameron has a different version of Python which
 doesn't seem to have sqlite support enabled.
 
 Agreed, but won't the package manager tell him if python-sqlite is
 installed?  That would be the next step since it appears that SQLite
 intself is already installed.  Since Ubuntu uses precompied binaries,
 Python should be configured for SQLite which again leaves no python-
 sqlite as the only possibility (yeah right).  BTW Python is easy to
 install manually.

When you install Python manually from source you need the header files for
sqlite3 to get sqlite3 support. These are in the libsqlite3-dev package.

I think you can distinguish a manually installed python from the packaged
one by the .../local/... in its path, e. g., on my machine

$ which python2.5 # in the distribution
/usr/bin/python2.5
$ which python2.6
/usr/local/bin/python2.6 # installed from source

I have installed libsqlite3-dev so I can't reproduce Cameron's  error, but
here's a similar one for bsddb: 

$ python2.5
Python 2.5.1 (r251:54863, Jul 31 2008, 23:17:43)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type help, copyright, credits or license for more information.
 import bsddb
 bsddb.__file__
'/usr/lib/python2.5/bsddb/__init__.pyc'

$ python2.6
Python 2.6b2+ (trunk:65902, Aug 20 2008, 08:38:26)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type help, copyright, credits or license for more information.
 import bsddb
Traceback (most recent call last):
  File stdin, line 1, in module
  File /usr/local/lib/python2.6/bsddb/__init__.py, line 58, in module
import _bsddb
ImportError: No module named _bsddb

Peter

PS: Yes, I'm using 2.6, but I don't think that's relevant for the problem.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Numeric literal syntax

2008-09-02 Thread Alan G Isaac

On 02 Sep 2008 06:10:51 GMT, Steven D'Aprano wrote:
At the risk of bike-shedding, 

[snip]



Peter Pearson wrote:

(startled noises) It is a delight to find a reference to
that half-century-old essay (High Finance) by the wonderful
C. Northcote Parkinson, but how many readers will catch the
allusion?



It is pretty common geek speek:
http://en.wikipedia.org/wiki/Color_of_the_bikeshed

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


Re: What is module initialization?

2008-09-02 Thread Fredrik Lundh

[EMAIL PROTECTED] wrote:


# myglobals.py:
answer = 42

# question.py
import myglobals
myglobals.answer = WTF ?



But if I do :-
#question.py
from myglobals import *
myglobals.answer = WTF ?

will this work?


with the above definition of myglobals, no.  from myglobals import 
doesn't add the module object to the importing module's namespace.


have you read:

http://effbot.org/zone/import-confusion.htm

?

/F

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


Re: Numeric literal syntax

2008-09-02 Thread Fredrik Lundh

Peter Pearson wrote:


(startled noises) It is a delight to find a reference to
that half-century-old essay (High Finance) by the wonderful
C. Northcote Parkinson, but how many readers will catch the
allusion?


anyone that's been involved in open source on the development side for 
more than, say, ten minutes.


http://www.bikeshed.com/

/F

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


Re: source for the property function

2008-09-02 Thread Christian Heimes

Rowland Smith wrote:
Anyone know where the source code for the built-in property function is 
located in a python distribution?


I would like to see how it works - mainly, how does it know which class 
it is being called from?


Property is not a function but a type. Properties are a common usage for 
the descriptor protocol.


You can find the implementation of the property type in the file 
http://svn.python.org/projects/python/branches/release25-maint/Objects/descrobject.c


Christian

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


converting a sed / grep / awk / . . . bash pipe line into python

2008-09-02 Thread hofer
Hi,

Something I have to do very often is filtering / transforming line
based file contents and storing the result in an array or a
dictionary.

Very often the functionallity exists already in form of a shell script
with sed / awk / grep , . . .
and I would like to have the same implementation in my script

What's a compact, efficient (no intermediate arrays generated /
regexps compiled only once) way in python
for such kind of 'pipe line'

Example 1 (in bash):  (annotated with comment (thus not working) if
copied / pasted
#---
cat file \   ### read from file
| sed 's/\.\..*//' \### remove '//' comments
| sed 's/#.*//' \   ### remove '#' comments
| grep -v '^\s*$'  \### get rid of empty lines
| awk '{ print $1 + $2   $2 }' \ ### knowing, that all remaining
lines contain always at least
\   ### two integers calculate
sum and 'keep' second number
| grep '^42 ' ### keep lines for which sum is 42
| awk '{ print $2 }' ### print number

Same example in perl:
# I guess (but didn't try), taht the perl example will create more
intermediate
# data structures than necessary.
# Ideally the python implementation shouldn't do this, but just
'chain' iterators.
#---
my $filename= file;
open(my $fh,$filename) or die failed opening file $filename;

# order of 'pipeline' is syntactically reversed (if compared to shell
script)
my @numbers =
map { $_-[1] }   # extract num 2
grep { $_-[0] == 42   }  # keep lines with result 42
map { [ $_-[0]+$_-[1],$_-[1] ]  }  # calculate sum of first two
nums and keep second num
map { [ split(' ',$_,3) ]  }  # split by white space
grep { ! ($_ =~ /^\s*$/) }# remove empty lines
map { $_ =~ s/#.*//; $_}  # strip '#' comments
map { $_ =~ s/\/\/.*// ; $_}  # strip '//' comments
$fh;
print Numbers are:\n,join(\n,@numbers),\n;

thanks in advance for any suggestions of how to code this (keeping the
comments)


H




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


Problems when working with different timezones

2008-09-02 Thread ocgstyles
Here's some Python code executed on Red Hat 3.4 web server located in
Mountain time (MDT).  You'll notice that the time after setting the
timezone to Eastern time (EST), the time is incorrectly 6 hours ahead,
when it should only be 3.

Python 2.5 (r25:51908, Mar 23 2007, 14:22:20)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2
Type help, copyright, credits or license for more information.
 import datetime, os
 datetime.datetime.today()
datetime.datetime(2008, 9, 2, 11, 25, 35, 39856)
 os.environ['TZ']='America/New_York'
 datetime.datetime.today()
datetime.datetime(2008, 9, 2, 17, 26, 0, 703537)

Here's the same thing executed on an Ubuntu box in EST.  I alter the
timezone to a MDT and it works as one would expect.

Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type help, copyright, credits or license for more information.
 import datetime, os
 datetime.datetime.today()
datetime.datetime(2008, 9, 2, 13, 11, 6, 438123)
 os.environ['TZ'] = 'America/Denver'
 datetime.datetime.today()
datetime.datetime(2008, 9, 2, 11, 11, 21, 43602)

What could be the reason for this failing on Red Hat?

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


Re: Relative imports and import X as Y

2008-09-02 Thread OKB (not okblacke)
Gabriel Genellina wrote:

 En Sun, 31 Aug 2008 07:27:12 -0300, Wojtek Walczak
 [EMAIL PROTECTED] escribió: 
 
 On Sun, 31 Aug 2008 06:40:35 GMT, OKB (not okblacke) wrote:

 Download the latest beta for your system and give it a try.

  Thanks for the advice, but I'd really rather not deal
  with 
 installing the entire thing alongside my existing version,
 possibly causing conflicts in who knows what ways. 

 Then you can download tar.gz package, compile it, and try it
 without installing :-) 
 
 Or use a virtual machine, or a live CD.

Gosh, thanks, everyone, for being so helpful!

-- 
--OKB (not okblacke)
Brendan Barnwell
Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail.
--author unknown
--
http://mail.python.org/mailman/listinfo/python-list

Re: (in memory) database

2008-09-02 Thread Paul Boddie
On 2 Sep, 17:38, Zentrader [EMAIL PROTECTED] wrote:
  I don't understand why Cameron has a different version of Python which
  doesn't seem to have sqlite support enabled.

 Agreed, but won't the package manager tell him if python-sqlite is
 installed?

It shouldn't need to be installed: the python2.5 package includes the
sqlite3 module and the _sqlite extension module. He's running a more
modern version of Ubuntu than I am, but I don't think that they've
reintroduced the python-sqlite package in any form.

  That would be the next step since it appears that SQLite
 intself is already installed.  Since Ubuntu uses precompied binaries,
 Python should be configured for SQLite which again leaves no python-
 sqlite as the only possibility (yeah right).  BTW Python is easy to
 install manually.

Indeed, which is why I think that there must be a manually installed
Python on his system, especially given that /usr/local/lib/python2.5/
sqlite3/__init__.py is one of the files mentioned in the traceback.

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


Re: How to write verbose scripts

2008-09-02 Thread Mensanator
On Sep 2, 11:55 am, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 I find myself writing command line tools in Python where I wish to
 include verbose output to stdout.

 I start with a helper function:

 def print_(obj, level=0):
 if _verbosity = level:
 print obj

 And then I end up with functions or methods looking like this:

 def parrot(x)
 print_(precondition, level=2)
 do_something()
 print_(status is good..., level=1)
 print_(parrot is squawking strongly now, level=2)
 do_something_else()
 print_(squawk squawk squawk, level=3)
 do_more()
 print_(postcondition, level=1)
 return something

 That often means that my functions end up with more message printing code
 than actual code. The whole thing seems messy and hard to manage for all
 but the smallest scripts.

 Worst of all, sometimes the messages I wish to print may be expensive to
 compute, and I don't want to waste time computing them if they aren't
 going to be printed because the verbosity is too low. But nor do I wish
 to fill my code with this:

 if _verbosity = 3:
 x = calculate_complicated_thing()
 print_(x, level=3)

 Is there a better way of doing this than the way I am going about it?

I do something like this, although I don't know if it would
be an improvement.

def collatz(a,p):
   3x+1 sequencer, no loop detection

  collatz(a,p)
  a: starting value
  p: print options (binary)
 bit 0 print even numbers (turns off power division)
 bit 1 print  odd numbers
 bit 2 print debug (if any)
  returns: CollatzSequenceParameters [R1count, R2count]
  
  ONE = gmpy.mpz(1)
  TWO = gmpy.mpz(2)
  TWE = gmpy.mpz(3)
  a = gmpy.mpz(a)
  t = 0
  u = 0
  done = 0

  if (p  1)==1:
print_evens = True
  else:
print_evens = False
  if (p  2)==2:
print_odds = True
  else:
print_odds = False
  if (p  4)==4:
print_debug = True
  else:
print_debug = False

  while done==0:
f = gmpy.scan1(a,0) # locate LS 1-bit
if f0: # it's even
  if print_evens:
print a,
a = a  1  # no power division
u += 1
  else:
a = a  f  # power division
u += f
else:
  if print_odds:
print a,
  if a==1:
done = 1
seq_end = t + u
  else:
a = a*TWE + ONE
t += 1
  return [u,t]




 --
 Steven

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


Re: Large amount of files to parse/organize, tips on algorithm?

2008-09-02 Thread cnb
On Sep 2, 7:06 pm, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 On Tue, 02 Sep 2008 09:48:32 -0700, cnb wrote:
  I have a bunch of files consisting of moviereviews.

  For each file I construct a list of reviews and then for each new file I
  merge the reviews so that in the end have a list of reviewers and for
  each reviewer all their reviews.

  What is the fastest way to do this?

 Use the timeit module to find out.

  1. Create one file with reviews, open next file an for each review see
  if the reviewer exists, then add the review else create new reviewer.

  2. create all the separate files with reviews then mergesort them?

 The answer will depend on whether you have three reviews or three
 million, whether each review is twenty words or twenty thousand words,
 and whether you have to do the merging once only or over and over again.

 --
 Steven



I merge once. each review has 3 fields, date rating customerid. in
total ill be parsing between 10K and 100K, eventually 450K reviews.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Large amount of files to parse/organize, tips on algorithm?

2008-09-02 Thread cnb
over 17000 files...

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


Re: How do I adjust the font size on IDLE when running on Mac OS 10.5.4? TIA.

2008-09-02 Thread Chris Rebert
Same as on all the other platforms.

1. Open IDLE
2. Go Options - Configure IDLE...
3. Choose the Fonts/Tabs section
4. Use the Size pulldown box

- Chris

On Tue, Sep 2, 2008 at 6:26 AM, Malcolm Lewis [EMAIL PROTECTED] wrote:


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




-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Large amount of files to parse/organize, tips on algorithm?

2008-09-02 Thread Eric Wertman
I think you really want use a relational database of some sort for this.

On Tue, Sep 2, 2008 at 2:02 PM, cnb [EMAIL PROTECTED] wrote:
 over 17000 files...

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

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


Re: converting a sed / grep / awk / . . . bash pipe line into python

2008-09-02 Thread Marc 'BlackJack' Rintsch
On Tue, 02 Sep 2008 10:36:50 -0700, hofer wrote:

 sed 's/\.\..*//' \### remove '//' comments | sed 's/#.*//'

Comment does not match the code.  Or vice versa.  :-)

Untested:

from __future__ import with_statement
from itertools import ifilter, ifilterfalse, imap


def is_junk(line):
line = line.rstrip()
return not line or line.startswith('//') or line.startswith('#')


def extract_numbers(line):
result = map(int, line.split()[:2])
assert len(result) == 2
return result


def main():
with open('test.txt') as lines:
clean_lines = ifilterfalse(is_junk, lines)
pairs = imap(extract_numbers, clean_lines)
print '\n'.join(b for a, b in pairs if a + b == 42)


if __name__ == '__main__':
main()

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


Re: Large amount of files to parse/organize, tips on algorithm?

2008-09-02 Thread Paul Rubin
cnb [EMAIL PROTECTED] writes:
 For each file I construct a list of reviews and then for each new file
 I merge the reviews so that in the end have a list of reviewers and
 for each reviewer all their reviews.
 
 What is the fastest way to do this?

Scan through all the files sequentially, emitting records like

(movie, reviewer, review)

Then use an external sort utility to sort/merge that output file
on each of the 3 columns.  Beats writing code.
--
http://mail.python.org/mailman/listinfo/python-list


rope class (heavyweight string)

2008-09-02 Thread castironpi
Does anyone want to talk about a Rope implementation in Python?  It
doesn't get faster than the native strings until about 2 megs.

P.S.  Didn't your momma ever tell you not to talk on newsgroups?
--
http://mail.python.org/mailman/listinfo/python-list


Re: source for the property function

2008-09-02 Thread Bruno Desthuilliers

Rowland Smith a écrit :

Anyone know where the source code for the built-in property function


Actually, it's a class, not a function.

is 
located in a python distribution?


property being a builtin type, you should find it somewhere in the 
CPython's C source AFAICT.


I would like to see how it works - mainly, how does it know which class 
it is being called from?


No need to look at the source for this - it's just an application of the 
descriptor protocol. Look up the doc on python.org, or google for python 
descriptor protocol. FWIW, it's the same protocol that is used for 
turning functions into methods, and writing your own custom descriptors 
is trivial.


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


Re: Inquiry regarding the name of subprocess.Popen class

2008-09-02 Thread Marc 'BlackJack' Rintsch
On Tue, 02 Sep 2008 11:39:09 -0400, Derek Martin wrote:

 On Tue, Sep 02, 2008 at 01:57:26PM +, Marc 'BlackJack' Rintsch
 wrote:
  I would argue that they don't represent processes at all; the object
  is a set of files which connect the standard I/O streams of a
  subprocess to its parent, and methods to operate on those files.
 
 And the process' ID, an attribute with the process' return code, a
 method to wait until the process is finished and file objects to
 communicate with the process.
 
 The name popen is an abbreviation of pipe open -- the function, and
 the class, open pipes to communicate with another process.  What you
 said is correct; however there are numerous other ways to open
 subprocesses.  The focus of popen is the communication aspect -- the
 opening and control of the pipes -- not the subprocess.  That's the key
 difference between popen() and all the other methods of starting a
 subprocess.

But I'm not talking about the `popen()` function but the 
`subprocess.Popen` class.

  The C library's popen() function, on which this class is based,
  provides a means to open a file and connect it to the standard steams
  of a subprocess, making it more closely analogous to what the Popen
  class does/provides.  As such, Popen is a better name to describe
  this object than subprocess would be.
 
 Is strongly disagree.  The class provides an interface to start and
 communicate with a `Subprocess`.  Instances stand for processes.
 
 There's more than one way to look at it.  You can disagree all you like,
 but your interpretation disagrees with the historical intent of popen.

That's why I think the name `Popen` is not so good for it.  Because it 
does more than `popen()` and if it is called `Subprocess` or just 
`Process` then it would be merely an implementation detail, that the 
`popen()` function is called at some point.  If it is at all, because 
`popen()` on C level can just open a pipe in *one* direction.

 Note that in all of these links that talk about popen, the focus is on
 opening pipes or file objects, not on subprocesses:
 
 http://www.opengroup.org/onlinepubs/009695399/functions/popen.html
 http://docs.python.org/lib/os-newstreams.html http://us3.php.net/popen
 http://docs.hp.com/en/B9106-90010/popen.3S.html
 http://www.faqs.org/docs/artu/ch07s02.html

And all of the links talk about the `popen()` function, not about the 
functionality the `Popen` class provides.  Which is much more than that 
simple pipe `popen()` returns.

 The Linux man page unfortunately copies (verbatim) the FreeBSD man page,
 which gets it wrong.  You can not open a process, but you can definitely
 open a pipe.

Ah, when their terminology doesn't match yours, they must get it 
wrong.  ;-)

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


Re: Large amount of files to parse/organize, tips on algorithm?

2008-09-02 Thread jay graves
On Sep 2, 1:02 pm, cnb [EMAIL PROTECTED] wrote:
 over 17000 files...

 netflixprize.

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

specifically:

http://pyflix.python-hosting.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Numeric literal syntax

2008-09-02 Thread Peter Pearson
On Tue, 02 Sep 2008 17:18:58 GMT, Alan G Isaac [EMAIL PROTECTED] wrote:
 On 02 Sep 2008 06:10:51 GMT, Steven D'Aprano wrote:
 At the risk of bike-shedding, 
 [snip]

 Peter Pearson wrote:
 (startled noises) It is a delight to find a reference to
 that half-century-old essay (High Finance) by the wonderful
 C. Northcote Parkinson, but how many readers will catch the
 allusion?

 It is pretty common geek speek:
 http://en.wikipedia.org/wiki/Color_of_the_bikeshed

Ah, the wondrous Wiki.

I thought I was a geek, for the past 40 years; but maybe its
time for me to be demoted to the dad on whose bookshelf
you'll find that old book.

-- 
To email me, substitute nowhere-spamcop, invalid-net.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to write verbose scripts

2008-09-02 Thread Diez B. Roggisch

Steven D'Aprano schrieb:
I find myself writing command line tools in Python where I wish to 
include verbose output to stdout.


I start with a helper function:


def print_(obj, level=0):
if _verbosity = level:
print obj


And then I end up with functions or methods looking like this:


def parrot(x)
print_(precondition, level=2)
do_something()
print_(status is good..., level=1)
print_(parrot is squawking strongly now, level=2)
do_something_else()
print_(squawk squawk squawk, level=3)
do_more()
print_(postcondition, level=1)
return something


That often means that my functions end up with more message printing code 
than actual code. The whole thing seems messy and hard to manage for all 
but the smallest scripts.


Worst of all, sometimes the messages I wish to print may be expensive to 
compute, and I don't want to waste time computing them if they aren't 
going to be printed because the verbosity is too low. But nor do I wish 
to fill my code with this:


if _verbosity = 3:
x = calculate_complicated_thing()
print_(x, level=3)



Is there a better way of doing this than the way I am going about it?


I use the logging-module.

Regarding the expensive computations: maysomething like this help:

class DeferredToString(object):

def __init__(self, func):
self.func = func

def __repr__(self):
return repr(self.func())

def __str__(self):
return str(self.func())



dts = DeferredToString

Because then you can do

logger.debug(Some text for an: %r, dts(lambda: long_computation()))

Because AFAIK the string is only interpolated if the logging level is 
actually put out.


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


Re: about downloading the selected information

2008-09-02 Thread Gabriel Genellina
En Tue, 02 Sep 2008 09:47:46 -0300, woaibeiyang [EMAIL PROTECTED] escribió:

 I have a problem to download the information from url
 http://www.ncbi.nlm.nih.gov/sites/entrez. Because it is impossible for me to
 add searching material to the url to construct a new url and then visit the
 website.
 I have the searching material, however I could not find the way to deal with
 this problem. I want to know how can I do this problem with python and which
 part of knowledge should I view first? Thanks!

Use an HTTP tracer (or logger, or sniffer...) to see the request that the 
browser sends to the server. Then analyze the page source to figure out how the 
different options modify the request sent.

-- 
Gabriel Genellina

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


Re: What is module initialization?

2008-09-02 Thread dudeja . rajat
On Tue, Sep 2, 2008 at 6:22 PM, Fredrik Lundh [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:

 # myglobals.py:
 answer = 42

 # question.py
 import myglobals
 myglobals.answer = WTF ?


 But if I do :-
 #question.py
 from myglobals import *
 myglobals.answer = WTF ?

 will this work?

 with the above definition of myglobals, no.  from myglobals import doesn't
 add the module object to the importing module's namespace.

 have you read:

 http://effbot.org/zone/import-confusion.htm

 ?

 /F

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


Thanks for your help guys that I got my problem resolved.



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


synthetic properties

2008-09-02 Thread rowland
I'm trying to come up with solution for adding synthetic properties to
python, similar to synthetic properties in Objective-C.

I'm playing around with doing this in a MetaClass.  I can dynamically
create the attributes that will back the property, but I'm having
trouble figuring out how to dynamically generate get/set methods to
pass to the built-in property() function.

Is it possible to define a lambda or a callable object that will act
as a getter method (or setter, that takes a value argument) during
MetaClass.__init__?  The hard part I'm guessing is getting the current
instance passed into the getter.  This is my first foray into
MetaClasses and dynamic functions/methods so any pointers are greatly
appreciated.


class ObjectivePythonObject( type ) :

def __new__( cls, name, bases, dct ) :
#print Allocating memory for class, name
return type.__new__(cls, name, bases, dct )

def __init__( cls, name, bases, dct ) :
#print Initializing class, name
for propertyInfo in cls.synthesized :
property = propertyInfo[ 0 ]
defaultValue = propertyInfo[ 1 ]
print property
setattr( cls, '_' + property, defaultValue )
# Create property with get/set methods...

class Person( object ) :

__metaclass__ = ObjectivePythonObject


synthesized = [ ( 'name', 'BobC' ),
( 'age', '48' ) ]

def __init__( self ) :
print self._name
print self._age


Thanks,
Rowland

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


Re: email.Message problem

2008-09-02 Thread Gabriel Genellina
En Tue, 02 Sep 2008 13:04:18 -0300, Corrado Gioannini [EMAIL PROTECTED] 
escribió:

 Hi all,
 i know i'm probably going to ask a very silly question, but i
 can't figure out where i'm doing wrong just reading the docs.

 trying to build and send a mail message using the email.* modules
 (with python 2.5).

 a simplified version of my script that breaks is this:

 mailtest.py

 messg = email.message.Message()

Replace this line with:
messg = email.mime.multipart.MIMEMultipart()
*OR*
Set the Content-Type header to multipart/mixed *before* anything else.

-- 
Gabriel Genellina

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


Re: configure kdevelop for python

2008-09-02 Thread David Boddie
On Sunday 31 August 2008 10:29, Sindhu wrote:

 am a newbie to python language and kdevelop, so i would like to know
 how to configure kdevelop for python programming? complete with a
 debugger?

Maybe asking on the kdevelop mailing list will yield a helpful answer:

http://lists.kde.org/?l=kdevelopr=1w=2

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


  1   2   3   >