Re: equivalent of py2exe in other os

2008-10-13 Thread Astan Chee

Hi,
Thanks for all the links and information. It seems that I can't make 
linux binaries in windows of my python code. What I mean is that I am 
using windows to develop my python code, but I want it to run in linux 
and mac. So far py2exe,gui2exe,pyinstaller,freeze,etc seems to all 
create .exe in because I am in windows. Is what I am after not possible 
so far?

Thanks again for all the help.
Cheers
Astan
PS: I already did some google and tried out all the suggestions everyone 
gave but still nothing.



Benjamin Kaplan wrote:



On Tue, Oct 7, 2008 at 10:58 AM, Joe Strout <[EMAIL PROTECTED] 
> wrote:


On Oct 7, 2008, at 8:43 AM, Benjamin Kaplan wrote:

I believe that all (or nearly all) Unix variants come with
Python preinstalled. Ubuntu, at least, has a lot of system
programs written in Python. Even Mac OS X requires Python.


Yes, but with significant differences between different Python
distributions, you might be safer bundling whatever version of
Python your app requires with the app itself.  Otherwise, you risk
your app failing (and probably puking up runtime exceptions all
over the poor user's lap) on some distros or versions.

(My Mac OS X machine comes with Python 2.5.1, for example, which
is hardly the latest.)


1) 2.6 doesn't break backwards-compatibility, just don't use anything 
added in 2.6 and you're fine.


2)wx hasn't been compiled for 2.6 yet, so the OP is probably still 
using 2.5 and there are no api changes between 2.5.1 and 2.5.2



Best,
- Joe


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




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


--
"Formulations of number theory: Complete, Consistent, Non-trivial. Choose two." 
-David Morgan-Mar




Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.

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


Re: type-checking support in Python?

2008-10-13 Thread Kay Schluehr
On 6 Okt., 16:19, Joe Strout <[EMAIL PROTECTED]> wrote:
> I'm just re-learning Python after nearly a decade away.  I've learned  
> a good healthy paranoia about my code in that time, and so one thing  
> I'd like to add to my Python habits is a way to both (a) make intended  
> types clear to the human reader of the code, in a uniform manner; and  
> (b) catch any type errors as early and automatically as possible.
>
> I found the "typecheck" module (http://oakwinter.com/code/typecheck/),  
> but I notice that it hasn't been updated since 2006, and it's not  
> included with the Python distribution.  Are there other modules  
> providing similar functionality that I should consider instead?

Incidentally I started to use the typecheck package just yesterday.
It's not that I'm using it in a typical application but I'm working on
a mapping of a statically typed language onto a Python framework that
emerges in parallel. So I have to rebuild the type semantics of the
original language in Python but defer typechecks until runtime.

My impressions so far have been mixed. I stumbled across some strange
failures that required uncommenting source code in the typecheck
package which might cause failures elsewhere. I also hit a barrier
when working with methods instead of functions. I also noticed that
passing two strings to a funtcion:

@accepts(Number, Number)
def add(x,y):
return x+y

is acceptable behaviour.

>From all those experiences I'd rate the package alpha and I'm sad
noticing that it is apparently abandonware. I'll continue to use it
nevertheless.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Deviation from object-relational mapping (pySQLFace)

2008-10-13 Thread Bruno Desthuilliers

[EMAIL PROTECTED] a écrit :

I have made a simple python module to handle SQL databases:
https://fedorahosted.org/pySQLFace/wiki
Its goal to separate relational database stuff (SQL) from algorythmic


s/algorythmic/algorithmic

!-)


code (python). A SQLFace is a facade initialized with a configuration
file (XML). It provides callable command objects for each sql query.
The call substitutes template variables with its parameters, and
returns the result of the query.
I would like to get some opinions on this approach.


Going back to the wiki... Tell you later.

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


Re: File Upload Size

2008-10-13 Thread rodmc
On 13 Oct, 00:10, Mike Driscoll <[EMAIL PROTECTED]> wrote:
> On Oct 12, 9:34 am, rodmc <[EMAIL PROTECTED]> wrote:
>
> > Hi,
>
> > Is there a way to get the size of a file on a remote machine before it
> > is uploaded? I would like to write some form of status counter which
> > is updated as a fie is uploaded, and also to use this feature to
> > prevent files which are too big from being uploaded.
>
> > Best,
>
> > rod
>
> Looks like ftplib does that. Check the 
> docs:http://www.python.org/doc/2.5.2/lib/module-ftplib.html
>
> Mike

Hi Mike,

Thanks for this information I will look at it. The only condition is
that everything must run via a webpage.

Best,

rod

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


Re: Deviation from object-relational mapping (pySQLFace)

2008-10-13 Thread Bruno Desthuilliers

[EMAIL PROTECTED] a écrit :

I have made a simple python module to handle SQL databases:
https://fedorahosted.org/pySQLFace/wiki
Its goal to separate relational database stuff (SQL) from algorythmic
code (python). A SQLFace is a facade initialized with a configuration
file (XML). It provides callable command objects for each sql query.
The call substitutes template variables with its parameters, and
returns the result of the query.
I would like to get some opinions on this approach.



First, I really don't see the point of XML for something as simple as 
specifying a SQL query and a couple metadata. This would be better done 
directly in Python using a metaclass, inheritance and a couple class 
attributes, ie:


from SQLFace import Query, Statement

class WbsTotal(Query):
   expression="SELECT hours,wbs FROM wbs_total"
   out = ['hours', 'wbs']


class AddProject(Statement):
expression="""
 INSERT INTO projects (project, description)
 VALUES (%s, %s)
 """
in_ = ['project', 'description']


Also, I'd rather have Queries being iterators (delegating to the cursor) 
instead of calling cursor.fetchall and returning the whole result.


My 2 cents

NB : btw, did you have a look at SQLAlchemy's low-level 
python-relational integration part (*not* the 'orm' part) ?

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


ANN: Mock 0.4.0 released

2008-10-13 Thread Fuzzyman
Mock 0.4.0 has just been released, the first release in about ten
months (but worth the wait).

Mock is a simple library for testing: specifically for mocking,
stubbing and patching.

