Re: help req installing python 2.6

2010-04-29 Thread James Mills
2010/4/29 sanam singh :
> hi,
> i am am facing problem in installing python 2.6 on ubuntu 9.04. When i sudo
> make i get following error :

You need to install the necessary development
headers/libraries required to build Python from source.

eg:

$ sudo apt-get install gdbm-dev

[ snip ]

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


Re: function name

2010-04-29 Thread Peter Otten
Steven D'Aprano wrote:

> Be aware though, that sys._getframe is marked as a private function (the
> leading underscore), which means that:
> 
> (1) It only exists in some Python implementations (CPython and possible
> nothing else?); and

$ jython
Jython 2.2.1 on java1.6.0_0
Type "copyright", "credits" or "license" for more information.
>>> import sys
>>> def f(): return sys._getframe().f_code.co_name
...
>>> f()
'f'

$ ipy
IronPython 1.1.1 (1.1.1) on .NET 2.0.50727.1433
Copyright (c) Microsoft Corporation. All rights reserved.
>>> import sys
>>> sys._getframe()
Traceback (most recent call last):
ValueError: _getframe is not implemented
>>> raise SystemExit # is there a sane way to quit ipy?

A quick websearch unearthed

http://blogs.msdn.com/dinoviehland/archive/2009/12/11/ironpython-2-6-
released.aspx

"""
IronPython 2.6 Released!

[...]

This release also changes how we support sys._getframe: a fully working 
version is now available by a command line option;  when not enabled 
sys._getframe doesn’t exist at all.
"""

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


dynamic function add to an instance of a class

2010-04-29 Thread Richard Lamboj

Hello,

i want to add functions to an instance of a class at runtime. The added 
function should contain a default parameter value. The function name and 
function default paramter values should be set dynamical.

Kind Regards,

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


Re: dynamic function add to an instance of a class

2010-04-29 Thread Xavier Ho
On Thu, Apr 29, 2010 at 5:55 PM, Richard Lamboj wrote:

>
> Hello,
>
> i want to add functions to an instance of a class at runtime. The added
> function should contain a default parameter value. The function name and
> function default paramter values should be set dynamical.
>
> Kind Regards,
>
> Richi
>  


What did you mean by "The function name and function default paramter values
should be set dynamical." ? Also, have you tried anything we can see?

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


printing table on the command line

2010-04-29 Thread Daniel Dalton
Hello,

I'm using the MySQLdb library in python to interface with a mysql
database I've created. I have written a command line app which runs from
the command line. I have 10 fields and hence, have found that each
record spreads over one line. What is the best way to print a table of a
database like this? Perhaps using tab spacing? Should I only print the
first 8 characters of each field, and allow the user to expand an
individual record? If so, how do I do this? I'm only new with python,
but %8s doesn't seem to do anything and with print it just prints the
number 8 before the string... 

I want to line up all the fields under the necessary headings, here is
the structure of the program:
for x in headings:
  print '%8s\t' % (x),
print '\n' # a few new lines
for x in records: # entire list of all records
  for i in x: # search individual record
print '%8s\t' % (i),
  print '\n'

This may not be 100% exact, but I'm just trying to simplify it so I
don't need to paste the entire program here, note that records is a list
of all records in the table, and i is obviously a list of fields for
each individual record. Headings is just a tupple of strings such as
"name", "email" etc, just the name of the fields. 

So all I want to do is print a nicely formatted table to the screen on
the console, with tab spacing, I've got 10 fields per record, so will I
have to just chop off some characters?

Any examples of how to do this would be great, as I'm blind and it's a
bit difficult to check the spacing.

Thank you very much,
Dan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dynamic function add to an instance of a class

2010-04-29 Thread James Mills
On Thu, Apr 29, 2010 at 5:55 PM, Richard Lamboj
 wrote:
> i want to add functions to an instance of a class at runtime. The added
> function should contain a default parameter value. The function name and
> function default paramter values should be set dynamical.

The normal way of doing this by binding a new
MethodType to an instance:

>>> class A(object):
... def foo(self):
... return "foo"
...
>>> def bar(self):
... return "bar"
...
>>> a = A()
>>> a.foo()
'foo'
>>> a.bar()
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'A' object has no attribute 'bar'
>>> from types import MethodType
>>> setattr(a, "bar", MethodType(bar, a))
>>> a.bar()
'bar'
>>> a.foo
>
>>> a.bar
>
>>>

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


Re: dynamic function add to an instance of a class

2010-04-29 Thread Peter Otten
Richard Lamboj wrote:

> i want to add functions to an instance of a class at runtime. The added
> function should contain a default parameter value. The function name and
> function default paramter values should be set dynamical.

>>> class A(object):
... def __init__(self, x):
... self.x = x
... def m(self):
... return self.f(self.x)
...
>>> a = A(42)
>>>
>>> def foo(self, a, b):
... return self.x + a**b
...
>>> from functools import partial
>>> a.f = partial(foo, a, 3)
>>> a.m()
109418989131512359251L
>>> 42 + 3**42 == _
True

Confused? The important points are

(1)

functools.partial(f, a1, a2, a3, ...)(b1, b2, b3, ...)

is equivalent to

f(a1, a2, a3, ..., b1, b2, b3, ...)

(2)

If you stick a function into an instance

a.f = f

the call

a.f()

will not automagically pass self as the first argument.

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


Re: dynamic function add to an instance of a class

2010-04-29 Thread Richard Lamboj

Am Thursday 29 April 2010 09:59:22 schrieb Xavier Ho:
> On Thu, Apr 29, 2010 at 5:55 PM, Richard Lamboj 
wrote:
> > Hello,
> >
> > i want to add functions to an instance of a class at runtime. The added
> > function should contain a default parameter value. The function name and
> > function default paramter values should be set dynamical.
> >
> > Kind Regards,
> >
> > Richi
> >  
>
> What did you mean by "The function name and function default paramter
> values should be set dynamical." ? Also, have you tried anything we can
> see?
>
> Cheers,
> Xav

No i don't have any sample code.

I just want to add new functions to an class instance at runtime and i also 
want to set the default parameter values of this new function.

Dynamical:
Class Test(object):
def add_function(self, function_name="new_function", param="new_param", 
value="new_value"):
...

or something like:

Class Test(object):
def add_function(self, function_name="new_function", 
parameters=[["param1", "value1"],["param2", "value2"]]):
...

Statical created it would look like:
Class Test(object):
def new_function1(new_parm1="new_value1"):
pass
def new_function2(new_parm2="new_value2"):
pass
def new_function3(new_parm3="new_value3"):
pass

Kind Regards,

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


Re: ooolib, reading writing a spread sheet and keep formatting

2010-04-29 Thread News123


Kushal Kumaran wrote:
> On Thu, Apr 29, 2010 at 5:46 AM, News123  wrote:
>> Hi,
>>
>> I'm making first attempts to modify a few cells of an openoffice
>> spreadsheet.
>>
> 
> Try the xlrd and xlwt modules, and the documentation at
> http://www.python-excel.org/

Thanks Kumar,

I installed xlrd, xlwt and xlsutils

Now I'm stuck with exactly the same probem, that I had with ooolib.
The newly written file lost all formating and replaced formulas with the
calculated values.


Does anyone have a simple example, which reads a file, modifies one cell
and writes out WITHOUT oss of formatting / formulas?


from xlrd import open_workbook
from xlutils.copy import copy

rb =  open_workbook('doc1.xls')
print "WB with %d sheets" % rb.nsheets
wb = copy(rb)
wb.save("doc2.xls") # file is created, but ALL formattng is lost and
formulas are now diplayed as text




> 
>> 
> 

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


Re: help req installing python 2.6

2010-04-29 Thread James Mills
2010/4/29 sanam singh :
> hi,
> it is saying
> sa...@ubuntu:~/Desktop/Python-2.6.5$ sudo apt-get install gdbm-dev
> Reading package lists... Done
> Building dependency tree
> Reading state information... Done
> E: Couldn't find package gdbm-dev

I'm sorry, but I don't actively use Debian/ubuntu based systems.

Please consult your package manager and search for
the "right package" to install.

"You need to install the development packages"

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


Re: ooolib, reading writing a spread sheet and keep formatting

2010-04-29 Thread News123
News123 wrote:
> 
> Kushal Kumaran wrote:
>> On Thu, Apr 29, 2010 at 5:46 AM, News123  wrote:
>>> Hi,
>>>
>>> I'm making first attempts to modify a few cells of an openoffice
>>> spreadsheet.
>>>
>> Try the xlrd and xlwt modules, and the documentation at
>> http://www.python-excel.org/

> I installed xlrd, xlwt and xlsutils
> 
> Now I'm stuck with exactly the same probem, that I had with ooolib.
> The newly written file lost all formating and replaced formulas with the
> calculated values.
> 

Well the xlsutils documentation states clearly:
> It is important to note that some things won't be copied:
> Formulae
>  •
> Names
>  •
> anything ignored by xlrd
>  •


