Re: dynamically generating temporary files through python/cgi (ot)

2007-11-01 Thread Hendrik van Rooyen


Miss Pfeffe  wrote:


>How do you make a python out of a banana?!

You kiss it just long enough - else it turns into a frog, so be careful!



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


Re: What is Jython?

2007-11-01 Thread Ant
On Nov 1, 6:54 am, [EMAIL PROTECTED] wrote:
...
> I would like to know more about Python and Jython?
> What is the difference between both of them?
> What is the future for Jython and which are the areas where it is
> used?

Jython is an implementation of Python for the Java VM. Currently it
stands as equivalent to Python v2.2, but progress has been rapidly
accelerating over the last year or so, and the next version will
probably be targeted at 2.5 AFAIK.

Jython also has access to all of the Java standard libraries (or any
Java libraries on the classpath for that matter.)

Jython is currently significantly slower than Python.

>From my experience Jython is most typically used as an embedded
extension/scripting language for Java applications in areas where
rapid development/change is required. This includes such areas as
scripting business logic, writing unit or functional tests etc. Take a
look at 
http://antroy.blogspot.com/2007/04/swing-testing-with-jython-and-jemmy.html
for an example of how I have successfully used Jython for Swing
testing. More information can be found on 
http://www.jython.org/Project/index.html

Cheers,

--
Ant.

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


Re: XML DOM, but in chunks

2007-11-01 Thread Stefan Behnel
Tommy Nordgren wrote:
>> On 31 okt 2007, at 21.24, Sean Davis wrote:
>>
>>> I have some very large XML files that are basically recordsets.  I
>>> would like to access each record, one-at-a-time, and I particularly
>>> like the ElementTree library for accessing the data.  Is there a way
>>> to have ElementTree read only one record of the data at a time?
>>> Alternatively, are there other ways that would allow one to parse out
>>> a record at a time and maintain some nice ways of accessing the
>>> elements within the record?
>>>
>>> Thanks,
>>> Sean
>>>
>> You need a Python (or other language) implementation of the SAX API
>> 
> The module you need is xml.sax

That's unlikely - few people "need" SAX. If they think they do, they just
don't know the alternatives. I think iterparse() is what he was looking for.

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


Re: What is Jython?

2007-11-01 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> Hello ..
> 
> I would like to know more about Python and Jython?
> What is the difference between both of them?
> What is the future for Jython and which are the areas where it is
> used?

Bad google day?

http://www.jython.org/

"""
What is Jython?

 Jython, lest you do not know of it, is the most compelling weapon 
the Java platform has for its survival into the 21st century:-)

 —Sean McGrath, CTO, Propylon

Jython is an implementation of the high-level, dynamic, object-oriented 
language Python seamlessly integrated with the Java platform. The 
predecessor to Jython, JPython, is certified as 100% Pure Java. Jython 
is freely available for both commercial and non-commercial use and is 
distributed with source code. Jython is complementary to Java and is 
especially suited for the following tasks:

 * Embedded scripting - Java programmers can add the Jython 
libraries to their system to allow end users to write simple or 
complicated scripts that add functionality to the application.
 * Interactive experimentation - Jython provides an interactive 
interpreter that can be used to interact with Java packages or with 
running Java applications. This allows programmers to experiment and 
debug any Java system using Jython.
 * Rapid application development - Python programs are typically 
2-10X shorter than the equivalent Java program. This translates directly 
to increased programmer productivity. The seamless interaction between 
Python and Java allows developers to freely mix the two languages both 
during development and in shipping products.

There are numerous alternative languages implemented for the Java VM. 
The following features help to separate Jython from the rest:

 * Dynamic compilation to Java bytecodes - leads to highest possible 
performance without sacrificing interactivity.
 * Ability to extend existing Java classes in Jython - allows 
effective use of abstract classes.
 * Optional static compilation - allows creation of applets, 
servlets, beans, ...
 * Bean Properties - make use of Java packages much easier.
 * Python Language - combines remarkable power with very clear 
syntax. It also supports a full object-oriented programming model which 
makes it a natural fit for Java's OO design.
"""


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


Re: XML document causes pickle to go into infinite recursion

2007-11-01 Thread Stefan Behnel
Orest Kozyar wrote:
> I'm working on a CGI script that pulls XML data from a public database
> (Medline) and caches this data using shelveleto minimize load on the
> database.  In general, the script works quite well, but keeps crashing
> every time I try to pickle a particular XML document.  Below is a
> script that illustrates the problem, followed by the stack trace that
> is generated (thanks to Kent Johnson who helped me refine the
> script).  I'd appreciate any advice for solving this particular
> problem.  Someone on Python-Tutor suggested that the XML document has
> a circular reference, but I'm not sure exactly what this means, or why
> the document would have a reference to itself.

minidom creates a pretty complete tree data structure, with loads of backlinks
to parent elements etc. That's where your circular references come from.

I don't know why you want to use pickle here (and not serialised XML or the
plain in-memory tree), but if memory consumption is an issue, try
cElementTree, which comes with Python 2.5 (or as an external module for older
versions). It's faster, more memory friendly and easier to use than minidom.
There's also lxml.objectify, in case you can't live without pickeling.

http://effbot.org/zone/celementtree.htm
http://codespeak.net/lxml

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


attaching someconfusing results in webbrowser.open on gnulinux

2007-11-01 Thread krishnakant Mane
hello all,
I had mentioned previously that I can't open html files in python.
I have my username as krishna and there is a documents folder.
so when I give webbrowser.open("file:///home/krishna/documents/tut.html")
on python prompt I get true as return value but web browser (firefox )
opens with page not found.
and the address bar shows the following address which indeed is wrong.
file:///home/krishna/"file:///home/krishna/documents/tut.html"
I can't understand what is happening.
regards,
Krishnakant.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: XML document causes pickle to go into infinite recursion

2007-11-01 Thread Stefan Behnel
Orest Kozyar wrote:
> I'm working on a CGI script that pulls XML data from a public database

Ah, I missed that bit on first read. Consider using something different than
CGI here if you want to do caching. FCGI would allow you to do in-memory
caching, for example, as would mod_python and a lot of other solutions.

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


Re: permuting over nested dicts?

2007-11-01 Thread Anand
On Oct 31, 10:21 pm, Christian Meesters <[EMAIL PROTECTED]> wrote:
> Hoi,
>
> I have the following data structure (of variable size actually, to make
> things simple, just that one):
> d = {'a': {'x':[1,2,3], 'y':[4,5,6]},
>  'b': {'x':[7,8,9], 'y':[10,11,12]}}
> This can be read as a dict of possibilities: The entities 'a' and 'b' have
> the parameters 'x' and 'y', each. And d['a']['x'] can be either 1 or 2 or
> 3. Does anybody know a convenient (and fast) way to permute over all
> possible nested dicts like
> {'a': {'x':1, 'y':4},
>  'b': {'x':7, 'y':10}}
> and
> {'a': {'x':2, 'y':4},
>  'b': {'x':7, 'y':10}}
> and so forth?
>
> Any link or snippet is appreciated.
>

This code works for dictionaries of any nested level.


def combine(key, value, permutations):
"""Adds key-value pair to every dictionary in the permutations.
If value is a list, then every key-element pair is added to every
permutation.
>>> list(combine('a', 1, [{}]))
[{'a': 1}]
>>> list(combine('a', [1, 2], [{}]))
[{'a': 1}, {'a': 2}]
>>> list(combine('a', 1, [{'b': 1}, {'b': 2}]))
[{'a': 1, 'b': 1}, {'a': 1, 'b': 2}]
>>> list(combine('a', [1, 2], [{'b': 1}, {'b': 2}]))
[{'a': 1, 'b': 1}, {'a': 2, 'b': 1}, {'a': 1, 'b': 2}, {'a':
2, 'b': 2}]
"""
for p in permutations:
if isinstance(value, list):
for v in value:
q = p.copy()
q[key] = v
yield q
else:
p[key] = value
yield p


def permute(d):
"""
>>> list(permute({'x': [1, 2, 3]}))
[{'x': 1}, {'x': 2}, {'x': 3}]
>>> list(permute({'a': [1, 2], 'b': [3, 4]}))
[{'a': 1, 'b': 3}, {'a': 2, 'b': 3}, {'a': 1, 'b': 4}, {'a': 2,
'b': 4}]
>>> list(permute({'a': {'x': [1, 2]}, 'b': [3, 4]}))
[{'a': {'x': 1}, 'b': 3}, {'a': {'x': 2}, 'b': 3}, {'a': {'x': 1},
'b': 4}, {'a': {'x': 2}, 'b': 4}]
"""
if not d:
return [{}]
else:
k, v = d.popitem()
if isinstance(v, dict):
v = list(permute(v))
return combine(k, v, permute(d))



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


Any free python module acts like "Image Processing Toolbox" in matlab?

2007-11-01 Thread oyster
as the title says, and thanx.
for example, that is the help on cpselect(input, base) starts the Control
Point Selection Tool (
www.mathworks.com/access/helpdesk/help/toolbox/images/cpselect.html)
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: setting variables in outer functions

2007-11-01 Thread Hrvoje Niksic
Duncan Booth <[EMAIL PROTECTED]> writes:

> In real life code methods are used to implement callbacks

When I said "closures are used ...", I wasn't trying to be preachy
about how I think callbacks should be implemented, just explaining the
use (and usefulness) of *closures*.  I'm not saying closures are the
only method of implementing stateful callbacks, nor that they're the
best method around in all circumstances.

> What is your point here?

I was simply responding to a subthread that only evaluated closures as
a SICP-style OOP implementation mechanism.  That is missing the point
of closures.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: attaching someconfusing results in webbrowser.open on gnulinux

2007-11-01 Thread D.Hering

krishnakant Mane wrote:
> hello all,
> I had mentioned previously that I can't open html files in python.
> I have my username as krishna and there is a documents folder.
> so when I give webbrowser.open("file:///home/krishna/documents/tut.html")
> on python prompt I get true as return value but web browser (firefox )
> opens with page not found.
> and the address bar shows the following address which indeed is wrong.
> file:///home/krishna/"file:///home/krishna/documents/tut.html"
> I can't understand what is happening.
> regards,
> Krishnakant.

I'm not familiar with the module, but maybe a comparison with this
cookbook example will help:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347810

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


Re: Method needed for skipping lines

2007-11-01 Thread Gustaf
Yu-Xi Lim wrote:

> David Mertz's Text Processing in Python might give you some more 
> efficient (and interesting) ways of approaching the problem.
> 
> http://gnosis.cx/TPiP/

Thank you for the link. Looks like a great resource.

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


Re: setting variables in outer functions

2007-11-01 Thread Duncan Booth
Hrvoje Niksic <[EMAIL PROTECTED]> wrote:

> In real-life code, closures are used to implement callbacks with
> automatic access to their lexical environment without the need for the
> bogus additional "void *" argument one so often sees in C callbacks,
> and without communication through global variables.  If the callbacks
> can access variables in the outer scope, it's only logical (and
> useful) for them to be able to change them.  Prohibiting modification
> reduces the usefulness of closures and causes ugly workarounds such as
> the avar[0] pattern.
> 

In real life code methods are used to implement callbacks with automatic 
access to their environment without the need for any C type hacks.

What is your point here? Python isn't C (or Javascript). If you have a 
function which takes a callback in Python you just pass it a bound method 
and you have all the context you want without resorting to ugly workrounds.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: permuting over nested dicts?