* Mock Homepage & Documentation http://www.voidspace.org.uk/python/mock.html
* mock.py (module only) `_. This means that if you have
setuptools you should be able to install mock with:

``easy_install mock``

The full changelog is:


* Default return value is now a new mock rather than None
* 'return_value' added as a keyword argument to the constructor
* New method 'assert_called_with'
* Added 'side_effect' attribute / keyword argument called when mock is
called
* patch decorator split into two decorators:

- ``patch_object`` which takes an object and an attribute name to
patch
  (plus optionally a value to patch with which defaults to a mock
object)
- ``patch`` which takes a string specifying a target to patch; in
the form
  'package.module.Class.attribute'. (plus optionally a value to
  patch with which defaults to a mock object)

* Can now patch objects with ``None``
* Change to patch for nose compatibility with error reporting in
wrapped functions
* Reset no longer clears children / return value etc - it just resets
  call count and call args. It also calls reset on all children (and
  the return value if it is a mock).

Thanks to Konrad Delong, Kevin Dangoor and others for patches and
suggestions.

See the following for examples of using Mock and patch:

* http://www.voidspace.org.uk/python/weblog/arch_d7_2008_10_11.shtml#e1019
--
http://mail.python.org/mailman/listinfo/python-list


Re: Append a new value to dict

2008-10-13 Thread Mathias Frey

Pat wrote:
I know it's not "fair" to compare language features, but it seems to me 
(a Python newbie) that appending a new key/value to a dict in Python is 
awfully cumbersome.


In Python, this is the best code I could come up with for adding a new 
key, value to a dict


mytable.setdefault( k, [] ).append( v )

In Perl, the code looks like this:

$h{ $key } = $value ;


There's a huge difference here:

In your Python example you're using a list. In the Perl example you're 
using a scalar value.



Is there a better/easier way to code this in Python than the 
obtuse/arcane setdefault code?


When just assigning a new key-value-pair there's no problem in Python. 
(Just refer to the answers before.) When I switched from Perl to Python 
however I commonly ran into this problem:


>>> counter = {}
>>> counter['A'] = 1
>>> counter['A'] += 1
>>> counter['A']
2

Ok - assigning a key-value-pair works fine. Incrementing works as well.

>>> counter['B'] += 1
Traceback (most recent call last):
  File "", line 1, in 
KeyError: 'B'

However incrementing a non-existing key throws an exception. So you 
either have to use a workaround:


>>> try:
...   counter['B'] += 1
... except KeyError:
...   counter['B'] = 1

Since this looks ugly somebody invented the setdefault method:

>>> counter['B'] = counter.setdefault('B',0) + 1

And this works with lists/arrays as well. When there's no list yet 
setdefault will create an empty list and append the first value. 
Otherwise it will just append.


Greetings from Vienna,
mathias
--
http://mail.python.org/mailman/listinfo/python-list


compile() and comments

2008-10-13 Thread Ed Leafe
	I've noticed an odd behavior with compile() and code that does not  
contain a trailing newline: if the last line is a comment inside of  
any block, a syntax error is thrown, but if the last line is a non- 
comment Python statement, there is no error. Here's an example (using  
2.5.1 on OS X)


>>> txt = """
... def foo():
...   print 'bar' """
>>> compcode = compile(t.strip(), "", "exec")
>>> compcode
 at 0x79608, file "", line 2>

>>> txt += "  # Comment on last line"
>>> compcode = compile(txt.strip(), "", "exec")
Traceback (most recent call last):
 File "", line 1, in 
 File "", line 4
   # Comment on last line
   ^
SyntaxError: invalid syntax
>>> compcode = compile(txt.strip() + "\n", "", "exec")
>>> compcode
 at 0x79a40, file "", line 2>

	Obviously the easy workaround is to add a newline and all is well, so  
this isn't a show-stopper, but is this a bug?


-- Ed Leafe



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


Re: Making class attributes non-case-sensitive?

2008-10-13 Thread Fuzzyman
On Oct 13, 10:11 am, Rafe <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I'm working within an application (making a lot of wrappers), but the
> application is not case sensitive. For example, Typing obj.name,
> obj.Name, or even object.naMe is all fine (as far as the app is
> concerned). The problem is, If someone makes a typo, they may get an
> unexpected error due accidentally calling the original attribute
> instead of the wrapped version. Does anyone have a simple solution for
> this?
>
> I can protect against some cases just by making an 'alias':
> class AClass(object):
> def name(self):
> print "hello"
>
> Name = name
>
> ...but this doesn't protect against typos, it gets more complicated
> with multi-word attribute names, and it makes my epydocs confusing to
> read since all spelling versions are shown (I AM concerned about my
> docs being clear, but not as much as stopping typo related errors).
>
> I thought about using my wrapper's __getattr__ and __setattr__, but I
> I am concerned about the overhead of every delegated attribute call
> running a search and compare (.lower() based compare?).
>
> Any ideas or precedence?

If you define '__getattr__' then it will only be called for attribute
names that don't exist. So only explicitly define the names you want
in the lowercase variant and then have something like the following:

def __getattr__(self, name):
return object.__getattr__(self, name.lower())

That way each name only appears once and you only get the extra
'__getattr__' in your epydoc docs.

Michael


>
> Cheers,
>
> - Rafe

--
http://www.ironpythoninaction.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: File Upload Size

2008-10-13 Thread Diez B. Roggisch
rodmc wrote:

> On 13 Oct, 00:10, Mike Driscoll <[EMAIL PROTECTED]> wrote:
>> On Oct 12, 9:34 am, rodmc <[EMAIL PROTECTED]> wrote:
>>
>> > Hi,
>>
>> > Is there a way to get the size of a file on a remote machine before it
>> > is uploaded? I would like to write some form of status counter which
>> > is updated as a fie is uploaded, and also to use this feature to
>> > prevent files which are too big from being uploaded.
>>
>> > Best,
>>
>> > rod
>>
>> Looks like ftplib does that. Check the
>> docs:http://www.python.org/doc/2.5.2/lib/module-ftplib.html
>>
>> Mike
> 
> Hi Mike,
> 
> Thanks for this information I will look at it. The only condition is
> that everything must run via a webpage.

Which is crucial information and rules out Mike's suggestion.

And the answer is: no, you can't access file-attributes on remote machines.
HTTP does require a content-length header though. If that exceeds a certain
size, you can terminate the connection.

You need to do that also if the client actually pushes more data than
announced.

And progress-counting can be done by counting the already arrived data &
making e.g. an Ajax-Call to fetch that from the server.

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


Re: Making class attributes non-case-sensitive?

2008-10-13 Thread Diez B. Roggisch
Rafe wrote:

> Hi,
> 
> I'm working within an application (making a lot of wrappers), but the
> application is not case sensitive. For example, Typing obj.name,
> obj.Name, or even object.naMe is all fine (as far as the app is
> concerned). The problem is, If someone makes a typo, they may get an
> unexpected error due accidentally calling the original attribute
> instead of the wrapped version. Does anyone have a simple solution for
> this?
> 
> I can protect against some cases just by making an 'alias':
> class AClass(object):
> def name(self):
> print "hello"
> 
> Name = name
> 
> ...but this doesn't protect against typos, it gets more complicated
> with multi-word attribute names, and it makes my epydocs confusing to
> read since all spelling versions are shown (I AM concerned about my
> docs being clear, but not as much as stopping typo related errors).
> 
> I thought about using my wrapper's __getattr__ and __setattr__, but I
> I am concerned about the overhead of every delegated attribute call
> running a search and compare (.lower() based compare?).
> 
> Any ideas or precedence?

Ideas? Don't do that... 

Seriously: where does that code come from, who's typing it? If it is python,
then make people follow python's rules. If it is some sort of homebrewn
language you map to python, adapt the mapper to enforce lower-case and make
all your properties lower case.

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


Re: Append a new value to dict

2008-10-13 Thread Tim Chase
In Python, this is the best code I could come up with for 
adding a new key, value to a dict


mytable.setdefault( k, [] ).append( v )


Naturally, right after writing my post I found that there is
an easier way:

table[ k ] = v


Just to be clear...these do two VERY different things:

  >>> v1=42
  >>> table1={}
  >>> k='foo'
  >>> table1.setdefault(k,[]).append(v1)
  >>> table2={}
  >>> table2[k]=v1
  >>> table1, table2
  ({'foo': [42]}, {'foo': 42})

Note that the value in the first case is a *list* while the
value in the 2nd case, the value is a scalar.  These differ in 
the behavior (continuing from above):


  >>> v2='Second value'
  >>> table1.setdefault(k,[]).append(v2)
  >>> table2[k]=v2
  >>> table1, table2
  ({'foo': [42, 'Second value']}, {'foo': 'Second value'})

Note that table1 now has *two* values associated with 'foo', 
while table2 only has the most recently assigned value.


Choose according to your use-case.  For some of my ETL & 
data-processing work, I often want the


  mydict.setdefault(key, []).append(value)

version to accrue values associated with a given unique key.

-tkc






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


Re: compile() and comments

2008-10-13 Thread Fuzzyman
Hello Ed,

It is certainly an odd restriction, but the docs for compile [1] do
explicitly state that the input must be newline terminated.

When compiling multi-line statements, two caveats apply: line
endings must be represented by a single newline character ('\n'), and
the input must be terminated by at least one newline character.

I always throw an extra newline onto any input to compile. I think the
behaviour maybe for detecting incomplete statements when you pass in
the obscure 'don't imply dedent' flag for interactive interpreter
loops.

[1] http://www.python.org/doc/2.5.2/lib/built-in-funcs.html

Michael Foord

On Oct 13, 1:06 pm, Ed Leafe <[EMAIL PROTECTED]> wrote:
> I've noticed an odd behavior with compile() and code that does not
> contain a trailing newline: if the last line is a comment inside of
> any block, a syntax error is thrown, but if the last line is a non-
> comment Python statement, there is no error. Here's an example (using
> 2.5.1 on OS X)
>
>  >>> txt = """
> ... def foo():
> ...   print 'bar' """
>  >>> compcode = compile(t.strip(), "", "exec")
>  >>> compcode
>  at 0x79608, file "", line 2>
>
>  >>> txt += "  # Comment on last line"
>  >>> compcode = compile(txt.strip(), "", "exec")
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "", line 4
> # Comment on last line
> ^
> SyntaxError: invalid syntax
>  >>> compcode = compile(txt.strip() + "\n", "", "exec")
>  >>> compcode
>  at 0x79a40, file "", line 2>
>
> Obviously the easy workaround is to add a newline and all is well, so
> this isn't a show-stopper, but is this a bug?
>
> -- Ed Leafe


--
http://www.ironpythoninaction.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Safe eval of insecure strings containing Python data structures?

2008-10-13 Thread lkcl
On Oct 9, 4:32 am, "James Mills" <[EMAIL PROTECTED]> wrote:
> On Thu, Oct 9, 2008 at 2:26 PM, Warren DeLano <[EMAIL PROTECTED]> wrote:
> > JSON rocks!  Thanks everyone.
>
> Yes it does :)
>
> > Ben wrote:
>
> >>More generally, you should never execute (via eval, exec, or whatever)
> >>*any* instruction from an untrusted path; especially not arbitrary
> >>data from an input stream.


 rubbish.  this is why a project i was involved with, to do execution
of code from a database instead of a filesystem had to be abandoned,
back in 2001.

 there are perfectly good systems for associating security context
with "arbitrary data" (as the security models of SE/Linux, based on
Flask, and the security model of windows nt, based on VAX/VMS
security, show).

 there was a flawed design decision in python 2.2 or python 2.3 which
resulted in an "escape route" - i believe it centered around either
__class__ or __new__ - in the c code, which the developers had not
considered, and would not correct.

 this decision resulted in the abandonment of the rexec.py module in
python: you can see for yourself because it raises a runtime exception
when you try to use it, issuing a warning.

 it's _perfectly_ possible to define security contexts and boundaries,
and to allow access to functions and modules on a per-security-context
basis.

*as defined by the application developer* [not by the developers of
python itself]

if an individual developer wants to allow "arbitrary code execution
from any data stream", it most certainly is _not_ anyone's place to
dictate to them that they "cannot do this".

 instead, there should be a mechanism in place which allows them to
choose which foot they want to lose with the loaded gun they're
pointing.

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


strip module bug

2008-10-13 Thread Poppy

I'm using versions 2.5.2 and 2.5.1 of python and have encountered a 
potential bug. Not sure if I'm misunderstanding the usage of the strip 
function but here's my example.

var = "detail.xml"
print var.strip(".xml")   ### expect to see 'detail', but get 'detai'
var = "overview.xml"
print var.strip(".xml") ### expect and get 'overview'

I have a work around using the replace function which happens to be the 
better choice for my script anyhow. But am curious about the strip module. 
Any thoughts? Is it removing the 'l' in detail because the strip function 
text ends in 'l'?


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


Re: PyGUI as a standard GUI API for Python?

2008-10-13 Thread lkcl
On Oct 11, 11:17 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> lkcl wrote:
>
> I got the impression that there is currently no Windows binary
> available.  Correct?  If not, perhaps someone trustworthy will someday
> donate one.

sorry, terry, you deleted a bit too much context :)
so, assuming that you mean "that there is currently no http://pyjd.org
windows binary", then then answer is:

pyjamas-desktop is pure python, relying on a modified version of
pywebkitgtk and a modified version of webkit to add glib bindings to
it.

i spent one week fighting with mingw32 to cross-compile webkit for
win32 - when i say fighting i mean segfaults at link time (!!), which
was tracked down to the msvc-compiled version of libicu 3.8 and
eliminated by hack-compiling libicu with mingw32; _rebuilding_ mingw32
from the latest svn at the time, in order to include support for
exceptions across thread boundaries (libstdc++ exceptions -
libgcc_a.dll)

all in all, it was a bitch :)

_then_ i started on cross-compiling python2.5 because there's no .exe
or .zip installer for python - only a .MSI, and, having installed MSI
under wine on linux with the excellent "winetricks" script, it causes
a segfault when you try to run a .MSI.

cross-compilation of python2.4 was successful (by the person who did
the initial patch, a year ago).  cross-compilation of python2.5, to
generate a libpython2.4.dll and .a, fails miserably.

why the python developers didn't include the patches, and keep them up-
to-date, isn't clear.

at that point, i gave up, despite valiant efforts, because it was
clear that, given that there was no financial incentive to continue, i
was wasting my time.

the bottom line is: if you want a windows version of pywebkitgtk, i'm
happy to assist and advise anyone of the process- it should be quite
straightforward _if_ you have MSVC and follow the standard procedure,
but i'm not about to spend my own time and effort on providing a win32
port using ming32, doing all the work _myself_, on my own, without
financial incentive and renumeration.

i'll happily explain to other people what _they_ need to do, though.

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


Re: strip module bug

2008-10-13 Thread Peter Otten
Poppy wrote:

> 
> I'm using versions 2.5.2 and 2.5.1 of python and have encountered a
> potential bug. Not sure if I'm misunderstanding the usage of the strip
> function but here's my example.
> 
> var = "detail.xml"
> print var.strip(".xml")   ### expect to see 'detail', but get 'detai'
> var = "overview.xml"
> print var.strip(".xml") ### expect and get 'overview'
> 
> I have a work around using the replace function which happens to be the
> better choice for my script anyhow. But am curious about the strip module.
> Any thoughts? Is it removing the 'l' in detail because the strip function
> text ends in 'l'?

The behaviour you intend, stripping a suffix, is achieved by

>>> var = "detail.xml"
>>> suffix = ".xml"
>>> if var.endswith(suffix):
... var = var[:-len(suffix)]
...

The var.strip(chars) /method/ does something different. It treats chars as a
set of characters and removes any of these characters from the end and the
beginning of the var string, i. e.

"detail.xml" d is not in ".xml" -> remove no further chars from the
beginning
"detail.xml" l is in ".xml", remove it
"detail.xm" m is in ".xml", remove it
"detail.x" x is in ".xml", remove it
"detail." . is in ".xml", remove it
"detail" l is in ".xml", remove it
"detai" i is not in ".xml", we're done

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


Re: strip module bug

2008-10-13 Thread bearophileHUGS
Poppy:
> var = "detail.xml"
> print var.strip(".xml")   ### expect to see 'detail', but get 'detai'
> var = "overview.xml"
> print var.strip(".xml") ### expect and get 'overview'

Python V.2.5 is not flawless, but you can't find bugs so easily. I've
found only two bugs in about three years of continuous usage (while I
have found about 27 new different bugs in the DMD compiler in about
one year of usage).

str.strip() isn't a module, and generally in Python it's called
"method", in this case a method of str (or unicode).

str.strip() as optional argument doesn't take the string you want to
remove, but a string that represent the set of chars you want to strip
away from both ends, so:

>>> "detail.xml".strip("lmx.")
'detai'
>>> "detail.xml".strip("abcdlz")
'etail.xm'

To strip the ending ".xml" you can use the str.partition() method, or
an alternative solution:

>>> var = "detail.xml"
>>> suffix = ".xml"
>>> if var.endswith(suffix):
... var2 = var[: -len(suffix)]
...
>>> var2
'detail'

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


Re: Append a new value to dict

2008-10-13 Thread bearophileHUGS
jdd:
> foo = {'bar': 'baz'}
> foo.update({'quux': 'blah'})

That creates a new dict, to throw it away. Don't do that. Use the
standard and more readable syntax:

> foo = {...}
> foo['quux'] = 'blah'

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


Re: strip module bug

2008-10-13 Thread Tim Chase
I'm using versions 2.5.2 and 2.5.1 of python and have encountered a 
potential bug. Not sure if I'm misunderstanding the usage of the strip 
function but here's my example.


var = "detail.xml"
print var.strip(".xml")   ### expect to see 'detail', but get 'detai'
var = "overview.xml"
print var.strip(".xml") ### expect and get 'overview'


.strip() takes a *set* of characters to remove, as many as are found:
  ____
 >>> 'xqxqxqxyxxyxqxqx'.strip('xq')
 'yxxy'

Using .replace() may work, but might have some odd side effects:

 >>> 'something.xml.zip'.replace('.xml')
 'something.zip'
 >>> 'this file has .xml in its name.xml'.replace('.xml')
 'this file has  in its name'

This also has problems if your filename and extension differ in 
case (removing ".xml" from "file.XML")


If you want to remove the extension, then I recommend using the 
python builtin:


  >>> import os
  >>> results = os.path.splitext('this has .xml in its name.xml')
  >>> results
  ('this has .xml in its name', '.xml')
  >>> fname, ext = results

Or, if you know what the extension is:

  >>> fname = 'this file has .xml in its name.xml'
  >>> ext = '.xml'
  >>> fname[:-len(ext)]
  'this file has .xml in its name'

Just a few ideas that are hopefully more robust.

-tkc




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


Re: strip module bug

2008-10-13 Thread Steven D'Aprano
On Mon, 13 Oct 2008 08:50:41 -0400, Poppy wrote:

> I'm using versions 2.5.2 and 2.5.1 of python and have encountered a
> potential bug. Not sure if I'm misunderstanding the usage of the strip
> function but here's my example.
> 
> var = "detail.xml"
> print var.strip(".xml")   ### expect to see 'detail', but get 'detai'
> var = "overview.xml"
> print var.strip(".xml") ### expect and get 'overview'


I got bitten by this once too. Most embarrassingly, I already knew the 
right behaviour but when somebody suggested it was a bug I got confused 
and convinced myself it was a bug. It's not.

You have misunderstood what strip() does. It does NOT mean "remove this 
string from the string if it is a suffix or prefix".

Consider:

>>> "abcd123".strip('123')
'abc'
>>> "abcd123".strip('321')
'abc'
>>> "abcd123111".strip('213')
'abc'

strip() removes *characters*, not substrings. It doesn't matter what 
order it sees them.

See help(''.strip) in the interactive interpreter for more detail.


By the way, the right way to deal with file extensions is:

>>> import os
>>> os.path.splitext('detail.xml')
('detail', '.xml')




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


Re: how to set the time of a directory?

2008-10-13 Thread oyster
so, let alone the 'bad' os.utime, is there any way to set the time of
directory in windows within official python release? can ctypes be
helpful, and how ?

I am using totalcommander, which is programmer in delphi, but can set
the time of a directory

thanx

2008/10/12, [EMAIL PROTECTED] <[EMAIL PROTECTED]>:
> From: MRAB <[EMAIL PROTECTED]>
> To: [email protected]
> Date: Sat, 11 Oct 2008 11:29:12 -0700 (PDT)
> Subject: Re: how to set the time of a directory?
> On Oct 11, 1:18 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> > On Oct 11, 1:27 am, "Timothy Grant" <[EMAIL PROTECTED]> wrote:> On Fri, Oct 
> > 10, 2008 at 10:16 PM, oyster <[EMAIL PROTECTED]> wrote:
> > > > os.utime works only against files. so what to do for a directory?
> > > > thanx
> >
> > > Not sure why you'd say that.
> >
> > I am. He's running Windows.
> >
> >
> >
> >
> >
> > > drwxr-xr-x  2 tjg  tjg   68 Oct 10 22:23 test
> > > ([EMAIL PROTECTED]) python
> > > Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:16)
> > > [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
> > > Type "help", "copyright", "credits" or "license" for more information.>>> 
> > > import os
> > > >>> help(os.utime)
> >
> > > Help on built-in function utime in module posix:
> >
> > > utime(...)
> > > utime(path, (atime, mtime))
> > > utime(path, None)
> >
> > > Set the access and modified time of the file to the given values.  If 
> > > the
> > > second form is used, set the access and modified times to the current 
> > > time.
> >
> > > >>> os.utime('test', None)
> > > >>> ^D
> >
> > > ([EMAIL PROTECTED]) ls -ltr
> > > drwxr-xr-x  2 tjg  tjg   68 Oct 10 22:24 test
> >
> > > --
> > > Stand Fast,
> > > tjg.  [Timothy Grant]
> > >>> os.utime('WinDir', None)
> >
> > Traceback (most recent call last):
> >   File "(stdin)", line 1, in 
> > WindowsError: [Error 5] Access is denied: 'WinDir'
> >
> >
> >
> > I consider this a bug. (Note that os.utime works for directories under
> > cygwin)
>
> This in issue #214245 (2000-09-16). See also
> http://mail.python.org/pipermail/python-bugs-list/2004-November/026124.html.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Append a new value to dict

2008-10-13 Thread Marc 'BlackJack' Rintsch
On Mon, 13 Oct 2008 14:10:43 +0200, Mathias Frey wrote:

> However incrementing a non-existing key throws an exception. So you
> either have to use a workaround:
> 
>  >>> try:
> ...   counter['B'] += 1
> ... except KeyError:
> ...   counter['B'] = 1
> 
> Since this looks ugly somebody invented the setdefault method:
> 
>  >>> counter['B'] = counter.setdefault('B',0) + 1

Nope, for this use case there is the `dict.get()` method:

counter['B'] = counter.get('B', 0) + 1

This assigns only *once* to ``counter['B']`` in every case.

`dict.setdefault()` is for situations where you really want to actually 
put the initial value into the dictionary, like with the list example by 
the OP.

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


How to set cookie in client machine

2008-10-13 Thread Good Z
Hello,

I want to set {name, value} cookie on client machine. 

My requirement is that when user comes to the website hosted on our server and 
login into his account, we would like to set user specific information in 
cookie that will be used later. Is there a generic program that may help me out 
in setting the cookie on client machine? 

Regards,
Mike



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


Re: how to start thread by group?

2008-10-13 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Gabriel
Genellina wrote:

> En Tue, 07 Oct 2008 13:25:01 -0300, Terry Reedy <[EMAIL PROTECTED]>
> escribió:
>
>> Lawrence D'Oliveiro wrote:
>>
>>> In message <[EMAIL PROTECTED]>,
>>> Gabriel Genellina wrote:
>>>
 Usually it's more efficient to create all the MAX_THREADS at once, and
 continuously feed them with tasks to be done.
>>>
>>>  Given that the bottleneck is most likely to be the internet
>>> connection, I'd say the "premature optimization is the root of all evil"
>>> adage applies here.
>>
>> Feeding a fixed pool of worker threads with a Queue() is a standard
>> design that is easy to understand and one the OP should learn.  Re-using
>> tested code is certainly efficient of programmer time.
> 
> I'd like to add that debugging a program that continuously creates and
> destroys threads is a real PITA.

That's God trying to tell you to avoid threads altogether.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Append a new value to dict

2008-10-13 Thread Bruno Desthuilliers

[EMAIL PROTECTED] a écrit :

jdd:

foo = {'bar': 'baz'}
foo.update({'quux': 'blah'})


That creates a new dict, to throw it away.


Just to make it clear for the easily confused ones (like me...): 
bearophile is talking about the dict passed as an argument to foo.update 
- not about the behaviour of dict.update itself (which of course 
modifies the dict in place) !-)


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


Re: urllib equivalent for HTTP requests

2008-10-13 Thread lkcl
On Oct 8, 7:34 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:

> > I would like to keep track of that but I realize that py does not have
> > a JS engine. :( Anyone with ideas on how to track these items or

 yep.

> What you can't do though is to get the requests that are issued 
> byJavascriptthat is *running*.

 yes you can.  see recent post i made just a few minutes ago giving
some insights into each of the available options.

look up pyv8; pykhtml; spidermonkey; webkit with the python bindings
to its glib bindings - pywebkitgtk - use my patched version and see
http://pyjd.sf.net to get precompiled versions; pyxpcomext and pydom
on developer.mozilla.org; webkit's DumpRenderTree with the --html
option, to name but a few.

there are _tons_ of options.  they're just an absolute bastard to
track down, because javascript is such a popular keyword to search
for, the results are almost useless.

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


Question

2008-10-13 Thread Aditi Meher
Hello

How to write code to store data into buffer using python?

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


IDLE on py3k

2008-10-13 Thread Jonathan Saxton
Being a bit of an old fart, I much prefer to do my text editing on a dark
background.  I find the paper-emulation paradigm an interesting idea but
lacking in ergonomic value.

With a bit of jiggering I was able to get the 2.5 version of IDLE to work
the way I want, namely a black background with text in various colours.  I
can ALMOST do the same thing with the IDLE that comes with python 3 except
that the window background remains steadfastly white.  So I see colour on
black for all the portions of the screen where text appears, but the blank
areas (end of line to right margin) are white.

Has anyone else encountered such a problem or am I the only one to even try
it?

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


Re: compile() and comments

2008-10-13 Thread Ed Leafe

On Oct 13, 2008, at 8:35 AM, Fuzzyman wrote:


It is certainly an odd restriction, but the docs for compile [1] do
explicitly state that the input must be newline terminated.



	Understood; what I found odd was that if the last non-newline- 
terminated statement was *not* a comment, no error was thrown.



-- Ed Leafe



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


Re: strip module bug

2008-10-13 Thread Poppy
Thanks Steven and Tim, I understand the strip module a lot more today. Also 
for some reason I was deciding against using the path functions but now 
decided to try and thus implemented them. My script is reading one file and 
writing a new file with a different extension.

So based on your suggestions I wrote this line.

import sys, os
xmlfile = sys.argv[1]
filout = os.path.splitext(xmlfile)[0] + ".xmlparse"  ### here is the new 
line


"Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Mon, 13 Oct 2008 08:50:41 -0400, Poppy wrote:
>
>> I'm using versions 2.5.2 and 2.5.1 of python and have encountered a
>> potential bug. Not sure if I'm misunderstanding the usage of the strip
>> function but here's my example.
>>
>> var = "detail.xml"
>> print var.strip(".xml")   ### expect to see 'detail', but get 'detai'
>> var = "overview.xml"
>> print var.strip(".xml") ### expect and get 'overview'
>
>
> I got bitten by this once too. Most embarrassingly, I already knew the
> right behaviour but when somebody suggested it was a bug I got confused
> and convinced myself it was a bug. It's not.
>
> You have misunderstood what strip() does. It does NOT mean "remove this
> string from the string if it is a suffix or prefix".
>
> Consider:
>
 "abcd123".strip('123')
> 'abc'
 "abcd123".strip('321')
> 'abc'
 "abcd123111".strip('213')
> 'abc'
>
> strip() removes *characters*, not substrings. It doesn't matter what
> order it sees them.
>
> See help(''.strip) in the interactive interpreter for more detail.
>
>
> By the way, the right way to deal with file extensions is:
>
 import os
 os.path.splitext('detail.xml')
> ('detail', '.xml')
>
>
>
>
> -- 
> Steven 


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


Append a new value to dict

2008-10-13 Thread Pat
I know it's not "fair" to compare language features, but it seems to me 
(a Python newbie) that appending a new key/value to a dict in Python is 
awfully cumbersome.


In Python, this is the best code I could come up with for adding a new 
key, value to a dict


mytable.setdefault( k, [] ).append( v )

In Perl, the code looks like this:

$h{ $key } = $value ;

Is there a better/easier way to code this in Python than the 
obtuse/arcane setdefault code?

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


Re: Question

2008-10-13 Thread Diez B. Roggisch
Aditi Meher wrote:

> Hello
> 
> How to write code to store data into buffer using python?
> 
> Please Reply

See here:

http://www.catb.org/~esr/faqs/smart-questions.html

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


Simultaneous LPT port access

2008-10-13 Thread Gatis
Hello!
Question: are my (following) considerations about simultaneous lpt
access true? Is "LPT server" needed? What could be possible
architecture of such component?
===
I'm writing program "alarm" that reads LPT input pin (activated by
motion sensor). 
If motion is sensed, program turns on notify device (beacon-connected
to LPT output pin) for 5 seconds. Than waits for a minute and repeats
"input read"/"notify switch on".
Now I want to add new function - fire alarm which in case of fire
turns on beacon permanently until fire alarm sensor switches off.
I'll try to implement frie alarm monitoring as new thread (my program
is without threads yet) because I have to poll lpt input from
firealarm every second.
But this means two threads are simultaneously reading/writing LPT
port. I guess it must not be allowed (does it?).
To access LPT I use following code:
IOports=open("/dev/port","r+b",0)
def GetChar(address):
IOports.seek(address)
return ord(IOports.read(1))
def PutChar(address,c):
IOports.seek(address)
IOports.write(chr(c))
class lpt:
def __init__(self,port=0x378):
self.address=port
def Put_Data(self,c):
PutChar(self.address,c)
def Get_Data(self):
return GetChar(self.address)
def Put_Status(self,c):
PutChar(self.address+1,c)
def Get_Status(self):
return GetChar(self.address+1)
def Put_Control(self,c):
PutChar(self.address+2,c)
def Get_Control(self):
return GetChar(self.address+2)
[found in
http://mail.python.org/pipermail/python-announce-list/2000-November/000567.html]
Simplest solution would be to add "LPT blocking" - if firealarm has
written and blocked LPT prot(by setting variable blockLPT), motion
alarm thread cannot any more change LPT output pin for beacon. 
But more elegant solution would be "LPT server" [Idea taken from
owfs-server] - thread that countinuously reads LPT inputs and serves
this info to all other threads. 
For writing - alarm threads sends write requests, LPT server executes
them one by one according to importance level (if house burns, don't
care for motion). 
===
Best regards,
Gatis Liepins--
http://mail.python.org/mailman/listinfo/python-list


Re: parsing javascript

2008-10-13 Thread lkcl
On Oct 12, 2:28 pm, Philip Semanchuk <[EMAIL PROTECTED]> wrote:
> On Oct 12, 2008, at 5:25 AM, S.SelvamSivawrote:
>
> > I have to do a parsing on webpagesand fetch urls.My problem is ,many
> > urls i
> > need to parse are dynamically loaded usingjavascriptfunction
> > (onload()).How to fetch those links from python? Thanks in advance.
>
> Selvam,
> You can try to find them yourself using string parsing, but that's
> difficult. The closer you want to get to "perfect" at finding URLs
> expressed in JS, the closer you'll get to rewriting a JS interpreter.
> For instance, this is not so hard to understand:
> "http://example.com/";
> but this is:
> "http://ZZZ_DOMAIN_ZZZ/index.html".replace(/ZZZ_DOMAIN_ZZZ/,
> the_domain_variable)
>
> This is a long-standing problem for any program that parses Web pages.

 yep :)

> You either have to embed a JS interpreter in your application or

 yep.

 there are several.

 pyv8 is the newest addition: http://advogato.org/article/985.html

 it's a python wrapper around google's v8 javascript execution
library.

 then there's pykhtml: http://paul.giannaros.org/pykhtml/

 it's a python wrapper around KHTML, providing very convenient access
to KDE's HTML capabilities: what pykhtml does is "pretends" that the
GUI part of KDE doesn't exist, so you can run your program as a
command-line shell; it will execute the javascript, which you will
have to wait a bit for of course; then you can walk the DOM tree
(using pykhtml bindings) using pykhtml.DOM.getElementById() and
getElementsByTagName("a") etc. etc. looking for the URLs.

 there's even an AJAX example included which does 1-second polling of
the DOM model, waiting for a spell-checking web site to deliver the
answer.

then there's webkit, with the new glib bindings:
https://bugs.webkit.org/show_bug.cgi?id=16401

which are then followed up by python bindings to _those_ bindings:
http://code.google.com/p/pywebkitgtk/issues/detail?id=13

this will also allow you to execute arbitrary javascript - again, it's
similar to KHTML and in fact webkit really _is_ the KDE KHTML code
(JavaScriptCore, KJS etc) but forked, improved, etc. etc.

unfortunately, the glib bindings are tied - at three key and strategic
locations - to gtk at the moment, which will take _very_ little work
to "un"tie them [pay me and i'll do the work], so you would need to
create a blank gtk window - just like is done with pykhtml, behind the
scenes.

it would be a very simple task to create a "dummy" - console-based -
port of webkit, providing an array of callbacks which you must hand to
the library.  at the moment, the design of webkit is not particularly
good in this respect: there are three ports, gtk, wx and qt, which are
heavily tied in to webkit.  it would be a _far_ better design to be
passing in a struct containing function callbacks (rather a lot of
them - about eighty!) and then what you could do is have a "console"-
based port of webkit, which would do the job you needed.

alternatively, if you don't mind wrapping a binary application with
e.g. Popen3 then look at the webkit DumpRenderTree application, paying
particular attention to using the --html option.  you won't have any
control over how long the javascript is executed for.  after an
arbitrary and small period of time, DumpRenderTree _stops_ executing
the javascript and prints out the HTML DOM model (in a non-html-layout
fashion - it's used for debugging and testing purposes but will
suffice for your purposes).

so, as it stands, pywebkitgtk is _no worse_ than pykhtml, but with a
little bit of tweaking, the "gtk" could be removed from "pywebkitgtk"
and you'd end up with... ohh... call it "pywebkitglib" ... which would
be much better as a stand-alone library, for your purposes



then there's also "spidermonkey", which is mozilla's javascript
engine.  i haven't investigated this option: haven't had a need to.

then there's also PyXPCOMExt, which is embedding python into mozilla,
and from there you have PyDOM, which allows you access to the DOM
model of the mozilla "thing".  so, if you don't mind embedding your
application into XULRunner, you've got a home for executing your app
and obtaining the urls, post-javascript-execution.

the neat thing about PyXPCOMExt is that you have complete and full
access to python - so your app can make external TCP and UDP sockets,
you can embed an entire _server_ in the damn thing if you want (you
could embed... python-twisted if you wanted!)  you can access the
filesystem - anything.  absolutely anything.  reason: the _entire_
python suite is embedded into the browser.  every single bit of it.


that's about all i've been able to find, so far.  there might be more
options out there.  not that there aren't enough already :)

all of them will allow you complete and full access to execution of
javascript, including AJAX execution.  which is why you'll need to do
that "polling" trick in many instances.

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


Re: Append a new value to dict

2008-10-13 Thread Kirk Strauser
At 2008-10-13T13:14:15Z, [EMAIL PROTECTED] writes:

> jdd:
>> foo = {'bar': 'baz'}
>> foo.update({'quux': 'blah'})
>
> That creates a new dict, to throw it away. Don't do that.

I use that if I'm changing many values at once, eg:

foo.update({
'quux': 'blah',
'baz' : 'bearophile',
'jdd' : 'dict',
})

instead of:

foo['quux'] = 'blah'
foo['baz'] = 'bearophile'
foo['jdd'] = 'dict'

because it seems to more clearly indicate what I'm doing, and has fewer
opportunities for types.  Still, there is a performance penalty.  Running
"my way" 10,000,000 times took 8.7s, and "your way" only took 4.7s.  If
you're doing this in an inner loop, that may be significant.  While we're on
the subject, use keyword arguments to dict like:

foo.update(dict(quux='blah', baz='bearophile', jdd='dict'))

was *much* slower, at 11.8s.
-- 
Kirk Strauser
The Day Companies
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where/how to propose an addition to a standard module?

2008-10-13 Thread pruebauno
On Oct 10, 3:10 pm, Joe Strout <[EMAIL PROTECTED]> wrote:
> I would like to propose a new method for the string.Template class.
> What's the proper procedure for doing this?  I've joined the python-
> ideas list, but that seems to be only for proposed language changes,
> and my idea doesn't require any change to the language at all.
>
>  From , it sounds like the
> PEP process is appropriate here, though other PEPs (like 
>   > make it sound as though these are meant for proposals for "Python
> 3000", which is not necessarily my intent.
>
> Here's a brief sketch of my proposal, in case it helps:
>
> Add a "match" function to string.Template, which takes a text string
> as a parameter.  If this text string can be matched to the template,
> by substituting some portion of the given string for each field of the
> template, then .match returns a dictionary, where each key is a field
> name and the value is the corresponding text from the input.  If the
> text string cannot be matched to the template, then .match returns None.
>
> I understand that if I'm to write a PEP, I'll need to flesh this out
> considerably as per PEP 0001.  But that document also suggests first
> discussing it here.  I'm still a newbie (or actually, oldbie-turned-
> nonbie-turned-newbie-again), so I could use some advice.  What's the
> next step in advocating for this idea?
>
> Thanks,
> - Joe

Whenever I needed such functionality I used the re module. The benefit
is that it uses unix style regular expression syntax and an egrep/awk/
perl/ruby user can understand it. You should show a few examples where
your proposal looks better than just using RE.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Append a new value to dict

2008-10-13 Thread pruebauno
On Oct 13, 9:41 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Mon, 13 Oct 2008 14:10:43 +0200, Mathias Frey wrote:
> > However incrementing a non-existing key throws an exception. So you
> > either have to use a workaround:
>
> >  >>> try:
> > ...   counter['B'] += 1
> > ... except KeyError:
> > ...   counter['B'] = 1
>
> > Since this looks ugly somebody invented the setdefault method:
>
> >  >>> counter['B'] = counter.setdefault('B',0) + 1
>
> Nope, for this use case there is the `dict.get()` method:
>
> counter['B'] = counter.get('B', 0) + 1
>
> This assigns only *once* to ``counter['B']`` in every case.
>
> `dict.setdefault()` is for situations where you really want to actually
> put the initial value into the dictionary, like with the list example by
> the OP.
>
> Ciao,
> Marc 'BlackJack' Rintsch

...and if you are using Python 2.5 or later you can use the
collections module with collections.defaultdict(list) or
collections.defaultdict(int) to do the same thing. I personally find
it easier to read.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Append a new value to dict

2008-10-13 Thread Pat

Pat wrote:
I know it's not "fair" to compare language features, but it seems to me 
(a Python newbie) that appending a new key/value to a dict in Python is 
awfully cumbersome.


In Python, this is the best code I could come up with for adding a new 
key, value to a dict


mytable.setdefault( k, [] ).append( v )

In Perl, the code looks like this:

$h{ $key } = $value ;

Is there a better/easier way to code this in Python than the 
obtuse/arcane setdefault code?


Naturally, right after writing my post I found that there is an easier way:

table[ k ] = v

I found that in "Python for Dummies". How apropos.
--
http://mail.python.org/mailman/listinfo/python-list


docpicture

2008-10-13 Thread bearophileHUGS
In Python code that processes some geometrical data I want to explain
what each variable like w1, w2, h2, h3, etc, means in the geometrical
objects. In such situation I don't use longer and more clear variable
names because in geometry I'm used to use short vertex/line/length
names, finding them more readable in the various formulas. Complex
formulas full of long names become huge and not much readable anyway.

To explain what those w1, w2, h2, h3 mean I can use text, or sometimes
ASCII art. But ASCII art is very low-resolution, so I have found that
a single little image can explain the meaning of lot of variables (and
other details) in a short space. Leaving the explanations to normal
textual comments.

So in this situation I have sometimes created a quite small image (1
bit/pixel) that encoded in png image format may require just few
hundred bytes. With Python I encode is binary data string in base64,
and I paste that as a string into the Python souce code. It probably
takes only 4-7 lines or so. With one or two more lines of Python I can
decode that string it and save as png again (usually this image
decoding line is commented out or executed only if a debugging global
variable is true). So far I have never used SVG vector images for such
purpose, but they are another possibility (the SVG ones may need to be
bzipped2 before the base64 encoding).

This way there's no risk of losing the essential image, because it's
embedded into the Python code.

Have you ever done this? Do you think such "documentation
picture" (analogous to a docstring) is an acceptable practice? I don't
need to do that often enough, so I think it doesn't deserve to become
supported by Python itself. While I presume emacs and similar
"advanced" editors can be programmed to recognize such string pictures
and show them inlined... :-)

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


Re: Append a new value to dict

2008-10-13 Thread paul

Pat schrieb:
I know it's not "fair" to compare language features, but it seems to me 
(a Python newbie) that appending a new key/value to a dict in Python is 
awfully cumbersome.


In Python, this is the best code I could come up with for adding a new 
key, value to a dict


mytable.setdefault( k, [] ).append( v )

In Perl, the code looks like this:

$h{ $key } = $value ;

Whats wrong with:

mytable[key] = value

cheers
 Paul

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


Making class attributes non-case-sensitive?

2008-10-13 Thread Rafe
Hi,

I'm working within an application (making a lot of wrappers), but the
application is not case sensitive. For example, Typing obj.name,
obj.Name, or even object.naMe is all fine (as far as the app is
concerned). The problem is, If someone makes a typo, they may get an
unexpected error due accidentally calling the original attribute
instead of the wrapped version. Does anyone have a simple solution for
this?

I can protect against some cases just by making an 'alias':
class AClass(object):
def name(self):
print "hello"

Name = name

...but this doesn't protect against typos, it gets more complicated
with multi-word attribute names, and it makes my epydocs confusing to
read since all spelling versions are shown (I AM concerned about my
docs being clear, but not as much as stopping typo related errors).

I thought about using my wrapper's __getattr__ and __setattr__, but I
I am concerned about the overhead of every delegated attribute call
running a search and compare (.lower() based compare?).

Any ideas or precedence?


Cheers,

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


Re: class point in python

2008-10-13 Thread Almar Klein
I made a class to store sets of points a few months ago.I don't consider it
finished enough to release it somewhere,
but I'm happy to share it if you're interested. Send me an
e-mail if you are.

Almar


2008/10/12 [EMAIL PROTECTED] <[EMAIL PROTECTED]>

> i am looking for a python implementation of this class, a point X,Y
> representation
>
> http://msdn.microsoft.com/en-us/library/system.drawing.point_methods.aspx
>
> is there any library that has this class?
>
> thanks
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Suggestion for the PythonDevelopment for next version

2008-10-13 Thread azrael
You know, sometimes it annoys me to write a for loop in Python. If we
use a list a=[1,2,3,4], and want to loop through it, Python offers the
next option
>>>for i in a:
>>>  print i
>>>
1
2
3
4

I love this. So simple and smooth. But what happens if we need also
the position of an object in a list. Then there comes this annoying
writing.

>>> for i in range(len(a)):
>>>  print a[i], i
>>>
1 0
2 1
3 2
4 3

I think that it would be great if the Python language, which is a
totaly OOP language, could also use the index variable from the first
example and consider it as an object with a Object variable. I mean
the following.

>>>for i in a:
>>>  print i, i.index# i.index is my sugesstion
>>>
1 0
2 1
3 2
4 3

I think that this would be great and we cou pass by this annoying
"range(len(a))" functions
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess.Popen(..., cwd=...) and Makefile $(PWD) don't play nice

2008-10-13 Thread Miki
> The problem is, he is not printing the name of the current working
> directory; he is printing the value of the variable $PWD.  That is
> likely set from the environment by the shell he started the Python
> program from, but Python does *not* update to reflect changes to
> the working directory.
Should I see it as a bug? Should subprocess change this?

> Use '@pwd' instead of '@echo $(PWD)'.
I'm using '$(shell pwd)', just wondered why $PWD didn't work.

Thanks for the explanation.
--
Miki <[EMAIL PROTECTED]>
http://pythonwise.blogspot.com

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


Re: Suggestion for the PythonDevelopment for next version

2008-10-13 Thread Diez B. Roggisch
azrael wrote:

> You know, sometimes it annoys me to write a for loop in Python. If we
> use a list a=[1,2,3,4], and want to loop through it, Python offers the
> next option
for i in a:
  print i

> 1
> 2
> 3
> 4
> 
> I love this. So simple and smooth. But what happens if we need also
> the position of an object in a list. Then there comes this annoying
> writing.
> 
 for i in range(len(a)):
  print a[i], i

> 1 0
> 2 1
> 3 2
> 4 3
> 
> I think that it would be great if the Python language, which is a
> totaly OOP language, could also use the index variable from the first
> example and consider it as an object with a Object variable. I mean
> the following.
> 
for i in a:
  print i, i.index# i.index is my sugesstion

> 1 0
> 2 1
> 3 2
> 4 3
> 
> I think that this would be great and we cou pass by this annoying
> "range(len(a))" functions

Luckily for those who read either the documentation or this form regulary,
the solution is already there (since python2.0 or so...)

for i, item in enumerate(iterable):
...

does the trick.

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


Module or script for backup

2008-10-13 Thread dudeja . rajat
Hi,

Is there a module or script already written for creating backup of files ?
-- 
Regrads,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list


Re: Suggestion for the PythonDevelopment for next version

2008-10-13 Thread Jean-Paul Calderone

On Mon, 13 Oct 2008 08:56:34 -0700 (PDT), azrael <[EMAIL PROTECTED]> wrote:

You know, sometimes it annoys me to write a for loop in Python. If we
use a list a=[1,2,3,4], and want to loop through it, Python offers the
next option

for i in a:
 print i


1
2
3
4

I love this. So simple and smooth. But what happens if we need also
the position of an object in a list. Then there comes this annoying
writing.


for i in range(len(a)):
 print a[i], i


1 0
2 1
3 2
4 3

I think that it would be great if the Python language, which is a
totaly OOP language, could also use the index variable from the first
example and consider it as an object with a Object variable. I mean
the following.


for i in a:
 print i, i.index# i.index is my sugesstion


1 0
2 1
3 2
4 3

I think that this would be great and we cou pass by this annoying
"range(len(a))" functions



Adding a random new attribute to arbitrary objects any time they happen
to end up in a for loop would be catastrophically terrible.  Consider
the enumerate builtin, instead.


for i, e in enumerate('abcd'):

... print i, e
... 
0 a

1 b
2 c
3 d

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


Re: Suggestion for s/the PythonDevelopment for next version/azrael

2008-10-13 Thread Bruno Desthuilliers

azrael a écrit :

You know, sometimes it annoys me to write a for loop in Python. If we
use a list a=[1,2,3,4], and want to loop through it, Python offers the
next option

for i in a:
 print i


1
2
3
4

I love this. So simple and smooth. But what happens if we need also
the position of an object in a list. Then there comes this annoying
writing.


for i in range(len(a)):
 print a[i], i


1 0
2 1
3 2
4 3



for index, obj in enumerate(any_sequence):
   print "obj %s is at position %s" % (obj, index)

print "And I might read the FineManual(tm) some day..."

HTH !-)


Oh, and while we're at it:


I think that it would be great if the Python language, which is a
totaly OOP language, could also use the index variable from the first
example and consider it as an object with a Object variable. I mean
the following.


>>>for i in a:
>>>  print i, i.index# i.index is my sugesstion


Python is 100% OO in that everything (at least everything you can bind 
to a name) is an object. But it doesn't mean everything has to be done 
using the dotted syntax...

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


Re: PyGUI as a standard GUI API for Python?

2008-10-13 Thread Propad
> the bottom line is: if you want a windows version of pywebkitgtk, i'm
> happy to assist and advise anyone of the process- it should be quite
> straightforward _if_ you have MSVC and follow the standard procedure,
> but i'm not about to spend my own time and effort on providing a win32
> port using ming32, doing all the work _myself_, on my own, without
> financial incentive and renumeration.

Is Visual Studio 2005 OK, or is some other compiler required?

> i'll happily explain to other people what _they_ need to do, though.
>
> l.

If Visual Studio 2005 suffices, I'd give it a try.

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


Re: Split entries from LDAP

2008-10-13 Thread Michael Ströder
Lars wrote:
> I'm trying
> to create a script that creates a variable list (just a txt file to be
> included in bash scripts) with hosts from LDAP.

What exactly do you want to do? I'd recommend against passing a custom
text format around. Use either LDIF or CSV with decent modules.

> The file will include
> some static entries and the hosts based on 'cn', 'ipHostNumber' and I
> might as well set the 'description' as commen,t when the list from
> LDAP is created.

Better give an example.

> I got all the entries in the variable "raw_res" and I now got some
> doubts on how to split each value up in every entry.

>   raw_res = l.search_s( basedn, ldap.SCOPE_SUBTREE, filter, attrs )

This is the synchronous method which might not be suitable for large
result sets.

> for I in range(len(raw_res)):
>   print I, ": ",

In a simple case you could do:

for dn,entry in raw_res:
  print dn,entry # or whatever

But in LDAPv3 search results can also be search continuation (or
sometimes called referrals). E.g. AD makes use of them when search from
the domain level (without subordinate ou). In python-ldap these are
returned as a 2-tuple (None,StringType with LDAP URL).

So be prepared to handle the case that in the example above dn is None
and entry is a LDAP URL pointing to another server or part of the DIT.

On my test server:

>>>
pprint.pprint(l.search_s('ou=Testing,dc=...',ldap.SCOPE_ONELEVEL,attrlist=['cn']))
[('uid=anna,ou=Testing,dc=stroeder,dc=de',
  {'cn': ['Anna Blume']}),
 ('cn=Fred Feuerstein,ou=Testing,dc=stroeder,dc=de',
  {'cn': ['Fred Feuerstein']}),
 (None, ['ldap://ldap.openldap.org/dc=openldap,dc=org??base'])]

Ciao, Michael.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Suggestion for the PythonDevelopment for next version

2008-10-13 Thread azrael
I know that. enumerate is a great function. But this way it always
adds some complexity. I think that it is more better to give a man a
better tool then to let him play with a not so good one. People like
Python because of his simplicity in comparison with c++. Maybe People
would like him even more it would be a bit more simple but the same
powerfull.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Suggestion for the PythonDevelopment for next version

2008-10-13 Thread Diez B. Roggisch
azrael wrote:

> I know that. enumerate is a great function. But this way it always
> adds some complexity. I think that it is more better to give a man a
> better tool then to let him play with a not so good one. People like
> Python because of his simplicity in comparison with c++. Maybe People
> would like him even more it would be a bit more simple but the same
> powerfull.

But the added complexity of your approach of setting an attribute at runtime
that can 

 - add arbitrary costs (who knows that setting the attribute might not
invoke a RPC-call?) for *every* enumeration of a list

 - conflict with multithreaded access or even only cartesian products of the
same list of objects, rendering it simply useless

is *less* hassle than putting a simple enumerate in place, just when needed?

You sure have an interesting view of complexity. Not exactly text-book-based
though.

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


Re: Making class attributes non-case-sensitive?

2008-10-13 Thread Peter Pearson
On Mon, 13 Oct 2008 04:08:03 -0700 (PDT), Rafe <[EMAIL PROTECTED]> wrote:
> Just so I don't hijack my own thread, the issue is 'how to wrap an
> object which is not case sensitive'.
>
> The reason I am stuck dealing with this?... The application's API is
> accessed through COM, 
[snip]
> XSI allows many languages to be used via COM, even from within the
> software (there are built-in code editors). In the early days,
> VBScript was the most common scripting language used while anything
> more hard-core was done in C++ (of course the C implementation is case
> sensitive - well as far as I know). Then JScript became the most
> common, now Python is considered standard.
[Much other stuff I didn't understand is snipped here.]

I apologize in advance if this appears unhelpful.  I
couldn't make hide nor hair of the above explanation.

The apparent requirement that there be no boundary between
the software's developers (who presumably are trained and
can learn case conventions) and its users is a completely
new one to me.  Can you possibly make such software
reliable?  Doesn't this open you up to the mother of all SQL
injection attacks?  I really would like to understand the
circumstances in which "Keep the users out of the code" (or,
pretty much equivalent, "Don't let the implementation
language drive the user interface") isn't the right answer.

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


Re: Python on JavaScript VM's (such as V8)?

2008-10-13 Thread lkcl
On Oct 7, 10:15 pm, Fuzzyman <[EMAIL PROTECTED]> wrote:
> On Oct 2, 1:06 pm,lkcl<[EMAIL PROTECTED]> wrote:
>
> > On Sep 3, 10:02 pm, [EMAIL PROTECTED] wrote:
>
> > > Berco Beute:
>
> > > > I wonder what it would take to implement Python inJavaScriptso it
>
> >  it's been done.  http://pyjamas.sf.net
>
> That's hardly an implementation of Python inJavascript-

 someone _is_ considering validating the pyjs.py interpreter to ensure
that it's NP complete.  however, it's an academic exercise that's not
driven by an actual real-world need.

 basically, running pyjs.py and the standard python 2.5 "compile"
module under pyv8.  just for kicks :)

 so, the beginnings of the process - to bootstrap your way entirely
into javascript-land, where you'd be able to "input" python and have
it compiled _to_ javascript _by_ a python-to-javascript compiler which
_itself_ has been compiled to javascript - the foundations have been
laid.

and it's not _as_ crazy as it sounds.  sufficient tests to demonstrate
unequivocably that the equivalent javascript _is_ equivalent; you then
have pyv8 empirically demonstrating a ten times - TEN times for
goodness sake - performance increase - that's got to be worth it.

especially if it can be done "automagically", behind the scenes, so
that when you type "python myapp.py" instead of executing forth-like
byte code (myapp.pyc) you "execute" javascript (myapp.pyj).


> it's a
> partial Python toJavascripttranslator.

 compiler.  python to javascript _compiler_ :)

 with a more complete python-to-javascript compiler in 
http://code.google.com/p/pyjamas
subversion - you'll need the llpamies branch, but you'll _also_ need
to go back to around sep 2007.  somewhere in between then and now,
luis tried to add proper support for **kwargs and he didn't complete
it.


> Still looks good though.

 yeh :)

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


Re: PyGUI as a standard GUI API for Python?

2008-10-13 Thread lkcl
> >> You can remove layouts from layouts with the QLayout.removeItem() method.

> >  yes... it didn't work.  a layout within a layout - i think it was a
> > QHorizontalLayout within a QGridLayout - didn't want to be removed.
> > it's probably a bug.

> Was it detached from the layout, but still visible?

i don't know if it _was_ detached from the layout, but it was
definitely still visible.  see 
http://pyjs.org/examples/gridtest/output/GridTest.html
for the example i was porting to pyqt4.  each time i clicked "Next", a
new set of N,N would be _overlaid_ on top of the old ones, even though
i was doing removeItem().

the code's at http://lkcl.net/pyjamas-desktop/pyqt4.tgz

although i'm interested to know if there's a solution (to this
particular problem), the amount of additional work to provide an
equivalent of the "1px", "10em", "25%" etc. subdivisions on layouts,
and the amount of additional work to provide "flowing" and HTML-
substitutable layouts (see http://pyjd.org/api/pyjamas.ui.HTMLPanel-class.html)
is just... it's a lot of work.

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


Re: Suggestion for the PythonDevelopment for next version

2008-10-13 Thread Kirk Strauser
At 2008-10-13T16:11:26Z, azrael <[EMAIL PROTECTED]> writes:

> I know that. enumerate is a great function. But this way it always
> adds some complexity. I think that it is more better to give a man a
> better tool then to let him play with a not so good one. People like
> Python because of his simplicity in comparison with c++. Maybe People
> would like him even more it would be a bit more simple but the same
> powerfull.

"enumerate" doesn't add complexity: it adds specificity.  When you use it,
there is no question of intent.  You are saying, explicitly, that you're
going to want to use the index.

Your way adds an enormous amount of complexity in that it's magic behavior
with no obviously good implementation.  What if the objects in my list
already have an attribute named "index" and I don't want your loop
contstruct to overwrite it?  What if I never use enumerate as it is and
don't want to pay for the extra overhead of modify every object I'll ever
get from an iterator?

Thanks, but no.  One of the things I love about Python is its lack of magic.
-- 
Kirk Strauser
The Day Companies
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question

2008-10-13 Thread Steven D'Aprano
On Mon, 13 Oct 2008 19:45:46 +0530, Aditi Meher wrote:

> Hello
> 
> How to write code to store data into buffer using python?
> 
> Please Reply

With a keyboard.

Although if you're really keen, you could use a magnetized needle and 
edit the sectors on the hard disk directly.


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


Re: PIL on windows XP x64 (64-bit)?

2008-10-13 Thread Lawrence D'Oliveiro
In message
<[EMAIL PROTECTED]>, Berco
Beute wrote:

> Has anybody here got PIL (the Image lib) working on Windows XP x64 (64-
> bit)? There is no version available for that platform from
> pythonware.com.

Shouldn't your distro maintainers have it in their repositories?
--
http://mail.python.org/mailman/listinfo/python-list


Question

2008-10-13 Thread Aditi Meher
Hello

How to write code to store data into buffer using python?

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


RegExp: "wontmatch"-function

2008-10-13 Thread pjacobi . de
Dear All,

I'm looking for a function which, given a regexp re and  and a string
str, returns
whether re won't match any string starting with str. (so it would
always
return False if str is "" or if str itself matches re -- but that are
only the
easy cases).

I have the vague feeling that the internal workings of the regexp
matcher
can answer the question, but that there's no way to get this result
from Python code.

Any ideas or prior art on how to get this function?

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


Re: Making class attributes non-case-sensitive?

2008-10-13 Thread Diez B. Roggisch
Rafe wrote:

> Just so I don't hijack my own thread, the issue is 'how to wrap an
> object which is not case sensitive'.
> 
> The reason I am stuck dealing with this?... The application's API is
> accessed through COM, so I don't know if I can do anything but react
> to what I get. The API was written while the app (Softimage|XSI - one
> of 3 leading 3D applications for high-end visual effects) was owned by
> Microsoft. I'm not sure if it is standard for Microsoft or just the
> way this app was implemented (perhaps because under-users were
> scripting in VBscript which is not case sensitive).
> 
> XSI allows many languages to be used via COM, even from within the
> software (there are built-in code editors). In the early days,
> VBScript was the most common scripting language used while anything
> more hard-core was done in C++ (of course the C implementation is case
> sensitive - well as far as I know). Then JScript became the most
> common, now Python is considered standard.
> 
> Anyway, the standard practice is to use mixed-case, so I need to
> adhere to it as the resulting framework I am creating needs to be
> intuitive to use (my end-user is still writing code. It's an API for
> an API I guess...)
> 
> I don't *think* I need to worry too much about performance because I'm
> not doing any serious processing, this is more about convention
> enforcement and quality control rather than number crunching. I might
> try to write something generic which gets executed by the wrappers
> __getattr__ and __setattr__, but I was hoping for some nifty
> workaround, maybe in the form of a decorator or something? Again...
> any ideas?

I still don't get the full picture - anyway, what I infer is this:

 - for your own sake, you want to stick with "proper" naming, whatever that
means

 - you can't control what will be called.

Then I'd go with the __getattr__-way, plus maybe a meta-class (or
postprocessing) that maps all attributes to a lower-case-variant as well,
so that the lookup is efficient.

Does that help?

Diez

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


Getting windows error while making a backup

2008-10-13 Thread dudeja . rajat
Hi,

I've this backup script that having some problems. Please some one suggest
what is that I'm missing in it.
This backup script deletes the previous backups and then create a new backup
by simply renaming the original folder to backup folder and creates a new
folder.

The folder contains many files and folders and many .svn (i.e. hidden and
readonly files and directories)

Well things seems to be done correctly but at times while renaming the
folder to backup I get this error
 WindowsError: [Error 5] Access is denied

Here is my code:

The thread class that removes the hidden and readonly permission from files
and folders. Then using shutil.rmtree to delete the files

import threading
import win32con
import win32api
import win32file
import sys
import shutil

sys.setrecursionlimit(5000)


class delDirTreeThread(threading.Thread):
def __init__(self, path):
self.path = path
threading.Thread.__init__(self)

def run(self):
self.delRecursive(self.path)
shutil.rmtree(self.path)

def delRecursive(self, path):
for file in os.listdir(path):
file_or_dir = os.path.join(path,file)
if os.path.isdir(file_or_dir):
print file_or_dir
print "file_or_dir: %s - %d" %(file_or_dir,
win32file.GetFileAttributesW(file_or_dir))
if win32file.GetFileAttributesW(file_or_dir) !=
win32con.FILE_ATTRIBUTE_NORMAL:
win32file.SetFileAttributesW(file_or_dir,
win32con.FILE_ATTRIBUTE_NORMAL)
if os.listdir(file_or_dir) != []:
self.delRecursive(file_or_dir) #it's a directory
recursive call to function again
else:

print file_or_dir
print "ELSE - file_or_dir: %s - %d" %(file_or_dir,
win32file.GetFileAttributesW(file_or_dir))
if win32file.GetFileAttributesW(file_or_dir) !=
win32con.FILE_ATTRIBUTE_NORMAL:
win32file.SetFileAttributesW(file_or_dir,
win32con.FILE_ATTRIBUTE_NORMAL)
#os.remove(file_or_dir) #it's a file, delete it



>From some part in application I call this threading class as:

delTree = delDirTreeThread(subdir)
delTree.start()
delTree.join()

subdir is the absolute path to the directory tree for which I want to create
a new backup and delete the older ones.

The very reason I did this inside a thread is because I want application to
wait until the backup created (making sure that the older ones are deleted
and new one created)

Can some one help in this?


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


SIGALRM problem

2008-10-13 Thread Paul Rubin
I'm trying to run a command on a remote host, something like:

   result = os.popen('ssh otherhost mycommand').read()

It is possible that the other host is down, in which case the ssh
command hangs, so I want my script to time out if this happens:

   def timeout(*x):
  raise IOError, 'timeout'
   signal(SIGALRM, timeout)
   alarm(20)

   result = os.popen('ssh otherhost mycommand').read()

I would expect the above to raise IOError if the ssh doesn't return
within 20 seconds, but it seems to hang when the other host is down,
until eventually the tcp connection times out after something like 5
minutes (which is much longer than I want to wait).

Anyone know if os.popen somehow pre-empts the alarm signal?  If it
does, I'd consider that a bug.

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


Re: Making class attributes non-case-sensitive?

2008-10-13 Thread Rafe
Just so I don't hijack my own thread, the issue is 'how to wrap an
object which is not case sensitive'.

The reason I am stuck dealing with this?... The application's API is
accessed through COM, so I don't know if I can do anything but react
to what I get. The API was written while the app (Softimage|XSI - one
of 3 leading 3D applications for high-end visual effects) was owned by
Microsoft. I'm not sure if it is standard for Microsoft or just the
way this app was implemented (perhaps because under-users were
scripting in VBscript which is not case sensitive).

XSI allows many languages to be used via COM, even from within the
software (there are built-in code editors). In the early days,
VBScript was the most common scripting language used while anything
more hard-core was done in C++ (of course the C implementation is case
sensitive - well as far as I know). Then JScript became the most
common, now Python is considered standard.

Anyway, the standard practice is to use mixed-case, so I need to
adhere to it as the resulting framework I am creating needs to be
intuitive to use (my end-user is still writing code. It's an API for
an API I guess...)

I don't *think* I need to worry too much about performance because I'm
not doing any serious processing, this is more about convention
enforcement and quality control rather than number crunching. I might
try to write something generic which gets executed by the wrappers
__getattr__ and __setattr__, but I was hoping for some nifty
workaround, maybe in the form of a decorator or something? Again...
any ideas?


Cheers,

- Rafe


On Oct 13, 4:15 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Rafe wrote:
> > Hi,
>
> > I'm working within an application (making a lot of wrappers), but the
> > application is not case sensitive. For example, Typing obj.name,
> > obj.Name, or even object.naMe is all fine (as far as the app is
> > concerned). The problem is, If someone makes a typo, they may get an
> > unexpected error due accidentally calling the original attribute
> > instead of the wrapped version. Does anyone have a simple solution for
> > this?
>
> > I can protect against some cases just by making an 'alias':
> > class AClass(object):
> >     def name(self):
> >         print "hello"
>
> >     Name = name
>
> > ...but this doesn't protect against typos, it gets more complicated
> > with multi-word attribute names, and it makes my epydocs confusing to
> > read since all spelling versions are shown (I AM concerned about my
> > docs being clear, but not as much as stopping typo related errors).
>
> > I thought about using my wrapper's __getattr__ and __setattr__, but I
> > I am concerned about the overhead of every delegated attribute call
> > running a search and compare (.lower() based compare?).
>
> > Any ideas or precedence?
>
> Ideas? Don't do that...
>
> Seriously: where does that code come from, who's typing it? If it is python,
> then make people follow python's rules. If it is some sort of homebrewn
> language you map to python, adapt the mapper to enforce lower-case and make
> all your properties lower case.
>
> Diez

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


Re: docpicture

2008-10-13 Thread Steven D'Aprano
On Mon, 13 Oct 2008 08:34:03 -0700, bearophileHUGS wrote:

> So in this situation I have sometimes created a quite small image (1
> bit/pixel) that encoded in png image format may require just few hundred
> bytes. With Python I encode is binary data string in base64, and I paste
> that as a string into the Python souce code. It probably takes only 4-7
> lines or so.
[...]
> Have you ever done this? Do you think such "documentation picture"
> (analogous to a docstring) is an acceptable practice? 

I've never done it, but I've often wished to be able to store diagrams in 
my code.


> I don't need to do
> that often enough, so I think it doesn't deserve to become supported by
> Python itself. 

I can't imagine Python having direct syntactic support for it, but I 
don't see any reason why the standard library couldn't some day grow a 
"docpicture" module, complete with a tiny (?) Tkinter app to display the 
diagram when requested.

I think this would be useful. If you choose to share your code under an 
appropriate licence, I would like to experiment with it.


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


Re: Append a new value to dict

2008-10-13 Thread jdd
On Oct 13, 7:21 am, Pat <[EMAIL PROTECTED]> wrote:

> Is there a better/easier way to code this in Python than the
> obtuse/arcane setdefault code?

foo = {'bar': 'baz'}
foo.update({'quux': 'blah'})
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python syntax question

2008-10-13 Thread Daniel
On Oct 8, 1:19 pm, "Blubaugh, David A." <[EMAIL PROTECTED]> wrote:
> Sir,
>
> I was just wondering that the module that you are utilizing (Rpyc) is a 
> remote process call module for python?  Is this what you are developing with 
> at this time?
>
> Thanks,
>
> David Blubaugh
>
> -Original Message-
> From: Daniel [mailto:[EMAIL PROTECTED]
> Sent: Wednesday, October 08, 2008 3:11 PM
> To: [EMAIL PROTECTED]
> Subject: Re: Python syntax question
>
> On Oct 8, 12:07 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> > On Wed, 08 Oct 2008 11:02:49 -0700, Daniel wrote:
> > > Here is one error I get when I try to import it:
>
> >  import Rpyc
> > > Traceback (most recent call last):
> > >   File "", line 1, in 
> > >   File "C:\Python25\lib\site-packages\Rpyc\__init__.py", line 7, in
> > > 
> > >     from Rpyc.Lib import rpyc_excepthook
> > >   File "C:\Python25\lib\site-packages\Rpyc\Lib.py", line 65
> > >     print("=== Remote traceback ===", file=stderr)
> > >                                                   ^
> > > SyntaxError: invalid syntax
>
> > > The little carrot points to the equal sign ('=') in 'file=stderr'
>
> > > What's the syntax problem?
>
> > That's Python 3.0 syntax where ``print`` is not a keyword anymore but
> > a function.  Won't work with Python 2.5.
>
> > Ciao,
> >         Marc 'BlackJack' Rintsch
>
> Thanks!  With that I was able to find a solution.
>
> This e-mail transmission contains information that is confidential and may be
> privileged. It is intended only for the addressee(s) named above. If you 
> receive
> this e-mail in error, please do not read, copy or disseminate it in any 
> manner.
> If you are not the intended recipient, any disclosure, copying, distribution 
> or
> use of the contents of this information is prohibited. Please reply to the
> message immediately by informing the sender that the message was misdirected.
> After replying, please erase it from your computer system. Your assistance in
> correcting this error is appreciated.
>
>

RPyC is use in pyscripter to provide remote debugging.  I was having
trouble getting the RPyC module working, and the reason is that the
RPyC site only provides a download for Python 3 (not sure why, since I
suspect that a lot of people are still in the 2.x releases).  Anyway,
I found an old version of RPyC and it worked out great.  I'm not
actually developing it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Suggestion for the PythonDevelopment for next version

2008-10-13 Thread azrael
case closed
--
http://mail.python.org/mailman/listinfo/python-list


Re: Making class attributes non-case-sensitive?

2008-10-13 Thread Matimus
On Oct 13, 4:08 am, Rafe <[EMAIL PROTECTED]> wrote:
> Just so I don't hijack my own thread, the issue is 'how to wrap an
> object which is not case sensitive'.
>
> The reason I am stuck dealing with this?... The application's API is
> accessed through COM, so I don't know if I can do anything but react
> to what I get. The API was written while the app (Softimage|XSI - one
> of 3 leading 3D applications for high-end visual effects) was owned by
> Microsoft. I'm not sure if it is standard for Microsoft or just the
> way this app was implemented (perhaps because under-users were
> scripting in VBscript which is not case sensitive).
>
> XSI allows many languages to be used via COM, even from within the
> software (there are built-in code editors). In the early days,
> VBScript was the most common scripting language used while anything
> more hard-core was done in C++ (of course the C implementation is case
> sensitive - well as far as I know). Then JScript became the most
> common, now Python is considered standard.
>
> Anyway, the standard practice is to use mixed-case, so I need to
> adhere to it as the resulting framework I am creating needs to be
> intuitive to use (my end-user is still writing code. It's an API for
> an API I guess...)
>
> I don't *think* I need to worry too much about performance because I'm
> not doing any serious processing, this is more about convention
> enforcement and quality control rather than number crunching. I might
> try to write something generic which gets executed by the wrappers
> __getattr__ and __setattr__, but I was hoping for some nifty
> workaround, maybe in the form of a decorator or something? Again...
> any ideas?
>
> Cheers,
>
> - Rafe
>
> On Oct 13, 4:15 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>
> > Rafe wrote:
> > > Hi,
>
> > > I'm working within an application (making a lot of wrappers), but the
> > > application is not case sensitive. For example, Typing obj.name,
> > > obj.Name, or even object.naMe is all fine (as far as the app is
> > > concerned). The problem is, If someone makes a typo, they may get an
> > > unexpected error due accidentally calling the original attribute
> > > instead of the wrapped version. Does anyone have a simple solution for
> > > this?
>
> > > I can protect against some cases just by making an 'alias':
> > > class AClass(object):
> > >     def name(self):
> > >         print "hello"
>
> > >     Name = name
>
> > > ...but this doesn't protect against typos, it gets more complicated
> > > with multi-word attribute names, and it makes my epydocs confusing to
> > > read since all spelling versions are shown (I AM concerned about my
> > > docs being clear, but not as much as stopping typo related errors).
>
> > > I thought about using my wrapper's __getattr__ and __setattr__, but I
> > > I am concerned about the overhead of every delegated attribute call
> > > running a search and compare (.lower() based compare?).
>
> > > Any ideas or precedence?
>
> > Ideas? Don't do that...
>
> > Seriously: where does that code come from, who's typing it? If it is python,
> > then make people follow python's rules. If it is some sort of homebrewn
> > language you map to python, adapt the mapper to enforce lower-case and make
> > all your properties lower case.
>
> > Diez
>
>

So, this application you are writing for allows you to script/write
callbacks in python? They are then somehow accessable through a COM
interface exposed by the application? You are worried that someone
using the application will run into case-sensitivity if they access
the code written in python?

There isn't much overhead with __getattr__ since it is _only_ called
if the initial look-up didn't find the name. You can do something like
this:

class C(object):
def __init__(self, ...):
...
self._lookingup = False
...

# If this is re-entered while already looking up a value,
# then we know that there is a problem. Not thread safe.
def __getattr__(self, attr):
try:
if self._lookingup:
raise AttributeError("'C' object has no attribute
%r"%attr)
self._lookingup = True
return getattr(self, attr.lower())
finally:
self._lookingup = False


def __setattr__(self, attr, value):
super(C, self).__setattr__(attr.lower(), value)

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


Re: Question

2008-10-13 Thread Chris Rebert
To be a bit less sarcastic than the other replies, your question is
*much* *much* too vague to be answered.
Unless you give us more specific information and ask a more precise
question, it's impossible help you.
See the link someone already replied with for some good advice on how
to do that.

Also, please don't double-post like you just did, as that's bad
netiquette and just wastes everyone's time.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

On Mon, Oct 13, 2008 at 7:15 AM, Aditi Meher <[EMAIL PROTECTED]> wrote:
> Hello
>
> How to write code to store data into buffer using python?
>
> Please Reply
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: SIGALRM problem

2008-10-13 Thread Mike Driscoll
On Oct 13, 11:45 am, Paul Rubin  wrote:
> I'm trying to run a command on a remote host, something like:
>
>    result = os.popen('ssh otherhost mycommand').read()
>
> It is possible that the other host is down, in which case the ssh
> command hangs, so I want my script to time out if this happens:
>
>    def timeout(*x):
>       raise IOError, 'timeout'
>    signal(SIGALRM, timeout)
>    alarm(20)
>
>    result = os.popen('ssh otherhost mycommand').read()
>
> I would expect the above to raise IOError if the ssh doesn't return
> within 20 seconds, but it seems to hang when the other host is down,
> until eventually the tcp connection times out after something like 5
> minutes (which is much longer than I want to wait).
>
> Anyone know if os.popen somehow pre-empts the alarm signal?  If it
> does, I'd consider that a bug.
>
> Thanks
> --Paul

Using some Google-Fu, I found this post:

http://mail.python.org/pipermail/python-list/2003-August/217530.html

It's old, but it looks ok...

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


Re: docpicture

2008-10-13 Thread skip

Steven> I can't imagine Python having direct syntactic support for it,
Steven> but I don't see any reason why the standard library couldn't
Steven> some day grow a "docpicture" module, complete with a tiny (?)
Steven> Tkinter app to display the diagram when requested.

Heck, if you go to the point of including a docpicture module, might as well
just support the feature in IDLE...  Other IDEs would probably pick up the
feature as well.

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


Re: Question

2008-10-13 Thread Bruno Desthuilliers

Aditi Meher a écrit :

Hello

How to write code to store data into buffer using python?


A text/code editor might be useful.

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


Re: docpicture

2008-10-13 Thread Benjamin Kaplan
On Mon, Oct 13, 2008 at 1:43 PM, <[EMAIL PROTECTED]> wrote:

>
>Steven> I can't imagine Python having direct syntactic support for it,
>Steven> but I don't see any reason why the standard library couldn't
>Steven> some day grow a "docpicture" module, complete with a tiny (?)
>Steven> Tkinter app to display the diagram when requested.
>
> Heck, if you go to the point of including a docpicture module, might as
> well
> just support the feature in IDLE...  Other IDEs would probably pick up the
> feature as well.
>
> Skip


So, the IDEs will support it. what happens when you run the interpreter from
the command line?

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


Re: Safe eval of insecure strings containing Python data structures?

2008-10-13 Thread George Sakkis
On Oct 13, 8:36 am, lkcl <[EMAIL PROTECTED]> wrote:
> On Oct 9, 4:32 am, "James Mills" <[EMAIL PROTECTED]> wrote:
>
> > On Thu, Oct 9, 2008 at 2:26 PM, Warren DeLano <[EMAIL PROTECTED]> wrote:
> > > JSON rocks!  Thanks everyone.
>
> > Yes it does :)
>
> > > Ben wrote:
>
> > >>More generally, you should never execute (via eval, exec, or whatever)
> > >>*any* instruction from an untrusted path; especially not arbitrary
> > >>data from an input stream.
>
>  rubbish.  this is why a project i was involved with, to do execution
> of code from a database instead of a filesystem had to be abandoned,
> back in 2001.
>
>  there are perfectly good systems for associating security context
> with "arbitrary data" (as the security models of SE/Linux, based on
> Flask, and the security model of windows nt, based on VAX/VMS
> security, show).
>
>  there was a flawed design decision in python 2.2 or python 2.3 which
> resulted in an "escape route" - i believe it centered around either
> __class__ or __new__ - in the c code, which the developers had not
> considered, and would not correct.
>
>  this decision resulted in the abandonment of the rexec.py module in
> python: you can see for yourself because it raises a runtime exception
> when you try to use it, issuing a warning.
>
>  it's _perfectly_ possible to define security contexts and boundaries,
> and to allow access to functions and modules on a per-security-context
> basis.
>
> *as defined by the application developer* [not by the developers of
> python itself]
>
> if an individual developer wants to allow "arbitrary code execution
> from any data stream", it most certainly is _not_ anyone's place to
> dictate to them that they "cannot do this".

That's why eval and exec still exist (and will probably be around for
a long time, if not forever). If you define your own external to
python security contexts, what did the deprecated rexec buy you that
eval/exec don't ? In any case, rexec is a single pure python module;
nothing stops you from copying it over to your project, hacking it and
keep using it at your own risk.

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


Re: RegExp: "wontmatch"-function

2008-10-13 Thread Kirk Strauser
At 2008-10-13T16:40:07Z, [EMAIL PROTECTED] writes:

def nomatch(value):
return not(value == '' or pattern.match(value))

-- 
Kirk Strauser
The Day Companies
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to set the time of a directory?

2008-10-13 Thread MRAB
On Oct 13, 2:40 pm, oyster <[EMAIL PROTECTED]> wrote:
> so, let alone the 'bad' os.utime, is there any way to set the time of
> directory in windows within official python release? can ctypes be
> helpful, and how ?
>
This appears to work:

import pywintypes
import win32file
import time

def set_dir_time(path, new_times=None):
if new_times is None:
t = time.localtime()
atime, mtime = t, t
else:
atime, mtime = time.localtime(new_times[0]),
time.localtime(new_times[1])
atime, mtime = pywintypes.Time(atime[0 : 6]),
pywintypes.Time(mtime[0 : 6])
handle = win32file.CreateFile(path, win32file.GENERIC_WRITE,
win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None,
win32file.OPEN_EXISTING, win32file.FILE_FLAG_BACKUP_SEMANTICS, 0)
win32file.SetFileTime(handle, None, atime, mtime)
handle.Close()


> I am using totalcommander, which is programmer in delphi, but can set
> the time of a directory
>
> thanx
>
> 2008/10/12, [EMAIL PROTECTED] <[EMAIL PROTECTED]>:
>
> > From: MRAB <[EMAIL PROTECTED]>
> > To: [EMAIL PROTECTED]
> > Date: Sat, 11 Oct 2008 11:29:12 -0700 (PDT)
> > Subject: Re: how to set the time of a directory?
> > On Oct 11, 1:18 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> > > On Oct 11, 1:27 am, "Timothy Grant" <[EMAIL PROTECTED]> wrote:> On Fri, 
> > > Oct 10, 2008 at 10:16 PM, oyster <[EMAIL PROTECTED]> wrote:
> > > > > os.utime works only against files. so what to do for a directory?
> > > > > thanx
>
> > > > Not sure why you'd say that.
>
> > > I am. He's running Windows.
>
> > > > drwxr-xr-x  2 tjg  tjg       68 Oct 10 22:23 test
> > > > ([EMAIL PROTECTED]) python
> > > > Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:16)
> > > > [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
> > > > Type "help", "copyright", "credits" or "license" for more 
> > > > information.>>> import os
> > > > >>> help(os.utime)
>
> > > > Help on built-in function utime in module posix:
>
> > > > utime(...)
> > > >     utime(path, (atime, mtime))
> > > >     utime(path, None)
>
> > > >     Set the access and modified time of the file to the given values.  
> > > > If the
> > > >     second form is used, set the access and modified times to the 
> > > > current time.
>
> > > > >>> os.utime('test', None)
> > > > >>> ^D
>
> > > > ([EMAIL PROTECTED]) ls -ltr
> > > > drwxr-xr-x  2 tjg  tjg       68 Oct 10 22:24 test
>
> > > > --
> > > > Stand Fast,
> > > > tjg.  [Timothy Grant]
> > > >>> os.utime('WinDir', None)
>
> > > Traceback (most recent call last):
> > >   File "(stdin)", line 1, in 
> > > WindowsError: [Error 5] Access is denied: 'WinDir'
>
> > > I consider this a bug. (Note that os.utime works for directories under
> > > cygwin)
>
> > This in issue #214245 (2000-09-16). See also
> >http://mail.python.org/pipermail/python-bugs-list/2004-November/02612
>
>

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


Re: SIGALRM problem

2008-10-13 Thread Paul Rubin
Mike Driscoll <[EMAIL PROTECTED]> writes:
> http://mail.python.org/pipermail/python-list/2003-August/217530.html
> It's old, but it looks ok...

Thanks.  Maybe I did a dumb thing by overloading IOError and os.popen
is actually catching that exception for purposes of its own.  I'll
try making a new exception.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Upgrading from 2.5 to 2.6

2008-10-13 Thread Matimus
> Python 2.5 and 2.6 can coexist, so there isn't any need for some
> kind of upgrade procedure. Installing 2.6 will not affect your
> 2.5 installation.

That isn't entirely true. In Windows, python files bound to a
particular version of python in the registry. So, for example, if you
double click on "some_prog.py" to run it, then it will by default
start up using python2.6 once it is installed. Also right-clicking on
a file and selecting "edit with Idle" will open the version of Idle
associated with 2.6 (under 2.6). This is a minor difference, but I
wouldn't say that there are no side effects. They can be easily worked
around.

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


Re: Mail reader & spam

2008-10-13 Thread Cousin Stanley

> I'm hesitating to change news readers 
>  

  You might try the python-based  XPN  news client at  

  http://xpn.altervista.org/index-en.html
  
  I've used it for the past few years 
  and like it very much 


-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona

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


Re: please solve

2008-10-13 Thread harijay
On Oct 12, 12:15 pm, Raymond Cote <[EMAIL PROTECTED]>
wrote:
> shweta mani wrote:
> > hi folks,
> > i have been assigned a project on Python. i need to execute a remote
> > shell script file from a windows machine through SSH twisted or
> > paramiko. if it is a normal file then directly with the command  sh
> > .sh it is getting executed.
> > self.conn.sendRequest(self, 'exec', common.NS(sh test1.sh), wantReply
> > = 1)
>
> You could take a look at the Fabric project for some ideas as to how to
> do this:
>    
>
> --R

ALso  please look at the pexpect module. This allows you to supply
"human" input to automate scripts that require it.
Look at http://www.noah.org/wiki/Pexpect#Description_of_Pexpect
Hope this helps
Harijay
--
http://mail.python.org/mailman/listinfo/python-list


Sending multi-part MIME package via HTTP-POST

2008-10-13 Thread [EMAIL PROTECTED]
This has got me somewhat stumped, so I'll throw it up here in hopes
that someone has ran into this before. I'm trying to send a MIME
package to Esko Backstage. I'm a bit confused as to how to send this
to the server in a manner that it'll be able to get and de-code the
MIME package in a valid way.

The big question is does this entire mime package belong in the
headers section of an HTTP request? If not, what is the best Pythonic
way to send this thing. I'm using 2.5's email package to create the
package and was trying to use its as_string() method to pump this
through httplib, but I'm getting a very vague server error message
that seems to indicate a malformed package. Here is the broken code:

hcon = httplib.HTTPConnection(JMF_GATEWAY)
hcon.putrequest('POST', JMF_GATEWAY_PATH)
hcon.endheaders()
hcon.send(msg.as_string())

I've pasted the string representation of the MIME package I'm trying
to send below. Any ideas would be greatly appreciated.

Content-Type: multipart/related;
boundary="===1845688244=="
MIME-Version: 1.0
start: cid:beginning

--===1845688244==
Content-Type: application/vnd.cip4-jmf+xml
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-ID: beginning


--===1845688244==
Content-Type: application/vnd.cip4-jdf+xml
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-ID: aJDF_1


http://www.esko-graphics.com/
EGschema1_0">









http://www.CIP4.org/
JDFSchema_1_1" xmlns:eg="http://www.esko-graphics.com/EGschema1_0";>












--===1845688244==--

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


gmpy and counting None

2008-10-13 Thread mmanns
Hi,

I just stumbled upon the following issue (I am running Debian):

$ python
Python 2.5.2 (r252:60911, Sep 29 2008, 21:15:13) 
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> [2, None].count(None)
1
>>> from gmpy import mpz
>>> [mpz(2), None].count(None)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: coercion to gmpy.mpz type failed
>>> 

Is this a bug in gmpy?

If yes is there any way to issue the bug at
http://code.google.com/p/gmpy/
without creating a gmail account?


Thanks

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


Transformation with ``parser`` ast

2008-10-13 Thread Malthe Borch

(Note: repost from python-dev)

The ``compiler.ast`` module makes parsing Python source-code and AST 
manipulation relatively painless and it's straight-forward to implement 
a transformer class.


However, I find that the ``compiler.pycodegen`` module imposes a hard 
limit on the length of functions since it calculates jump points in a 
recursion.


I'm using this module to compile an XML dynamic template into Python 
code (akin to "Mako") and functions may grow to a rather large size.


Now it seems that the ``parser`` module, which parses source code into 
``parser.st`` trees does not have the same limitations, however, I could 
not find a transformer class compatible with its tree structure.


What's the recommended way of working with the AST tree from the 
``parser`` module?


\malthe

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


Re: how to start thread by group?

2008-10-13 Thread [EMAIL PROTECTED]
On Oct 13, 6:54 am, Lawrence D'Oliveiro <[EMAIL PROTECTED]
central.gen.new_zealand> wrote:
> In message <[EMAIL PROTECTED]>, Gabriel
>
>
>
> Genellina wrote:
> > En Tue, 07 Oct 2008 13:25:01 -0300, Terry Reedy <[EMAIL PROTECTED]>
> > escribió:
>
> >> Lawrence D'Oliveiro wrote:
>
> >>> In message <[EMAIL PROTECTED]>,
> >>> Gabriel Genellina wrote:
>
>  Usually it's more efficient to create all the MAX_THREADS at once, and
>  continuously feed them with tasks to be done.
>
> >>>  Given that the bottleneck is most likely to be the internet
> >>> connection, I'd say the "premature optimization is the root of all evil"
> >>> adage applies here.
>
> >> Feeding a fixed pool of worker threads with a Queue() is a standard
> >> design that is easy to understand and one the OP should learn.  Re-using
> >> tested code is certainly efficient of programmer time.
>
> > I'd like to add that debugging a program that continuously creates and
> > destroys threads is a real PITA.
>
> That's God trying to tell you to avoid threads altogether.

Especially in a case like this that's tailor made for a trivial state-
machine solution if you really want multiple connections.
--
http://mail.python.org/mailman/listinfo/python-list


Re: docpicture

2008-10-13 Thread skip

Benjamin> So, the IDEs will support it. what happens when you run the
Benjamin> interpreter from the command line?

Probably get ignored.  What else would you propose?  It's not executable
code anyway, just a special comment or portion of a docstring.

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


Re: Quality control in open source development

2008-10-13 Thread Steve Holden
Dave wrote:
> With the open source licenses that allow redistribution of modified
> code, how do you keep someone unaffiliated with the Python community
> from creating his or her own version of python, and declaring it to be
> Python 2.6, or maybe Python 2.7 without any approval of anyone at the
> PSF? Maybe their code is terrible, and not even compatible with the
> rest of Python! How can the PSF, for example, maintain the quality and
> coheren of new code contributed to be part of Python, or derivative
> works that claim to be some future version of Python? If licensees can
> redisribute as they like, isn't this a huge problem? Is this dealt
> with be restricting use of the Python trademarks?  Just curious..

The PSF relies on the Python core developers to maintain quality. As far
as redistribution is concerned there are requirements to describe the
changes made to the basic Python distribution in derived works.

As far as calling it "Python" is concerned, the PSF maintains a
trademark on the word "Python" used to describe computer software. An
informal description of PSF policy on uses of the trademark can be found at

  http://www.python.org/psf/trademarks/

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: docpicture

2008-10-13 Thread Benjamin Kaplan
On Mon, Oct 13, 2008 at 2:48 PM, Joe Strout <[EMAIL PROTECTED]> wrote:

> On Oct 13, 2008, at 12:09 PM, Benjamin Kaplan wrote:
>
>  Heck, if you go to the point of including a docpicture module, might as
>> well
>> just support the feature in IDLE...  Other IDEs would probably pick up the
>> feature as well.
>>
>> So, the IDEs will support it. what happens when you run the interpreter
>> from the command line?
>>
>
> Nothing.  It's just a doc string containing a bunch of hex codes.  Doc
> strings are ignored by the interpreter (AIUI).
>

I mean what happens when you type help() into the interactive console on the
command line? You will see the docstrings, and there will be a whole bunch
of random hex characters there.
--
http://mail.python.org/mailman/listinfo/python-list


Re: docpicture

2008-10-13 Thread Joe Strout

On Oct 13, 2008, at 2:43 PM, Benjamin Kaplan wrote:

I mean what happens when you type help() into the interactive  
console on the command line? You will see the docstrings, and there  
will be a whole bunch of random hex characters there.



Good point.  It might be better put in a specially-tagged comment,  
rather than in the docstring.


I still think it's a nifty idea though.

Best,
- Joe

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


Re: PyGUI as a standard GUI API for Python?

2008-10-13 Thread Terry Reedy

lkcl wrote:

On Oct 11, 11:17 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:

lkcl wrote:

I got the impression that there is currently no Windows binary
available.  Correct?  If not, perhaps someone trustworthy will someday
donate one.


sorry, terry, you deleted a bit too much context :)


I was referring to this at pyjd.org:

Pre-built amd64 .debs are available for download, providing 
pywebkitgtk-1.0, libwebkit-1.0-2 and libwebkit-dev, here:


* Download libwebkit-dev, libwebkit-1.0-2 and pywebkitgtk-1.0

and this
>> If not, perhaps someone trustworthy will someday donate one.

was my acknowledgement that a Windows binary is not trivial and that I 
don't expect one from you after all the nice work you have done.


[compiling with mingw32]

why the python developers didn't include the patches, and keep them up-
to-date, isn't clear.


Mostly likely because no one who uses mingw32 has volunteered to become 
the mingw32 Python developer who would update such patches to current 
Python (now 2.6/3.0) and support them by responding to bug reports and 
by upgrading them to 2.7/3.1 in the next few years.


Any system supported in core Python code with a set of #includes needs 
*someone* who will support that set.  If the supporter disappears and no 
one else volunteers, the #includes become obsolete and get deleted.


Terry Jan Reedy



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


Re: PyGUI as a standard GUI API for Python?

2008-10-13 Thread Terry Reedy

Propad wrote:

the bottom line is: if you want a windows version of pywebkitgtk, i'm
happy to assist and advise anyone of the process- it should be quite
straightforward _if_ you have MSVC and follow the standard procedure,
but i'm not about to spend my own time and effort on providing a win32
port using ming32, doing all the work _myself_, on my own, without
financial incentive and renumeration.


Is Visual Studio 2005 OK, or is some other compiler required?


I believe 2.4/2.5 used VS 2003 while 2.6/3.0 do (and 2.7/3.1 will) at 
least officially use VS 2008.  The free express version apparently 
works.  It is possible the extension extension modules compiled with 
2005 have/will work.  I would ask in a separate thread with VS 2005 in 
the subject line.



i'll happily explain to other people what _they_ need to do, though.

l.


If Visual Studio 2005 suffices, I'd give it a try.

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



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


Re: gmpy and counting None

2008-10-13 Thread Mensanator
On Oct 13, 2:43 pm, <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I just stumbled upon the following issue (I am running Debian):
>
> $ python
> Python 2.5.2 (r252:60911, Sep 29 2008, 21:15:13)
> [GCC 4.3.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> [2, 
> None].count(None)
> 1
> >>> from gmpy import mpz
> >>> [mpz(2), None].count(None)
>
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: coercion to gmpy.mpz type failed
>
>
>
> Is this a bug in gmpy?

Does the underlying GMP code support Nulls?

>
> If yes is there any way to issue the bug athttp://code.google.com/p/gmpy/
> without creating a gmail account?
>
> Thanks
>
> Martin

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


Selecting random elements from a list.

2008-10-13 Thread aditya shukla
Hello folks,

i have a list say list1=[a,b,c,...z] ie 26 elements i have to take 5
elements from it randomly and save in another list.Please explain how to do
this?


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


documentation: what is "::="?

2008-10-13 Thread Anita Kean
Hello

I just downloaded the new python2.6 documentation,
full of hopes it would solve some basic mysteries for me.
I'm new to python, so please forgive my ignorance.
I've two questions.

1) Everywhere in the old and new documentation, the 
string of characters "::=" is used in "explaining" things - but
I can nowhere find any stated meaning of this string.
I've had no luck searching on it on search engines - 
and even less if I don't quote it - the search engine returns an
error.

I couldn't find one occurrence of it in the new 2.6 tutorial,
nor in the sphinx-generated index of symbols, where "==" and
other character strings appear.
But for example in the reference directory, a grep on "::=" 
returns many many hits,
and the first one in simple_stmts.html (which I sort of
hoped _would_ be simple) was (quote):
> 
> Simple statements¶
> 
>Simple statements are comprised within a single logical line. Several
>simple statements may occur on a single line separated by semicolons.
>The syntax for simple statements is:
> simple_stmt ::=  expression_stmt
>  | assert_stmt
>  | assignment_stmt
>  | augmented_assignment_stmt
>  | pass_stmt
>  | del_stmt
>  | print_stmt
>  | return_stmt
>  | yield_stmt
>  | raise_stmt
>  | break_stmt
>  | continue_stmt
>  | import_stmt
>  | global_stmt
>  | exec_stmt
> 
> Expression statements¶   
> ...
(unquote)

So what's the relationship between the left and right hand sides of the "::=" 
string here? 

2) There is one other symbol the Python documentation seems to have appropriated
but never documents which I also come up against constantly, but which is never
defined - its use of "<==>"

e.g. in the os module docs
__str__(...)
 |  x.__str__() <==> str(x)

(and that's all there is on __str__ in os)

I'm guessing something like "if and only if" is implicated here?
But for example, if I import the sys module and perform the following three 
commands,
print sys.path
sys.path.__str__()
str(sys.path)

the first two give me the python path, and the last reports an error:
> 
> >>> str(sys.path)
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib/python2.5/locale.py", line 244, in str
> return format("%.12g", val)
>   File "/usr/lib/python2.5/locale.py", line 147, in format
> formatted = percent % value
> TypeError: float argument required
> 
What is it I'm not understanding here?

Are "::=" and "<==>" documented anywhere in the python docs?
Thanks 
Anita


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


Re: docpicture

2008-10-13 Thread skip
>> Nothing.  It's just a doc string containing a bunch of hex codes.  Doc
>> strings are ignored by the interpreter (AIUI).

Benjamin> I mean what happens when you type help() into the interactive
Benjamin> console on the command line? You will see the docstrings, and
Benjamin> there will be a whole bunch of random hex characters there.

If an IDE can be trained to recognize and display such a picture I sorta
assume help() can be trained to recognize and ignore it.

Skip

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


Re: Selecting random elements from a list.

2008-10-13 Thread Benjamin Kaplan
On Mon, Oct 13, 2008 at 5:29 PM, aditya shukla
<[EMAIL PROTECTED]>wrote:

> Hello folks,
>
> i have a list say list1=[a,b,c,...z] ie 26 elements i have to take 5
> elements from it randomly and save in another list.Please explain how to do
> this?
>
>
> Aditya
>


http://docs.python.org/library/random.html#module-random



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


Re: documentation: what is "::="?

2008-10-13 Thread Diez B. Roggisch

Anita Kean schrieb:

Hello

I just downloaded the new python2.6 documentation,
full of hopes it would solve some basic mysteries for me.
I'm new to python, so please forgive my ignorance.
I've two questions.

1) Everywhere in the old and new documentation, the 
string of characters "::=" is used in "explaining" things - but

I can nowhere find any stated meaning of this string.
I've had no luck searching on it on search engines - 
and even less if I don't quote it - the search engine returns an

error.

I couldn't find one occurrence of it in the new 2.6 tutorial,
nor in the sphinx-generated index of symbols, where "==" and
other character strings appear.
But for example in the reference directory, a grep on "::=" 
returns many many hits,

and the first one in simple_stmts.html (which I sort of
hoped _would_ be simple) was (quote):

Simple statements¶

   Simple statements are comprised within a single logical line. Several
   simple statements may occur on a single line separated by semicolons.
   The syntax for simple statements is:
simple_stmt ::=  expression_stmt
 | assert_stmt
 | assignment_stmt
 | augmented_assignment_stmt
 | pass_stmt
 | del_stmt
 | print_stmt
 | return_stmt
 | yield_stmt
 | raise_stmt
 | break_stmt
 | continue_stmt
 | import_stmt
 | global_stmt
 | exec_stmt

Expression statements¶   
...

(unquote)

So what's the relationship between the left and right hand sides of the "::=" 
string here? 


http://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_Form


2) There is one other symbol the Python documentation seems to have appropriated
but never documents which I also come up against constantly, but which is never
defined - its use of "<==>"

e.g. in the os module docs
__str__(...)
 |  x.__str__() <==> str(x)

(and that's all there is on __str__ in os)

I'm guessing something like "if and only if" is implicated here?


It's equivalence, like in

x = 2 <==> 2*x = 4

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


Re: Selecting random elements from a list.

2008-10-13 Thread Timothy Grant
On Mon, Oct 13, 2008 at 2:29 PM, aditya shukla
<[EMAIL PROTECTED]> wrote:
> Hello folks,
>
> i have a list say list1=[a,b,c,...z] ie 26 elements i have to take 5
> elements from it randomly and save in another list.Please explain how to do
> this?
>
>
> Aditya
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>


I would start here http://docs.python.org/library/random.html  you are
likely interested in choice or sample.

-- 
Stand Fast,
tjg.  [Timothy Grant]
--
http://mail.python.org/mailman/listinfo/python-list


ANN: PySmell v0.6 released

2008-10-13 Thread Orestis Markou
I'm happy to announce PySmell v0.6, an autocompletion library for  
Python and Vim (other editors pending).


New features include:

 * Import statement completion
 * Support for multiple TAGS files (that means external libraries)
 * Support for analysing Python 2.4-2.5 stdlib.

Plus many bugfixes and minor improvements.

Download link: http://orestis.gr/static/downloads/pysmell-0.6.tgz
Github: http://github.com/orestis/pysmell
TODO: http://github.com/orestis/pysmell/wikis/todo

What is PySmell?


PySmell is a python IDE completion helper.

It tries to statically analyze Python source code, without executing it,
and generates information about a project's structure that IDE tools can
use.

The first target is Vim, because that's what I'm using and because its
completion mechanism is very straightforward.

Download and Installation
=

PySmell's code is available at
[GitHub](http://github.com/orestis/pysmell/tree/v0.6). You can click
'Download' to get it as a zip/tar if you don't have git installed.

Extract and drop the pysmell package somewhere in your `PYTHONPATH`.
Distutils support coming soon - patches welcome!

Usage
=

To generate a PYSMELLTAGS file, use:

cd /root/of/project /dir/of/pysmell.py .

If you want to specifically include or exclude some files or directories
(eg. tests), you can use:

/dir/of/pysmell.py [Package Package File File ...] [-x Excluded  
Excluded ...]


Check for more options by invoking `pysmell.py` without any arguments

Vim integration
===

To use PySmell omnicompletion from inside Vim, you have to have:

1. Python support
2. The pysmell package in your PYTHONPATH (sometimes
Vim is silly about this)
3. Source pysmell/pysmell.vim
4. `:set omnifunc=pysmell#Complete` Note: If you want to always use  
pysmell for

python, do: `autocmd FileType python set omnifunc=pysmell#Complete`
5. [OPTIONAL] Select a matcher of your liking - look at pysmell.vim for
options. Eg: `:let g:pysmell_matcher='camel-case'`

You can then use ^X^O to invoke Vim's omnicompletion.


You can find more documentation in the README.markdown file.

Orestis Markou
--
[EMAIL PROTECTED]
http://orestis.gr/




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


  1   2   >