So probably I can't use xlrd / xlwt to perform my desired task. :-(
(Or it least I don't know how)

For extracting data or creating xls from scratch t seems rather nice though


bye


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


Re: printing table on the command line

2010-04-29 Thread James Mills
On Thu, Apr 29, 2010 at 6:03 PM, Daniel Dalton  wrote:
> Hello,

Hi,

> Any examples of how to do this would be great, as I'm blind and it's a
> bit difficult to check the spacing.

You're welcome to adapt some of my old code
written just for this very purpose. I even have a
tool called 'pysqlplus' that's much-like the mysql
command-line tool but will also work for sqlite
and oracle databases (if you have the python drivers
installed).

See:

http://bitbucket.org/prologic/pymills/src/tip/pymills/table.py

and

http://bitbucket.org/prologic/tools/src/tip/pysqlplus

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


Re: printing table on the command line

2010-04-29 Thread Peter Otten
Daniel Dalton wrote:

> Hello,
> 
> I'm using the MySQLdb library in python to interface with a mysql
> database I've created. I have written a command line app which runs from
> the command line. I have 10 fields and hence, have found that each
> record spreads over one line. What is the best way to print a table of a
> database like this? Perhaps using tab spacing? Should I only print the
> first 8 characters of each field, and allow the user to expand an
> individual record? If so, how do I do this? I'm only new with python,
> but %8s doesn't seem to do anything and with print it just prints the
> number 8 before the string...
> 
> I want to line up all the fields under the necessary headings, here is
> the structure of the program:
> for x in headings:
>   print '%8s\t' % (x),
> print '\n' # a few new lines
> for x in records: # entire list of all records
>   for i in x: # search individual record
> print '%8s\t' % (i),
>   print '\n'
> 
> This may not be 100% exact, but I'm just trying to simplify it so I
> don't need to paste the entire program here, note that records is a list
> of all records in the table, and i is obviously a list of fields for
> each individual record. Headings is just a tupple of strings such as
> "name", "email" etc, just the name of the fields.
> 
> So all I want to do is print a nicely formatted table to the screen on
> the console, with tab spacing, I've got 10 fields per record, so will I
> have to just chop off some characters?
> 
> Any examples of how to do this would be great, as I'm blind and it's a
> bit difficult to check the spacing.

You can limit the number of characters by adding a second number to the 
format string:

>>> column = "alpha"
>>> print ("%-3.3s" % column).replace(" ", "*")
alp

A minus added to the format string controls where the extra spaces are 
added:

>>> print ("%8.8s" % column).replace(" ", "*")
***alpha
>>> print ("%-8.8s" % column).replace(" ", "*")
alpha***

I've added the str.replace() call that replaces spaces with asterisks only 
to make it easier for you to find out where python adds spaces.

To process a list of columns use the str.join() method:

>>> headings = ["alpha", "beta", "a_very_lng_heading"]
>>> print "\t".join("%-8.8s" % s for s in headings).replace(" ", "*")
alpha***betaa_very_l

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


Re: dynamic function add to an instance of a class

2010-04-29 Thread News123
Peter Otten wrote:
> Richard Lamboj wrote:
> 
>> i want to add functions to an instance of a class at runtime. The added
>> function should contain a default parameter value. The function name and
>> function default paramter values should be set dynamical.
> 
 class A(object):
> ... def __init__(self, x):
> ... self.x = x
> ... def m(self):
> ... return self.f(self.x)
> ...
 a = A(42)

 def foo(self, a, b):
> ... return self.x + a**b
> ...
 from functools import partial
 a.f = partial(foo, a, 3)
 a.m()
> 109418989131512359251L
 42 + 3**42 == _
> True
> 
> Confused? The important points are
> 
> (1)
> 
> functools.partial(f, a1, a2, a3, ...)(b1, b2, b3, ...)
> 
> is equivalent to
> 
> f(a1, a2, a3, ..., b1, b2, b3, ...)
> 
> (2)
> 
> If you stick a function into an instance
> 
> a.f = f


> 
> the call
> 
> a.f()
> 
> will not automagically pass self as the first argument.
> 
The drawback would be, that
b = A(123)
b.f()
would still be called with a as bound object.


N

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


Re: dynamic function add to an instance of a class

2010-04-29 Thread Richard Lamboj

Am Thursday 29 April 2010 10:13:01 schrieb Peter Otten:
> Richard Lamboj wrote:
> > i want to add functions to an instance of a class at runtime. The added
> > function should contain a default parameter value. The function name and
> > function default paramter values should be set dynamical.
> >
> >>> class A(object):
>
> ... def __init__(self, x):
> ... self.x = x
> ... def m(self):
> ... return self.f(self.x)
> ...
>
> >>> a = A(42)
> >>>
> >>> def foo(self, a, b):
>
> ... return self.x + a**b
> ...
>
> >>> from functools import partial
> >>> a.f = partial(foo, a, 3)
> >>> a.m()
>
> 109418989131512359251L
>
> >>> 42 + 3**42 == _
>
> True
>
> Confused? The important points are
>
> (1)
>
> functools.partial(f, a1, a2, a3, ...)(b1, b2, b3, ...)
>
> is equivalent to
>
> f(a1, a2, a3, ..., b1, b2, b3, ...)
>
> (2)
>
> If you stick a function into an instance
>
> a.f = f
>
> the call
>
> a.f()
>
> will not automagically pass self as the first argument.
>
> Peter

Thats what i want:

from functools import partial

class A(object):
def add_function(self, function_name, value):
setattr(self, function_name, partial(self.test, value))

def test(self, value):
print value


a = A()
a.add_function("func1", "value1")
a.func1()

Thanks to all for helping me!

Kind Regard,

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


Re: dynamic function add to an instance of a class

2010-04-29 Thread Peter Otten
News123 wrote:

> Peter Otten wrote:
>> Richard Lamboj wrote:
>> 
>>> i want to add functions to an instance of a class at runtime. The added
>>> function should contain a default parameter value. The function name and
>>> function default paramter values should be set dynamical.
>> 
> class A(object):
>> ... def __init__(self, x):
>> ... self.x = x
>> ... def m(self):
>> ... return self.f(self.x)
>> ...
> a = A(42)
>
> def foo(self, a, b):
>> ... return self.x + a**b
>> ...
> from functools import partial
> a.f = partial(foo, a, 3)
> a.m()
>> 109418989131512359251L
> 42 + 3**42 == _
>> True
>> 
>> Confused? The important points are
>> 
>> (1)
>> 
>> functools.partial(f, a1, a2, a3, ...)(b1, b2, b3, ...)
>> 
>> is equivalent to
>> 
>> f(a1, a2, a3, ..., b1, b2, b3, ...)
>> 
>> (2)
>> 
>> If you stick a function into an instance
>> 
>> a.f = f
> 
> 
>> 
>> the call
>> 
>> a.f()
>> 
>> will not automagically pass self as the first argument.
>> 
> The drawback would be, that
> b = A(123)
> b.f()
> would still be called with a as bound object.

There is no b.f until you explicitly assign it with

b.f = f

If you want the function to work uniformly across all instances of the class 
you are better off with adding it to the class

def f(self, x, y):
...

A.f = f

However, if you want x to have a fixed value -- that is beyond the 
capabilities of functols partial. You have to wrap f in another function:

A.f = lambda self, y: f(self, 42, y)

Peter

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


help req installing python 2.6

2010-04-29 Thread sanam singh

hi,
 i have tried 
sa...@ubuntu:~/Desktop/Python-2.6.5$ sudo apt-get build-dep python
but still the problem persists . when i make the package i get :

Failed to find the necessary bits to build these modules:
_bsddb _curses_curses_panel   
_sqlite3   bsddb185   bz2 
dbmgdbm   readline
sunaudiodev   
To find the necessary bits, look in setup.py in detect_modules() for the 
module's name.

running build_scripts

Please help.

> From: prolo...@shortcircuit.net.au
> Date: Thu, 29 Apr 2010 17:22:21 +1000
> Subject: Re: help req installing python 2.6
> To: python-list@python.org
> 
> 2010/4/29 sanam singh :
> > hi,
> > i am am facing problem in installing python 2.6 on ubuntu 9.04. When i sudo
> > make i get following error :
> 
> You need to install the necessary development
> headers/libraries required to build Python from source.
> 
> eg:
> 
> $ sudo apt-get install gdbm-dev
> 
> [ snip ]
> 
> cheers
> James
> -- 
> http://mail.python.org/mailman/listinfo/python-list
  
_
Hotmail: Trusted email with powerful SPAM protection.
https://signup.live.com/signup.aspx?id=60969-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Remembering the context

2010-04-29 Thread Jean-Michel Pichavant

GZ wrote:

Hi All,

I am looking at the following code:

def fn():

def inner(x):
 return tbl[x]

tbl={1:'A', 2:'B'}
f1 = inner   # I want to make a frozen copy of the values of tbl
in f1
tbl={1:'C', 2:'D'}
f2 = inner
   return (f1,f2)

f1,f2 = fn()
f1(1)  # output C
f2(1) # output C

What I want is for f1 to make a frozen copy of tbl at the time f1 is
made and f2 to make another frozen copy of tbl at the time f2 is made.
In other words, I want f1(1)=='A' and f2(1)=='C'.
  


something like

def makeInner(a_tbl):
   def inner(x):
   return a_tbl[x]
   return inner

def fn():
   tbl = {1:'A', 2:'B'}
   f1 = makeInner(tbl)
   tbl = {1:'C', 2:'D'}
   f2 = makeInner(tbl)
   return f1,f2

f1,f2 = fn()

In [4]: print f1(1)
A

In [5]: print f2(1)
C

JM

PS : smelling code anyway :o)
--
http://mail.python.org/mailman/listinfo/python-list


Re: dynamic function add to an instance of a class

2010-04-29 Thread News123
Peter Otten wrote:
> News123 wrote:

>>>
>> The drawback would be, that
>> b = A(123)
>> b.f()
>> would still be called with a as bound object.
> 
> There is no b.f until you explicitly assign it with
> 
> b.f = f

you are sooo right.
My fault.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: replacing words in HTML file

2010-04-29 Thread Daniel Fetchinson
> | > Any idea how I can replace words in a html file? Meaning only the
> | > content will get replace while the html tags, javascript, & css are
> | > remain untouch.
> |
> | I'm not sure what you tried and what you haven't but as a first trial
> | you might want to
> |
> | 
> |
> | f = open( 'new.html', 'w' )
> | f.write( open( 'index.html' ).read( ).replace( 'replace-this', 'with-that'
> ) )
> | f.close( )
> |
> | 
>
> If 'replace-this' occurs inside the javascript etc or happens to be an
> HTML tag name, it will get mangled. The OP didn't want that.

Correct, that is why I started with "I'm not sure what you tried and
what you haven't but as a first trial you might". For instance if the
OP wants to replace words which he knows are not in javascript and/or
css and he knows that these words are also not in html attribute
names/values, etc, etc, then the above approach would work, in which
case BeautifulSoup is a gigantic overkill. The OP needs to specify
more clearly what he wants, before really useful advice can be given.

Cheers,
Daniel


> The only way to get this right is to parse the file, then walk the doc
> tree enditing only the text parts.
>
> The BeautifulSoup module (3rd party, but a single .py file and trivial to
> fetch and use, though it has some dependencies) does a good job of this,
> coping even with typical not quite right HTML. It gives you a parse
> tree you can easily walk, and you can modify it in place and write it
> straight back out.
>
> Cheers,
> --
> Cameron Simpson  DoD#743
> http://www.cskk.ezoshosting.com/cs/
>
> The Web site you seek
> cannot be located but
> endless others exist
> - Haiku Error Messages
> http://www.salonmagazine.com/21st/chal/1998/02/10chal2.html
>


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help req installing python 2.6

2010-04-29 Thread Peter Otten
James Mills wrote:

> 2010/4/29 sanam singh :
>> hi,
>> it is saying
>> sa...@ubuntu:~/Desktop/Python-2.6.5$ sudo apt-get install gdbm-dev
>> Reading package lists... Done
>> Building dependency tree
>> Reading state information... Done
>> E: Couldn't find package gdbm-dev
> 
> I'm sorry, but I don't actively use Debian/ubuntu based systems.
> 
> Please consult your package manager and search for
> the "right package" to install.
> 
> "You need to install the development packages"

The right package is probably

$ sudo aptitude install libgdbm-dev

My primitive method of looking for candidates is

$ aptitude search dbm | grep dev

and I just learned that 

$ aptitude search .*dbm.*dev

also works.

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


matching strings in a large set of strings

2010-04-29 Thread Karin Lagesen
Hello.

I have approx 83 million strings, all 14 characters long. I need to be
able to take another string and find out whether this one is present
within the 83 million strings.

Now, I have tried storing these strings as a list, a set and a dictionary.
I know that finding things in a set and a dictionary is very much faster
than working with a list, so I tried those first. However, I run out of
memory building both the set and the dictionary, so what I seem to be left
with is the list, and using the in method.

I imagine that there should be a faster/better way than this?

TIA,

Karin

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


Re: matching strings in a large set of strings

2010-04-29 Thread Peter Otten
Karin Lagesen wrote:

> I have approx 83 million strings, all 14 characters long. I need to be
> able to take another string and find out whether this one is present
> within the 83 million strings.
> 
> Now, I have tried storing these strings as a list, a set and a dictionary.
> I know that finding things in a set and a dictionary is very much faster
> than working with a list, so I tried those first. However, I run out of
> memory building both the set and the dictionary, so what I seem to be left
> with is the list, and using the in method.
> 
> I imagine that there should be a faster/better way than this?

Do you need all matches or do you just have to know whether there are any? 
Can the search string be shorter than 14 characters?

One simple improvement over the list may be using one big string instead of 
the 83 million short ones and then search it using string methods.

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


Default if none

2010-04-29 Thread Astley Le Jasper
I realise I could roll my own here, but I wondered if there was an
inbuilt version of this?

>.
def default_if_none(*args):
for arg in args:
if arg:
return arg
return None

x = None
y = 5
z = 6

print default_if_none(x,y,z)

>> 5

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


Re: matching strings in a large set of strings

2010-04-29 Thread Stefan Behnel

Karin Lagesen, 29.04.2010 11:38:

I have approx 83 million strings, all 14 characters long. I need to be
able to take another string and find out whether this one is present
within the 83 million strings.

Now, I have tried storing these strings as a list, a set and a dictionary.
I know that finding things in a set and a dictionary is very much faster
than working with a list, so I tried those first. However, I run out of
memory building both the set and the dictionary, so what I seem to be left
with is the list, and using the in method.

I imagine that there should be a faster/better way than this?


Try one of the dbm modules in the stdlib. They give you dictionary-like 
lookups on top of a persistent database.


Stefan

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


Re: Default if none

2010-04-29 Thread Chris Rebert
On Thu, Apr 29, 2010 at 3:16 AM, Astley Le Jasper
 wrote:
> I realise I could roll my own here, but I wondered if there was an
> inbuilt version of this?
>
>>.
> def default_if_none(*args):
>    for arg in args:
>        if arg:
>            return arg
>    return None
>
> x = None
> y = 5
> z = 6
>
> print default_if_none(x,y,z)

If none of the potential values are considered boolean false:

print x or y or z

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: assigning multi-line strings to variables

2010-04-29 Thread Gregory Ewing

Lie Ryan wrote:

No, the implicit concatenation is there because Python didn't always
have triple quoted string. Nowadays it's an artifact and triple quoted
string is much preferred.


I don't agree. I often use implicit concatenation when I'm
writing a format string that won't fit on one source line,
because it allows me to fit it into the surrounding indentation
structure without introducing unwanted spaces into the string.

Both tecnhiques have their places.

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


Re: CGI python 3 write RAW BINARY

2010-04-29 Thread Dodo

Le 29/04/2010 01:45, Antoine Pitrou a écrit :

Le Wed, 28 Apr 2010 23:54:07 +0200, Dodo a écrit :


Help! this is driving me crazy lol
I want to print raw binary data to display an image file BUT
python3 outputs b'' instead of so the
browser can't read the image!!

   f = open("/some/path/%s" % x, 'rb')
   print(f.read())


print() implicitly converts its arguments to str (i.e. unicode strings)
and then writes them to sys.stdout, which is a text IO wrapper.
If you want to bypass the unicode layer, you have to use
sys.stdout.buffer instead.
That is:

sys.stdout.buffer.write(f.read())

Regards

Antoine.