2007-11-01 Thread Anand
On Nov 1, 2:12 pm, Anand <[EMAIL PROTECTED]> wrote:
> On Oct 31, 10:21 pm, Christian Meesters <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hoi,
>
> > I have the following data structure (of variable size actually, to make
> > things simple, just that one):
> > d = {'a': {'x':[1,2,3], 'y':[4,5,6]},
> >  'b': {'x':[7,8,9], 'y':[10,11,12]}}
> > This can be read as a dict of possibilities: The entities 'a' and 'b' have
> > the parameters 'x' and 'y', each. And d['a']['x'] can be either 1 or 2 or
> > 3. Does anybody know a convenient (and fast) way to permute over all
> > possible nested dicts like
> > {'a': {'x':1, 'y':4},
> >  'b': {'x':7, 'y':10}}
> > and
> > {'a': {'x':2, 'y':4},
> >  'b': {'x':7, 'y':10}}
> > and so forth?
>
> > Any link or snippet is appreciated.
>
> This code works for dictionaries of any nested level.
>
> def combine(key, value, permutations):
> """Adds key-value pair to every dictionary in the permutations.
> If value is a list, then every key-element pair is added to every
> permutation.
> >>> list(combine('a', 1, [{}]))
> [{'a': 1}]
> >>> list(combine('a', [1, 2], [{}]))
> [{'a': 1}, {'a': 2}]
> >>> list(combine('a', 1, [{'b': 1}, {'b': 2}]))
> [{'a': 1, 'b': 1}, {'a': 1, 'b': 2}]
> >>> list(combine('a', [1, 2], [{'b': 1}, {'b': 2}]))
> [{'a': 1, 'b': 1}, {'a': 2, 'b': 1}, {'a': 1, 'b': 2}, {'a':
> 2, 'b': 2}]
> """
> for p in permutations:
> if isinstance(value, list):
> for v in value:
> q = p.copy()
> q[key] = v
> yield q
> else:
> p[key] = value
> yield p
>
> def permute(d):
> """
> >>> list(permute({'x': [1, 2, 3]}))
> [{'x': 1}, {'x': 2}, {'x': 3}]
> >>> list(permute({'a': [1, 2], 'b': [3, 4]}))
> [{'a': 1, 'b': 3}, {'a': 2, 'b': 3}, {'a': 1, 'b': 4}, {'a': 2,
> 'b': 4}]
> >>> list(permute({'a': {'x': [1, 2]}, 'b': [3, 4]}))
> [{'a': {'x': 1}, 'b': 3}, {'a': {'x': 2}, 'b': 3}, {'a': {'x': 1},
> 'b': 4}, {'a': {'x': 2}, 'b': 4}]
> """
> if not d:
> return [{}]
> else:
> k, v = d.popitem()
> if isinstance(v, dict):
> v = list(permute(v))
> return combine(k, v, permute(d))

better solution:

def permute(d):
def newdict(d, k, v):
d = d.copy()
d[k] = v
return d

permutations = [{}]
for key, value in d.items():
if isinstance(value, dict):
value = list(permute(value))
elif not isinstance(value, list):
value = [value]
permutations = [newdict(p, key, v) for p in permutations for v
in value]
return permutations

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


Iterable Flattener with Depth.

2007-11-01 Thread Pradeep Jindal
Hi,

5 minute solution to one of my requirements. I wanted to flatten
iterables upto a specific depth.
To be true, didn't search for it on the internet prior to writing this one.


def flatten_iter(my_iter, depth=None):
"""my_iter can be a iterable except string containing nested
iterables upto any depth. This function will flat all
(except string) down to a list containing all the elements in
nested-order.
To add to it you can specify optional depth (int or long)
argument and the
function will flatten the iterable upto that depth (nesting).
"""
if not hasattr(my_iter, '__iter__') or isinstance(my_iter, basestring):
return [my_iter]
elif depth != None and depth <= 0:
return my_iter
temp = []
for x in my_iter:
temp.extend(flatten_iter(x, None if depth == None else depth-1))
return temp