@Gary : How do I reply to a http request then?

@Antoine : It not sys.stdout.buffer.write but sys.stdout.write() 
instead. But it still doesn't work, now I have empty content


#!/usr/bin/python3
import cgi, os, sys
form = cgi.FieldStorage()
all = os.listdir("/some/path/with/files/")
for x in all:
if x.find( form['id'].value ) != -1:
ext = x.split(".")[-1]
print("Content-type:image/%s\n\n" % ext)
f = open("/some/path/with/files/%s" % x, 'rb')
sys.stdout.write( f.read() )
f.close()
break

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


How to forward request through lighttpd server to xmlrpc server

2010-04-29 Thread Mishra Gopal-QBX634
Hi,
 
I have Lighttpd web server running on port 80.
and i have a xmlrpc web server running on port 8085
 
How i can send all my request/response to xmlrpc server through lighttpd
server running on port 80?
 
Thanks and regards,
Gopal
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: matching strings in a large set of strings

2010-04-29 Thread Mark Tolonen


"Karin Lagesen"  wrote in message 
news:416f727c6f5b0edb932b425db9579808.squir...@webmail.uio.no...

Hello.

I have approx 83 million strings, all 14 characters long. I need to be
able to take another string and find out whether this one is present
within the 83 million strings.

Now, I have tried storing these strings as a list, a set and a dictionary.
I know that finding things in a set and a dictionary is very much faster
than working with a list, so I tried those first. However, I run out of
memory building both the set and the dictionary, so what I seem to be left
with is the list, and using the in method.

I imagine that there should be a faster/better way than this?


You may be overthinking it.  How fast does it need to be?  I generated the 
following file:


   >>> f=open('test.txt','wt')
   >>> for i in xrange(8300):
   ...  f.write('0123456789ABCD\n')
   ...
   >>> f.close()

It took about 15 seconds to search that file with a command line search tool 
(Windows, and a slow IDE hard drive):


findstr xyz test.txt

It took about twice that to search via Python with 'in':

   >>> for line in open('test.txt'):
   ...  if 'xyz' in line:
   ...   print line
   ...

Reading only a line at a time has the advantage of using very little memory. 
Storing 83 million 14-character strings in memory requires a minimum of 
about 1.2GB not counting overhead for lists/sets/dictionaries.


-Mark


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


Re: Default if none

2010-04-29 Thread Astley Le Jasper
... oh ... that simple. Now I feel dumb.

Thanks!

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


Re: replacing words in HTML file

2010-04-29 Thread james_027
On Apr 29, 5:31 am, Cameron Simpson  wrote:
> On 28Apr2010 22:03, Daniel Fetchinson  wrote:
> | > Any idea how I can replace words in a html file? Meaning only the
> | > content will get replace while the html tags, javascript, & css are
> | > remain untouch.
> |
> | I'm not sure what you tried and what you haven't but as a first trial
> | you might want to
> |
> | 
> |
> | f = open( 'new.html', 'w' )
> | f.write( open( 'index.html' ).read( ).replace( 'replace-this', 'with-that' 
> ) )
> | f.close( )
> |
> | 
>
> If 'replace-this' occurs inside the javascript etc or happens to be an
> HTML tag name, it will get mangled. The OP didn't want that.
>
> The only way to get this right is to parse the file, then walk the doc
> tree enditing only the text parts.
>
> The BeautifulSoup module (3rd party, but a single .py file and trivial to
> fetch and use, though it has some dependencies) does a good job of this,
> coping even with typical not quite right HTML. It gives you a parse
> tree you can easily walk, and you can modify it in place and write it
> straight back out.
>
> Cheers,
> --
> Cameron Simpson  DoD#743http://www.cskk.ezoshosting.com/cs/
>
> The Web site you seek
> cannot be located but
> endless others exist
> - Haiku Error 
> Messageshttp://www.salonmagazine.com/21st/chal/1998/02/10chal2.html

Hi all,

Thanks for all your input. Cameron Simpson get the idea of what I am
trying to do. I've been looking at beautiful soup so far I don't know
how to perform search and replace within it.

Any suggest good read?

Thanks all,

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


Re: ooolib, reading writing a spread sheet and keep formatting

2010-04-29 Thread cjw

On 28-Apr-10 23:18 PM, Kushal Kumaran wrote:

On Thu, Apr 29, 2010 at 5:46 AM, News123  wrote:

Hi,

I'm making first attempts to modify a few cells of an openoffice
spreadsheet.



Try the xlrd and xlwt modules, and the documentation at
http://www.python-excel.org/

The tutorial here is beautifully done:

http://python-excel.googlegroups.com/web/python-excel.pdf?gda=68Un3kIAAABrjVmXvI2FnKbK79o6Y1oCuHLcf1VKsaM-EVGjvOiGtNXEtWX7y7b6ByPnawQ3OxpV4u3aa4iAIyYQIqbG9naPgh6o8ccLBvP6Chud5KMzIQ

Does it fly with .ods files?

Colin W.









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


Re: pyjamas 0.7 released

2010-04-29 Thread lkcl
On Apr 29, 6:37 am, Wolfgang Strobl  wrote:
> Look at it from the point of view of people walking by, trying to decide
> whether they should invest some of their time into digging into yet
> another framework and library.

 yes.  _their_ time - not mine.  the pyjamas project has always been
done on the basis that skilled software developers such as myself and
others ... how-to-say... "invite" other people to benefit from the
fact that they want to have tools which make _their_ lives easier.

 as we receive absolutely no money of any kind from any sponsor or
other free software organisation nor from any corporation, there _is_
no money to spend on doing the "usual" kind of free software project,
where the developers are paid / funded to deal with issues effectively
"for free".

 so instead i encourage and invite people to contribute, and some do,
and some don't: the end-result is the product of everyone's collective
input.

>
>
> >> and that there is no way of
> >> telling, other than by trying each one out in turn?
>
> > yepp  that's correct.  across multiple browsers and across multiple
> >desktop platforms.  nine in total.  which is why i asked for community
> >input this time.
>
> It's hard to come by with valuable input when the baseline - what is
> expected to work under which circumstances is unknown. Don't expect the
> community having as much knowledge about all the relevant topics as you
> have.

 at least _some_ input would be good!  the knowledge doesn't have to
be there: just the bugreports saying "there's a problem and here's
exactly how you reproduce it" would be a start!

> So please make it simpler for more people to help.

 ... how?? there's a bugtracker, wiki, svn repository, over 30
examples and a developer list.  the code really _is_ very very small
(the UI widget set, with around 75 widgets, minus the license header
text is only around 4,000 lines _total_, making it very very simple
and very very easy for people to get used to).  suggestions welcome!

> Other people have
> other projects, where they invest some of their own time and money in.

 yes. been there. didn't receive any return on investment. did some
projects. received about 25% of required money to pay bills.  need
£15k pa; receiving approximately £7-8k.

> >>  I didn't look at
> >> every example again, but AFAIK, this didn't change with 0.7. (Tried with
> >> Python 2.6.4/5 on WinXP/7 with Firefox and Chrome, if that matters).
>
> > then please issue bugreports for as many as you feel comfortable
> >with / have time for.  
>
> Ok, will do.

 thanks.  i fixed the lightout one, don't worry about that.

> > no, because they're all intended to work.  ohh... wait... are you
> >referring to some of the django-based ones?  
>
> No. Having written a few small django apps myself, I'm certainly aware
> about such dependencies. But are you aware that's there is no simple way
> to tell whether certain apps have environment dependencies like this?
> Avoiding examples depending on django is obvious.  What about the
> infohierarchy sample, for example?

 that's reading text files using HTTPRequest (just like the Bookreader
and Slideshow examples), so there's no dependency like that.

 each of the examples, if it has dependencies such as django, it's
assumed that you know how to install and configure django, and there's
instructions in the README to set things up.

> I'm talking about messages like
> lightout TypeError: lightout.RootPanel().,get is no function
> and such.

 hooray!  thank you!  a bugreport!  ok, that was a one line fix:

@@ -85,6 +85,6 @@ class Game(SimplePanel):
 if __name__ == '__main__':
 pyjd.setup("public/lightout.html")
 game = Game(3)
-RootPanel().get('game').add(game)
+RootPanel('game').add(game)

 so, don't worry about that one, it's done.  small change to the API
(to support something that someone else needed) had knock-on effects.

> I'll make a list over the weekend.

 thank you.  greatly appreciated.

> >> Given my original motivation for looking into it - may I ask whether
> >> there is a working example for a dnd operation, somewhere?
> > the person who started the port of gwt-dnd requested that they be
> >"left alone" to complete it, but then didn't.  the use of java2py.py
> >and manual conversion i can do about 1000 lines per day, and people
> >i've guided before usually take about 3x longer than me.  i don't have
> >money to work on even 1 line let alone 1000, so if you'd like to go
> >through the code, converting it and the examples, i'm happy to advise
> >(on thepyjamas-dev list so that other people can contribute as well
> >if they choose).
>
> Hey, I'm just asking, after looking around for a while and finding none,
> I'm not demanding anything.

 no problem, i understood that you weren't - i was just making it
clear that i know what's involved.

> Thanks for the detailed explaination of how to do a conversion, which
> I've deleted here for brevity. I'll give it a try, but it will requir

Re: replacing words in HTML file

2010-04-29 Thread Iain King
On Apr 29, 10:38 am, Daniel Fetchinson 
wrote:
> > | > Any idea how I can replace words in a html file? Meaning only the
> > | > content will get replace while the html tags, javascript, & css are
> > | > remain untouch.
> > |
> > | I'm not sure what you tried and what you haven't but as a first trial
> > | you might want to
> > |
> > | 
> > |
> > | f = open( 'new.html', 'w' )
> > | f.write( open( 'index.html' ).read( ).replace( 'replace-this', 'with-that'
> > ) )
> > | f.close( )
> > |
> > | 
>
> > If 'replace-this' occurs inside the javascript etc or happens to be an
> > HTML tag name, it will get mangled. The OP didn't want that.
>
> Correct, that is why I started with "I'm not sure what you tried and
> what you haven't but as a first trial you might". For instance if the
> OP wants to replace words which he knows are not in javascript and/or
> css and he knows that these words are also not in html attribute
> names/values, etc, etc, then the above approach would work, in which
> case BeautifulSoup is a gigantic overkill. The OP needs to specify
> more clearly what he wants, before really useful advice can be given.
>
> Cheers,
> Daniel
>

Funny, everyone else understood what the OP meant, and useful advice
was given.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: matching strings in a large set of strings

2010-04-29 Thread MRAB

Karin Lagesen wrote:

Hello.

I have approx 83 million strings, all 14 characters long. I need to be
able to take another string and find out whether this one is present
within the 83 million strings.

Now, I have tried storing these strings as a list, a set and a dictionary.
I know that finding things in a set and a dictionary is very much faster
than working with a list, so I tried those first. However, I run out of
memory building both the set and the dictionary, so what I seem to be left
with is the list, and using the in method.

I imagine that there should be a faster/better way than this?


You could sort the list and then use a binary chop (Google can tell you
what that is if you don't know already).
--
http://mail.python.org/mailman/listinfo/python-list


Re: matching strings in a large set of strings

2010-04-29 Thread Duncan Booth
MRAB  wrote:

> Karin Lagesen wrote:
>> Hello.
>> 
>> I have approx 83 million strings, all 14 characters long. I need to
>> be able to take another string and find out whether this one is
>> present within the 83 million strings.
>> 
>> Now, I have tried storing these strings as a list, a set and a
>> dictionary. I know that finding things in a set and a dictionary is
>> very much faster than working with a list, so I tried those first.
>> However, I run out of memory building both the set and the
>> dictionary, so what I seem to be left with is the list, and using the
>> in method. 
>> 
>> I imagine that there should be a faster/better way than this?
>> 
> You could sort the list and then use a binary chop (Google can tell
> you what that is if you don't know already).
> 

... and Python comes batteries included. You can use bisect.bisect_left to 
do the binary chop and then you just have to check whether it found the 
string.


-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Add a method to a gtk class?

2010-04-29 Thread Wolfnoliir
Hi,
I would like to add a method to the gtk.TextBuffer class to save a text
buffer to a file, but I get an error:

line 22, in 
gtk.TextBuffer.save_to_file = gtk_TextBuffer_save_to_file
TypeError: can't set attributes of built-in/extension type 'gtk.TextBuffer'

Here is the code:

10 import gtk
15
16 def gtk_TextBuffer_save_to_file(self, filePath) :
17 with open(filePath, 'w') as file:
18 start = self.get_start_iter()
19 end   = self.get_end_iter()
20 text  = self.get_text(start, end, False)
21 file.write(text)
22 gtk.TextBuffer.save_to_file = gtk_TextBuffer_save_to_file

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


Re: Add a method to a gtk class?

2010-04-29 Thread Joe Riopel
On Thu, Apr 29, 2010 at 11:43 AM, Wolfnoliir  wrote:
> I would like to add a method to the gtk.TextBuffer class to save a text
> buffer to a file, but I get an error:

I don't know gtk, but can you inherit from the TextBuffer class create
your own TexBuffer subclass with the save_to_file method?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Add a method to a gtk class?

2010-04-29 Thread Wolfnoliir
On 29/04/2010 17:03, Joe Riopel wrote:
> On Thu, Apr 29, 2010 at 11:43 AM, Wolfnoliir  wrote:
>> I would like to add a method to the gtk.TextBuffer class to save a text
>> buffer to a file, but I get an error:
> 
> I don't know gtk, but can you inherit from the TextBuffer class create
> your own TexBuffer subclass with the save_to_file method?

I suppose I could but the point of adding a method is to make things
simpler (than having a separate function) so I don't really want to do that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CGI python 3 write RAW BINARY

2010-04-29 Thread Antoine Pitrou
Le Thu, 29 Apr 2010 12:53:53 +0200, Dodo a écrit :
> 
> @Antoine : It not sys.stdout.buffer.write but sys.stdout.write()
> instead. But it still doesn't work, now I have empty content

Let me insist: please use sys.stdout.buffer.write().
You'll also have to call sys.stdout.flush() before doing so.


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


How to get ipRouteTable from Cisco router?

2010-04-29 Thread gvozdikov
Hello!

I want to get route tables from Cisco routers in the network. What i
have:

import re

from pysnmp.entity.rfc3413.oneliner import cmdgen

s = r'(%s)' % ('(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.)\
{3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)')
pattern = re.compile(s)
file = 'routers.txt'
s = open(file).read()
i = 0
router_list = []
while True:
match = pattern.search(s, i)
if match:
router_list.append(match.group(1))
i = match.end() + 1
else:
break

class router:
def __init__(self, who):
self.name = who

routetable = {}

router1 = router(router_list[0])

cmdGen = cmdgen.CommandGenerator()
errorIndication, errorStatus, errorIndex, varBindTable =
cmdGen.nextCmd(
cmdgen.CommunityData('test-agent', public, 0),
cmdgen.UdpTransportTarget((router1.name, 161)),
(1,3,6,1,2,1,4,21,1,1))

if errorIndication:
print errorIndication
else:
if errorStatus:
print '%s at %s\n' %
(errorStatus.prettyPrint(),varBindTable[-1][int(errorIndex)-1])
else:
for varBindTableRow in varBindTable:
for oid, val in varBindTableRow:
 print varBindTableRow


Result:

Code: Select all
[(ObjectName('1.3.6.1.2.1.4.21.1.1.0.0.0.0'), IpAddress('0.0.0.0'))]
[(ObjectName('1.3.6.1.2.1.4.21.1.1.10.9.0.0'), IpAddress('10.9.0.0'))]
[(ObjectName('1.3.6.1.2.1.4.21.1.1.192.168.1.0'),
IpAddress('192.168.1.0'))]


How can i get IpAddress values from this list and put they in the
dictionary? Or may be there is much better solution?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Add a method to a gtk class?

2010-04-29 Thread Michael Torrie
On 04/29/2010 10:03 AM, Wolfnoliir wrote:
> On 29/04/2010 17:03, Joe Riopel wrote:
>> On Thu, Apr 29, 2010 at 11:43 AM, Wolfnoliir  wrote:
>>> I would like to add a method to the gtk.TextBuffer class to save a text
>>> buffer to a file, but I get an error:
>>
>> I don't know gtk, but can you inherit from the TextBuffer class create
>> your own TexBuffer subclass with the save_to_file method?
> 
> I suppose I could but the point of adding a method is to make things
> simpler (than having a separate function) so I don't really want to do that.

Given that Gtk+ classes in python are often thin wrappers around opaque,
binary Gobject-based objects, perhaps the gtk.TextBuffer cannot be
monkey-patched in this way.


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


using python2.6 on windows without installation

2010-04-29 Thread Mirko Vogt
Hey,

is there a way to use python2.6 without having used the installation
routine?

When I install python2.6 and copy over the python-directory (C:\programs
\python2.6) to another windows host and trying to execute python.exe
there, I get an error that python26.dll could not be found.

On the host where I used the installation routine, python26.dll is
stored in C:\windows\system32 which (obviously) isn't on the host where
I just copied the python directory to.

Is it possible to include python26.dll in the application folder or tell
python not to look in C:\windows\system32 for its library?

Backround is: I'd like to put the python directory on a share which is
mounted by several windows hosts.
That way I do not need to touch every windows host when I'm going to
update a python installation but just the one which is sharing it to all
others.

Thanks a lot in advance!

mirko



-- 
This email address is used for mailinglist purposes only.
Non-mailinglist emails will be dropped automatically.
If you want to get in contact with me personally, please mail to:
mirko.vogt  nanl  de

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


Re: replacing words in HTML file

2010-04-29 Thread Daniel Fetchinson
>> > | > Any idea how I can replace words in a html file? Meaning only the
>> > | > content will get replace while the html tags, javascript, & css are
>> > | > remain untouch.
>> > |
>> > | I'm not sure what you tried and what you haven't but as a first trial
>> > | you might want to
>> > |
>> > | 
>> > |
>> > | f = open( 'new.html', 'w' )
>> > | f.write( open( 'index.html' ).read( ).replace( 'replace-this',
>> > 'with-that'
>> > ) )
>> > | f.close( )
>> > |
>> > | 
>>
>> > If 'replace-this' occurs inside the javascript etc or happens to be an
>> > HTML tag name, it will get mangled. The OP didn't want that.
>>
>> Correct, that is why I started with "I'm not sure what you tried and
>> what you haven't but as a first trial you might". For instance if the
>> OP wants to replace words which he knows are not in javascript and/or
>> css and he knows that these words are also not in html attribute
>> names/values, etc, etc, then the above approach would work, in which
>> case BeautifulSoup is a gigantic overkill. The OP needs to specify
>> more clearly what he wants, before really useful advice can be given.
>
> Funny, everyone else understood what the OP meant, and useful advice
> was given.

It was a lucky day for the OP then!

:)

Cheers,
Daniel


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
http://mail.python.org/mailman/listinfo/python-list


print executed query

2010-04-29 Thread someone
Hello!

Is there a way to print a query for logging purpose as it was or will
be sent to database, if I don't escape values of query by myself?

cursor.execute(query, [id, somestring])

I could print query and values separate, but it would be great, if I
could see how query is constructed and can the also copy it and
execute in console.

Im using psycopg2, btw

Thanks!

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


How to pretty-print cyclic dictionaries?

2010-04-29 Thread Dietrich Bollmann
Hi,

I would like to represent graphs as cyclic dictionaries in Python.

The python code for the graphs is generated by some other program
(written in lisp) and I wonder what would be the best syntax for writing
the cycles in Python?

The following works:

>>> a = {}
>>> a['a'] = a

As can be seen here:

>>> a
{'a': {...}}
>>> a['a']
{'a': {...}}
>>> a['a']['a']
{'a': {...}}
>>> a['a']['a']['a']
{'a': {...}}
>>> 

but I wonder if there is some easier syntax to represent the cycles?

"Tags" like the following would be ideal:

[0] {'a': [0]}

but is there something like this in Python?

Thanks, Dietrich


PS:  If there is such a representation, how could I make Python print it
out?

The normal printing is not very informative:

>>> a
{'a': {...}}

And Pythons pretty-print functionality is not better either:

>>> pprint.pprint(a)
{'a': }

Any idea?

Thanks again :)




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


Re: CGI python 3 write RAW BINARY

2010-04-29 Thread Dodo

Le 29/04/2010 17:07, Antoine Pitrou a écrit :

Le Thu, 29 Apr 2010 12:53:53 +0200, Dodo a écrit :


@Antoine : It not sys.stdout.buffer.write but sys.stdout.write()
instead. But it still doesn't work, now I have empty content


Let me insist: please use sys.stdout.buffer.write().
You'll also have to call sys.stdout.flush() before doing so.


Oh, I tested on my windows machine avec sys.stdout.buffer.write() didn't 
work.

I just tested on my linux server, and it works

So, let's modify the script

sys.stdout.buffer.write( f.read() )
sys.stdout.flush()