py> temp = [1,[2,[3,4,5],'bash'],6,[7,[8,[9,10,['hi', 'hello', 11, 12]

py> flatten_iter(temp,1)

[1, 2, [3, 4, 5], 'bash', 6, 7, [8, [9, 10, ['hi', 'hello']]], 11, 12]

py> flatten_iter(temp,2)

[1, 2, 3, 4, 5, 'bash', 6, 7, 8, [9, 10, ['hi', 'hello']], 11, 12]

py> flatten_iter(temp)

[1, 2, 3, 4, 5, 'bash', 6, 7, 8, 9, 10, 'hi', 'hello', 11, 12]

py> flatten_iter(temp,3)

[1, 2, 3, 4, 5, 'bash', 6, 7, 8, 9, 10, ['hi', 'hello'], 11, 12]



Any comments?

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


Re: permuting over nested dicts?

2007-11-01 Thread Ant
On Nov 1, 9:12 am, Anand <[EMAIL PROTECTED]> wrote:
...
> This code works for dictionaries of any nested level.

At least up to the max recursion depth.

--
Ant.

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


Re: Method needed for skipping lines

2007-11-01 Thread Gustaf
Bruno Desthuilliers wrote:

> Here's a straightforward solution:



Thank you. I learned several things from that. :-)

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


Re: permuting over nested dicts?

2007-11-01 Thread Christian Meesters
Thanks everyone,

I knew there must be a snippet somewhere, just couldn't find one! (Just for
the sake of completeness: Order doesn't matter and I hope that with my data
I won't reach the recursion depth limit.)

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


Re: Dictionary help

2007-11-01 Thread wes weston
Steve wrote:
> I'm currently working on a little database type program is which I'm 
> using a dictionary to store the information. The key is a component a and 
> the definition is a list of parts that make up the component. My problem 
> is I need to list out several components, but not all, and there 
> associated parts to a printer. Not having any luck. I can list them to 
> the screen but not the printer. Any help/ideas would be appreciated.
> 
> Steve

You can do os.system("") after
putting your stuf in a file.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: setting variables in outer functions

2007-11-01 Thread Dustan
On Oct 31, 5:59 pm, "Chris Mellon" <[EMAIL PROTECTED]> wrote:
> On Oct 31, 2007 5:49 PM, Dustan <[EMAIL PROTECTED]> wrote:
[snip]

I'm not going to respond to any of this, but I'm just going to say:
I'm not claiming that the use of closures is common. I'm just claiming
that it can be useful. I have used closures exactly once. I feel that
that one time, it was for a good cause.

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


Re: What is Jython?

2007-11-01 Thread Ze'ev
On Nov 1, 10:37 am, Ant <[EMAIL PROTECTED]> wrote:
> On Nov 1, 6:54 am, [EMAIL PROTECTED] wrote:
> ...
>
> > I would like to know more about Python and Jython?
> > What is the difference between both of them?
> > What is the future for Jython and which are the areas where it is
> > used?
>
> Jython is an implementation of Python for the Java VM. Currently it
> stands as equivalent to Python v2.2, but progress has been rapidly
> accelerating over the last year or so, and the next version will
> probably be targeted at 2.5 AFAIK.
>
> Jython also has access to all of the Java standard libraries (or any
> Java libraries on the classpath for that matter.)
>
> Jython is currently significantly slower than Python.
>
> >From my experience Jython is most typically used as an embedded
>
> extension/scripting language for Java applications in areas where
> rapid development/change is required. This includes such areas as
> scripting business logic, writing unit or functional tests etc. Take a
> look 
> athttp://antroy.blogspot.com/2007/04/swing-testing-with-jython-and-jemm...
> for an example of how I have successfully used Jython for Swing
> testing. More information can be found 
> onhttp://www.jython.org/Project/index.html
>
> Cheers,
>
> --
> Ant.

On Nov 1, 10:37 am, Ant <[EMAIL PROTECTED]> wrote:
...
> Jython is currently significantly slower than Python.
...
Not according to this : 
http://blogs.warwick.ac.uk/dwatkins/entry/benchmarking_parallel_python_1_2/

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


Which persistence is for me?

2007-11-01 Thread Neal Becker
I need to organize the results of some experiments.  Seems some sort of
database is in order.

I just took a look at DBAPI and the new sqlite interface in python2.5.  I
have no experience with sql.  I am repulsed by e.g.:
c.execute("""insert into stocks
  values ('2006-01-05','BUY','RHAT',100,35.14)""")

ewww.  How unpythonic.  I don't want to use a string to specify what
function to execute.  I want to call a function (c.insert?).

Is there some other interface/database that I might like better?

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


Re: marshal vs pickle

2007-11-01 Thread Aaron Watters
On Nov 1, 12:04 am, Paul Rubin  wrote:
> Raymond Hettinger <[EMAIL PROTECTED]> writes:
> > ''' This is not a general "persistence" module.  For general
> > persistence and transfer of Python objects through RPC calls, see
> > the modules :mod:`pickle` and :mod:`shelve`.
>
> That advice should be removed since Python currently does not have a
> general persistence or transfer module in its stdlib.  There's been an
> open bug/RFE about it for something like 5 years.  The issue is that
> any sensible general purpose RPC mechanism MUST make reasonable
> security assertions that nothing bad happens if you deserialize
> untrusted data.  The pickle module doesn't make such guarantees and in
> fact its documentation explicitly warns against unpickling untrusted
> data.  Therefore pickle should not be used as a general RPC
> mechanism.

This is absolutely correct.  Marshal is more secure than pickle
because marshal *cannot* execute code automatically whereas pickle
does.  The assertion that marshal is less secure than pickle is
absurd.

This is exactly why the gadfly server mode uses marshal and not
pickle.

  -- Aaron Watters

===
why do you hang out with that sadist?
beats me!  -- kliban

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


Re: Which persistence is for me?

2007-11-01 Thread Jean-Paul Calderone
On Thu, 01 Nov 2007 07:47:25 -0400, Neal Becker <[EMAIL PROTECTED]> wrote:
>I need to organize the results of some experiments.  Seems some sort of
>database is in order.
>
>I just took a look at DBAPI and the new sqlite interface in python2.5.  I
>have no experience with sql.  I am repulsed by e.g.:
>c.execute("""insert into stocks
>  values ('2006-01-05','BUY','RHAT',100,35.14)""")
>
>ewww.  How unpythonic.  I don't want to use a string to specify what
>function to execute.  I want to call a function (c.insert?).
>
>Is there some other interface/database that I might like better?
>

There are a lot of choices.  Take a look, for example, at storm:

https://storm.canonical.com/

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


Re: Iterable Flattener with Depth.

2007-11-01 Thread bearophileHUGS
Pradeep Jindal:
> Any comments?

Something with similar functionality (plus another 20 utility
functions/classes or so) has probably to go into the std lib... :-)

Bye,
bearophile

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


Re: Which persistence is for me?

2007-11-01 Thread Amit Khemka
On 11/1/07, Neal Becker <[EMAIL PROTECTED]> wrote:
> I need to organize the results of some experiments.  Seems some sort of
> database is in order.
>
> I just took a look at DBAPI and the new sqlite interface in python2.5.  I
> have no experience with sql.  I am repulsed by e.g.:
> c.execute("""insert into stocks
>   values ('2006-01-05','BUY','RHAT',100,35.14)""")
>
> ewww.  How unpythonic.  I don't want to use a string to specify what
> function to execute.  I want to call a function (c.insert?).
>
> Is there some other interface/database that I might like better?

Why you can always look at some "pure" database solutions. If
persistence is all you require, have a look at "anydbm" and or
"shelve" modules .

Cheers,
-- 
--
Amit Khemka
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: attaching someconfusing results in webbrowser.open on gnulinux

2007-11-01 Thread J. Cliff Dyer
krishnakant Mane wrote:
> hello all,
> I had mentioned previously that I can't open html files in python.
> I have my username as krishna and there is a documents folder.
> so when I give webbrowser.open("file:///home/krishna/documents/tut.html")
> on python prompt I get true as return value but web browser (firefox )
> opens with page not found.
> and the address bar shows the following address which indeed is wrong.
> file:///home/krishna/"file:///home/krishna/documents/tut.html"
> I can't understand what is happening.
> regards,
> Krishnakant.
>   

I haven't used the module, but it looks like webbrowser.open() is
treating your URL as a relative pathname instead.  So it takes the
current working directory (/home/krishna/), and appends the relative
path you gave it (file:///home/krishna/documents/tut.html).  Instead,
try calling:

webbrowser.open("documents/tut.html")

If that works, also try

webbrowser.open("/home/krishna/documents/tut.html")

I suspect both of those will work.  There must be some other syntax for
opening URLs directly. Or maybe it interoperates with urllib.

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


Re: Which persistence is for me?

2007-11-01 Thread Joe Riopel
This might be worth a look: http://www.sqlalchemy.org/docs/04/ormtutorial.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py2exe (or other exe builder) on Vista system for Vista/XP install targets.

2007-11-01 Thread kyosohma
On Oct 31, 7:08 am, Michael <[EMAIL PROTECTED]> wrote:
> I'm trying to build a exe on a vista system using py2exe. It will
> deploy to vista and XP systems. If it matters, the application uses
> pyserial, as well. I have VS Studio 2005 installed on this laptop as
> well. I've found this so far that seems to be identical to what I'm
> seeing (for non-python 
> programs):http://www.thescripts.com/forum/thread611031.html
>
> When I attempt to run, I get "The procedure entry point
> _except_handler4_common could not be located in the dynamic link
> library mscvrt.dll."  Apparently vista has one more
> _except_handler#_common function than XP does.
>
> I've used py2exe several times before (however not recenty, as it was
> before Vista came out). I'm using a very basic setup file right now:
> from distutils.core import setup
> import py2exe
>
> setup(console=['responderbot.py'])
>
> Are there any ways to either py2exe work or any other exe builder for
> my build environment and deployment scenario? I don't really want to
> dig around in py2exe/pyserial internals to force it to use the dll's
> that the MS support person said it should be using. Will any automated
> exe builder work where I am?
>
> I've heard IronPython can compile down to an exeis it a valid
> alternative? Should my CPython utility be compatible with ipy? I only
> use the random,time,sys, and serial modules. I really know very little
> about ipy.
>
>   --Michael

I use GUI2Exe, a wrapper of py2exe that I find easier to use. You can
find it here:

http://xoomer.alice.it/infinity77/main/GUI2Exe.html

There's also this interesting utility (that I've never used) from
Frederik Lundh:

http://effbot.org/zone/exemaker.htm

I've heard good things about PyInstaller (the one Gary mentioned). As
far as I know, py2exe doesn't use Visual Studio to do its compiling,
so I don't think that's relevant.

Mike

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


Re: What is Jython?

2007-11-01 Thread Ant
On Nov 1, 11:37 am, Ze'ev <[EMAIL PROTECTED]> wrote:
...
> ...> Jython is currently significantly slower than Python.
>
> ...
> Not according to this 
> :http://blogs.warwick.ac.uk/dwatkins/entry/benchmarking_parallel_pytho...

Well I'm damned - I thought that I'd be writing about this being a
parallel example, and Java (and hence Jython)'s better threading
support. Decided to run a few of my old "mathchallenge" scripts
through both Python and Jython, and on some of the examples Python was
running almost 4 times slower...

So that's parallel processing and mathematical processing that seems
faster in Jython. It's be interesting to see a proper comparison of
how different types of program run.

The VM startup overhead is much slower mind, but then that's only an
issue for very small programs.

Cheers,

--
Ant.

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


Re: Which persistence is for me?

2007-11-01 Thread Giles Brown
On 1 Nov, 11:47, Neal Becker <[EMAIL PROTECTED]> wrote:
> I need to organize the results of some experiments.  Seems some sort of
> database is in order.
>
> I just took a look at DBAPI and the new sqlite interface in python2.5.  I
> have no experience with sql.  I am repulsed by e.g.:
> c.execute("""insert into stocks
>   values ('2006-01-05','BUY','RHAT',100,35.14)""")
>
> ewww.  How unpythonic.  I don't want to use a string to specify what
> function to execute.  I want to call a function (c.insert?).
>
> Is there some other interface/database that I might like better?

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

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


PyQt with embedded python in Qt App

2007-11-01 Thread cgrebeld
Is it possible for a Qt C++ application, which embeds the python
interpreter, to import and use PyQt?  There can be only one
QApplication, which is created in the C++ side, so how would I use
that from the python side?

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


Re: What is Jython?

2007-11-01 Thread Ant
On Nov 1, 1:23 pm, Ant <[EMAIL PROTECTED]> wrote:
> On Nov 1, 11:37 am, Ze'ev <[EMAIL PROTECTED]> wrote:
> ...
>
> > ...> Jython is currently significantly slower than Python.
>
> > ...
> > Not according to this 
> > :http://blogs.warwick.ac.uk/dwatkins/entry/benchmarking_parallel_pytho...
>...
> So that's parallel processing and mathematical processing that seems
> faster in Jython. It's be interesting to see a proper comparison of
> how different types of program run.

Simple rexex processing of a large log file on the other hand was 10x
faster in Python than Jython, so I guess it depends on what you want
to achieve.

--
Ant

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


source example including the python shell in a wxPython application

2007-11-01 Thread chewie54
Is there an python example that shows how to include a python shell in
a wxPython application.

I have looked the wxPython demo  but I was wondering if there are any
others that might be helpful in seeing how to connect the shell into
the app and allow scripting so that the shell knows all about the app
classes and variables.

thanks,

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


Re: python in academics?

2007-11-01 Thread Cameron Walsh
sandipm wrote:
> seeing posts from students on group. I am curious to know, Do they
> teach python in academic courses in universities?
> 
Sydney University teaches user interface design, some data mining and 
some natural language processing in Python.  Software development is 
still largely a Java or C affair.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which persistence is for me?

2007-11-01 Thread Neal Becker
Neal Becker wrote:

> I need to organize the results of some experiments.  Seems some sort of
> database is in order.
> 
> I just took a look at DBAPI and the new sqlite interface in python2.5.  I
> have no experience with sql.  I am repulsed by e.g.:
> c.execute("""insert into stocks
>   values ('2006-01-05','BUY','RHAT',100,35.14)""")
> 
> ewww.  How unpythonic.  I don't want to use a string to specify what
> function to execute.  I want to call a function (c.insert?).
> 
> Is there some other interface/database that I might like better?
> 

I'm looking at lxml.  I'd like to store hierarchical data, and would prefer
to avoid binary formats.

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


Re: source example including the python shell in a wxPython application

2007-11-01 Thread Chris Mellon
On Nov 1, 2007 8:48 AM, chewie54 <[EMAIL PROTECTED]> wrote:
> Is there an python example that shows how to include a python shell in
> a wxPython application.
>
> I have looked the wxPython demo  but I was wondering if there are any
> others that might be helpful in seeing how to connect the shell into
> the app and allow scripting so that the shell knows all about the app
> classes and variables.
>
> thanks,
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

There's a chapter about it in the wxPIA book, and you can look at the
sources of the wx.py package. When you create a shell, you pass it a
dict that it uses as its global namespace.
-- 
http://mail.python.org/mailman/listinfo/python-list


C extension question

2007-11-01 Thread chris . cenotti
I am currently trying to port some Python and Python C extension code
to C#, and am having trouble understanding what is happening in a
piece of the code.

The pertinent pieces of code are below, and my question follows the
snippets:

in foo.py:
  (mgrid,xgrid,ygrid,zgrid,ngrids) = IP.CreateGridCell()

in IP.c:
  static PyObject *PyCreateGridCell()
  {
GRIDCELL *grid = alloc(...);
for(i=0; ihttp://mail.python.org/mailman/listinfo/python-list


Re: PyQt with embedded python in Qt App

2007-11-01 Thread Phil Thompson
On Thursday 01 November 2007, cgrebeld wrote:
> Is it possible for a Qt C++ application, which embeds the python
> interpreter, to import and use PyQt?  There can be only one
> QApplication, which is created in the C++ side, so how would I use
> that from the python side?

QtGui.QApplication.instance()

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


Re: ANN: O'Reilly e-book, "Getting Started with Pyparsing"

2007-11-01 Thread Paul McGuire
On Nov 1, 1:25 am, Paul McGuire <[EMAIL PROTECTED]> wrote:
> Several chapter excerpts are available online, including this
> chapter on the Zen of Pyparsing:http://preview.tinyurl.com/yp4v48
>
Here is a better link: 
http://my.safaribooksonline.com/9780596514235/what_makes_pyparsing_so_special

-- Paul

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


Re: marshal vs pickle

2007-11-01 Thread Aaron Watters
On Oct 31, 6:10 pm, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
> On Oct 31, 12:27 pm, Aaron Watters <[EMAIL PROTECTED]> wrote:
>
> Makes more sense to use cPickle and be done with it.
>
> FWIW, I've updated the docs to be absolutely clear on the subject:
>
> '''
> This is not a general "persistence" module.  For general persistence
> and...

Alright already.  Here is the patched file you want

http://nucular.sourceforge.net/kisstree_pickle.py

This will make all your nucular indices portable across python
versions and machine architectures.  I'll add this to the
next release with a bunch of other stuff too.

By the way there is another module that uses marshal for
strictly temporary storage in http://nucular.sourceforge.net
-- but if I change that one the build time for nucular indices
fully DOUBLES!!  That's too much pain for me.  Sorry.

Also, it's always been a mystery to me why Python can't
keep the marshal module backwards compatible and portable.
You folks seem like pretty smart programmers to me.  If
you need help, let me know.  It's a damn shame Python doesn't
have a serialization module with the safety, speed, and
simplicity of marshal and also the portability of pickle.
I guess I have to live with it :(.
  -- Aaron Watters

===
Wow, do you play basketball?
No, do you play miniature golf?
   -- seen in Newsweek years ago

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


just a crazy question

2007-11-01 Thread Robert LaMarca
Hi all.. 

Was planning to use Python (maybe C later) to mock parallel processing 
project.. About to put together a set of computers for this.. Wondered if 
anyone had any knowledge or ideas about using a playstation  running linux? 

My first impressions are that it is interesting.. for $400, one can get access 
to 6 smps under linux.. 

For about $300-$600 one could build basic x86 node. probably between 2 and 
4 cores on the x86 node, though the quads are still a bit pricey.

Upside of PS3... lotsa cores for less... Downside.. less, a lot less RAM.. Of 
course, the PS3 does not allow access to the graphics, but for my purposes, I 
don't mind that.. 

So.. how is Python for memory management?  ... 

My plan is to try measuring the memory usage of my python code elements and 
take a guess as to how it might perform on a cell-system.. . naturally a good 
idea in any event.. But.. Just thought maybe someone out in Python world would 
have an idea? 

Thanks!

Best
Robert





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


Re: A Python 3000 Question

2007-11-01 Thread Steven D'Aprano
On Wed, 31 Oct 2007 22:48:12 -0700, Carl Banks wrote:

>> I hope you're not serious that $# would make a good operator.
> 
> If you happen to know where I borrowed it from, it would be pretty
> evident that I wasn't being serious.

Ooh, now I'm curious.


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


Re: setting variables in outer functions

2007-11-01 Thread Neil Cerutti
On 2007-11-01, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> Duncan Booth <[EMAIL PROTECTED]> writes:
>
>> In real life code methods are used to implement callbacks
>
> When I said "closures are used ...", I wasn't trying to be
> preachy about how I think callbacks should be implemented, just
> explaining the use (and usefulness) of *closures*.  I'm not
> saying closures are the only method of implementing stateful
> callbacks, nor that they're the best method around in all
> circumstances.
>
>> What is your point here?
>
> I was simply responding to a subthread that only evaluated
> closures as a SICP-style OOP implementation mechanism.  That is
> missing the point of closures.

It really depends on how wide your definition of primitive object
system is. Can you come up with a use-case for nonlocal that
doesn't appear to be a primitive object system?

-- 
Neil Cerutti
To succeed in the world it is not enough to be stupid, you must also be well-
mannered. --Voltaire
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib.getproxies and PAC

2007-11-01 Thread Duncan Booth
gooli <[EMAIL PROTECTED]> wrote:

> Hi,
> 
> I'm using urllib to get html pages from the web but my computer is
> behind a proxy.
> 
> The proxy is automatically configured in Internet Explorer via a
> proxy.pac file (http://en.wikipedia.org/wiki/Proxy_auto-config).
> 
>>From what I can see in the urllib source it only handles proxies that
> are manually configured in IE and doesn't concern itself with
> automatic configuration.
> 
> Does anybody know of some code that can handle all the proxy
> configuration variants?
> 
Automatic proxy configuration involves retrieving a javascript file from a 
server and calling the javascript for each URL to find out which proxy to 
use. There really isn't any easy way to implement that in Python.

Your best bet may be to drive Internet Explorer through COM automation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: permuting over nested dicts?

2007-11-01 Thread Boris Borcic
Christian Meesters wrote:
> Hoi,
> 
> I have the following data structure (of variable size actually, to make
> things simple, just that one):
> d = {'a': {'x':[1,2,3], 'y':[4,5,6]},
>  'b': {'x':[7,8,9], 'y':[10,11,12]}}
> This can be read as a dict of possibilities: The entities 'a' and 'b' have
> the parameters 'x' and 'y', each. And d['a']['x'] can be either 1 or 2 or
> 3. Does anybody know a convenient (and fast) way to permute over all
> possible nested dicts like
> {'a': {'x':1, 'y':4},
>  'b': {'x':7, 'y':10}}
> and
> {'a': {'x':2, 'y':4},
>  'b': {'x':7, 'y':10}}
> and so forth?
> 
> Any link or snippet is appreciated.
> 
> TIA
> Christian

def cases(d) :
 import re
 bits = re.split('(\[.*?\])',repr(d))
 vv = [('_%s' % k, ' for _%s in %s' % (k,v))
 for k,v in enumerate(bits[1::2])]
 expr = [p+v for p,(v,_) in zip(bits[::2],vv)]+bits[-1:]+[v for _,v in vv]
 return eval('(%s)' % ''.join(expr))

for t in cases({'a': {'x':[1,2,3], 'y':[4,5,6]},
'b': {'x':[7,8,9], 'y':[10,11,12]}}) :
print t


{'a': {'y': 4, 'x': 1}, 'b': {'y': 10, 'x': 7}}
{'a': {'y': 4, 'x': 1}, 'b': {'y': 10, 'x': 8}}
{'a': {'y': 4, 'x': 1}, 'b': {'y': 10, 'x': 9}}
{'a': {'y': 4, 'x': 1}, 'b': {'y': 11, 'x': 7}}
{'a': {'y': 4, 'x': 1}, 'b': {'y': 11, 'x': 8}}
{'a': {'y': 4, 'x': 1}, 'b': {'y': 11, 'x': 9}}
{'a': {'y': 4, 'x': 1}, 'b': {'y': 12, 'x': 7}}
{'a': {'y': 4, 'x': 1}, 'b': {'y': 12, 'x': 8}}
{'a': {'y': 4, 'x': 1}, 'b': {'y': 12, 'x': 9}}
{'a': {'y': 4, 'x': 2}, 'b': {'y': 10, 'x': 7}}


Caveats : (1) assert eval(repr(d))==d
   (2) no square bracket in either keys or values
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python in academics?

2007-11-01 Thread Charles Allen
sandipm:
> seeing posts from students on group. I am curious to know, Do they
> teach python in academic courses in universities?

Bruce Sherwood and Ruth Chabay have an introductory physics text that
uses python for getting students doing computer simulation and
visualization very "early" compared to most course sequences:



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


urllib.getproxies and PAC

2007-11-01 Thread gooli
Hi,

I'm using urllib to get html pages from the web but my computer is
behind a proxy.

The proxy is automatically configured in Internet Explorer via a
proxy.pac file (http://en.wikipedia.org/wiki/Proxy_auto-config).

>From what I can see in the urllib source it only handles proxies that
are manually configured in IE and doesn't concern itself with
automatic configuration.

Does anybody know of some code that can handle all the proxy
configuration variants?

Thanks.

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


to sum a list in a dictonary

2007-11-01 Thread Beema shafreen
hi everybody,
   I need to sum a list in dictionary...
my script,
   d = {}
probes = list(enumerate((i.split('\t')[2],i.split('\t')[3],
i.split('\t')[4])for
i in open('final_lenght_probe_span')))
for idx, (probe_id, span, length) in probes:
 try :
l = [span,length.strip(),probes[idx+1][1][1]]
d[probe_id] = sum[l]

 except IndexError :
none = 0
l = [span,length,None]
d[probe_id] = sum[l]
for key in d.keys():
print key, d[key]


I used an built-in fuction sum to add the list, but is results in error...
now how do i do it

my file used is:
  2709852 2709911   A_16_P21360207  405 -59
  2710316 2710367   A_14_P136880-42 -51
  2710325 2710384   A_16_P21360209  876 -59
  2711260 2711319   A_16_P21360210  -22 -59
  2711297 2711356   A_16_P03641959  254 -59
  2711610 2711659   A_16_P03641960  982 -49
  2712641 2712696   A_16_P03641962  1011-55
  2713707 2713765   A_16_P41563648  43  -58
  2713808 2713861   A_16_P03641963  -16 -53
  2713845 2713893   A_16_P41563649  3460-48
  2717353 2717412   A_16_P03641964  214 -59
  2717626 2717685   A_16_P41563655  25  -59
  2717710 2717754   A_16_P03641965  1250-44
-- 
http://mail.python.org/mailman/listinfo/python-list

serving html from a python script in IE

2007-11-01 Thread bluegray
I'm writing a script that outputs html. It works fine in Firefox,
however, IE wants to download the file instead of displaying the
output. I keep getting the file download dialog instead of the html
page.

I am doing something like this:

print 'Content-Type: text/html ; charset=utf-8\nCache-Control: no-cache
\n'
print 'some text and html'

I also tried various things in .htaccess which has the following line:

AddHandler cgi-script .py

Any help will be appreciated.

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


Re: Need some help...

2007-11-01 Thread Boris Borcic
Ricardo Aráoz wrote:
> Boris Borcic wrote:
>> [EMAIL PROTECTED] wrote:
>>> I want to create a program that I type in a word.
>>>
>>> for example...
>>>
>>> chaos
>>>
>>> each letter equals a number
>>>
>>> A=1
>>> B=20
>>>
>>>  and so on.
>>>
>>> So Chaos would be
>>>
>>> C=13 H=4 A=1 O=7 S=5
>>>
>>> I want to then have those numbers
>>> 13+4+1+7+5 added together to be 30.
>>>
>>> How can I do that?
>>>
>>> Also, just curious, but, how could I then have the 3 and 0 added
>>> together to be 3?
>>>
>>> Please help me out.
>>>
>>> Thank you.
>>>
>>  >>> sum(dict(C=13,H=4,A=1,O=7,S=5)[_] for _ in 'CHAOS')
>> 30
>>  >>> sum(eval(ch) for ch in str(_))
>> 3
> 
> 
 def sumToOneDigit(num) :
>   if num < 10 :
>   return num
>   else :
>   return sumToOneDigit(sum(int(i) for i in str(num)))
> 
>   
 sumToOneDigit(sum(ord(ch) for ch in 'chaos'.upper()))
> 6
> 
> 
> 
> HTH

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


Re: Print a list to a string?

2007-11-01 Thread mrstephengross
> >>> import cStringIO
> >>> s = cStringIO.StringIO()
> >>> print >>s, [1, 2, 1.0/5, 'hello world']
> >>> s.getvalue()

Thanks--this works perfectly!

-_Steve

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


Re: A Python 3000 Question

2007-11-01 Thread J. Cliff Dyer
Steven D'Aprano wrote:
> On Wed, 31 Oct 2007 22:48:12 -0700, Carl Banks wrote:
>
>   
>>> I hope you're not serious that $# would make a good operator.
>>>   
>> If you happen to know where I borrowed it from, it would be pretty
>> evident that I wasn't being serious.
>> 
>
> Ooh, now I'm curious.
>
>
>   
Here's a hint for you:

http://www.google.com/codesearch?q=%22%24%23array%22&hl=en&btnG=Search+Code

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

Re: to sum a list in a dictonary

2007-11-01 Thread Beema shafreen
hi everybody ,i have tried with the improving my  code like this but i face
the problem since i am not able to concatenate the  str, lis.. but if i
donot use none i wont get the respective list i require... is there any
solution to this

dd = {}
dd2 ={}
probes = list(enumerate((i.split('\t')[2],i.split('\t')[3],
i.split('\t')[4])for
i in open('final_lenght_probe_span')))
for idx, (probe_id, span, length) in probes:
 try :
dd[probe_id] = [span,length.strip(),probes[idx+1][1][1]]


 except IndexError :
None = 0( is this a right way)
dd[probe_id] = [span,length,None]
dd2 = dict(zip(dd.keys(), [[sum(item)] for item in dd.values()]))
print dd2

1)the error shown is
when i assign NONE =0
None = 0
SyntaxError: assignment to None
2)when i donot assign NONE
TypeError: unsupported operand type(s) for +: 'int' and 'str'




On 11/1/07, Beema shafreen <[EMAIL PROTECTED]> wrote:
>
> hi everybody,
>I need to sum a list in dictionary...
> my script,
>d = {}
> probes = list(enumerate((i.split('\t')[2],i.split('\t')[3], 
> i.split('\t')[4])for
> i in open('final_lenght_probe_span')))
> for idx, (probe_id, span, length) in probes:
>  try :
> l = [span,length.strip(),probes[idx+1][1][1]]
> d[probe_id] = sum[l]
>
>  except IndexError :
> none = 0
> l = [span,length,None]
> d[probe_id] = sum[l]
> for key in d.keys():
> print key, d[key]
>
>
> I used an built-in fuction sum to add the list, but is results in error...
>
> now how do i do it
>
> my file used is:
>   2709852 2709911   A_16_P21360207  405 -59
>   2710316 2710367   A_14_P136880-42 -51
>   2710325 2710384   A_16_P21360209  876 -59
>   2711260 2711319   A_16_P21360210  -22 -59
>   2711297 2711356   A_16_P03641959  254 -59
>   2711610 2711659   A_16_P03641960  982 -49
>   2712641 2712696   A_16_P03641962  1011-55
>   2713707 2713765   A_16_P41563648  43  -58
>   2713808 2713861   A_16_P03641963  -16 -53
>   2713845 2713893   A_16_P41563649  3460-48
>   2717353 2717412   A_16_P03641964  214 -59
>   2717626 2717685   A_16_P41563655  25  -59
>   2717710 2717754   A_16_P03641965  1250-44
>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list

AOP and pep 246

2007-11-01 Thread Rustom Mody
I am interested in AOP in python.  From here one naturally (or
google-ly) reaches peak.
But peak seems to be discontinued.
Whereas pep-246 on adaptors seems to be rejected in favor of something else.

What??

Can someone please throw some light on whats the current state of the art?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: attaching someconfusing results in webbrowser.open on gnulinux

2007-11-01 Thread Sion Arrowsmith
krishnakant Mane <[EMAIL PROTECTED]> wrote:
> when I give webbrowser.open("file:///home/krishna/documents/tut.html")
>on python prompt I get true as return value but web browser (firefox )
>opens with page not found.
>and the address bar shows the following address which indeed is wrong.
>file:///home/krishna/"file:///home/krishna/documents/tut.html"
>I can't understand what is happening.

Neither can I, since webbrowser.open() (a) works fine for me
with a file: URL of that form using both Firefox and Konqueror
and (b) returns None in response to this success. This is with
2.4.4 -- what version are you running?

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: serving html from a python script in IE

2007-11-01 Thread kyosohma
On Nov 1, 9:52 am, bluegray <[EMAIL PROTECTED]> wrote:
> I'm writing a script that outputs html. It works fine in Firefox,
> however, IE wants to download the file instead of displaying the
> output. I keep getting the file download dialog instead of the html
> page.
>
> I am doing something like this:
>
> print 'Content-Type: text/html ; charset=utf-8\nCache-Control: no-cache
> \n'
> print 'some text and html'
>
> I also tried various things in .htaccess which has the following line:
>
> AddHandler cgi-script .py
>
> Any help will be appreciated.

Do you have the "shebang" listed at the top of your code (i.e. #!/path/
to/python)? Are you importing the cgi module at the top of your code?

>From what I've read, you don't need to modify the htaccess file...

See also:

Tutorials:
http://www.cs.virginia.edu/~lab2q/
http://wiki.python.org/moin/CgiScripts
http://www.upriss.org.uk/python/PythonCourse.html

Docs:
http://www.python.org/doc/essays/ppt/sd99east/index.htm
http://docs.python.org/lib/module-cgi.html

Mike

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


python at command prompt

2007-11-01 Thread c3950ig
Hi,
I am python newbie and the command prompt is having an issue with
python. I installed python 2.4.4 onto my windows machine, opened a
command prompt window, and typed python to start the interactive mode.
Got the following error.

D:\>python
'python' is not recognized as an internal or external command,
operable program or batch file.

The following programs work fine
IDLE (Python GUI)
Python (command line)
PythonWin

For some strange reason, python is not recognized at the command
prompt.
Does anyone have any ideas as to why this is happening?
thanks,

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


How can I have one element list or tuple?

2007-11-01 Thread nico
The following example returns a string type, but I need a tuple...
>>> var = ("Hello")
>>> print type(var)


I need that for a method parameter.
Thx

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


Re: python at command prompt

2007-11-01 Thread Tim Chase
> D:\>python
> 'python' is not recognized as an internal or external command,
> operable program or batch file.
[snip]
> For some strange reason, python is not recognized at the command
> prompt.

Sounds like your path isn't set correctly.  See the first section 
here[1] on "Finding python.exe"

-tkc

[1]http://www.imladris.com/Scripts/PythonForWindows.html



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


Re: How can I have one element list or tuple?

2007-11-01 Thread Neil Cerutti
On 2007-11-01, nico <[EMAIL PROTECTED]> wrote:
> The following example returns a string type, but I need a tuple...
 var = ("Hello")
 print type(var)
>
>
> I need that for a method parameter.

var = "hello",

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


Re: How can I have one element list or tuple?

2007-11-01 Thread Steven D'Aprano
On Thu, 01 Nov 2007 09:21:40 -0700, nico wrote:

> The following example returns a string type, but I need a tuple...
 var = ("Hello")
 print type(var)
> 
> 
> I need that for a method parameter.
> Thx


It is the comma, not the brackets, that create tuples. The brackets are 
recommended for clarity, but aren't always required (except for grouping).

>>> 1, 2, 3
(1, 2, 3)

The only exception is the special case of an empty tuple, which you 
create with an empty pair of brackets:

>>> ()

So for a one-element tuple:

>>> "Parrot",
('Parrot',)



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


Re: AOP and pep 246

2007-11-01 Thread Kay Schluehr
On 1 Nov., 16:18, "Rustom Mody" <[EMAIL PROTECTED]> wrote:
> I am interested in AOP in python.  From here one naturally (or
> google-ly) reaches peak.
> But peak seems to be discontinued.
> Whereas pep-246 on adaptors seems to be rejected in favor of something else.
>
> What??
>
> Can someone please throw some light on whats the current state of the art?

AOP was a research that gone nowhere - at least not in its orginal
AspectJ form: declaring aspect code that targets business code,
weaving the aspect code into the business app using a code generator.
There was much excitement about it around 2001 that faded away since
then. What's left from the glory are certain classes of higher order
functions - you might call them "decorators".

When you want to restore the AOP research program in its full
flexibility for your own purposes without using a code generator you
can keep a higher order decorator and customize functions following
the rationale of this recipe:

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

I do think most people prefer a more direct style of composition that
is better localized. I actually never used this recipe for any
production code.

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


Re: choose from a list

2007-11-01 Thread barronmo
This is really remarkable.  My previous experience with programming
was in VB for Applications; doing the same thing seemed much more
complicated.  This little function is only about 15 lines of code and
it forms the basis for my entire application.  With a few simple
modifications I'll be able to get anything out of the database with a
minimum of entries from the user.

It turns out that 'results' was a tuple of dictionaries.  I got an
error trying to call the tuple; converting it to a list worked.  Here
is the current function:


import MySQLdb

def name_find(namefrag):

 conn = MySQLdb.connect(host = "localhost",
  user = "root",
  passwd = "Barron85",
  db = "meds")
 cursor = conn.cursor(MySQLdb.cursors.DictCursor)
 cursor.execute("SELECT patient_ID, firstname, lastname FROM
demographics WHERE lastname LIKE '%s%%'" % (namefrag))

 results = cursor.fetchall()
 for index, row in enumerate(results):
  print "%d %s   %s %s" % (index, row["patient_ID"],
row["firstname"], row["lastname"])
 indx = int(raw_input("Select the record you want: "))
 results_list = list(results)
 return results_list[indx]['patient_ID']

 cursor.close()
 conn.close()

This returns the patient_ID after selecting a name from the list, eg
615L.  I'm not sure why the "L" is there but it shouldn't be hard to
remove.  Mensanator, thanks a lot for your help.  This has been quite
a lot to digest--huge leap in my understanding of Python.

Michael Barron




On Oct 31, 12:32 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> On Oct 30, 7:39?pm, barronmo <[EMAIL PROTECTED]> wrote:
>
> > I didn't know "result" was alist!
>
> I don't use MySQL but that's how others work.
> Eachlistitem is a record, each record a tuple
> of field values.
>
> > Can all that info be stored in alist?
>
> If you don't fetch too many records at once.
> This is a test of my word database using ODBC
> and MS-ACCESS (the SQL is very simple since
> all the actual work is done in MS-ACCESS, Python
> is just retrieving the final results).
>
> import dbi
> import odbc
> con = odbc.odbc("words")
> cursor = con.cursor()
> cursor.execute("SELECT * FROM signature_anagram_summary")
> results = cursor.fetchall()
>
> Here, results (the recipient of .fetchall) is alistof tuples.
> The contents are:
>
> [(9, 10, 'anoretics', '101010001110011100'),
> (9, 10, 'atroscine', '101010001110011100'),
> (9, 10, 'certosina', '101010001110011100'),
> (9, 10, 'creations', '101010001110011100'),
> (9, 10, 'narcotise', '101010001110011100'),
> (9, 10, 'ostracine', '101010001110011100'),
> (9, 10, 'reactions', '101010001110011100'),
> (9, 10, 'secration', '101010001110011100'),
> (9, 10, 'tinoceras', '101010001110011100'),
> (9, 10, 'tricosane', '101010001110011100')]
>
> > How do the columns work?
>
> I don't know, I don't get column names. It looked like
> from your example that you can use names, I would have
> to use indexes, such as results[3][2] to get 'creations'.
> Maybe MySQL returns dictionaries instead of tuples.
>
> > I was curious to see what the data
> > looked like but I can't seem to print "result" from the prompt.  Do
> > variables used inside functions live or die once the function
> > executes?
>
> Yeah, they die. You would have to have the function return
> the resultslistand indx, then you could use it's contents
> as criteria for further queries.
>
> So you might want to say
>
> name_find_results,indx = name_find(namefrag)
>
> > If they die, how do I get around this?
>
> Add 'return results,indx' to the function. Or better still,
> just return the record the user selected
> return results[indx]
> You wouldn't need indx anymore since there's only 1 record.
>
> > I tried defining 'r
> > = ""' in the module before the function and then using it instead of
> > "result" but that didn't help.
>
> > Mike


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


Re: serving html from a python script in IE

2007-11-01 Thread bluegray
Yes, I have all the necessary shebang and imports. As I said, the
script works fine in Firefox. It's something specific to IE that is
the problem. The following is a test script that also causes IE to
download instead of displaying the page. It works fine elsewhere. I
also did some searching, and python scripts on other servers seem to
work in IE. So it's maybe something specific to my server. I have no
idea what though.

#!/usr/bin/python

print "Content-Type: application/xhtml+xml;charset=utf-8\nCache-
Control: no-cache\n"

print '''
http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";>
http://www.w3.org/1999/xhtml"; xml:lang="en" lang="en">


An XHTML 1.0 Strict standard template






  Your HTML content here 


'''

[EMAIL PROTECTED] wrote:
> On Nov 1, 9:52 am, bluegray <[EMAIL PROTECTED]> wrote:
> > I'm writing a script that outputs html. It works fine in Firefox,
> > however, IE wants to download the file instead of displaying the
> > output. I keep getting the file download dialog instead of the html
> > page.
> >
> > I am doing something like this:
> >
> > print 'Content-Type: text/html ; charset=utf-8\nCache-Control: no-cache
> > \n'
> > print 'some text and html'
> >
> > I also tried various things in .htaccess which has the following line:
> >
> > AddHandler cgi-script .py
> >
> > Any help will be appreciated.
>
> Do you have the "shebang" listed at the top of your code (i.e. #!/path/
> to/python)? Are you importing the cgi module at the top of your code?
>
> >From what I've read, you don't need to modify the htaccess file...
>
> See also:
>
> Tutorials:
> http://www.cs.virginia.edu/~lab2q/
> http://wiki.python.org/moin/CgiScripts
> http://www.upriss.org.uk/python/PythonCourse.html
>
> Docs:
> http://www.python.org/doc/essays/ppt/sd99east/index.htm
> http://docs.python.org/lib/module-cgi.html
>
> Mike

Yes, I have all the necessary shebang and imports. As I said, the
script works fine in Firefox. It's something specific to IE that is
the problem. The following is a test script that also causes IE to
download instead of displaying the page. It works fine elsewhere. I
also did some searching, and python scripts on other servers seem to
work in IE. So it's maybe something specific to my server. I have no
idea what though.

#!/usr/bin/python

print "Content-Type: application/xhtml+xml;charset=utf-8\nCache-
Control: no-cache\n"

print '''
http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";>
http://www.w3.org/1999/xhtml"; xml:lang="en" lang="en">


An XHTML 1.0 Strict standard template






  Your HTML content here 


'''

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


Re: python at command prompt

2007-11-01 Thread c3950ig
[snip]
> Sounds like your path isn't set correctly.  See the first section
> here[1] on "Finding python.exe"
>
> -tkc
>
> [1]http://www.imladris.com/Scripts/PythonForWindows.html

Thanks Tim,
I set the pythonpath to where the python interpreter is located C:
\Python24
However I still get the same error message. Is there something else
that must be configured?
thanks.

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


Re: choose from a list

2007-11-01 Thread [EMAIL PROTECTED]
On Nov 1, 11:54 am, barronmo <[EMAIL PROTECTED]> wrote:
> This is really remarkable.  My previous experience with programming
> was in VB for Applications; doing the same thing seemed much more
> complicated.  This little function is only about 15 lines of code and
> it forms the basis for my entire application.  With a few simple
> modifications I'll be able to get anything out of the database with a
> minimum of entries from the user.
>
> It turns out that 'results' was a tuple of dictionaries.  I got an
> error trying to call the tuple; converting it to a list worked.  Here
> is the current function:
>
> import MySQLdb
>
> def name_find(namefrag):
>
>  conn = MySQLdb.connect(host = "localhost",
>   user = "root",
>   passwd = "Barron85",
>   db = "meds")
>  cursor = conn.cursor(MySQLdb.cursors.DictCursor)
>  cursor.execute("SELECT patient_ID, firstname, lastname FROM
> demographics WHERE lastname LIKE '%s%%'" % (namefrag))
>
>  results = cursor.fetchall()
>  for index, row in enumerate(results):
>   print "%d %s   %s %s" % (index, row["patient_ID"],
> row["firstname"], row["lastname"])
>  indx = int(raw_input("Select the record you want: "))
>  results_list = list(results)
>  return results_list[indx]['patient_ID']
>
>  cursor.close()
>  conn.close()
>
> This returns the patient_ID after selecting a name from the list, eg
> 615L.  I'm not sure why the "L" is there but it shouldn't be hard to
> remove.  

It's a long integer. You don't have to worry about it:

>>> a = long(615)
>>> a
615L
>>> print a
615

Notice the L is gone when you go to use it:

>>> print 'SELECT * FROM test WHERE pid=%s' % a
SELECT * FROM test WHERE pid=615


> Mensanator, thanks a lot for your help.  This has been quite
> a lot to digest--huge leap in my understanding of Python.
>
> Michael Barron
>
> On Oct 31, 12:32 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Oct 30, 7:39?pm, barronmo <[EMAIL PROTECTED]> wrote:
>
> > > I didn't know "result" was alist!
>
> > I don't use MySQL but that's how others work.
> > Eachlistitem is a record, each record a tuple
> > of field values.
>
> > > Can all that info be stored in alist?
>
> > If you don't fetch too many records at once.
> > This is a test of my word database using ODBC
> > and MS-ACCESS (the SQL is very simple since
> > all the actual work is done in MS-ACCESS, Python
> > is just retrieving the final results).
>
> > import dbi
> > import odbc
> > con = odbc.odbc("words")
> > cursor = con.cursor()
> > cursor.execute("SELECT * FROM signature_anagram_summary")
> > results = cursor.fetchall()
>
> > Here, results (the recipient of .fetchall) is alistof tuples.
> > The contents are:
>
> > [(9, 10, 'anoretics', '101010001110011100'),
> > (9, 10, 'atroscine', '101010001110011100'),
> > (9, 10, 'certosina', '101010001110011100'),
> > (9, 10, 'creations', '101010001110011100'),
> > (9, 10, 'narcotise', '101010001110011100'),
> > (9, 10, 'ostracine', '101010001110011100'),
> > (9, 10, 'reactions', '101010001110011100'),
> > (9, 10, 'secration', '101010001110011100'),
> > (9, 10, 'tinoceras', '101010001110011100'),
> > (9, 10, 'tricosane', '101010001110011100')]
>
> > > How do the columns work?
>
> > I don't know, I don't get column names. It looked like
> > from your example that you can use names, I would have
> > to use indexes, such as results[3][2] to get 'creations'.
> > Maybe MySQL returns dictionaries instead of tuples.
>
> > > I was curious to see what the data
> > > looked like but I can't seem to print "result" from the prompt.  Do
> > > variables used inside functions live or die once the function
> > > executes?
>
> > Yeah, they die. You would have to have the function return
> > the resultslistand indx, then you could use it's contents
> > as criteria for further queries.
>
> > So you might want to say
>
> > name_find_results,indx = name_find(namefrag)
>
> > > If they die, how do I get around this?
>
> > Add 'return results,indx' to the function. Or better still,
> > just return the record the user selected
> > return results[indx]
> > You wouldn't need indx anymore since there's only 1 record.
>
> > > I tried defining 'r
> > > = ""' in the module before the function and then using it instead of
> > > "result" but that didn't help.
>
> > > Mike- Hide quoted text -
>
> - Show quoted text -


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


Re: AOP and pep 246

2007-11-01 Thread Michele Simionato
On Nov 1, 4:18 pm, "Rustom Mody" <[EMAIL PROTECTED]> wrote:
> I am interested in AOP in python.  From here one naturally (or
> google-ly) reaches peak.
> But peak seems to be discontinued.
> Whereas pep-246 on adaptors seems to be rejected in favor of something else.
>
> What??
>
> Can someone please throw some light on whats the current state of the art?

See http://www.python.org/dev/peps/pep-3119


 Michele Simionato

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


Re: serving html from a python script in IE

2007-11-01 Thread Richard Brodie

"bluegray" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> print "Content-Type: application/xhtml+xml

That's your problem. You can't use that Mime type
because IE doesn't support XHMTL. No "appendix C"
hair splitting comments, please. 


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


Re: serving html from a python script in IE

2007-11-01 Thread J. Cliff Dyer
bluegray wrote:
> I'm writing a script that outputs html. It works fine in Firefox,
> however, IE wants to download the file instead of displaying the
> output. I keep getting the file download dialog instead of the html
> page.
>
> I am doing something like this:
>
> print 'Content-Type: text/html ; charset=utf-8\nCache-Control: no-cache
> \n'
> print 'some text and html'
>
> I also tried various things in .htaccess which has the following line:
>
> AddHandler cgi-script .py
>
> Any help will be appreciated.
>
>   
If you take out the space between text/html and ; it works just fine.

(In other words, there is no mime-type "text/html ")

Cheers,
Cliff

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


Re: serving html from a python script in IE

2007-11-01 Thread bluegray
> If you take out the space between text/html and ; it works just fine.
>
> (In other words, there is no mime-type "text/html ")

Thanks! That did it. What a difference a space makes ;)

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


Syntax coloring in Python interpreter

2007-11-01 Thread braver
Greetings -- as a long time user of both Python and Ruby interpreters,
I got used to the latter's syntax-coloring gem, wirble, which
colorizes Ruby syntax on the fly.  Is there anything similar for
Python?

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


Re: C extension question

2007-11-01 Thread Matimus
On Nov 1, 7:07 am, [EMAIL PROTECTED] wrote:
> I am currently trying to port some Python and Python C extension code
> to C#, and am having trouble understanding what is happening in a
> piece of the code.
>
> The pertinent pieces of code are below, and my question follows the
> snippets:
>
> in foo.py:
>   (mgrid,xgrid,ygrid,zgrid,ngrids) = IP.CreateGridCell()
>
> in IP.c:
>   static PyObject *PyCreateGridCell()
>   {
> GRIDCELL *grid = alloc(...);
> for(i=0; i {
>   grid[cnt] =  //etc fill in grid array
>   cnt++;
> }
>
> PyObject *GRIDRET = PyCObject_FromVoidPtr((void *)grid,NULL);
> return Py_BuildValue("Oi",GRIDRET,cnt-1);
>
>   typedef struct {
> XYZ p[8];
> double val[8];
>   } GRIDCELL;
>
>   typedef struct {
> double x,y,z;
>   } XYZ;
>
> So my question is (and I hope it's not too silly a question), what is
> happening to the grid array pointer in the C code that it maps to
> multiple variables (which all are arrays) on the python side.  Is the
> grid variable being assigned to mgrid, xgrid, ygrid and zgrid whole,
> or is it being split somehow (and if so, how)?  Thanks for the help.

PyCreateGridCell uses [1]Py_BuildValue to generate a tuple containing
a Object (its not really clear to me exactly what this object is) and
an integer. From the looks of it I would say that PyCreateGridCell
does not return something that can be unpacked into 5 things like the
python code suggests. Hoever, there is no guarantee that
PyCreateGridCell is the function that gets called by Python when
IP.CreateGridCell is called. You have to look at the method table to
see what it maps to. I would read the introduction [2] at least to the
Extending and Embedding documentation.

Why do you need to do this anyway. If you _need_ to use .NET you could
save time by using IronPython instead of rewriting the whole thing in
C#.

[1] http://docs.python.org/api/arg-parsing.html#l2h-216
[2] http://docs.python.org/ext/intro.html

Matt

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


Re: Syntax coloring in Python interpreter

2007-11-01 Thread Lee Capps

On Nov 1, 2007, at 1:45 PM, braver wrote:

> Greetings -- as a long time user of both Python and Ruby interpreters,
> I got used to the latter's syntax-coloring gem, wirble, which
> colorizes Ruby syntax on the fly.  Is there anything similar for
> Python?
>

I believe IPython can do this:

http://ipython.scipy.org/moin/

---
Lee Capps
Technology Specialist
CTE Resource Center
[EMAIL PROTECTED]



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


Re: python at command prompt

2007-11-01 Thread Mark Elston
* [EMAIL PROTECTED] wrote (on 11/1/2007 9:58 AM):
> [snip]
>> Sounds like your path isn't set correctly.  See the first section
>> here[1] on "Finding python.exe"
>>
>> -tkc
>>
>> [1]http://www.imladris.com/Scripts/PythonForWindows.html
> 
> Thanks Tim,
> I set the pythonpath to where the python interpreter is located C:
> \Python24
> However I still get the same error message. Is there something else
> that must be configured?
> thanks.
> 

It's not the PYTHONPATH environment variable that you need to set.

You need to set the PATH environment variable to include C:\Python24.
That is where the Python executable is locate.

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


Re: python at command prompt

2007-11-01 Thread Tim Chase
>> [1]http://www.imladris.com/Scripts/PythonForWindows.html
> 
> I set the pythonpath to where the python interpreter is located C:
> \Python24
> However I still get the same error message. Is there something else
> that must be configured?

Make sure you're setting your PATH, not your PYTHONPATH variable.

 From your command-prompt, issue

   c:\test\> path

to see what your current path is.  You _should_ see your 
python2.x\bin folder in there.  If not, are you re-using the same 
command-prompt window?  I vaguely remember that it requires you 
to close the cmd window and open a new one to pick up the new 
environment-variable changes.

Alternatively, if you don't want to lose history in that 
particular window, you can update your path for that particular 
window using

   c:\test\> set path=%PATH%;c:\progra~1\python2.4\bin

or whatever your path is.

-tkc





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


Re: marshal vs pickle

2007-11-01 Thread Raymond Hettinger
On Nov 1, 4:45 am, Aaron Watters <[EMAIL PROTECTED]> wrote:
> Marshal is more secure than pickle

"More" or "less" make little sense in a security context which
typically is an all or nothing affair.  Neither module is designed for
security.  From the docs for marshal:

'''
Warning: The marshal module is not intended to be secure against
erroneous or maliciously constructed data. Never unmarshal data
received from an untrusted or unauthenticated source.
'''

If security is a focus, then use xmlrpc or some other tool that
doesn't construct arbitrary code objects.

I don't think you are doing the OP any favors by giving advice in
contravention of the docs and against the intended purpose of the two
modules.  Bjoern's post covered the topic succinctly and accurately.


Raymond

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


setting and getting column in numpymatrix

2007-11-01 Thread [EMAIL PROTECTED]
hi
i am looking for an efficient way to get a specific column of a
numpy.matrix ..
also i want to set  a column  of the matrix with a given set of
values ..i couldn't find any methods for this in matrix doc..do i have
to write   the functions from scratch?

TIA
dn

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


Re: Dictionary help

2007-11-01 Thread Steve
On Thu, 01 Nov 2007 04:16:10 -0700, wes weston wrote:

> Steve wrote:
>> I'm currently working on a little database type program is which I'm
>> using a dictionary to store the information. The key is a component a
>> and the definition is a list of parts that make up the component. My
>> problem is I need to list out several components, but not all, and
>> there associated parts to a printer. Not having any luck. I can list
>> them to the screen but not the printer. Any help/ideas would be
>> appreciated.
>> 
>> Steve
> 
> You can do os.system("") after
> putting your stuf in a file.

Thank you for the reply. I finally got it printing in Linux.

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


Re: python at command prompt

2007-11-01 Thread kyosohma
On Nov 1, 1:23 pm, Tim Chase <[EMAIL PROTECTED]> wrote:
> >> [1]http://www.imladris.com/Scripts/PythonForWindows.html
>
> > I set the pythonpath to where the python interpreter is located C:
> > \Python24
> > However I still get the same error message. Is there something else
> > that must be configured?
>
> Make sure you're setting your PATH, not your PYTHONPATH variable.
>
>  From your command-prompt, issue
>
>c:\test\> path
>
> to see what your current path is.  You _should_ see your
> python2.x\bin folder in there.  If not, are you re-using the same
> command-prompt window?  I vaguely remember that it requires you
> to close the cmd window and open a new one to pick up the new
> environment-variable changes.
>
> Alternatively, if you don't want to lose history in that
> particular window, you can update your path for that particular
> window using
>
>c:\test\> set path=%PATH%;c:\progra~1\python2.4\bin
>
> or whatever your path is.
>
> -tkc

And if you don't want to do it via the command line, you can right-
click My Computer, choose Properties, click the Advanced Tab and then
hit the Environmental Variables (or just press the Windows Key and
Pause/Break). Anyway, you'll see 2 boxes. Choose the lower one labeled
"System Variables", double-click the Variable labeled "path" and then
just add the path to your Python folder (make sure to separate it from
the one before it with a semi-colon.

For me, it would be something like C:\Python24

Mike

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


Strange problem when using re module with threads

2007-11-01 Thread Wei Lee Woon
Dear all

I've been getting a rather strange problem with the following multithreaded
code (reduced to the minimum which still results in the problem):

import threading
import re

class hey(threading.Thread):
def run(self):
print re.compile("\d+").search("hey95you").group();

thlist=[]
for tech in range(2):
thlist.append(hey())
thlist[-1].start()

for th in thlist:
th.join()

After saving this to a file (say "test.py"), if I try to run this from the
console using "python test.py", it seems to work fine, but when i try to run
it from the python interactive shell using "import test", it freezes up (if
i don't issue the join() it is fine, though). Any ideas why this is so?

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

Re: Syntax coloring in Python interpreter

2007-11-01 Thread Neil Cerutti
On 2007-11-01, Lee Capps <[EMAIL PROTECTED]> wrote:
>
> On Nov 1, 2007, at 1:45 PM, braver wrote:
>> Greetings -- as a long time user of both Python and Ruby
>> interpreters, I got used to the latter's syntax-coloring gem,
>> wirble, which colorizes Ruby syntax on the fly.  Is there
>> anything similar for Python?
>>
>
> I believe IPython can do this:
>
> http://ipython.scipy.org/moin/

IPython's syntax coloring doesn't work with Windows 2000 and up,
since (last I checked) it relies on a readline.py file, which
relies on ANSI.SYS, which is not supported by the Windows
console.

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


shelve.open() and error 22: invalid argument

2007-11-01 Thread max . aginaga
Hi everyone

I've come across the following problem: on two different linux
machines, both running python 2.5 (r25:51908), I have the same file
'd.dat'. The md5 checksums are the same.

Now, on one machine the following code works

>>> import shelve
>>> d=shelve.open('d.dat')
>>>

while on the other...

Traceback (most recent call last):
  File "", line 1, in 
  File "local/lib/python2.5/shelve.py", line 225, in open
return DbfilenameShelf(filename, flag, protocol, writeback)
  File "local/lib/python2.5/shelve.py", line 209, in __init__
Shelf.__init__(self, anydbm.open(filename, flag), protocol,
writeback)
  File "local/lib/python2.5/anydbm.py", line 83, in open
return mod.open(file, flag, mode)
  File "local/lib/python2.5/dbhash.py", line 16, in open
return bsddb.hashopen(file, flag, mode)
  File "local/lib/python2.5/bsddb/__init__.py", line 299, in hashopen
e = _openDBEnv(cachesize)
  File "local/lib/python2.5/bsddb/__init__.py", line 355, in
_openDBEnv
e.set_lk_detect(db.DB_LOCK_DEFAULT)
bsddb.db.DBInvalidArgError: (22, 'Invalid argument')

What is happening? I am running the same Python interpreter on the
same file! Why different results? (To make things weirder, this
actually fails on the machine in which I created the d.dat file using
the shelve module!)

Please advise, knowledgeable pythoners! The archives are full of
references to this 22 invalid argument error msg, but precious few
anwers.

Cheers!

Max

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


Re: Syntax coloring in Python interpreter

2007-11-01 Thread Chris Mellon
On Nov 1, 2007 3:01 PM, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> On 2007-11-01, Lee Capps <[EMAIL PROTECTED]> wrote:
> >
> > On Nov 1, 2007, at 1:45 PM, braver wrote:
> >> Greetings -- as a long time user of both Python and Ruby
> >> interpreters, I got used to the latter's syntax-coloring gem,
> >> wirble, which colorizes Ruby syntax on the fly.  Is there
> >> anything similar for Python?
> >>
> >
> > I believe IPython can do this:
> >
> > http://ipython.scipy.org/moin/
>
> IPython's syntax coloring doesn't work with Windows 2000 and up,
> since (last I checked) it relies on a readline.py file, which
> relies on ANSI.SYS, which is not supported by the Windows
> console.
>

If you scroll down about half a page in the above link you'll find a
link to a readline implementation for Windows.

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


Is it possible to use a instance property as a default value ?

2007-11-01 Thread stef mientki
hello,

I would like to use instance parameters as a default value, like this:

class PlotCanvas(wx.Window):
def __init__(self)
self.Buf_rp = 0
self.Buf_wp = 0

def Draw ( self, x1 = self.Buf_rp, x2 = self.Buf_wp ) :

is something like this possible ?

thanks,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to use a instance property as a default value ?

2007-11-01 Thread Chris Mellon
On Nov 1, 2007 3:18 PM, stef mientki <[EMAIL PROTECTED]> wrote:
> hello,
>
> I would like to use instance parameters as a default value, like this:
>
> class PlotCanvas(wx.Window):
> def __init__(self)
> self.Buf_rp = 0
> self.Buf_wp = 0
>
> def Draw ( self, x1 = self.Buf_rp, x2 = self.Buf_wp ) :
>
> is something like this possible ?
>

No, because self is not in scope at the time that default arguments
are evaluated. The traditional workaround is to use x1=None, and if x1
is None: x1 = self.Buf_rp.

You can write a decorator to make this a little less boilerplateish.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: marshal vs pickle

2007-11-01 Thread Aaron Watters
On Nov 1, 2:15 pm, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
> On Nov 1, 4:45 am, Aaron Watters <[EMAIL PROTECTED]> wrote:
>
> > Marshal is more secure than pickle
>
> "More" or "less" make little sense in a security context which
> typically is an all or nothing affair.  Neither module is designed for
> security.  From the docs for marshal:
>
> '''
> Warning: The marshal module is not intended to be secure against
> erroneous or maliciously constructed data. Never unmarshal data
> received from an untrusted or unauthenticated source.
> '''
>
> If security is a focus, then use xmlrpc or some other tool that
> doesn't construct arbitrary code objects.

I disagree.  Xmlrpc is insecure if you compile
and execute  one of the strings
you get from it.  Marshal is similarly insecure if you evaluate a code
object it hands you.  If you aren't that dumb, then neither one
is a problem.  As far as I'm concerned marshal.load is not any
more insecure than file.read.

Pickle on the other hand can execute just about anything without
you knowing anything about it.  It is a horrendous mistake
to suggest that anyone should implement RPC using pickle.  If they
want it to be fast they can use marshal, except for that thing
about non-portability which was a design mistake, imho.

By the way: here is a test program which shows pickle running
4 times slower than marshal on my machine using python 2.5.1:

"""
import marshal
import cPickle
import time

def pdump(value, f):
#cPickle.dump(value, f, 2)
return cPickle.dumps(value, 2)

def mdump(value, f):
#marshal.dump(value, f)
return marshal.dumps(value)

def test(dump, fn):
now = time.time()
#f = open(fn, "wb")
f = None
for i in range(3):
D = {}
for j in range(20):
k = (i*133+j*119)%151
D[ (str(k),str(j)) ] = (str(i), [k, str(k)])
dump(D.items(), f)
#f.close()
elapsed = time.time()-now
print dump, elapsed

if __name__=="__main__":
test(mdump, "mdump.dat")
test(pdump, "ptemp.dat")
"""

  -- Aaron Watters
===
If you think you are smart enough to write multi-threaded programs
you're not.   -- Jim Ahlstrom's corollary to Murphy's Law.

http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=ahlstrom

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


Re: shelve.open() and error 22: invalid argument

2007-11-01 Thread Jonathan Gardner
On Nov 1, 1:08 pm, [EMAIL PROTECTED] wrote:
> Hi everyone
>
> I've come across the following problem: on two different linux
> machines, both running python 2.5 (r25:51908), I have the same file
> 'd.dat'. The md5 checksums are the same.
>
> Now, on one machine the following code works
>
> >>> import shelve
> >>> d=shelve.open('d.dat')
>
> while on the other...
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "local/lib/python2.5/shelve.py", line 225, in open
> return DbfilenameShelf(filename, flag, protocol, writeback)
>   File "local/lib/python2.5/shelve.py", line 209, in __init__
> Shelf.__init__(self, anydbm.open(filename, flag), protocol,
> writeback)
>   File "local/lib/python2.5/anydbm.py", line 83, in open
> return mod.open(file, flag, mode)
>   File "local/lib/python2.5/dbhash.py", line 16, in open
> return bsddb.hashopen(file, flag, mode)
>   File "local/lib/python2.5/bsddb/__init__.py", line 299, in hashopen
> e = _openDBEnv(cachesize)
>   File "local/lib/python2.5/bsddb/__init__.py", line 355, in
> _openDBEnv
> e.set_lk_detect(db.DB_LOCK_DEFAULT)
> bsddb.db.DBInvalidArgError: (22, 'Invalid argument')
>
> What is happening? I am running the same Python interpreter on the
> same file! Why different results? (To make things weirder, this
> actually fails on the machine in which I created the d.dat file using
> the shelve module!)
>

This comes up outside of Python as well. Look into your BDB setup. I
bet you that the two machines have different versions of BDB
libraries.

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


Re: just a crazy question

2007-11-01 Thread Jonathan Gardner
On Nov 1, 7:16 am, Robert LaMarca <[EMAIL PROTECTED]> wrote:
> So.. how is Python for memory management?  ...
>

Terrible. If you have a memory-intensive application, use ASM (perhaps
C), not Python (or any other high-level language for that matter.)

> My plan is to try measuring the memory usage of my python code elements and 
> take a guess as to how it might perform on a cell-system.. . naturally a good 
> idea in any event.. But.. Just thought maybe someone out in Python world 
> would have an idea?
>

This probably won't work at all as expected. If you wanted to get
Python processes to run on the cells, you'd probably need a special
interpreter written with that in mind. My memory of how the cell
technology works is that there is really a tiny amount of memory in
each cell and you need to think at a fundamentally low level to get
anything useful done.

I'm extremely interested in what you discover, and I'm sure others are
well. I'd love to be proven wrong in my assumptions. So keep us posted
when you find something interesting or useful.

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


Re: Is it possible to use a instance property as a default value ?

2007-11-01 Thread stef mientki
Chris Mellon wrote:
> On Nov 1, 2007 3:18 PM, stef mientki <[EMAIL PROTECTED]> wrote:
>   
>> hello,
>>
>> I would like to use instance parameters as a default value, like this:
>>
>> class PlotCanvas(wx.Window):
>> def __init__(self)
>> self.Buf_rp = 0
>> self.Buf_wp = 0
>>
>> def Draw ( self, x1 = self.Buf_rp, x2 = self.Buf_wp ) :
>>
>> is something like this possible ?
>>
>> 
>
> No, because self is not in scope at the time that default arguments
> are evaluated. The traditional workaround is to use x1=None, and if x1
> is None: x1 = self.Buf_rp.
>
>   
thanks Chris,
I was afraid of that ;-)

cheers,
Stef

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


Re: marshal vs pickle

2007-11-01 Thread Jean-Paul Calderone
On Thu, 01 Nov 2007 20:35:15 -, Aaron Watters <[EMAIL PROTECTED]> wrote:
>On Nov 1, 2:15 pm, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
>> On Nov 1, 4:45 am, Aaron Watters <[EMAIL PROTECTED]> wrote:
>>
>> > Marshal is more secure than pickle
>>
>> "More" or "less" make little sense in a security context which
>> typically is an all or nothing affair.  Neither module is designed for
>> security.  From the docs for marshal:
>>
>> '''
>> Warning: The marshal module is not intended to be secure against
>> erroneous or maliciously constructed data. Never unmarshal data
>> received from an untrusted or unauthenticated source.
>> '''
>>
>> If security is a focus, then use xmlrpc or some other tool that
>> doesn't construct arbitrary code objects.
>
>I disagree.  Xmlrpc is insecure if you compile
>and execute  one of the strings
>you get from it.  Marshal is similarly insecure if you evaluate a code
>object it hands you.  If you aren't that dumb, then neither one
>is a problem.  As far as I'm concerned marshal.load is not any
>more insecure than file.read.

You're mistaken.

  $ python
  Python 2.4.3 (#2, Oct  6 2006, 07:52:30)
  [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
  Type "help", "copyright", "credits" or "license" for more information.
  >>> import marshal
  >>> marshal.loads('RKp,U\xf7`\xef\xe77\xc1\xea\xd8\xec\xbe\\')
  Segmentation fault

Plenty of other nasty stuff can happen when you call marshal.loads, too.

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


Re: python at command prompt

2007-11-01 Thread Matimus
On Nov 1, 9:58 am, [EMAIL PROTECTED] wrote:
> [snip]
>
> > Sounds like your path isn't set correctly.  See the first section
> > here[1] on "Finding python.exe"
>
> > -tkc
>
> > [1]http://www.imladris.com/Scripts/PythonForWindows.html
>
> Thanks Tim,
> I set the pythonpath to where the python interpreter is located C:
> \Python24
> However I still get the same error message. Is there something else
> that must be configured?
> thanks.

You don't want to use PYTHONPATH for pointing to the python
executable. PYTHONPATH is for telling python where to look for
modules. What you need to do is set PATH to point to where the python
exectuable lives (probably C:\Python24) and you might want to add the
scripts directory as well (c:\Python24\Scripts).

To do that, right click on 'My Computer' select 'properties'. In the
dialog that appears select the 'Advanced' tab. Click the 'Environment
Variables' button near the bottom of the dialog. In the System
variables section of the new window look for a variable named 'Path',
and edit its contents to include C:\Python24 and C:\Python24\Scripts.
Each entry should be separated by a semi-colon. There is also a way to
do this by editing the registry which I'm sure you could find by doing
a google search.

I'm a little surprised that python doesn't do this by default, or at
least give it as an option during installation.

Matt

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


Re: How python writes text into another windows application

2007-11-01 Thread Meitham
Thank you all for your kind answers.
I was going to use just shell.SendKeys("fu bar"), but as your answers
suggested pywinauto is a ready framework that covers all I need.

I wanted to play some politics with TNT, but I'm new in the company and
my manager won't listen :).

Meitham

Wolfgang Draxinger wrote:
> Meitham wrote:
> 
>> My question is, how do I write the data into another
>> application fields. My target application is the TNT
>> consignment manager. I asked TNT for their API to make my life
>> easier but they refused to release it :(.
> 
> You know what the word "market" means? Just tell TNT, that it
> seems they don't need you as a customer and so you will change
> to another parcel service.
> 
> I had the very same situation with a regional parcel service a
> few years ago, you won't believe how quick they were in
> providing me with API information, in the prospect of loosing a
> valuable customer (the fact that you want to automatize the
> process suggests, that you have a lot of stuff to be delivered).
> 
> If they still don't bite, just show them a calculation, that it's
> cheaper for you, to choose another parcel service that might
> cost more, but you can save that money with the automatized data
> entry.
> 
> Of course it's possible to send keypresses, mouse moves/clicks
> and other messages to another application, but then you _MUST_
> make sure, that no other application or a user interferes in the
> process, and if an update of the software changes the interface
> you have to reimplement the stuff from grounds up.
> 
> Wolfgang Draxinger

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


Re: marshal vs pickle

2007-11-01 Thread Aaron Watters
On Nov 1, 4:59 pm, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On Thu, 01 Nov 2007 20:35:15 -, Aaron Watters <[EMAIL PROTECTED]> wrote:
> >On Nov 1, 2:15 pm, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
> >> On Nov 1, 4:45 am, Aaron Watters <[EMAIL PROTECTED]> wrote:
>
> >> > Marshal is more secure than pickle
>
> >> "More" or "less" make little sense in a security context which
> >> typically is an all or nothing affair.  Neither module is designed for
> >> security.  From the docs for marshal:
>
> >> '''
> >> Warning: The marshal module is not intended to be secure against
> >> erroneous or maliciously constructed data. Never unmarshal data
> >> received from an untrusted or unauthenticated source.
> >> '''
>
> >> If security is a focus, then use xmlrpc or some other tool that
> >> doesn't construct arbitrary code objects.
>
> >I disagree.  Xmlrpc is insecure if you compile
> >and execute  one of the strings
> >you get from it.  Marshal is similarly insecure if you evaluate a code
> >object it hands you.  If you aren't that dumb, then neither one
> >is a problem.  As far as I'm concerned marshal.load is not any
> >more insecure than file.read.
>
> You're mistaken.
>
>   $ python
>   Python 2.4.3 (#2, Oct  6 2006, 07:52:30)
>   [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
>   Type "help", "copyright", "credits" or "license" for more information.
>   >>> import marshal
>   >>> marshal.loads('RKp,U\xf7`\xef\xe77\xc1\xea\xd8\xec\xbe\\')
>   Segmentation fault
>
> Plenty of other nasty stuff can happen when you call marshal.loads, too.

I'll grant you the above as a denial of service attack.  You are right
that I was mistaken in that sense.  (btw, it doesn't core dump for
2.5.1)

That is/was a bug in marshal.  Someone should fix it.  Properly
implemented,
marshal is not fundamentally insecure.  Can you give me an example
where someone can erase the filesystem using marshal.load?  I saw one
for pickle.load once.

  -- Aaron Watters

===
http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=chocolate

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


Re: XML document causes pickle to go into infinite recursion

2007-11-01 Thread Orest Kozyar

> minidom creates a pretty complete tree data structure, with loads of backlinks
> to parent elements etc. That's where your circular references come from.
>
> I don't know why you want to use pickle here (and not serialised XML or the
> plain in-memory tree), but if memory consumption is an issue, try
> cElementTree, which comes with Python 2.5 (or as an external module for older
> versions). It's faster, more memory friendly and easier to use than minidom.
> There's also lxml.objectify, in case you can't live without pickeling.

I wasn't aware of cElementTree.  When I was looking for examples of
how to parse XML documents, most of the tutorials I came across used
minidom.  Thanks for pointing this out.  I've switched over, and I
like ElementTree much better than minidom (the structure returned by
the minidom parser always seemed overly complex).

I've also gotten rid of the pickling and am storing the XML files as
raw text in directories, so this got rid of my other problem with
shelve.

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


Re: Syntax coloring in Python interpreter

2007-11-01 Thread Neil Cerutti
On 2007-11-01, Chris Mellon <[EMAIL PROTECTED]> wrote:
> On Nov 1, 2007 3:01 PM, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>> On 2007-11-01, Lee Capps <[EMAIL PROTECTED]> wrote:
>> >
>> > On Nov 1, 2007, at 1:45 PM, braver wrote:
>> >> Greetings -- as a long time user of both Python and Ruby
>> >> interpreters, I got used to the latter's syntax-coloring gem,
>> >> wirble, which colorizes Ruby syntax on the fly.  Is there
>> >> anything similar for Python?
>> >>
>> >
>> > I believe IPython can do this:
>> >
>> > http://ipython.scipy.org/moin/
>>
>> IPython's syntax coloring doesn't work with Windows 2000 and
>> up, since (last I checked) it relies on a readline.py file,
>> which relies on ANSI.SYS, which is not supported by the
>> Windows console.
>
> If you scroll down about half a page in the above link you'll
> find a link to a readline implementation for Windows.

That pyreadline.py appears to be an improvement on the Windows
support when I last looked  (6 months or so ago). Thanks for the
heads up.

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


Re: XML document causes pickle to go into infinite recursion

2007-11-01 Thread Orest Kozyar
> > I'm working on a CGI script that pulls XML data from a public database
>
> Ah, I missed that bit on first read. Consider using something different than
> CGI here if you want to do caching. FCGI would allow you to do in-memory
> caching, for example, as would mod_python and a lot of other solutions.

What I'm aiming for is sort of a "permanent" disk cache/mirror that
adds records as needed.  The main issue is that the database (PubMed)
requests that we limit requests to once every three seconds.  I often
need to access data for hundreds of records, so I've set up a cron job
to cache the needed records to disk overnight.  I was using shelve
before, but the size of the file grew to about 500 mB and I started
having issues with shelve performance.  So, I just stopped using
shelve and am storing each record separately on disk now.

Thanks!
Orest

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


Re: marshal vs pickle

2007-11-01 Thread Jean-Paul Calderone
On Thu, 01 Nov 2007 21:15:06 -, Aaron Watters <[EMAIL PROTECTED]> wrote:
>On Nov 1, 4:59 pm, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
>> On Thu, 01 Nov 2007 20:35:15 -, Aaron Watters <[EMAIL PROTECTED]> wrote:
>> >On Nov 1, 2:15 pm, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
>> >> On Nov 1, 4:45 am, Aaron Watters <[EMAIL PROTECTED]> wrote:
>>
>> >> > Marshal is more secure than pickle
>>
>> >> "More" or "less" make little sense in a security context which
>> >> typically is an all or nothing affair.  Neither module is designed for
>> >> security.  From the docs for marshal:
>>
>> >> '''
>> >> Warning: The marshal module is not intended to be secure against
>> >> erroneous or maliciously constructed data. Never unmarshal data
>> >> received from an untrusted or unauthenticated source.
>> >> '''
>>
>> >> If security is a focus, then use xmlrpc or some other tool that
>> >> doesn't construct arbitrary code objects.
>>
>> >I disagree.  Xmlrpc is insecure if you compile
>> >and execute  one of the strings
>> >you get from it.  Marshal is similarly insecure if you evaluate a code
>> >object it hands you.  If you aren't that dumb, then neither one
>> >is a problem.  As far as I'm concerned marshal.load is not any
>> >more insecure than file.read.
>>
>> You're mistaken.
>>
>>   $ python
>>   Python 2.4.3 (#2, Oct  6 2006, 07:52:30)
>>   [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
>>   Type "help", "copyright", "credits" or "license" for more information.
>>   >>> import marshal
>>   >>> marshal.loads('RKp,U\xf7`\xef\xe77\xc1\xea\xd8\xec\xbe\\')
>>   Segmentation fault
>>
>> Plenty of other nasty stuff can happen when you call marshal.loads, too.
>
>I'll grant you the above as a denial of service attack.  You are right
>that I was mistaken in that sense.  (btw, it doesn't core dump for
>2.5.1)
>
>That is/was a bug in marshal.  Someone should fix it.  Properly
>implemented,
>marshal is not fundamentally insecure.

One can then ask the question of whether or not marshal is properly
implemented in any extant version of CPython. ;)  It isn't much
comfort to know that marshal is ideologically sound after someone
uses it to exploit your service.

>Can you give me an example
>where someone can erase the filesystem using marshal.load?  I saw one
>for pickle.load once.
>

Many bugs which lead to a segfault can also be exploited to execute
arbitrary code.  Not all such bugs can be.  I haven't looked closely
at the marshal source code to determine if it can be or not in this
case.

My observations agree with yours, for what it's worth.  A cursory
investigation doesn't reveal any inputs which cause segfaults in
[EMAIL PROTECTED] with marshal.loads(), although there are still many which
will cause it to allocate huge amounts of memory, another effective
DoS attack.

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


PyCheck for a classes defined in python and user data in PyObject_HEAD

2007-11-01 Thread sndive
q#1:
in C I want to check if a given PyObject is a xml.dom.minidom.Node (or
a derivative).
how do i extract a PyTypeObject for such a class?

issue #2
I'm in a situation when i don't really need to extend python with any
classes of my own but
i do have extra luggage for the python data structures such as tuples,
lists, dictionaries, etc
on the c++ side. I see no place in PyObject_HEAD where i can stick a
void* to my extra data.
If i enter a feature request into bugzilla for python do you think it
will be well received?
#ifdefed of course like the prev/next extras.
I'm surprised noone else is using evil twin approach.
The reason i'm asking is because while for dictionaries i can stick
weak pointer back to my c++
object in a key with an obscure name while in lists this would change
the list size and thus
is obviously not as easy to "hide" from the client code.
a placeholder in a pyobject would've been of help here

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


Re: PyQt with embedded python in Qt App

2007-11-01 Thread Bart.
Thursday 01 of November 2007 15:13:55 Phil Thompson napisał(a):
> On Thursday 01 November 2007, cgrebeld wrote:
> > Is it possible for a Qt C++ application, which embeds the python
> > interpreter, to import and use PyQt?  There can be only one
> > QApplication, which is created in the C++ side, so how would I use
> > that from the python side?
>
> QtGui.QApplication.instance()
>

What I can do with this pointer?
It is possible to add window to application ?
It is possible to connect to application signals?

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

  1   2   >