Now I have:
malformed header from script. Bad header=ÿØÿà: show.py
and it tells me Internal Server error :(

I can't see the error messages (traceback)
any idea to do so?

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


Re: print executed query

2010-04-29 Thread Philip Semanchuk


On Apr 29, 2010, at 12:01 PM, someone wrote:


Hello!

Is there a way to print a query for logging purpose as it was or will
be sent to database, if I don't escape values of query by myself?

cursor.execute(query, [id, somestring])

I could print query and values separate, but it would be great, if I
could see how query is constructed and can the also copy it and
execute in console.

Im using psycopg2, btw



If you can fiddle with the Postgres server settings, the server has  
options for logging lots of things, including the queries it executes.



Hope this helps
Philip

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


Re: How to pretty-print cyclic dictionaries?

2010-04-29 Thread Robert Kern

On 4/29/10 11:23 AM, Dietrich Bollmann wrote:

Hi,

I would like to represent graphs as cyclic dictionaries in Python.

The python code for the graphs is generated by some other program
(written in lisp) and I wonder what would be the best syntax for writing
the cycles in Python?


You can implement your ideas using Armin Ronacher's pretty.py:

  http://pypi.python.org/pypi/pretty

The default pretty printer for dicts looks like this:

def dict_pprinter(obj, p, cycle):
if cycle:
return p.text('{...}')
p.begin_group(1, '{')
keys = obj.keys()
try:
keys.sort()
except Exception, e:
# Sometimes the keys don't sort.
pass
for idx, key in enumerate(keys):
if idx:
p.text(',')
p.breakable()
p.pretty(key)
p.text(': ')
p.pretty(obj[key])
p.end_group(1, '}')

You could conceivably subclass RepresentationPrinter (the variable p above is an 
instance of this) that will assign increasing ID numbers to repeated objects so 
you can tag them.


--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: How to pretty-print cyclic dictionaries?

2010-04-29 Thread Chris Rebert
On Thu, Apr 29, 2010 at 9:23 AM, Dietrich Bollmann  wrote:
> Hi,
>
> I would like to represent graphs as cyclic dictionaries in Python.
>
> The python code for the graphs is generated by some other program
> (written in lisp) and I wonder what would be the best syntax for writing
> the cycles in Python?
>
> The following works:
>
 a = {}
 a['a'] = a
>
> As can be seen here:
>
 a
> {'a': {...}}
 a['a']
> {'a': {...}}
 a['a']['a']
> {'a': {...}}
 a['a']['a']['a']
> {'a': {...}}

>
> but I wonder if there is some easier syntax to represent the cycles?
>
> "Tags" like the following would be ideal:
>
> [0] {'a': [0]}
>
> but is there something like this in Python?

Pretty sure that's a No.

> PS:  If there is such a representation, how could I make Python print it
> out?
>
> The normal printing is not very informative:
>
 a
> {'a': {...}}
>
> And Pythons pretty-print functionality is not better either:
>
 pprint.pprint(a)
> {'a': }
>
> Any idea?

If you want a prettier print, you could try serializing it to YAML and
printing the result out; YAML has syntax for "tags".

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: building python 3 -- _dbm necessary bits

2010-04-29 Thread Mark Olbert
On Thu, 29 Apr 2010 15:51:26 +1000, James Mills  
wrote:

>On Thu, Apr 29, 2010 at 1:12 PM, Mark Olbert
> wrote:
>> I'm getting an error message about make not being able to find the necessary 
>> bits to build modules related to _dbm. Yet I have
>> libgdbm installed installed on my system. Suggestions on how to fix this?
>
>You need the development C headers for
>gdbm. If you're using a Debian-based system
>try something like:
>
>$ apt-get install gdbm-dev
>
>cheers
>James

Okay. But I compiled & installed gdbm from source obtained from the gnu 
archive, so I presume the necessary files would be included
(this is on a linux system).

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


Re: assigning multi-line strings to variables

2010-04-29 Thread goldtech
Thank you to posters for help to my question. Seems I had trouble with
triple quotes strings in the PythonWin shell. But using the Idle shell
things work as expected. But this is probably another issue...any way,
w/Idle's shell I got the "action" regarding multiline strings I
expected.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using python2.6 on windows without installation

2010-04-29 Thread Miki
 > Is it possible to include python26.dll in the application folder or
tell
> python not to look in C:\windows\system32 for its library?
The needed DLLs should be in the PATH. The simplest way is to place
all
the required DLLs next to the python executable.

You can use http://www.dependencywalker.com/ to find out which DLLs
are needed.

HTH,
--
Miki
http://pythonwise.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print executed query

2010-04-29 Thread Miki

> Is there a way to print a query for logging purpose as it was or will
> be sent to database, if I don't escape values of query by myself?
> ...
> Im using psycopg2, btw
http://initd.org/psycopg/docs/advanced.html#connection-and-cursor-factories

HTH,
--
Miki
http://pythonwise.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: building python 3 -- _dbm necessary bits

2010-04-29 Thread James Mills
On Fri, Apr 30, 2010 at 3:00 AM, Mark Olbert
 wrote:
> Okay. But I compiled & installed gdbm from source obtained from the gnu 
> archive, so I presume the necessary files would be included
> (this is on a linux system).

Perhaps check where gdbm has installed it's development sources
and whether or not the python build scripts can pick it up ? (./configure)

Also maybe check ./configure options (maybe you're system is different) ?

Without knowing more about your system I can't offer any further useful advise.

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


Re: matching strings in a large set of strings

2010-04-29 Thread Miki

> I have approx 83 million strings, all 14 characters long. I need to be
> able to take another string and find out whether this one is present
> within the 83 million strings.
Have a look at the shelve module.

If you want to write the algorithm yourself, I suggest
http://en.wikipedia.org/wiki/Trie

HTH,
--
Miki
http://pythonwise.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


array matching

2010-04-29 Thread Bill Jordan
Hey guys,

I am sorry if this is not the right list to post some questions. I have a 
simple question please and would appreciate some answers as I am new to Python.

I have 2 D array: test = [[A,1],[B,2],[A,3][B,4]]
I want to arrang this array in different arrays so each one will have what is 
attached to. For example I want the output:

A =[1,3] and B=[2,4]

Thanks,
Bill


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


Python's regular expression help

2010-04-29 Thread goldtech
Hi,
Trying to start out with simple things but apparently there's some
basics I need help with. This works OK:
>>> import re
>>> p = re.compile('(ab*)(sss)')
>>> m = p.match( 'absss' )
>>> m.group(0)
'absss'
>>> m.group(1)
'ab'
>>> m.group(2)
'sss'
...
But two questions:

How can I operate a regex on a string variable?
I'm doing something wrong here:

>>> f=r'abss'
>>> f
'abss'
>>> m = p.match( f )
>>> m.group(0)
Traceback (most recent call last):
  File "", line 1, in 
m.group(0)
AttributeError: 'NoneType' object has no attribute 'group'

How do I implement a regex on a multiline string?  I thought this
might work but there's problem:

>>> p = re.compile('(ab*)(sss)', re.S)
>>> m = p.match( 'ab\nsss' )
>>> m.group(0)
Traceback (most recent call last):
  File "", line 1, in 
m.group(0)
AttributeError: 'NoneType' object has no attribute 'group'
>>>

Thanks for the newbie regex help, Lee
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's regular expression help

2010-04-29 Thread Dodo

Le 29/04/2010 20:00, goldtech a écrit :

Hi,
Trying to start out with simple things but apparently there's some
basics I need help with. This works OK:

import re
p = re.compile('(ab*)(sss)')
m = p.match( 'absss' )
m.group(0)

'absss'

m.group(1)

'ab'

m.group(2)

'sss'
...
But two questions:

How can I operate a regex on a string variable?
I'm doing something wrong here:


f=r'abss'
f

'abss'

m = p.match( f )
m.group(0)

Traceback (most recent call last):
   File "", line 1, in
 m.group(0)
AttributeError: 'NoneType' object has no attribute 'group'

How do I implement a regex on a multiline string?  I thought this
might work but there's problem:


p = re.compile('(ab*)(sss)', re.S)
m = p.match( 'ab\nsss' )
m.group(0)

Traceback (most recent call last):
   File "", line 1, in
 m.group(0)
AttributeError: 'NoneType' object has no attribute 'group'




Thanks for the newbie regex help, Lee


for multiline, I use re.DOTALL

I do not know match(), findall is pretty efficient :
my = "LINK"
res = re.findall(">(.*?)<",my)
>>> res
['LINK']

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


Re: How to pretty-print cyclic dictionaries?

2010-04-29 Thread Garrick P
Chris Rebert  rebertia.com> writes:

...

> If you want a prettier print, you could try serializing it to YAML and
> printing the result out; YAML has syntax for "tags".
> 
> Cheers,
> Chris
> --
> http://blog.rebertia.com

Works fairly well.

$ python
Python 2.6.4 (r264:75706, Mar  1 2010, 14:28:00)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import yaml
>>> a = {}
>>> a['a'] = a
>>> a
{'a': {...}}
>>> print yaml.dump(a)
&id001
a: *id001
>>> b = {}
>>> b['b'] = b
>>> b['a'] = a
>>> a['b'] = b
>>> print yaml.dump(a)
&id001
a: *id001
b: &id002
  a: *id001
  b: *id002




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


Re: Python's regular expression help

2010-04-29 Thread MRAB

goldtech wrote:

Hi,
Trying to start out with simple things but apparently there's some
basics I need help with. This works OK:

import re
p = re.compile('(ab*)(sss)')
m = p.match( 'absss' )
m.group(0)

'absss'

m.group(1)

'ab'

m.group(2)

'sss'
...
But two questions:

How can I operate a regex on a string variable?
I'm doing something wrong here:


f=r'abss'
f

'abss'

m = p.match( f )
m.group(0)

Traceback (most recent call last):
  File "", line 1, in 
m.group(0)
AttributeError: 'NoneType' object has no attribute 'group'


Look closely: the regex contains 3 letter 's', but the string referred
to by f has only 2.


How do I implement a regex on a multiline string?  I thought this
might work but there's problem:


p = re.compile('(ab*)(sss)', re.S)
m = p.match( 'ab\nsss' )
m.group(0)

Traceback (most recent call last):
  File "", line 1, in 
m.group(0)
AttributeError: 'NoneType' object has no attribute 'group'

Thanks for the newbie regex help, Lee


The string contains a newline between the 'b' and the 's', but the regex
isn't expecting any newline (or any other character) between the 'b' and
the 's', hence no match.
--
http://mail.python.org/mailman/listinfo/python-list


Re: array matching

2010-04-29 Thread MRAB

Bill Jordan wrote:

Hey guys,
 
I am sorry if this is not the right list to post some questions. I have 
a simple question please and would appreciate some answers as I am new 
to Python.
 
I have 2 D array: test = [[A,1],[B,2],[A,3][B,4]]
I want to arrang this array in different arrays so each one will have 
what is attached to. For example I want the output:
 
A =[1,3] and B=[2,4]
 

Build a dict of lists, ie the key is the first member of the sublist and
the value is a list of second members of the sublist.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python's regular expression help

2010-04-29 Thread Tim Chase

On 04/29/2010 01:00 PM, goldtech wrote:

Trying to start out with simple things but apparently there's some
basics I need help with. This works OK:

import re
p = re.compile('(ab*)(sss)')
m = p.match( 'absss' )



f=r'abss'
f

'abss'

m = p.match( f )
m.group(0)

Traceback (most recent call last):
   File "", line 1, in
 m.group(0)
AttributeError: 'NoneType' object has no attribute 'group'


'absss' != 'abss'

Your regexp looks for 3 "s", your "f" contains only 2.  So the 
regexp object doesn't, well, match.  Try


  f = 'absss'

and it will work.  As an aside, using raw-strings for this text 
doesn't change anything, but if you want, you _can_ write it as


  f = r'absss'

if it will make you feel better :)


How do I implement a regex on a multiline string?  I thought this
might work but there's problem:


p = re.compile('(ab*)(sss)', re.S)
m = p.match( 'ab\nsss' )
m.group(0)

Traceback (most recent call last):
   File "", line 1, in
 m.group(0)
AttributeError: 'NoneType' object has no attribute 'group'


Well, it depends on what you want to do -- regexps are fairly 
precise, so if you want to allow whitespace between the two, you 
can use


  r = re.compile(r'(ab*)\s*(sss)')

If you want to allow whitespace anywhere, it gets uglier, and 
your capture/group results will contain that whitespace:


  r'(a\s*b*)\s*(s\s*s\s*s)'

Alternatively, if you don't want to allow arbitrary whitespace 
but only newlines, you can use "\n*" instead of "\s*"


-tkc



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


Re: print executed query

2010-04-29 Thread someone
On Apr 29, 7:23 pm, Miki  wrote:
> > Is there a way to print a query for logging purpose as it was or will
> > be sent to database, if I don't escape values of query by myself?
> > ...
> > Im using psycopg2, btw
>
> http://initd.org/psycopg/docs/advanced.html#connection-and-cursor-fac...
>
> HTH,
> --
> Mikihttp://pythonwise.blogspot.com

thanks, I'm already passing  cursor_factory=RealDictCursor for results
as dicts. Will try combine both.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Default if none

2010-04-29 Thread Michel Claveau - MVP
Hi!

> print x or y or z
> If none of the potential values are considered boolean false

But :
  a=None
  b=False
  c=None
  print a or b or c
  > None



@-salutations
-- 
Michel Claveau 

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


Re: Default if none

2010-04-29 Thread Michel Claveau - MVP
Re! 

Look also : 
  >>> print False or None
  None
  >>> print None or False
  False

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


Re: Issues while building pyfsevents in python 3.1

2010-04-29 Thread Terry Reedy

On 4/29/2010 2:30 AM, mathan kumar wrote:


I m trying port pyfsevents coded in python2.6 to python3.1.


Specifying system and compiler/version might help responders.

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


Re: assigning multi-line strings to variables

2010-04-29 Thread Lie Ryan
On 04/29/10 20:40, Gregory Ewing wrote:
> Lie Ryan wrote:
>> No, the implicit concatenation is there because Python didn't always
>> have triple quoted string. Nowadays it's an artifact and triple quoted
>> string is much preferred.
> 
> I don't agree. I often use implicit concatenation when I'm
> writing a format string that won't fit on one source line,
> because it allows me to fit it into the surrounding indentation
> structure without introducing unwanted spaces into the string.
> 
> Both tecnhiques have their places.
> 

That statement should be quantified with "for large chunks of text".
Format string is typically 2-3 lines at most, not enough to qualify as
large chunk.
-- 
http://mail.python.org/mailman/listinfo/python-list


http://pypi.python.org/pypi

2010-04-29 Thread gert
How do you upload a plain text .py file as a source file?

I get

Error processing form
invalid distribution file
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ooolib, reading writing a spread sheet and keep formatting

2010-04-29 Thread News123
cjw wrote:
> On 28-Apr-10 23:18 PM, Kushal Kumaran wrote:
>> On Thu, Apr 29, 2010 at 5:46 AM, News123  wrote:
>>> Hi,
>>>
>>> I'm making first attempts to modify a few cells of an openoffice
>>> spreadsheet.
>>>
>>
>> Try the xlrd and xlwt modules, and the documentation at
>> http://www.python-excel.org/
> The tutorial here is beautifully done:
> 
> http://python-excel.googlegroups.com/web/python-excel.pdf?gda=68Un3kIAAABrjVmXvI2FnKbK79o6Y1oCuHLcf1VKsaM-EVGjvOiGtNXEtWX7y7b6ByPnawQ3OxpV4u3aa4iAIyYQIqbG9naPgh6o8ccLBvP6Chud5KMzIQ
> 
I agree, Reading the documentation you get very quickly an overview of
what can be done.
> 
> Does it fly with .ods files?
>

It works only with xls, but as OpenOffice can read and write xls this
wouldn't be a problem for me.

However:

I'd like to read in a spreadsheet, perform only minor modifications and
write it back with the exact formatting. this is unfortunately not working.




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


Email attachment problem

2010-04-29 Thread Alan Harris-Reid

Hi there,

I want to send an email with an attachment using the following code 
(running under Python 3.1, greatly simplified to show example)


   from email.mime.multipart import MIMEMultipart
   from email.mime.text import MIMEText

   msg = MIMEMultipart()
   msg['From'] = from_addr
   msg['To'] = to_addr
   msg['Subject'] = subject
   msg.attach(MIMEText(body))

   fp = open(att_file)
   att_msg = MIMEText(fp.read())
   attachment = att_msg.add_header('Content-Disposition', 'attachment', 
filename=att_file)

   msg.attach(attachment)

   # set string to be sent as 3rd parameter to smptlib.SMTP.sendmail()
   send_string = msg.as_string()


The attachment object msg1 returns 'email.mime.text.MIMEText' object at 
', but when the att_msg.add_header(...) line runs the result is 
None, hence the program falls-over in msg.as_string() because no part of 
the attachment can have a None value.  (Traceback shows "'NoneType' 
object has no attribute 'get_content_maintype'" in line 118 of _dispatch 
in generator.py, many levels down from msg.as_string())


Has anyone any idea what the cause of the problem might be?  Any help 
would be appreciated.


Alan Harris-Reid
--
http://mail.python.org/mailman/listinfo/python-list


Re: assigning multi-line strings to variables

2010-04-29 Thread Lie Ryan
On 04/29/10 16:34, Steven D'Aprano wrote:
> On Thu, 29 Apr 2010 02:16:46 +0100, MRAB wrote:
> 
>> Steven D'Aprano wrote:
>>> On Thu, 29 Apr 2010 06:17:42 +1000, Lie Ryan wrote:
>>>
> Consider that the concatenation language feature probably is there
> because it's useful (e.g. it preserves indentation and allows per
> line comments).
 No, the implicit concatenation is there because Python didn't always
 have triple quoted string.
>>>
>>> Do you have a source for that?
>>>
>>> Both triple-quoted strings and implicit concatenation go back to at
>>> least Python 1.4:
>>>
>>> http://docs.python.org/release/1.4/tut/node71.html
>>> http://docs.python.org/release/1.4/tut/node70.html
>>>
>> The page here:
>>
>>  http://svn.python.org/projects/python/branches/py3k/Misc/HISTORY
>>
>> says release 1.0.2 (4 May 1994).
> 
> Yes, it says:
> 
> * String literals follow Standard C rules: they may be continued 
> on the next line using a backslash; adjacent literals are 
> concatenated at compile time.
> 
> * A new kind of string literals, surrounded by triple quotes 
> (""" or '''), can be continued on the next line without a 
> backslash.
> 
> 
> These are adjacent entries in the same release. That's pretty good 
> evidence that both implicit concatenation and triple quotes were 
> introduced at the same time.

Yes, apparently my statement that implicit concatenation is an artifact
is erroneous but it doesn't make the important points less true, that
implicit concatenation is not suitable for integrating large chunk of
text into source code.

And if you do care about the two extra newlines, you can add two
backslashes:

s = """\
...
insert large chunks
...\
"""

which is a constant-time preformatting compared to prepending and
appending every line with quotes, which is O(n) (and we're talking about
the oh-so-expensive programmer's time here).

Ben Finney also showed the trick to let a large chunk to appear indented
and stripping the indenting at runtime in another thread (which is
actually rarely needed since, since as I previously said, huge chunk of
text is usually global-level variable; though the trick does come handy
sometimes).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CGI python 3 write RAW BINARY

2010-04-29 Thread Antoine Pitrou
Le Thu, 29 Apr 2010 18:33:08 +0200, Dodo a écrit :
> Oh, I tested on my windows machine avec sys.stdout.buffer.write() didn't
> work.
> I just tested on my linux server, and it works
> 
> So, let's modify the script
> 
>   sys.stdout.buffer.write( f.read() )
>   sys.stdout.flush()

Sorry, I should have been clearer. You have to flush sys.stdout before 
using sys.stdout.buffer, such that the unicode layer doesn't keep any 
unwritten data. So this should be:

sys.stdout.flush()
sys.stdout.buffer.write( f.read() )

Regards

Antoine.

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


Re: matching strings in a large set of strings

2010-04-29 Thread Terry Reedy

On 4/29/2010 5:38 AM, Karin Lagesen wrote:

Hello.

I have approx 83 million strings, all 14 characters long. I need to be
able to take another string and find out whether this one is present
within the 83 million strings.


If the 'other string' is also 14 chars, so that you are looking for 
exact matches, and you are doing this repeatedly, you might look to 
match hash values first.


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


Re: Default if none

2010-04-29 Thread Chris Rebert
On Thu, Apr 29, 2010 at 12:01 PM, Michel Claveau - MVP
 wrote:
> Hi!
>
>> print x or y or z
>> If none of the potential values are considered boolean false
>
> But :
>  a=None
>  b=False
>  c=None
>  print a or b or c
>  > None

Consider:

def read_default_from_config(cfg_file):
#pseudocode
if not_specified_in(cfg_file):
return None
return read_value_from(cfg_file)

a = None
b = read_default_from_config("1.cfg")
c = read_default_from_config("2.cfg")

print a or b or c

Now, what happens when the user puts a default of 0 in 1.cfg? This was
my intended point.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: modifying open office spreadsheet (with OO installed)

2010-04-29 Thread News123
Mumbling to myself, perhaps somebody else is interested.

News123 wrote:
> Hi,
> 
> 
> I wanted to know who can recommend a good module/library, that allows to
> modify an Open Office spreadsheet.
> 
> One can assume, that Open Office is installed on the host.
> 
> 
Following url gives a small introduction about using the PyUno-bridge to
open-read-modify-save a spread sheet
http://stuvel.eu/ooo-python




A simple sample code snippet could look like:
( Danny.OOo.OOoLib from above url )

import os
import uno
import unohelper
import Danny.OOo.OOoLib as OOoLib

#must start open office with
#soffice "-accept=socket,host=localhost,port=8100;urp;"
fname = "tst.ods"
new_fname = "tstnew.ods"
url = unohelper.systemPathToFileUrl(
os.path.abspath(fname))
desktop = OOoLib.getDesktop()
doc = desktop.loadComponentFromURL(
url, "_blank", 0, () )

sheet = doc.getSheets().getByIndex(0)
cell = sheet.getCellByPosition(0,0)
text_value = cell.getFormula()
if text_value > 3:
   new_val = "was greater three"
else:
   new_val = "was not greater three"
celltochange = sheet.getCellByPosition(1,0)
celltochange.setFormula(new_val)
url = unohelper.systemPathToFileUrl(
os.path.abspath(new_fname))
doc.storeToURL(url, ())
doc.close(True)



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


Re: using python2.6 on windows without installation

2010-04-29 Thread Terry Reedy

On 4/29/2010 11:25 AM, Mirko Vogt wrote:

Hey,

is there a way to use python2.6 without having used the installation
routine?

When I install python2.6 and copy over the python-directory (C:\programs
\python2.6) to another windows host and trying to execute python.exe
there, I get an error that python26.dll could not be found.

On the host where I used the installation routine, python26.dll is
stored in C:\windows\system32 which (obviously) isn't on the host where
I just copied the python directory to.

Is it possible to include python26.dll in the application folder or tell
python not to look in C:\windows\system32 for its library?

Backround is: I'd like to put the python directory on a share which is
mounted by several windows hosts.
That way I do not need to touch every windows host when I'm going to
update a python installation but just the one which is sharing it to all
others.


Try
Movable Python - The Portable Python Distribution.
www.voidspace.org.uk/python/movpy/

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


Re: Email attachment problem

2010-04-29 Thread Chris Rebert
On Thu, Apr 29, 2010 at 1:06 PM, Alan Harris-Reid
 wrote:
> Hi there,
>
> I want to send an email with an attachment using the following code (running
> under Python 3.1, greatly simplified to show example)
>
>   from email.mime.multipart import MIMEMultipart
>   from email.mime.text import MIMEText
>
>   msg = MIMEMultipart()
>   msg['From'] = from_addr
>   msg['To'] = to_addr
>   msg['Subject'] = subject
>   msg.attach(MIMEText(body))
>
>   fp = open(att_file)
>   att_msg = MIMEText(fp.read())
>   attachment = att_msg.add_header('Content-Disposition', 'attachment',
> filename=att_file)
>   msg.attach(attachment)
>
>   # set string to be sent as 3rd parameter to smptlib.SMTP.sendmail()
>   send_string = msg.as_string()
>
>
> The attachment object msg1 returns 'email.mime.text.MIMEText' object at
> ', but when the att_msg.add_header(...) line runs the result is
> None, hence the program falls-over in msg.as_string() because no part of the
> attachment can have a None value.  (Traceback shows "'NoneType' object has
> no attribute 'get_content_maintype'" in line 118 of _dispatch in
> generator.py, many levels down from msg.as_string())
>
> Has anyone any idea what the cause of the problem might be?  Any help would
> be appreciated.

.add_header() modifies the MIMEText object *in-place*; per Python
conventions, mutator methods return None; hence, attachment = None.

Try instead (untested):
att_msg.add_header('Content-Disposition', 'attachment', filename=att_file)
msg.attach(att_msg)

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Add a method to a gtk class?

2010-04-29 Thread Wolfnoliir
On 29/04/2010 17:22, Michael Torrie wrote:
> On 04/29/2010 10:03 AM, Wolfnoliir wrote:
>> On 29/04/2010 17:03, Joe Riopel wrote:
>>> On Thu, Apr 29, 2010 at 11:43 AM, Wolfnoliir  wrote:
 I would like to add a method to the gtk.TextBuffer class to save a text
 buffer to a file, but I get an error:
>>>
>>> I don't know gtk, but can you inherit from the TextBuffer class create
>>> your own TexBuffer subclass with the save_to_file method?
>>
>> I suppose I could but the point of adding a method is to make things
>> simpler (than having a separate function) so I don't really want to do that.
> 
> Given that Gtk+ classes in python are often thin wrappers around opaque,
> binary Gobject-based objects, perhaps the gtk.TextBuffer cannot be
> monkey-patched in this way.
> 
> 
OK, I suppose I will just have to use an ordinary function then.
-- 
http://mail.python.org/mailman/listinfo/python-list


Upgrading from Python 2.6.4 to 2.6.5 on Windows OS

2010-04-29 Thread python
I have a bunch of 3rd party packages loaded in my site-packages
folder. Will these packages be affected if I upgrade my Python
(32-bit Windows) installation from 2.6.4 to 2.6.5?

Are there any gotchas I should watch out for when performing this
type of upgrade? Does it ever make sense (and is it even
possible) to install 2 side-by-side minor releases of Python like
2.6.4 and 2.6.5?

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


Re: http://pypi.python.org/pypi

2010-04-29 Thread James Mills
On Fri, Apr 30, 2010 at 5:53 AM, gert  wrote:
> How do you upload a plain text .py file as a source file?

http://lmgtfy.com/?q=python+distutils+tutorial
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: array matching

2010-04-29 Thread cjw

On 29-Apr-10 14:46 PM, MRAB wrote:

Bill Jordan wrote:

Hey guys,

I am sorry if this is not the right list to post some questions. I
have a simple question please and would appreciate some answers as I
am new to Python.

I have 2 D array: test = [[A,1],[B,2],[A,3][B,4]]
I want to arrang this array in different arrays so each one will have
what is attached to. For example I want the output:

A =[1,3] and B=[2,4]


Build a dict of lists, ie the key is the first member of the sublist and
the value is a list of second members of the sublist.


You might consider numpy, which is designed for arrays.

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


Re: modifying open office spreadsheet (with OO installed)

2010-04-29 Thread Jim Byrnes

News123 wrote:

Mumbling to myself, perhaps somebody else is interested.


Yes I am.


News123 wrote:

Hi,


I wanted to know who can recommend a good module/library, that allows to
modify an Open Office spreadsheet.

One can assume, that Open Office is installed on the host.



Following url gives a small introduction about using the PyUno-bridge to
open-read-modify-save a spread sheet
http://stuvel.eu/ooo-python




A simple sample code snippet could look like:
( Danny.OOo.OOoLib from above url )

import os
import uno
import unohelper
import Danny.OOo.OOoLib as OOoLib

#must start open office with
#soffice "-accept=socket,host=localhost,port=8100;urp;"
fname = "tst.ods"
new_fname = "tstnew.ods"
url = unohelper.systemPathToFileUrl(
 os.path.abspath(fname))
desktop = OOoLib.getDesktop()
doc = desktop.loadComponentFromURL(
 url, "_blank", 0, () )

sheet = doc.getSheets().getByIndex(0)
cell = sheet.getCellByPosition(0,0)
text_value = cell.getFormula()
if text_value>  3:
new_val = "was greater three"
else:
new_val = "was not greater three"
celltochange = sheet.getCellByPosition(1,0)
celltochange.setFormula(new_val)
url = unohelper.systemPathToFileUrl(
 os.path.abspath(new_fname))
doc.storeToURL(url, ())
doc.close(True)



I am teaching myself Python because I like to script spreadsheets.  Up 
until now I was unable to find any entry level info on using Python with 
OO.  Thanks for posting this link.


Regards,  JIm



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


Re: CGI python 3 write RAW BINARY

2010-04-29 Thread Dodo

Le 29/04/2010 22:21, Antoine Pitrou a écrit :

Le Thu, 29 Apr 2010 18:33:08 +0200, Dodo a écrit :

Oh, I tested on my windows machine avec sys.stdout.buffer.write() didn't
work.
I just tested on my linux server, and it works

So, let's modify the script

sys.stdout.buffer.write( f.read() )
sys.stdout.flush()


Sorry, I should have been clearer. You have to flush sys.stdout before
using sys.stdout.buffer, such that the unicode layer doesn't keep any
unwritten data. So this should be:

sys.stdout.flush()
sys.stdout.buffer.write( f.read() )

Regards

Antoine.



I don't get a thing.
Now with the fix :
All browsers shows a different thing, but not the image!
http://ddclermont.homeip.net/misc/python/

If I save it to computer :
* Windows image viewer won't read it
* Irfanview can read it without problems

Dorian

PS : ça commence sérieusement à m'énerver
--
http://mail.python.org/mailman/listinfo/python-list


Re: CGI python 3 write RAW BINARY

2010-04-29 Thread Dodo

Le 29/04/2010 18:33, Dodo a écrit :

Le 29/04/2010 17:07, Antoine Pitrou a écrit :

Le Thu, 29 Apr 2010 12:53:53 +0200, Dodo a écrit :


@Antoine : It not sys.stdout.buffer.write but sys.stdout.write()
instead. But it still doesn't work, now I have empty content


Let me insist: please use sys.stdout.buffer.write().
You'll also have to call sys.stdout.flush() before doing so.



Oh, I tested on my windows machine avec sys.stdout.buffer.write() didn't
work.
I just tested on my linux server, and it works

So, let's modify the script

sys.stdout.buffer.write( f.read() )
sys.stdout.flush()

Now I have:
malformed header from script. Bad header=ÿØÿà: show.py
and it tells me Internal Server error :(

I can't see the error messages (traceback)
any idea to do so?

Dorian


Ok, I just checked, the CRC of the file in the server is not the same 
the in the browser

I don't understand how the data could be modified...

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


Re: Python's regular expression help

2010-04-29 Thread goldtech
On Apr 29, 11:49 am, Tim Chase  wrote:
> On 04/29/2010 01:00 PM, goldtech wrote:
>
> > Trying to start out with simple things but apparently there's some
> > basics I need help with. This works OK:
>  import re
>  p = re.compile('(ab*)(sss)')
>  m = p.match( 'absss' )
>
>  f=r'abss'
>  f
> > 'abss'
>  m = p.match( f )
>  m.group(0)
> > Traceback (most recent call last):
> >    File "", line 1, in
> >      m.group(0)
> > AttributeError: 'NoneType' object has no attribute 'group'
>
> 'absss' != 'abss'
>
> Your regexp looks for 3 "s", your "f" contains only 2.  So the
> regexp object doesn't, well, match.  Try
>
>    f = 'absss'
>
> and it will work.  As an aside, using raw-strings for this text
> doesn't change anything, but if you want, you _can_ write it as
>
>    f = r'absss'
>
> if it will make you feel better :)
>
> > How do I implement a regex on a multiline string?  I thought this
> > might work but there's problem:
>
>  p = re.compile('(ab*)(sss)', re.S)
>  m = p.match( 'ab\nsss' )
>  m.group(0)
> > Traceback (most recent call last):
> >    File "", line 1, in
> >      m.group(0)
> > AttributeError: 'NoneType' object has no attribute 'group'
>
> Well, it depends on what you want to do -- regexps are fairly
> precise, so if you want to allow whitespace between the two, you
> can use
>
>    r = re.compile(r'(ab*)\s*(sss)')
>
> If you want to allow whitespace anywhere, it gets uglier, and
> your capture/group results will contain that whitespace:
>
>    r'(a\s*b*)\s*(s\s*s\s*s)'
>
> Alternatively, if you don't want to allow arbitrary whitespace
> but only newlines, you can use "\n*" instead of "\s*"
>
> -tkc

Yes, most of my problem is w/my patterns not w/any python re syntax.

I thought re.S will take a multiline string with any spaces or
newlines and make it appear as one line to the regex. Make "/n" be
ignored in a way...still playing w/it. Thanks for the help!
-- 
http://mail.python.org/mailman/listinfo/python-list


Performance of list.index - how to speed up a silly algorithm?

2010-04-29 Thread Laszlo Nagy

I have some ten thousand rows in a table. E.g.

columns = ["color","size","weight","value"]
rows = [
[ "Yellow", "Big", 2, 4 ],
[ "Blue", "Big", 3, -4 ],
[ "Blue", "Small", 10, 55 ],
...
]

Some columns are dimensions, others are measures. I want to convert this 
to an indexed version, that looks like this:


dimension_names = ["color","size"] # List of dimension names
dimension_cols = [0,1] # Column indexes for dimension values
dimension_values = { # Dimension value occurences for each dimension
0: ["Yellow","Blue",],
1: ["Big","Small",...],
}
measure_names = ["weight","value"] # List of measure names
measure_cols = [2,3] # List of measure columns
facts = [ # Facts, containing tuples of (dimension_value_incides, 
measure_values )

( (0,0) , (2,4) ),
( (1,0) , (3,-4) ),
( (1,1) , (10,55) ),
...
]

This is how I try to convert to the indexed version:

#1. Iterate over all rows, and collect possible dimension values.

cnt = 0
for row in iterator_factory():
cnt += 1
for dimension_idx,col_idx in enumerate(dimension_cols):
dimension_values[colidx].append(row[cold_idx])
if cnt%1:
dimension_values[colidx] = list(set(dimension_values[colidx]))

#2. Index facts by dimension values

facts = []
for row in iterator_factory():
dv = []
for dimension_idx,col_idx in enumerate(dimension_cols):
dv.append( dimension_values[col_idx].index(row[col_idx]) ) # 
THIS IS THE PROBLEMATIC LINE!

mv = [ row[col_idx] for col_idx in measure_cols ]
facts.append( dv,mv )

(In reality, rows and facts are not stored in memory, because there can 
be 100 000+ facts. I did not want to bore you with the full source code.)


And finally, here is my problem. If a dimension has many possible 
values, then the list.index() code above slows down eveything. In my 
test case, the problematic dimension had about 36 000 different values, 
and the number of rows was about 60 000. Calling index() on a list of 36 
000 values, times 60 000, is too slow.


Test performance was 262 rows/sec. If I use dv.append(0) instead of " 
dv.append( dimension_values[col_idx].index(row[col_idx]) ) " then it 
goes up to 11520 rows/sec. If I exclude the problematic dimension, and 
only leave the others (with 1000 or less values) then goes up to 3000 
rows/sec.


Maybe this should be implemented in C. But I believe that the algorithm 
itself must be wrong (regardless of the language). I really think that 
I'm doing something wrong. Looks like my algorithm's processing time is 
not linear to the number of rows. Not even log(n)*n. There should be a 
more effective way to do this. But how?


I had the idea of sorting the rows by a given dimension. Then it would 
be obvious to speed up the indexing part - for that dimension. PROBABLY 
sorting all rows would be faster than calling list.index() for each row. 
But... it does not seem very efficient either. What if I have 1 million 
rows and 10 dimensions? Do I sort 1 million rows on the disk 10 times? 
Some of you might have ran into the same problem before, and can tell me 
which is the most efficient way to do this.


Thanks,

   Laszlo

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


Komodo Edit: Editor settings?

2010-04-29 Thread John Doe
Komodo Edit 5.1

I would very much like to stop code from expanding automatically. 
Like when several consecutive lines of code have a plus sigh in the 
left margin, meaning they are collapsed, when I go to copy or cut one 
of those collapsed lines, the collapsed lines that follow that line 
automatically expand. Are there any related settings that might keep 
code from automatically expanding when nearby code is being edited?

Thanks.

Otherwise and overall, IMO it is a great free program. Love the color 
coding.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: replacing words in HTML file

2010-04-29 Thread Cameron Simpson
On 29Apr2010 05:03, james_027  wrote:
| On Apr 29, 5:31 am, Cameron Simpson  wrote:
| > On 28Apr2010 22:03, Daniel Fetchinson  wrote:
| > | > Any idea how I can replace words in a html file? Meaning only the
| > | > content will get replace while the html tags, javascript, & css are
| > | > remain untouch.
[...]
| > The only way to get this right is to parse the file, then walk the doc
| > tree enditing only the text parts.
| >
| > The BeautifulSoup module (3rd party, but a single .py file and trivial to
| > fetch and use, though it has some dependencies) does a good job of this,
| > coping even with typical not quite right HTML. It gives you a parse
| > tree you can easily walk, and you can modify it in place and write it
| > straight back out.
| 
| Thanks for all your input. Cameron Simpson get the idea of what I am
| trying to do. I've been looking at beautiful soup so far I don't know
| how to perform search and replace within it.

Well the BeautifulSoup web page helped me:
  http://www.crummy.com/software/BeautifulSoup/documentation.html

Here's a function from a script I wrote to bulk edit a web site. I was
replacing OBJECT and EMBED nodes with modern versions:

  def recurse(node):
global didmod
for O in node.contents:
  if isinstance(O,Tag):
for attr in 'src', 'href':
  if attr in O:
rurl=O[attr]
rurlpath=pathwrt(rurl,SRCPATH)
if not os.path.exists(rurlpath):
  print >>sys.stderr, "%s: MISSING: %s" % (SRCPATH, rurlpath,)
O2=None
if O.name == "object":
  O2, SUBOBJ = fixmsobj(O)
elif O.name == "embed":
  O2, SUBOBJ = fixembed(O)
if O2 is not None:
  O.replaceWith(O2)
  SUBOBJ.replaceWith(O)
  ##print >>sys.stderr, "%s: update: new OBJECT: %s" % (SRCPATH, 
str(O2), )
  didmod=True
  continue
recurse(O)

but you have only to change it a little to modify things that aren't Tag
objects. The calling end looks like this:

  with open(SRCPATH) as srcfp:
srctext = srcfp.read()
  SOUP = BeautifulSoup(srctext)
  didmod = False# icky global set by recurse()
  recurse(SOUP)
  if didmod:
srctext = str(SOUP)

If didmod becomes True we recompute srctext and resave the file (or save it
to a copy).

Cheers,
-- 
Cameron Simpson  DoD#743
http://www.cskk.ezoshosting.com/cs/

Democracy is the theory that the people know what they want, and deserve to
get it good and hard.   - H.L. Mencken
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Performance of list.index - how to speed up a silly algorithm?

2010-04-29 Thread MRAB

Laszlo Nagy wrote:

I have some ten thousand rows in a table. E.g.

columns = ["color","size","weight","value"]
rows = [
[ "Yellow", "Big", 2, 4 ],
[ "Blue", "Big", 3, -4 ],
[ "Blue", "Small", 10, 55 ],
...
]

Some columns are dimensions, others are measures. I want to convert this 
to an indexed version, that looks like this:


dimension_names = ["color","size"] # List of dimension names
dimension_cols = [0,1] # Column indexes for dimension values
dimension_values = { # Dimension value occurences for each dimension
0: ["Yellow","Blue",],
1: ["Big","Small",...],
}
measure_names = ["weight","value"] # List of measure names
measure_cols = [2,3] # List of measure columns
facts = [ # Facts, containing tuples of (dimension_value_incides, 
measure_values )

( (0,0) , (2,4) ),
( (1,0) , (3,-4) ),
( (1,1) , (10,55) ),
...
]

This is how I try to convert to the indexed version:

#1. Iterate over all rows, and collect possible dimension values.

cnt = 0
for row in iterator_factory():
cnt += 1
for dimension_idx,col_idx in enumerate(dimension_cols):
dimension_values[colidx].append(row[cold_idx])
if cnt%1:
dimension_values[colidx] = list(set(dimension_values[colidx]))

#2. Index facts by dimension values

facts = []
for row in iterator_factory():
dv = []
for dimension_idx,col_idx in enumerate(dimension_cols):
dv.append( dimension_values[col_idx].index(row[col_idx]) ) # 
THIS IS THE PROBLEMATIC LINE!

mv = [ row[col_idx] for col_idx in measure_cols ]
facts.append( dv,mv )

(In reality, rows and facts are not stored in memory, because there can 
be 100 000+ facts. I did not want to bore you with the full source code.)


And finally, here is my problem. If a dimension has many possible 
values, then the list.index() code above slows down eveything. In my 
test case, the problematic dimension had about 36 000 different values, 
and the number of rows was about 60 000. Calling index() on a list of 36 
000 values, times 60 000, is too slow.


Test performance was 262 rows/sec. If I use dv.append(0) instead of " 
dv.append( dimension_values[col_idx].index(row[col_idx]) ) " then it 
goes up to 11520 rows/sec. If I exclude the problematic dimension, and 
only leave the others (with 1000 or less values) then goes up to 3000 
rows/sec.


Maybe this should be implemented in C. But I believe that the algorithm 
itself must be wrong (regardless of the language). I really think that 
I'm doing something wrong. Looks like my algorithm's processing time is 
not linear to the number of rows. Not even log(n)*n. There should be a 
more effective way to do this. But how?


I had the idea of sorting the rows by a given dimension. Then it would 
be obvious to speed up the indexing part - for that dimension. PROBABLY 
sorting all rows would be faster than calling list.index() for each row. 
But... it does not seem very efficient either. What if I have 1 million 
rows and 10 dimensions? Do I sort 1 million rows on the disk 10 times? 
Some of you might have ran into the same problem before, and can tell me 
which is the most efficient way to do this.


The .index method does a linear search, checking on average 1/2 of the 
items in the list. That's why it's so slow.


In order to avoid that you could build a dict of each value in
dimension_values[col_idx] and its index in a single pass so that it
becomes a quick lookup.
--
http://mail.python.org/mailman/listinfo/python-list


Re: using python2.6 on windows without installation

2010-04-29 Thread John Yeung
On Apr 29, 4:32 pm, Terry Reedy  wrote:
>
> Try Movable Python - The Portable Python Distribution.
> www.voidspace.org.uk/python/movpy/

You could also try Portable Python, which is somewhat newer and has
2.5, 2.6, and 3.0:

  http://www.portablepython.com/

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


Re: Performance of list.index - how to speed up a silly algorithm?

2010-04-29 Thread Mensanator
On Apr 29, 5:21 pm, Laszlo Nagy  wrote:
> I have some ten thousand rows in a table. E.g.
>
> columns = ["color","size","weight","value"]
> rows = [
>      [ "Yellow", "Big", 2, 4 ],
>      [ "Blue", "Big", 3, -4 ],
>      [ "Blue", "Small", 10, 55 ],
>      ...
> ]
>
> Some columns are dimensions, others are measures. I want to convert this
> to an indexed version, that looks like this:
>
> dimension_names = ["color","size"] # List of dimension names
> dimension_cols = [0,1] # Column indexes for dimension values
> dimension_values = { # Dimension value occurences for each dimension
>      0: ["Yellow","Blue",],
>      1: ["Big","Small",...],}
>
> measure_names = ["weight","value"] # List of measure names
> measure_cols = [2,3] # List of measure columns
> facts = [ # Facts, containing tuples of (dimension_value_incides,
> measure_values )
>      ( (0,0) , (2,4) ),
>      ( (1,0) , (3,-4) ),
>      ( (1,1) , (10,55) ),
>      ...
> ]
>
> This is how I try to convert to the indexed version:
>
> #1. Iterate over all rows, and collect possible dimension values.
>
> cnt = 0
> for row in iterator_factory():
>      cnt += 1
>      for dimension_idx,col_idx in enumerate(dimension_cols):
>          dimension_values[colidx].append(row[cold_idx])
>          if cnt%1:
>              dimension_values[colidx] = list(set(dimension_values[colidx]))
>
> #2. Index facts by dimension values
>
> facts = []
> for row in iterator_factory():
>      dv = []
>      for dimension_idx,col_idx in enumerate(dimension_cols):
>          dv.append( dimension_values[col_idx].index(row[col_idx]) ) #
> THIS IS THE PROBLEMATIC LINE!
>      mv = [ row[col_idx] for col_idx in measure_cols ]
>      facts.append( dv,mv )
>
> (In reality, rows and facts are not stored in memory, because there can
> be 100 000+ facts. I did not want to bore you with the full source code.)
>
> And finally, here is my problem. If a dimension has many possible
> values, then the list.index() code above slows down eveything. In my
> test case, the problematic dimension had about 36 000 different values,
> and the number of rows was about 60 000. Calling index() on a list of 36
> 000 values, times 60 000, is too slow.
>
> Test performance was 262 rows/sec. If I use dv.append(0) instead of "
> dv.append( dimension_values[col_idx].index(row[col_idx]) ) " then it
> goes up to 11520 rows/sec. If I exclude the problematic dimension, and
> only leave the others (with 1000 or less values) then goes up to 3000
> rows/sec.
>
> Maybe this should be implemented in C. But I believe that the algorithm
> itself must be wrong (regardless of the language). I really think that
> I'm doing something wrong. Looks like my algorithm's processing time is
> not linear to the number of rows. Not even log(n)*n. There should be a
> more effective way to do this. But how?
>
> I had the idea of sorting the rows by a given dimension. Then it would
> be obvious to speed up the indexing part - for that dimension. PROBABLY
> sorting all rows would be faster than calling list.index() for each row.
> But... it does not seem very efficient either. What if I have 1 million
> rows and 10 dimensions? Do I sort 1 million rows on the disk 10 times?
> Some of you might have ran into the same problem before, and can tell me
> which is the most efficient way to do this.
>
> Thanks,

Have you considered using a SQL database? Personally, I would use
MS-Access and link it to Python via ODBC. That way, I could use
the Access drag-and-drop design tools and either

  - copy the SQL code of working query designs to Python

or

 - use the ODBC to link to said queries rather than directly
   to the raw tables

Of course, Python has SQLlight now, I just don't know SQL that well.

>
>     Laszlo

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


Re: using python2.6 on windows without installation

2010-04-29 Thread Christian Heimes

Mirko Vogt wrote:

Hey,

is there a way to use python2.6 without having used the installation
routine?

When I install python2.6 and copy over the python-directory (C:\programs
\python2.6) to another windows host and trying to execute python.exe
there, I get an error that python26.dll could not be found.

On the host where I used the installation routine, python26.dll is
stored in C:\windows\system32 which (obviously) isn't on the host where
I just copied the python directory to.

Is it possible to include python26.dll in the application folder or tell
python not to look in C:\windows\system32 for its library?


You need to include more than just python26.dll. The correct MSVCRT 
version must be shipped with your package or it has to be installed by 
your users.


Fear not, my friend! The solution for your quest is easy to come by. 
Install Python 2.6 again but this time chose "install only for me" 
instead of "for all users". With this option all necessary files land 
into one directory. As long as you have no need for fancy stuff like COM 
and Windows services you have to worry about python26.dll in Windows' 
system32 directory.


At work we run our entire application stack including Python2.6, tons of 
Python packages with extensions, a complete Java runtime environment and 
a pile of DLLs from svn. Works like a charm.


Christian

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


Re: assigning multi-line strings to variables

2010-04-29 Thread Carl Banks
On Apr 28, 11:16 am, "Alf P. Steinbach"  wrote:
> On 28.04.2010 18:54, * Lie Ryan:

> > Python have triple-quoted string when you want to include large amount
> > of text;
>
> Yes, that's been mentioned umpteen times in this thread, including the *very
> first* quoted sentence above.
>
> It's IMHO sort of needless to repeat that after quoting it, and providing yet
> another example right after quoting an example.
>
> Probably you didn't notice?


I think he repeated it just to let people know that they can get what
they want without following your adsurd advice.


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


Re: Email attachment problem

2010-04-29 Thread Alan Harris-Reid

Chris Rebert wrote:

On Thu, Apr 29, 2010 at 1:06 PM, Alan Harris-Reid
 wrote:
  

Hi there,

I want to send an email with an attachment using the following code (running
under Python 3.1, greatly simplified to show example)

  from email.mime.multipart import MIMEMultipart
  from email.mime.text import MIMEText

  msg = MIMEMultipart()
  msg['From'] = from_addr
  msg['To'] = to_addr
  msg['Subject'] = subject
  msg.attach(MIMEText(body))

  fp = open(att_file)
  att_msg = MIMEText(fp.read())
  attachment = att_msg.add_header('Content-Disposition', 'attachment',
filename=att_file)
  msg.attach(attachment)

  # set string to be sent as 3rd parameter to smptlib.SMTP.sendmail()
  send_string = msg.as_string()


The attachment object msg1 returns 'email.mime.text.MIMEText' object at
', but when the att_msg.add_header(...) line runs the result is
None, hence the program falls-over in msg.as_string() because no part of the
attachment can have a None value.  (Traceback shows "'NoneType' object has
no attribute 'get_content_maintype'" in line 118 of _dispatch in
generator.py, many levels down from msg.as_string())

Has anyone any idea what the cause of the problem might be?  Any help would
be appreciated.



.add_header() modifies the MIMEText object *in-place*; per Python
conventions, mutator methods return None; hence, attachment = None.

Try instead (untested):
att_msg.add_header('Content-Disposition', 'attachment', filename=att_file)
msg.attach(att_msg)

Cheers,
Chris
--
http://blog.rebertia.com

Hi Chris,

You are right - that does the trick.

Many thanks,
Alan

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


RE: [melbourne-pug] array matching

2010-04-29 Thread Filip
You could use dictionary of lists

 

test = {

A: [1, 3],

B: [2, 4]

}

 

print test[A]

[1, 3]

 

test[A].append(5)

 

print test[A]

[1, 3, 5]

 

Cheers,

 

Fil

  _  

From: melbourne-pug-bounces+filipz=3g.nec.com...@python.org
[mailto:melbourne-pug-bounces+filipz=3g.nec.com...@python.org] On Behalf Of
Bill Jordan
Sent: Friday, 30 April 2010 3:58 AM
To: python-...@python.org; python-list@python.org; bangpyp...@python.org;
melbourne-...@python.org; portl...@python.org
Subject: [melbourne-pug] array matching

 

Hey guys,

 

I am sorry if this is not the right list to post some questions. I have a
simple question please and would appreciate some answers as I am new to
Python.

 

I have 2 D array: test = [[A,1],[B,2],[A,3][B,4]]

I want to arrang this array in different arrays so each one will have what
is attached to. For example I want the output:

 

A =[1,3] and B=[2,4]

 

Thanks,

Bill

 

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


dll errors in compiled python program

2010-04-29 Thread Alex Hall
Hi all,
I am stumped. The compiled version of my project works on my pc, but
when I put it on a thumb drive and try it on a laptop without python
installed I get this:

Traceback (most recent call last):
  File "sw.pyw", line 3, in 
  File "modes\arm.pyc", line 4, in 
  File "dependencies\wmi1_3\wmi.pyc", line 140, in 
  File "win32com\__init__.pyc", line 5, in 
  File "win32api.pyc", line 12, in 
  File "win32api.pyc", line 10, in __load
ImportError: DLL load failed: The specified procedure could not be found.
Traceback (most recent call last):
  File "sw.pyw", line 3, in 
  File "modes\arm.pyc", line 4, in 
  File "dependencies\wmi1_3\wmi.pyc", line 140, in 
  File "win32com\__init__.pyc", line 5, in 
  File "win32api.pyc", line 12, in 
  File "win32api.pyc", line 10, in __load
ImportError: DLL load failed: The specified procedure could not be found.

It repeated it twice in the log file; that is no mistake. The compiled exe is at
http://www.gateway2soemewhere.com/sw/sw_beta.zip

Thanks in advance. I will be amazed when this finally works the way it should!!


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: assigning multi-line strings to variables

2010-04-29 Thread Alf P. Steinbach

On 30.04.2010 01:29, * Carl Banks:

On Apr 28, 11:16 am, "Alf P. Steinbach"  wrote:

On 28.04.2010 18:54, * Lie Ryan:



Python have triple-quoted string when you want to include large amount
of text;


Yes, that's been mentioned umpteen times in this thread, including the *very
first* quoted sentence above.

It's IMHO sort of needless to repeat that after quoting it, and providing yet
another example right after quoting an example.

Probably you didn't notice?



I think he repeated it just to let people know that they can get what
they want without following your adsurd advice.


Perhaps you could quote the advice that you find absurd, and explain how you 
interpret the quoted text?


My previous experience with you is that you immediately called me "insane" (and 
worse) for suggesting a solution that could work in principle and did work in 
practice for the problem posed in that thread; I think you resorted to such 
characterizations because you had stated that it was impossible.


So until you get a bit more concrete I'm interpreting your characterization 
(about what?) as just confirming & uphelding the impression you made back then.



Cheers & hth.,

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


find integers in f.readline()

2010-04-29 Thread elsa
Hi people,

I'm having a problem getting the info I need out of a file.

I've opened the file with f=open('myFile','r').

Next, I take out the first line with line=f.readline()

line looks like this:

'83927 300023_25_5_09_FL 9086 9134 F3LQ2BE01AQLXF 1 49 + 80
ZA8Z89HIB7M'

I then split it into parts with parts = line.split()

['83927', '300023_25_5_09_FL', '9086', '9134', 'F3LQ2BE01AQLXF', '1',
'49', '+', '80', 'ZA8Z89HIB7M']

Now, I need to test whether I can call int(parts[0]) or not. Some of
the lines in my file start with a value which represents and integer
(as above), while others are just strings of characters. I want to
extract just the lines like the one above, that start with an integer.
Any suggestions?

Thanks,

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


  1   2   >