Re: Extending classes __init__behavior for newbies

2011-02-15 Thread Duncan Booth
Westley Martínez  wrote:

>> In the end i promise they will respect you more for your honesty. And
>> it will not be a respect forged from fear, no, it will be something
>> greater! A respect forged from collaboration. A respect of comrades in
>> arms. This is the future i bring to c.l.py!
> HEIL DER FUHRER!

Godwin was right. You lose.

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


Re: lint warnings

2011-02-15 Thread Andrea Crotti

Il giorno 15/feb/2011, alle ore 04.10, Ben Finney ha scritto:

> Andrea Crotti  writes:
> The ‘map’ builtin is deprecated; using a list comprehension is neater
> and more efficient.

Ok well it depends,
map(int, biglist)
is better than:
[int(x) for x in biglist]
at least for me.

Efficiency is probably not a big issue apparently, and it's really not important
until I see that this is a bottleneck.

> 
> It makes the code unnecessarily ambiguous; the person reading the code
> can't tell that it's a relative import.

Yes but what if I move those two files (parameter and the importing module)
away, the import will continue to work if it's not relative to the upper 
directory.

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


Re: generating .zip including __main__.py file in top root using distutils

2011-02-15 Thread alain.spineux
I answer myself to put my question on top of the list again.


On Feb 12, 7:47 pm, aspineux  wrote:
> Python 2.6 can run a zip file, searching for __main__.py in the root
> of the zip archive and running it.
> How can I create such an archive using distutils (and not
> setuptools) ?
>
> If I use
> # python setup.py bdist --format=zip
> I get a "dumb" zip file with a deep tree structure from "/" and I
> cannot put the __main__.py in the root archive
>
> If I use
> # python setup.py sdist --format=zip
> I get a more compact tree. But the tree start bellow directory named
> "mypackage-version",
>
> my-package-1.0/
>   setup.py
>   __main__.py
>   
>
> If I use setuptool, generating .EGG I get exacly what I want !
> But I read it is bad to use setuptool and EGGs since pip is
> available :-)
>
> I was hopping distutils have been updated when adding the zip trick,
> but I didn't find the trick.
>
> Help

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


interleave string

2011-02-15 Thread Andrea Crotti
Just a curiosity not a real problem, I want to pass from a string like

xxaabbddee
to
xx:aa:bb:dd:ee

so every two characters insert a ":".
At the moment I have this ugly inliner
interleaved = ':'.join(orig[x:x+2] for x in range(0, len(orig), 2))

but also something like this would work
[''.join((x,y)) for x, y in zip(orig[0::2], orig[1::2])]

any other ideas?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: interleave string

2011-02-15 Thread Wojciech Muła
On Tue, 15 Feb 2011 10:53:56 +0100 Andrea Crotti
 wrote:

> Just a curiosity not a real problem, I want to pass from a string like
> 
> xxaabbddee
> to
> xx:aa:bb:dd:ee
> 
> so every two characters insert a ":".
> At the moment I have this ugly inliner
> interleaved = ':'.join(orig[x:x+2] for x in range(0,
> len(orig), 2))
> 
> but also something like this would work
> [''.join((x,y)) for x, y in zip(orig[0::2], orig[1::2])]
> 
> any other ideas?

import re

s = 'xxaabbddee'
m = re.compile("(..)")
s1 = m.sub("\\1:", s)[:-1]

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


Re: interleave string

2011-02-15 Thread Valentin Baciu
Hello,

How about this:

>>> str = 'xxaabbddee'
>>> ':'.join(map(''.join, zip(str[::2], str[1::2])))

In my example, it should not matter that the letters are repeating.

On Tue, Feb 15, 2011 at 11:53 AM, Andrea Crotti
wrote:

> Just a curiosity not a real problem, I want to pass from a string like
>
> xxaabbddee
> to
> xx:aa:bb:dd:ee
>
> so every two characters insert a ":".
> At the moment I have this ugly inliner
>interleaved = ':'.join(orig[x:x+2] for x in range(0, len(orig), 2))
>
> but also something like this would work
> [''.join((x,y)) for x, y in zip(orig[0::2], orig[1::2])]
>
> any other ideas?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Missing SIGCHLD

2011-02-15 Thread Dinh
Hi,

I currently build a process management system which is able to fork child
processes (fork()) and keep them alive (waitpid() ).

 if pid in self.current_workers:
 os.waitpid(pid, 0)

If a child process dies, it should trigger a SIGCHLD signal and a handler is
installed to catch the signal and start a new child process. The code is
nothing special, just can be seen in any Python tutorial you can find on the
net.

signal.signal(signal.SIGCHLD, self.restart_child_process)
signal.signal(signal.SIGHUP, self.handle) # reload
signal.signal(signal.SIGINT, self.handle)
signal.signal(signal.SIGTERM, self.handle)
signal.signal(signal.SIGQUIT, self.handle)

However, this code does not always work as expected. Most of the time, it
works. When a child process exits, the master process receives a SIGCHLD and
restart_child_process() method is invoked automatically to start a new child
process. But the problem is that sometimes, I know a child process exits due
to an unexpected exception (via log file) but it seems that master process
does not know about it. No SIGCHLD and so restart_child_process() is not
triggered. Therefore, no new child process is forked.

Could you please kindly tell me why this happens? Is there any special code
that need being installed to ensure that every dead child will be informed
correctly?

Mac OSX 10.6
Python 2.6.6

Thanks


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


Re: Question on Creating exe file with py2exe

2011-02-15 Thread aspineux
On 13 fév, 06:20, joy99  wrote:
> On Feb 13, 1:29 am, aspineux  wrote:
>
>
>
>
>
> > Hi
>
> > I'm releasing a .exe made with py2exe myself an got this problem too.
> > 99% of the time the required DLL is already installed by another
> > application and you don't need to care about it.
> > The 1% is about empty or fresh windows install (server most of the
> > time)
> > For them, I provide a link to the M$ vcredist and a warning in my
> > download page asking them to install it them self.
>
> > Take a look at my site for the vcredist link 
> > :http://www.magikmon.com/mksbackup/download.en.html
>
> > Regards
>
> > Alain
>
> > On Feb 12, 9:06 pm, joy99  wrote:
>
> > > Dear Room,
>
> > > I am using Windows XP (SP2) and a Python Version "Python 2.6.5
> > > (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on
> > > win32".
>
> > > I was looking to create exe files. Reviewing various posts here, I
> > > felt py2exe may be the best thing I can opt for.
>
> > > But for Python2.6 I found the following note in the py2exe tutorial:
> > > "For Python 2.6, the DLL you need is called MSVCR90.dll. Py2exe is not
> > > able to automatically include this DLL in your dist directory, so you
> > > must provide it yourself.
>
> > > To complicate things, there is more than one version of this DLL in
> > > existance, each with the same filename. You need the same version that
> > > the Python interpreter was compiled with, which is version
> > > 9.0.21022.8. Through the remainder of these instructions, hover your
> > > mouse over the dll file (or the vcredist_x86.exe installer executable)
> > > to confirm which version you've got. "
>
> > > My questions are:
> > > (i) From where I can download "MSVCR90.dll" ? Is there any trusted
> > > site?
> > > (ii) How to install the same?
> > > (iii) Would py2exe work fine if I install it?
> > > (iv) Is there any other exe creating program which does not have all
> > > these problems?
>
> > > As it is a room for expert python developers, I felt to ask you, if
> > > any one can kindly find some time to resolve my query, I would be
> > > honored.
>
> > > Thanks in Advance,
> > > Best Regards,
> > > Subhabrata.
>
> Hi Alain,
> Thank you for your product information. But, with my problem
> installation is okay.
> The first two steps:
> "from distutils.core import setup
>  import py2exe"
> but as I am giving
> "setup(console=['file.py'])"
>
> the setup file is not being generated.

What do you mean ? Do you expect the 3 lines above will generate a
setup.py file ?
You are wrong you must create your setup.py file yourself, and this
file must contains
the 3 lines above, and more a lot more ..
Then you will run

 python setup.py py2exe

to generate your .exe file


> It is giving some error
> messages.
> Any suggestions?
> Best Regards,
> Subhabrata.- Masquer le texte des messages précédents -
>
> - Afficher le texte des messages précédents -

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


[ANN] Data Plotting Library DISLIN 10.1

2011-02-15 Thread Helmut Michels

Dear Python users,

I am pleased to announce version 10.1 of the data plotting software
DISLIN.

DISLIN is a high-level and easy to use plotting library for
displaying data as curves, bar graphs, pie charts, 3D-colour plots,
surfaces, contours and maps. Several output formats are supported
such as X11, VGA, PostScript, PDF, CGM, WMF, HPGL, TIFF, GIF, PNG,
BMP and SVG.

The software is available for the most C, Fortran 77 and Fortran 90/95
compilers. Plotting extensions for the interpreting languages Perl,
Python and Java are also supported.

DISLIN distributions can be copied from the DISLIN home page

 http://www.dislin.de

and via FTP from the server

 ftp://ftp.gwdg.de/pub/grafik/dislin

All DISLIN distributions are free for non-commercial use. Licenses
for commercial use are available from the site http://www.dislin.de.

 ---
  Helmut Michels
  Max Planck Institute for
  Solar System Research  Phone: +49 5556 979-334
  Max-Planck-Str. 2  Fax  : +49 5556 979-240
  D-37191 Katlenburg-Lindau  Mail : mich...@mps.mpg.de
--
http://mail.python.org/mailman/listinfo/python-list


Re: interleave string

2011-02-15 Thread Alex Willmer
On Feb 15, 10:09 am, Wojciech Muła
 wrote:
> import re
>
> s = 'xxaabbddee'
> m = re.compile("(..)")
> s1 = m.sub("\\1:", s)[:-1]

One can modify this slightly:

s = 'xxaabbddee'
m = re.compile('..')
s1 = ':'.join(m.findall(s))

Depending on one's taste this could be clearer. The more general
answer, from the itertools docs:

from itertools import izip_longest

def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)

s2 = ':'.join(''.join(pair) for pair in grouper(2, s, ''))

Note that this behaves differently to the previous solutions, for
sequences with an odd length.
-- 
http://mail.python.org/mailman/listinfo/python-list


lint warnings

2011-02-15 Thread Gerald Britton
I find:

map(func, iterable)

to be "neater" than:

[func(item) for item in iterable]

If nothing else, the "map" version is shorter.  More importantly, in
the 2.x series (which I am often limited to for compatibility
reasons), the variable used in the list comprehension leaks to the
following code:

$ python
Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> del item
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'item' is not defined
>>> [int(item) for item in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> item
9
>>>

which can cause hard-to-find bugs.  Fortunately this has been corrected in 3.x.

Also, as already shown, the map version is faster. BTW, if you like:

[item for item in iterable if predicate(item)]

you can use:

filter(predicate, item)

I find the latter neater for the same reasons as above

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


Re: lint warnings

2011-02-15 Thread Duncan Booth
Gerald Britton  wrote:

> I find:
> 
> map(func, iterable)
> 
> to be "neater" than:
> 
> [func(item) for item in iterable]
> 
> If nothing else, the "map" version is shorter.

That's only true if you wanted to call an existing function. If you wanted 
to do something involving a more complex expression that you can write 
inline then the list comprehension is shorter.


> Also, as already shown, the map version is faster.

In most cases the list comprehension is faster. Try timing it.

C:\Python27>python.exe lib\timeit.py -s "def double(x): return x*2" -s 
"data=range(1)" "map(double, data)"
1000 loops, best of 3: 1.82 msec per loop

C:\Python27>python.exe lib\timeit.py -s "def double(x): return x*2" -s 
"data=range(1)" "[x*2 for x in data]"
1000 loops, best of 3: 879 usec per loop

map is only likely to be faster if you wanted to call a function in both cases. 
If you have an expression that can be inlined you save the function call 
overhead with the list comprehension.

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


Re: Extending classes __init__behavior for newbies

2011-02-15 Thread Westley Martínez
On Tue, 2011-02-15 at 08:36 +, Duncan Booth wrote:
> Westley Martínez  wrote:
> 
> >> In the end i promise they will respect you more for your honesty. And
> >> it will not be a respect forged from fear, no, it will be something
> >> greater! A respect forged from collaboration. A respect of comrades in
> >> arms. This is the future i bring to c.l.py!
> > HEIL DER FUHRER!
> 
> Godwin was right. You lose.
> 
> -- 
> Duncan Booth http://kupuguy.blogspot.com
Who's more trollish? The troll, or the troll who follows him?

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


Re: interleave string

2011-02-15 Thread MRAB

On 15/02/2011 09:53, Andrea Crotti wrote:

Just a curiosity not a real problem, I want to pass from a string like

xxaabbddee
to
xx:aa:bb:dd:ee

so every two characters insert a ":".
At the moment I have this ugly inliner
 interleaved = ':'.join(orig[x:x+2] for x in range(0, len(orig), 2))

but also something like this would work
[''.join((x,y)) for x, y in zip(orig[0::2], orig[1::2])]

any other ideas?


interleaved = "{}{}:{}{}:{}{}:{}{}".format(*orig)
--
http://mail.python.org/mailman/listinfo/python-list


How to inspect a variable (sys.modules) for changes in the execution of a program?

2011-02-15 Thread Jorge Vargas
Hello,

I have the following situation. In a big project that involves many
dependencies (and sadly some sys.module hacks) we have a bug, and it
will really help if i could monitor all changes made to that variable.
Is there a way to trace those changes ?
-- 
http://mail.python.org/mailman/listinfo/python-list


lint warnings

2011-02-15 Thread Gerald Britton
>> I find:
>>
>> map(func, iterable)
>>
>> to be "neater" than:
>>
>> [func(item) for item in iterable]
>>
>> If nothing else, the "map" version is shorter.

>That's only true if you wanted to call an existing function. If you wanted
>to do something involving a more complex expression that you can write
>inline then the list comprehension is shorter.

not necessarily, no.

>>> [-i if i < 0 else i for i in range(-10,0)]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

vs.

>>> map(abs, range(-10,0))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]



> Also, as already shown, the map version is faster.

>In most cases the list comprehension is faster. Try timing it.

I have as have many others (including the previous poster who provided timings)

>C:\Python27>python.exe lib\timeit.py -s "def double(x): return x*2" -s 
>"data=range(1)" "map(double, data)"
>1000 loops, best of 3: 1.82 msec per loop

C:\Python27>python.exe lib\timeit.py -s "def double(x): return x*2" -s
"data=range(1)" "[x*2 for x in data]"
1000 loops, best of 3: 879 usec per loop

granted, but not on topic here.  we're talking about map vs list comps
when you want to use a function.

>map is only likely to be faster if you wanted to call a function in both cases.

Which is exactly the point.

>f you have an expression that can be inlined you save the function call
>overhead with the list comprehension.

Of course, but that's not the point.


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


[ANN] Oktest 0.8.0 released - a new-style testing library

2011-02-15 Thread Makoto Kuwata
I released Oktest 0.8.0.
http://pypi.python.org/pypi/Oktest/
http://packages.python.org/Oktest/

Oktest is a new-style testing library for Python.
::

from oktest import ok, NG
ok (x) > 0 # same as assert_(x > 0)
ok (s) == 'foo'# same as assertEqual(s, 'foo')
ok (s) != 'foo'# same as assertNotEqual(s, 'foo')
ok (f).raises(ValueError)  # same as assertRaises(ValueError, f)
ok (u'foo').is_a(unicode)  # same as assert_(isinstance(u'foo', unicode))
NG (u'foo').is_a(int)  # same as assert_(not isinstance(u'foo', int))
ok ('A.txt').is_file() # same as assert_(os.path.isfile('A.txt'))
NG ('A.txt').is_dir()  # same as assert_(not os.path.isdir('A.txt'))

See http://packages.python.org/Oktest/ for details.

NOTICE!! Oktest is a young project and specification may change in the future.


Enhancements and Changes


* add ``NG()`` which is same as not_ok().

* enhanced to proive egg files for Python 3.

* enhanced to support assertion method chaining. ::

ok ("sos".upper()).is_a(str).matches(r'^[A-Z]+$') == "SOS"

* ``ok().matches()`` can take flag parameter which is passed to re.compile().

ok ("\nSOS\n").matches(r'^[A-Z]+$', re.M)
## same as:
#ok("\nSOS\n").matches(r.compile(r'^[A-Z]$', re.M))

* enhance helper methods to be available without with-statement.
  (this is necessary for Python 2.4 which is default version on CentOS.)

from oktest.helper import chdir

def fn():
  ok (os.getcwd()) == "/tmp"
chdir("/tmp").run(fn)
## this is same as:
#with chdir("/tmp"):
#  ok (os.getcwd()) == "/tmp"

from oktest.dummy import dummy_file

def fn():
  ok ("A.txt").is_file()
  ok (open("A.txt").read()) == "SOS"
dummy_file("A.txt", "SOS").run(fun)
## this is same as:
#with dummy_file("A.txt", "SOS"):
#  ok (open("A.txt").read()) == "SOS"

* ``spec()`` now checks environment variable $SPEC.
  This is useful to filter test cases.

## test script
from oktest import oktest, run
class StrTest(object):
  def test_upper(self):
if spec("returns upper case string"):
  ok ("sos".upper()) == "SOS"
if spec("doesn't change non-alphabetics"):
  ok ("sos123<>".upper()) == "SOS123<>"
if __name__ == "__main__":
  run()

## terminal
$ SPEC="returns upper case string" python test1.py

* fix ``oktest.run()`` to print correct traceback if ok() is called from
  nested function.

* fix content of README.txt.


--
regards,
makoto kuwata
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Non-linear regression help in Python

2011-02-15 Thread sturlamolden
On 15 Feb, 05:24, Akand Islam  wrote:

> Dear Sturlamolden,
> Thanks for reply. I will follow-up if I need further assistance.
>
> -- Akand

You should rather use the SciPy user mailing list than
comp.lang.python for this.

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


newbie question about PYTHONPATH

2011-02-15 Thread Tim Hanson
I am to the point in _Learning_Python_  where functions are introduced.

I decided to experiment by putting a function into  a file and importing it 
into Idle.  Of course, Idle couldn't find it, so I executed the following 
command in Bash:

PYTHONPATH=/home/foo/prog/learning_python
export PYTHONPATH
env | grep PYTHONPATH

~$PYTHONPATH=/home/foo/prog/learning_python

Idle still won't find it.  I'm doing something wrong?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie question about PYTHONPATH

2011-02-15 Thread Panupat Chongstitwattana
I think the command line should look something along this line

export PYTHONPATH=$HOME/foo/prog/learning_python/:

with a colon at the end.

On Wed, Feb 16, 2011 at 12:49 AM, Tim Hanson  wrote:
> I am to the point in _Learning_Python_  where functions are introduced.
>
> I decided to experiment by putting a function into  a file and importing it
> into Idle.  Of course, Idle couldn't find it, so I executed the following
> command in Bash:
>
> PYTHONPATH=/home/foo/prog/learning_python
> export PYTHONPATH
> env | grep PYTHONPATH
>
> ~$PYTHONPATH=/home/foo/prog/learning_python
>
> Idle still won't find it.  I'm doing something wrong?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to inspect a variable (sys.modules) for changes in the execution of a program?

2011-02-15 Thread Chris Rebert
On Tue, Feb 15, 2011 at 7:17 AM, Jorge Vargas  wrote:
> Hello,
>
> I have the following situation. In a big project that involves many
> dependencies (and sadly some sys.module hacks) we have a bug, and it
> will really help if i could monitor all changes made to that variable.
> Is there a way to trace those changes ?

Is the variable's value of a mutable or immutable type? What is the
variable's scope (e.g. module-level global, or object attribute)? Is
the variable subject to getting rebound to an entirely new
value/object?

The answers to these questions will determine how much work will be
required to trace "changes" to the variable. I know of no built-in way
to directly do such a thing, but the underlying functionality
necessary to implement such a feature (e.g. sys.settrace,
__getattribute__, __setattr__) does exist.

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


Re: Missing SIGCHLD

2011-02-15 Thread Dan Stromberg
On Tue, Feb 15, 2011 at 2:57 AM, Dinh  wrote:
> Hi,
>
> I currently build a process management system which is able to fork child
> processes (fork()) and keep them alive (waitpid() ).
>
>  if pid in self.current_workers:
>  os.waitpid(pid, 0)
>
> If a child process dies, it should trigger a SIGCHLD signal and a handler is
> installed to catch the signal and start a new child process. The code is
> nothing special, just can be seen in any Python tutorial you can find on the
> net.
>
>     signal.signal(signal.SIGCHLD, self.restart_child_process)
>     signal.signal(signal.SIGHUP, self.handle) # reload
>     signal.signal(signal.SIGINT, self.handle)
>     signal.signal(signal.SIGTERM, self.handle)
>     signal.signal(signal.SIGQUIT, self.handle)
>
> However, this code does not always work as expected. Most of the time, it
> works. When a child process exits, the master process receives a SIGCHLD and
> restart_child_process() method is invoked automatically to start a new child
> process. But the problem is that sometimes, I know a child process exits due
> to an unexpected exception (via log file) but it seems that master process
> does not know about it. No SIGCHLD and so restart_child_process() is not
> triggered. Therefore, no new child process is forked.
>
> Could you please kindly tell me why this happens? Is there any special code
> that need being installed to ensure that every dead child will be informed
> correctly?
>
> Mac OSX 10.6
> Python 2.6.6

Hi Dinh.

I've done no Mac OS/X programming, but I've done Python and *ix
signals some - so I'm going to try to help you, but it'll be kind of
stabbing in the dark.

*ix signals have historically been rather unreliable and troublesome
when used heavily.

There are BSD signals, SysV signals, and POSIX signals - they all try
to solve the problems in different ways.  Oh, and Linux has a way of
doing signals using file descriptors that apparently helps quite a
bit.  I'm guessing your Mac will have available BSD and maybe POSIX
signals, but you might check on that.

You might try using ktrace on your Mac to see if any SIGCHLD signals
are getting lost (it definitely happens in some scenarios), and
hopefully, which kind of (C level) signal API CPython is using on your
Mac also.

You might also make sure your SIGCHLD signal handler is not just
waitpid'ing once per invocation, but rather doing a nonblocking
waitpid in a loop until no process is found, in case signals are lost
(especially if/when signals occur during signal handler processing).

If the loop in your signal handler doesn't help (enough), you could
also try using a nonblocking waitpid in a SIGALARM handler in addition
to your SIGCHLD handler.

Some signal API's want you to reenable the signal as your first action
in your signal handler to shorten a race window.  Hopefully Mac OS/X
doesn't need this, but you might check on it.

BTW, CPython signals and CPython threads don't play very nicely
together; if you're combining them, you might want to study up on
this.

Oh, also, signals in CPython will tend to cause system calls to return
without completing, and giving an EINTR in errno, and not all CPython
modules will understand what to do with that.  :(  Sadly, many
application programmers tend to ignore the EINTR possibility.

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


file find skips first letter

2011-02-15 Thread Wanderer
I'm using code

def getFiles(self, fileBase):
"""return a list of the filenames in a director containing a
base word
"""

allFiles = os.listdir(self.resultDir)
baseFiles = []
for f in allFiles:
if f.find(fileBase) > 0:
baseFiles.append(f)

return baseFiles

but the code can't find files with fileBase in it if the fileBase
starts the filename.

if the filenames are rnoise##.tif and fileBase is "rnoise" the file
won't be found. If fileBase is "noise" the files will be found.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: file find skips first letter

2011-02-15 Thread Mel
Wanderer wrote:

> I'm using code
> 
> def getFiles(self, fileBase):
> """return a list of the filenames in a director containing a
> base word
> """
> 
> allFiles = os.listdir(self.resultDir)
> baseFiles = []
> for f in allFiles:
> if f.find(fileBase) > 0:
> baseFiles.append(f)
> 
> return baseFiles
> 
> but the code can't find files with fileBase in it if the fileBase
> starts the filename.
> 
> if the filenames are rnoise##.tif and fileBase is "rnoise" the file
> won't be found. If fileBase is "noise" the files will be found.

(untested) Try

if f.find(fileBase) > -1:


Mel.

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


Re: file find skips first letter

2011-02-15 Thread Alexander Kapps

On 15.02.2011 19:32, Wanderer wrote:

I'm using code

 def getFiles(self, fileBase):
 """return a list of the filenames in a director containing a
base word
 """

 allFiles = os.listdir(self.resultDir)
 baseFiles = []
 for f in allFiles:
 if f.find(fileBase)>  0:
 baseFiles.append(f)

 return baseFiles

but the code can't find files with fileBase in it if the fileBase
starts the filename.

if the filenames are rnoise##.tif and fileBase is "rnoise" the file
won't be found. If fileBase is "noise" the files will be found.


str.find() returns the index to the left-most occurrence or -1 if 
the substring is not found. So, if the file name starts with 
fileBase, find() return 0 which you filter out with your test 
f.find(fileBase)> 0.


Either use f.find(fileBase) >= 0 or better:

baseFiles = []
for f in allFiles:
if fileBase in f:
baseFiles.append(f)


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


Re: file find skips first letter

2011-02-15 Thread Miki Tebeka
> def getFiles(self, fileBase):
> """return a list of the filenames in a director containing a
> base word
> """
> ...
Have a look at the glob module, it does what you want.

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


Re: newbie question about PYTHONPATH

2011-02-15 Thread Alexander Kapps

On 15.02.2011 19:12, Panupat Chongstitwattana wrote:

Panupat, please don't top-post, it messes the the natural order of 
the discussion. Thanks.



I think the command line should look something along this line

export PYTHONPATH=$HOME/foo/prog/learning_python/:

with a colon at the end.


Nope, the colon is only needed as a delimiter if you give more than 
one file.



On Wed, Feb 16, 2011 at 12:49 AM, Tim Hanson  wrote:

I am to the point in _Learning_Python_  where functions are introduced.

I decided to experiment by putting a function into  a file and importing it
into Idle.  Of course, Idle couldn't find it, so I executed the following
command in Bash:

PYTHONPATH=/home/foo/prog/learning_python
export PYTHONPATH
env | grep PYTHONPATH

~$PYTHONPATH=/home/foo/prog/learning_python

Idle still won't find it.  I'm doing something wrong?


$ export PYTHONPATH=~/src/python/
$ idle

works fine here. Where are you setting PYTHONPATH and from where do 
you run idle? If you set it in a terminal window, but run idle from 
a Desktop menu it won't work as exporting environment variables does 
only affect sub-processes. You might want to set PYTHONPATH in your 
~/.bash_profile and then re-login.


Also, how do you name your file? A Python module must end in .py


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


Re: file find skips first letter

2011-02-15 Thread MRAB

On 15/02/2011 18:48, Mel wrote:

Wanderer wrote:


I'm using code

 def getFiles(self, fileBase):
 """return a list of the filenames in a director containing a
base word
 """

 allFiles = os.listdir(self.resultDir)
 baseFiles = []
 for f in allFiles:
 if f.find(fileBase)>  0:
 baseFiles.append(f)

 return baseFiles

but the code can't find files with fileBase in it if the fileBase
starts the filename.

if the filenames are rnoise##.tif and fileBase is "rnoise" the file
won't be found. If fileBase is "noise" the files will be found.


(untested) Try

if f.find(fileBase)>  -1:


Python is a 0-based language, so if fileBase is at the start of f then
the result is 0. If fileBase isn't in f then the result is -1.

An alternative is:

if fileBase in f:
--
http://mail.python.org/mailman/listinfo/python-list


Displaying SVG in tkinter using cairo and rsvg

2011-02-15 Thread Martin P. Hellwig

Hi all,

Information on using tkinter for displaying an svg image seems a bit low 
spread on the Internet. I recently played around with pygame and svg and 
realized, hold on this can be done with tk too. So I thought I post a 
little example for future generations :-) (and also have stored at 
http://dcuktec.googlecode.com/hg/source/examples/cairo_rsvg_tkinter.py).


So here it is if you are interested:

---
#! /usr/bin/env python
"""
Tkinter example for displaying SVG in a PhotoImage class using cairo and 
rsvg.
Note that this is relatively slow, this is mainly due to converting the 
cairo

surface data to the appropriate rgb values and putting each pixel in the
PhotoImage class.
"""
import cairo
import rsvg
# I had a bit of trouble finding the rsvg python wrapper, turns out it 
is part
# of the GnomePythonDesktop package, windows users are even less 
supported see:
# http://cairographics.org/cairo_rsvg_and_python_in_windows/ to get it 
working.

import Tkinter

def _alpha_blending(rgba, back):
"Return a rgb tuple composed from a rgba and back(ground) tuple/list."
paired = zip(rgba[:-1], back)
alpha = rgba[-1]
tmp = list()
for upper, lower in paired:
blend = (((255 - alpha) * lower) + (alpha * upper)) / 255
tmp.append(blend)

return(tuple(tmp))

def convert(bgra_buffer, width, height):
"Convert bgra buffer to photoimage put"
idx = 0
end = len(bgra_buffer)
arguments = list()

while idx < end:
rgba = (ord(bgra_buffer[idx + 2]),
ord(bgra_buffer[idx + 1]),
ord(bgra_buffer[idx + 0]),
ord(bgra_buffer[idx + 3]))
back = (255, 255, 255)
rgb = _alpha_blending(rgba, back)
arguments += rgb
idx += 4

template = ' '.join(height *['{%s}' % (' 
'.join(width*["#%02x%02x%02x"]))])

return(template % tuple(arguments))


def photoimage_from_svg(file_path_name):
"Return a Tkinter.PhotoImage with the content set to the rendered 
SVG."

svg = rsvg.Handle(file=file_path_name)
width, height = svg.get_dimension_data()[:2]
surface = cairo.ImageSurface(cairo.FORMAT_RGB24, int(width), 
int(height))

context = cairo.Context(surface)
svg.render_cairo(context)
image = Tkinter.PhotoImage(width=width, height=height)
data = convert(surface.get_data(), width, height)
image.put(data)
return(image)

if __name__ == '__main__':
SVG = """
http://www.w3.org/1999/02/22-rdf-syntax-ns#";
   xmlns:svg="http://www.w3.org/2000/svg";
   xmlns="http://www.w3.org/2000/svg";
   id="test" version="1.1" width="900" height="600">
   
   
   
   
   
   
"""
import os, tempfile
#
PATH = tempfile.mkstemp()[1]
OPEN = open(PATH, 'w')
OPEN.writelines(SVG)
OPEN.close()
ROOT = Tkinter.Tk()
#
IMAGE = photoimage_from_svg(PATH)
#
os.remove(PATH)
BUTTON = Tkinter.Button(ROOT, image=IMAGE)
BUTTON._photoimage = IMAGE
BUTTON.grid()
Tkinter.mainloop()
---
--
mph
--
http://mail.python.org/mailman/listinfo/python-list


Problem w/ MySQLdb

2011-02-15 Thread Victor Subervi
Hi;
I have a function that calls the following class:

#!/usr/bin/python

import sys,os
sys.path.append(os.getcwd())
import MySQLdb
from login import login
import re, string

def buildTableColorShortOptions():
  user, passwd, db, host = login()
  database = MySQLdb.connect(host, user, passwd, db)
  cursor = database.cursor()
  cursor.execute('''create table if not exists colorShortOptions (
Color varchar(40) not null,
Value bool not null default '0'
) engine=innodb''')
  cursor.execute("insert into colorShortOptions (Color) values ('indigo')")
  cursor.execute("insert into colorShortOptions (Color) values ('maroon')")
  cursor.execute("insert into colorShortOptions (Color) values ('violet')")
  cursor.execute("insert into colorShortOptions (Color) values ('tan')")
  cursor.execute("insert into colorShortOptions (Color) values ('lime')")
  cursor.execute("insert into colorShortOptions (Color) values ('blue')")
  cursor.execute("insert into colorShortOptions (Color) values ('fuchsia')")
  cursor.execute("insert into colorShortOptions (Color) values ('cobalt
blue')")
  cursor.execute("insert into colorShortOptions (Color) values ('black')")
  cursor.execute("insert into colorShortOptions (Color) values ('rose
pink')")
  cursor.execute("insert into colorShortOptions (Color) values ('air force
blue')")
  cursor.execute("insert into colorShortOptions (Color) values ('orange')")
  cursor.execute("insert into colorShortOptions (Color) values ('white')")
  cursor.execute("insert into colorShortOptions (Color) values ('red')")
  cursor.execute("insert into colorShortOptions (Color) values ('yellow
green')")
  cursor.execute("insert into colorShortOptions (Color) values ('navy
blue')")
  cursor.execute("insert into colorShortOptions (Color) values ('salmon')")
  cursor.execute("insert into colorShortOptions (Color) values ('yellow')")
  cursor.execute("insert into colorShortOptions (Color) values ('olive')")
  cursor.execute("insert into colorShortOptions (Color) values ('sky
blue')")
  cursor.execute("insert into colorShortOptions (Color) values ('silver')")
  cursor.execute("insert into colorShortOptions (Color) values ('gray')")
  cursor.execute("insert into colorShortOptions (Color) values ('green')")
  cursor.execute("insert into colorShortOptions (Color) values ('teal')")
  cursor.close()

It builds the table but fails from the first insertion. Trying to insert
using that code directly in MySQL does indeed work. Why?
TIA,
Beno
-- 
http://mail.python.org/mailman/listinfo/python-list


How can I define __getattr__ to operate on all items of container and pass arguments?

2011-02-15 Thread Jeremy
I have a container object.  It is quite frequent that I want to call a function 
on each item in the container.  I would like to do this whenever I call a 
function on the container that doesn't exist, i.e., the container would return 
an attribute error.

For example

class Cont(object):
def __init__(self): 
self.items = []

def contMethod(self, args):
print("I'm in contMethod.")

def __getattr__(self, name):
for I in self.items:
# How can I pass arguments to I.__dict__[name]?
I.__dict__[name]


>>> C = Cont()
>>> # Add some items to C
>>>C.contMethod()
I'm in contMethod.
>>>C.itemMethod('abc')
??


The trouble I'm getting into is that I can't pass arguments to the attributes 
in the contained item.  In the example above, I can't pass 'abc' to the 
'itemMethod' method of each item in the container.  

Does someone know how I can accomplish this?

Thanks,
Jeremy

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


Re: file find skips first letter

2011-02-15 Thread Tim Chase

On 02/15/2011 12:32 PM, Wanderer wrote:

 if f.find(fileBase)>  0:


.find() returns "-1" on failure, not 0.  You want ">=" instead of 
just ">", or even more readably


  if fileBase in f:

-tkc




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


logging module -- better timestamp accuracy on Windows

2011-02-15 Thread benhoyt
The Python logging module calls time.time() in LogRecord.__init__ to fetch the 
timestamp of the log record. However, time.time() isn't particularly accurate 
on Windows. We're logging start and end of our requests in our web server, 
which can be milliseconds apart, and the log timestamps often show up as 
identical, but time.clock() is telling us several milliseconds have actually 
elapsed.

The fix is to use time.clock() if running on win32 (like "timeit" does). Here's 
how I've improved the accuracy for us:

-
if sys.platform == 'win32':
# Running on win32, time.clock() is much more accurate than
# time.time(), use it for LogRecord timestamps

# Get the initial time and call time.clock() once to "start" it
_start_time = time.time()
time.clock()

def _formatTimeAccurate(self, record, datefmt):
# This is a bit nasty, as it modifies record.created and
# record.msecs, but apart from monkey-patching Formatter.__init__,
# how else do we do it?
accurate_time = _start_time + time.clock()
record.created = time.localtime(accurate_time)
record.msecs = (accurate_time - int(accurate_time)) * 1000
return time.strftime(datefmt, record.created)

# Override logging.Formatter's formatTime() so all logging calls
# go through this
logging.Formatter.formatTime = _formatTimeAccurate
-

This works, but as you can see, it's a bit hacky. Is there a better way to fix 
it? (I'd like the fix to affect all loggers, including the root logger.)

I'm somewhat surprised that no one else has run into this before. Maybe I'm the 
only one who uses logging heavily under Windows ... :-)

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


Re: How can I define __getattr__ to operate on all items of container and pass arguments?

2011-02-15 Thread Chris Rebert
On Tue, Feb 15, 2011 at 12:29 PM, Jeremy  wrote:
> I have a container object.  It is quite frequent that I want to call a 
> function on each item in the container.  I would like to do this whenever I 
> call a function on the container that doesn't exist, i.e., the container 
> would return an attribute error.

s/function/method/

> For example
>
> class Cont(object):
>    def __init__(self):
>        self.items = []
>
>    def contMethod(self, args):
>        print("I'm in contMethod.")
>
>    def __getattr__(self, name):
>        for I in self.items:
>            # How can I pass arguments to I.__dict__[name]?
>            I.__dict__[name]
>

> The trouble I'm getting into is that I can't pass arguments to the attributes 
> in the contained item.  In the example above, I can't pass 'abc' to the 
> 'itemMethod' method of each item in the container.
>
> Does someone know how I can accomplish this?

Recall that:
x.y(z)
is basically equivalent to:
_a = x.y
_a(z)

So the arguments haven't yet been passed when __getattr__() is
invoked. Instead, you must return a function from __getattr__(); this
function will then get called with the arguments. Thus (untested):

def __getattr__(self, name):
def _multiplexed(*args, **kwargs):
return [getattr(item, name)(*args, **kwargs) for item in self.items]
return _multiplexed

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


Re: Problem w/ MySQLdb

2011-02-15 Thread MRAB

On 15/02/2011 20:24, Victor Subervi wrote:

Hi;
I have a function that calls the following class:

#!/usr/bin/python

import sys,os
sys.path.append(os.getcwd())
import MySQLdb
from login import login
import re, string

def buildTableColorShortOptions():
   user, passwd, db, host = login()
   database = MySQLdb.connect(host, user, passwd, db)
   cursor = database.cursor()
   cursor.execute('''create table if not exists colorShortOptions (
 Color varchar(40) not null,
 Value bool not null default '0'
 ) engine=innodb''')
   cursor.execute("insert into colorShortOptions (Color) values ('indigo')")
   cursor.execute("insert into colorShortOptions (Color) values ('maroon')")

[snip]

   cursor.execute("insert into colorShortOptions (Color) values ('teal')")
   cursor.close()

It builds the table but fails from the first insertion. Trying to insert
using that code directly in MySQL does indeed work. Why?


You didn't commit the changes.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How can I define __getattr__ to operate on all items of container and pass arguments?

2011-02-15 Thread MRAB

On 15/02/2011 20:29, Jeremy wrote:

I have a container object.  It is quite frequent that I want to call a function 
on each item in the container.  I would like to do this whenever I call a 
function on the container that doesn't exist, i.e., the container would return 
an attribute error.

For example

class Cont(object):
 def __init__(self):
 self.items = []

 def contMethod(self, args):
 print("I'm in contMethod.")

 def __getattr__(self, name):
 for I in self.items:
 # How can I pass arguments to I.__dict__[name]?
 I.__dict__[name]



C = Cont()
# Add some items to C
C.contMethod()

I'm in contMethod.

C.itemMethod('abc')

??


The trouble I'm getting into is that I can't pass arguments to the attributes 
in the contained item.  In the example above, I can't pass 'abc' to the 
'itemMethod' method of each item in the container.

Does someone know how I can accomplish this?


Try calling it. All you're currently doing is looking it up and then
discarding it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How can I define __getattr__ to operate on all items of container and pass arguments?

2011-02-15 Thread Steven D'Aprano
On Tue, 15 Feb 2011 12:29:36 -0800, Jeremy wrote:

> def __getattr__(self, name):
> for I in self.items:
> # How can I pass arguments to I.__dict__[name]?
> I.__dict__[name]

The same way you would pass arguments to any other function: with 
function call syntax.

I.__dict__[name](arg1, arg2, arg3, ...)


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


Re: Extending classes __init__behavior for newbies

2011-02-15 Thread James Mills
On Tue, Feb 15, 2011 at 1:44 PM, Steven D'Aprano
 wrote:
> I don't. If you (generic you) have separate "write the code" and "test
> the code" phases, your project is in trouble. You can probably get away
> with it if it's a tiny throw-away script, but for anything more
> substantial, you should be testing *as you are writing*. The two need to
> go in parallel.
>
> I don't follow full-blown test driven development where you write the
> test before you write the code, but still, the time to find out your
> infrastructure is fundamentally broken is *before* you have finished it,
> not three months later when you have built the entire app on top of it.

Perhaps I should have clarified. I agreed only with the
fact that if you spend more time in "careful" design
you might spend less time fixing "defects".

Agreed, test-driven development tends to lend itself
to higher quality code.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem w/ MySQLdb

2011-02-15 Thread Jerry Hill
On Tue, Feb 15, 2011 at 3:24 PM, Victor Subervi  wrote:
> It builds the table but fails from the first insertion. Trying to insert
> using that code directly in MySQL does indeed work. Why?

In what way does it fail?  Does it give you a stack trace, and if so,
what does it say?  Does it create the table, but not populate any
data?  If that's the case, you probably need to call commit() after
you do your inserts.

I'm not familiar with the MySQLDB module in particular, but python
database adapters typically do not autocommit, unless you explicitly
ask for that behavior.

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


Re: How to inspect a variable (sys.modules) for changes in the execution of a program?

2011-02-15 Thread Emile van Sebille

On 2/15/2011 10:19 AM Chris Rebert said...

On Tue, Feb 15, 2011 at 7:17 AM, Jorge Vargas  wrote:

Hello,

I have the following situation. In a big project that involves many
dependencies (and sadly some sys.module hacks) we have a bug, and it
will really help if i could monitor all changes made to that variable.
Is there a way to trace those changes ?


Is the variable's value of a mutable or immutable type? What is the
variable's scope (e.g. module-level global, or object attribute)? Is
the variable subject to getting rebound to an entirely new
value/object?

The answers to these questions will determine how much work will be
required to trace "changes" to the variable. I know of no built-in way
to directly do such a thing, but the underlying functionality
necessary to implement such a feature (e.g. sys.settrace,
__getattribute__, __setattr__) does exist.


Out of curiosity, if it's immutable, what approach might you try to 
capture/trace reassignment?  I've got a toy tracer that breaks with 
simple assignment:


>>> A=tracer(3)
>>> A
3
>>> A+=3
value changed by 3 by add
>>> A
6
>>> B=A+6
value changed by 6 by add
>>> B
12
>>> B+=3
value changed by 3 by add
>>> B
15
>>> A = 4
>>> A+=4
>>>

Emile


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


Re: lint warnings

2011-02-15 Thread Steven D'Aprano
On Tue, 15 Feb 2011 14:32:13 +, Duncan Booth wrote:

> 
>> Also, as already shown, the map version is faster.
> 
> In most cases the list comprehension is faster. Try timing it.

For an extremely specialised and minimal definition of "most cases".


> C:\Python27>python.exe lib\timeit.py -s "def double(x): return x*2" -s
> "data=range(1)" "map(double, data)" 1000 loops, best of 3: 1.82 msec
> per loop
> 
> C:\Python27>python.exe lib\timeit.py -s "def double(x): return x*2" -s
> "data=range(1)" "[x*2 for x in data]" 1000 loops, best of 3: 879
> usec per loop

You're not comparing apples and apples. Try calling the function double() 
from the list comp, instead of inlining it.

Yes, if you can avoid a function call, list comps are faster than map. 
That's a valuable micro-optimization, although the warning about 
premature optimizations and small efficiencies apply. But the number of 
operations that can be inlined is only a vanishingly small subset of all 
operations you might choose to perform, and in general, map is faster 
than list comps with both C built-ins and pure Python functions.

There's no doubt that list comps are a moderate win for readability and 
speed when you can inline the function as opposed to defining a lambda 
inside the map. But otherwise, it's a myth that map is generally slower 
and longer than list comps. It's usually the other way around:

map(function, data)
[function(x) for x in data]

Even in Python3 where map becomes an iterator, it's still shorter:

list(map(function, data))
[function(x) for x in data]

(by two whole characters! Woo hoo, I don't need to upgrade my hard 
drive!!! *wink*)

Conceptually, a map is a single operation. You don't have to think about 
the implementation, namely, "iterate over the sequence, extracting each 
item into a temporary variable, and call the function on that temporary 
variable". You just map the function to the sequence, and don't worry 
about the implementation. I really appreciate that. Sometimes I wish that 
Python would let me write function(data), although given that this would 
be ambiguous, map is the next best thing.


> map is only likely to be faster if you wanted to call a function in both
> cases. If you have an expression that can be inlined you save the
> function call overhead with the list comprehension.

Exactly.


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


Re: How can I define __getattr__ to operate on all items of container and pass arguments?

2011-02-15 Thread Jeremy
On Tuesday, February 15, 2011 1:44:55 PM UTC-7, Chris Rebert wrote:
> On Tue, Feb 15, 2011 at 12:29 PM, Jeremy  wrote:
> > I have a container object.  It is quite frequent that I want to call a 
> > function on each item in the container.  I would like to do this whenever I 
> > call a function on the container that doesn't exist, i.e., the container 
> > would return an attribute error.
> 
> s/function/method/
> 
> > For example
> >
> > class Cont(object):
> >    def __init__(self):
> >        self.items = []
> >
> >    def contMethod(self, args):
> >        print("I'm in contMethod.")
> >
> >    def __getattr__(self, name):
> >        for I in self.items:
> >            # How can I pass arguments to I.__dict__[name]?
> >            I.__dict__[name]
> >
> 
> > The trouble I'm getting into is that I can't pass arguments to the 
> > attributes in the contained item.  In the example above, I can't pass 'abc' 
> > to the 'itemMethod' method of each item in the container.
> >
> > Does someone know how I can accomplish this?
> 
> Recall that:
> x.y(z)
> is basically equivalent to:
> _a = x.y
> _a(z)
> 
> So the arguments haven't yet been passed when __getattr__() is
> invoked. Instead, you must return a function from __getattr__(); this
> function will then get called with the arguments. Thus (untested):
> 
> def __getattr__(self, name):
> def _multiplexed(*args, **kwargs):
> return [getattr(item, name)(*args, **kwargs) for item in self.items]
> return _multiplexed

Perfect, that's what I needed.  I realized that I didn't have the arguments to 
the function, but couldn't figure out how to do it.  This works like a charm.  
Thanks a lot!

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


Re: How to inspect a variable (sys.modules) for changes in the execution of a program?

2011-02-15 Thread Mel
Emile van Sebille wrote:

> Out of curiosity, if it's immutable, what approach might you try to
> capture/trace reassignment?  I've got a toy tracer that breaks with
> simple assignment:

AFAIK you'd have to replace the namespace dictionaries with dictionary-like 
things that would react to rebinding.

Mel.

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


Re: Problem w/ MySQLdb

2011-02-15 Thread Victor Subervi
It's been too long since I've worked on this. Yep, I forgot to commit.
Thanks,
Beno

On Tue, Feb 15, 2011 at 5:21 PM, Jerry Hill  wrote:

> On Tue, Feb 15, 2011 at 3:24 PM, Victor Subervi 
> wrote:
> > It builds the table but fails from the first insertion. Trying to insert
> > using that code directly in MySQL does indeed work. Why?
>
> In what way does it fail?  Does it give you a stack trace, and if so,
> what does it say?  Does it create the table, but not populate any
> data?  If that's the case, you probably need to call commit() after
> you do your inserts.
>
> I'm not familiar with the MySQLDB module in particular, but python
> database adapters typically do not autocommit, unless you explicitly
> ask for that behavior.
>
> --
> Jerry
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Extending classes __init__behavior for newbies

2011-02-15 Thread rantingrick
On Feb 14, 9:44 pm, Steven D'Aprano  wrote:
> On Tue, 15 Feb 2011 09:47:54 +1000, James Mills wrote:
> > On Tue, Feb 15, 2011 at 9:32 AM, rantingrick 
> > wrote:
> >> Those who write code bases should "design-in" practicality, re-
> >> usability, and extendability as a forethought and NOT an afterthought.
> >> Of course i am not suggesting that everyone must be clairvoyant.
> >> However the vast amount of time involved in a coding project should be
> >> spent in the design and testing phases and NOT actually writing code.
> >> If you spend more time writing code you are not being professional, you
> >> are being sloppy -- and it WILL catch up to you.
>
> > I actually agree with this. :)
>
> I don't. If you (generic you) have separate "write the code" and "test
> the code" phases, your project is in trouble. You can probably get away
> with it if it's a tiny throw-away script, but for anything more
> substantial, you should be testing *as you are writing*. The two need to
> go in parallel.

My statement made no such mention of "separate phases" or how each
phase should be ordered. Here, l'll paraphrase for the folks who's
attention span cannot last for a full paragraph. *ahem*... "You should
spend more time designing and testing code than writing it"... I hope
that was clear enough for you.

# In Code form.
if (dev.design_time + dev.test_time) < dev.write_time:
print('Good Job Skippy!')
else:
raise ScriptKiddieError



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


Re: Extending classes __init__behavior for newbies

2011-02-15 Thread rantingrick
On Feb 15, 4:16 pm, rantingrick  wrote:

> # In Code form.
> if (dev.design_time + dev.test_time) < dev.write_time:
>     print('Good Job Skippy!')
> else:
>     raise ScriptKiddieError

Oops, you see what i mean!!! :-)

if (dev.design_time + dev.test_time) > dev.write_time:
     print('Good Job Skippy!')
 else:
     raise ScriptKiddieError
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to inspect a variable (sys.modules) for changes in the execution of a program?

2011-02-15 Thread python
Jorge,

It's been a while since I felt the need to use a Python debugger, but I
could swear that most (all?) Python debuggers allow you to watch a
specific variable.

Check out the debuggers on the following page:
http://wiki.python.org/moin/PythonDebuggers

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


Re: How to inspect a variable (sys.modules) for changes in the execution of a program?

2011-02-15 Thread Chris Rebert
On Tue, Feb 15, 2011 at 1:29 PM, Emile van Sebille  wrote:
> On 2/15/2011 10:19 AM Chris Rebert said...
>> On Tue, Feb 15, 2011 at 7:17 AM, Jorge Vargas
>>  wrote: 
>>> I have the following situation. In a big project that involves many
>>> dependencies (and sadly some sys.module hacks) we have a bug, and it
>>> will really help if i could monitor all changes made to that variable.
>>> Is there a way to trace those changes ?
>>
>> Is the variable's value of a mutable or immutable type? What is the
>> variable's scope (e.g. module-level global, or object attribute)? Is
>> the variable subject to getting rebound to an entirely new
>> value/object?
>>
>> The answers to these questions will determine how much work will be
>> required to trace "changes" to the variable. I know of no built-in way
>> to directly do such a thing, but the underlying functionality
>> necessary to implement such a feature (e.g. sys.settrace,
>> __getattribute__, __setattr__) does exist.
>
> Out of curiosity, if it's immutable, what approach might you try to
> capture/trace reassignment?  I've got a toy tracer that breaks with simple
> assignment:
>
 A=tracer(3)
 A
> 3
 A+=3
> value changed by 3 by add

I was thinking of a trace (as in sys.settrace()) function that'd grab
the value (or possibly object ID) of the variable every time it was
called (possibly excluding certain event types) and see whether it
changed vs. the value the variable had the last time it was called.
This would obviously be rather inefficient.

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


floating point woes

2011-02-15 Thread Hans-Peter Jansen
Hi,

while I usually cope with the woes of floating point issues, this is 
one, that I didn't expect:

>>> round(2.385, 2)
2.3799

Doesn't the docs say, it's rounded up for this case?


Values are rounded to the closest multiple of 10 to the power minus n; 
if two multiples are equally close, rounding is done away from 0


Well, that one is clearly rounding down.

What's up, eh, down here?

Pete

Python 2.6 (r26:66714, Feb  8 2011, 08:50:11) 
[GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2

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


Map vs. List Comprehensions (was "lint warnings")

2011-02-15 Thread Gerald Britton
Generally, I prefer map() over list comprehensions since they are more
succinct and run faster for non-trivial examples.  However, I've been
considering another use case related to functions in the operator
module.  Here are some examples:

[x.method() for x in data]
[x[0] for x in data]
[x.attr for x in data]

can be implemented as:

from operator import methodcaller, itemgetter, attrgetter

m = methodcaller('method')
g = itemgetter(0)
a = attrgetter('attr')

map(m, data)
map(g, data)
map(a, data)

I find that using map here generally is a little slower than the list
comprehension, perhaps because of the extra work the operator methods
have to do:

>>> m = methodcaller('upper')
>>> g = itemgetter(0)
>>> a = attrgetter('__class__')
>>> s = "a"

>>> Timer('[x.upper() for x in s]', 'from __main__ import s').timeit()
1.8678569793701172
>>> Timer('map(m, s)', 'from __main__ import s, m').timeit()
2.1330718994140625

>>> Timer('[x[0] for x in s]', 'from __main__ import s').timeit()
1.6577358245849609
>>> Timer('map(g, s)', 'from __main__ import s, g').timeit()
1.8645310401916504

>>> Timer('[x.__class__ for x in s]', 'from __main__ import s').timeit()
1.7232599258422852
>>> Timer('map(a, s)', 'from __main__ import s, a').timeit()
2.4131419658660889
>>>

So, what's the feeling out there?  Go with map and the operators or
stick with the list comps?

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


Re: floating point woes

2011-02-15 Thread André Roberge
On Tuesday, February 15, 2011 7:49:34 PM UTC-4, Hans-Peter Jansen wrote:
> Hi,
> 
> while I usually cope with the woes of floating point issues, this is 
> one, that I didn't expect:
> 
> >>> round(2.385, 2)
> 2.3799
> 
> Doesn't the docs say, it's rounded up for this case?

The problem is probably that 2.385 can not be represented as 2.3850

>>> a = 2.385
>>> a
2.3848

André
> 
> 
> Values are rounded to the closest multiple of 10 to the power minus n; 
> if two multiples are equally close, rounding is done away from 0
> 
> 
> Well, that one is clearly rounding down.
> 
> What's up, eh, down here?
> 
> Pete
> 
> Python 2.6 (r26:66714, Feb  8 2011, 08:50:11) 
> [GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2

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


Re: Extending classes __init__behavior for newbies

2011-02-15 Thread Westley Martínez
On Tue, 2011-02-15 at 14:16 -0800, rantingrick wrote:
> On Feb 14, 9:44 pm, Steven D'Aprano  +comp.lang.pyt...@pearwood.info> wrote:
> > On Tue, 15 Feb 2011 09:47:54 +1000, James Mills wrote:
> > > On Tue, Feb 15, 2011 at 9:32 AM, rantingrick 
> > > wrote:
> > >> Those who write code bases should "design-in" practicality, re-
> > >> usability, and extendability as a forethought and NOT an afterthought.
> > >> Of course i am not suggesting that everyone must be clairvoyant.
> > >> However the vast amount of time involved in a coding project should be
> > >> spent in the design and testing phases and NOT actually writing code.
> > >> If you spend more time writing code you are not being professional, you
> > >> are being sloppy -- and it WILL catch up to you.
> >
> > > I actually agree with this. :)
> >
> > I don't. If you (generic you) have separate "write the code" and "test
> > the code" phases, your project is in trouble. You can probably get away
> > with it if it's a tiny throw-away script, but for anything more
> > substantial, you should be testing *as you are writing*. The two need to
> > go in parallel.
> 
> My statement made no such mention of "separate phases" or how each
> phase should be ordered. Here, l'll paraphrase for the folks who's
> attention span cannot last for a full paragraph. *ahem*... "You should
> spend more time designing and testing code than writing it"... I hope
> that was clear enough for you.
> 
> # In Code form.
> if (dev.design_time + dev.test_time) < dev.write_time:
> print('Good Job Skippy!')
> else:
> raise ScriptKiddieError
> 
> 
> 
It doesn't matter; you'll always end up spending the most time debugging
the code

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


Re: floating point woes

2011-02-15 Thread Westley Martínez
On Wed, 2011-02-16 at 00:49 +0100, Hans-Peter Jansen wrote:
> Hi,
> 
> while I usually cope with the woes of floating point issues, this is 
> one, that I didn't expect:
> 
> >>> round(2.385, 2)
> 2.3799
> 
> Doesn't the docs say, it's rounded up for this case?
> 
> 
> Values are rounded to the closest multiple of 10 to the power minus n; 
> if two multiples are equally close, rounding is done away from 0
> 
> 
> Well, that one is clearly rounding down.
> 
> What's up, eh, down here?
> 
> Pete
> 
> Python 2.6 (r26:66714, Feb  8 2011, 08:50:11) 
> [GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2
> 
It's actually rounding up, but 2.38 cannot be represented precisely by
floating points. This was fixed in Python 3.1.

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


Re: floating point woes

2011-02-15 Thread Benjamin Kaplan
On Tue, Feb 15, 2011 at 6:49 PM, Hans-Peter Jansen  wrote:
> Hi,
>
> while I usually cope with the woes of floating point issues, this is
> one, that I didn't expect:
>
 round(2.385, 2)
> 2.3799
>
> Doesn't the docs say, it's rounded up for this case?
>
> 
> Values are rounded to the closest multiple of 10 to the power minus n;
> if two multiples are equally close, rounding is done away from 0
> 
>
> Well, that one is clearly rounding down.
>
> What's up, eh, down here?
>
> Pete
>

The number you are rounding is not 2.385. It is not possible to
represent that number in binary, just like you cannot represent the
value 1/3 in decimal. So instead, you're using the nearest
approximation that an IEEE 754 Double-Precision Floating Point number
can get you, which happens to be about 2.3848. And that
rounds down to 2.38. Which also cannot be precisely represented in
binary, so you get 2.3799 instead.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: floating point woes

2011-02-15 Thread Ian Kelly
On Tue, Feb 15, 2011 at 4:49 PM, Hans-Peter Jansen  wrote:
> Hi,
>
> while I usually cope with the woes of floating point issues, this is
> one, that I didn't expect:
>
 round(2.385, 2)
> 2.3799
>
> Doesn't the docs say, it's rounded up for this case?
>
> 
> Values are rounded to the closest multiple of 10 to the power minus n;
> if two multiples are equally close, rounding is done away from 0
> 
>
> Well, that one is clearly rounding down.
>
> What's up, eh, down here?

Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 2.385
2.3848

Looks to me like it's working as expected...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: floating point woes

2011-02-15 Thread Chris Rebert
On Tue, Feb 15, 2011 at 3:49 PM, Hans-Peter Jansen  wrote:
> Hi,
>
> while I usually cope with the woes of floating point issues, this is
> one, that I didn't expect:
>
 round(2.385, 2)
> 2.3799
>
> Doesn't the docs say, it's rounded up for this case?
>
> 
> Values are rounded to the closest multiple of 10 to the power minus n;
> if two multiples are equally close, rounding is done away from 0
> 
>
> Well, that one is clearly rounding down.
>
> What's up, eh, down here?

http://docs.python.org/library/functions.html#round :
"""
Note: The behavior of round() for floats can be surprising: for
example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This
is not a bug: it’s a result of the fact that most decimal fractions
can’t be represented exactly as a float. See "Floating Point
Arithmetic: Issues and Limitations"[1] for more information.
"""
[1]: http://docs.python.org/tutorial/floatingpoint.html

And indeed:
>>> from decimal import Decimal
>>> Decimal(2.385)
Decimal('2.3847868371792719699442386627197265625')

Which, rounded to 2 decimal places, gives us 2.38, which is in turn
approximated as:
2.37989341858963598497211933135986328125

I encourage reading [1].

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


Re: floating point woes

2011-02-15 Thread Chris Rebert
On Tue, Feb 15, 2011 at 4:09 PM, Chris Rebert  wrote:
> On Tue, Feb 15, 2011 at 3:49 PM, Hans-Peter Jansen  wrote:
>> Hi,
>>
>> while I usually cope with the woes of floating point issues, this is
>> one, that I didn't expect:
>>
> round(2.385, 2)
>> 2.3799
>>
>> Doesn't the docs say, it's rounded up for this case?
>>
>> 
>> Values are rounded to the closest multiple of 10 to the power minus n;
>> if two multiples are equally close, rounding is done away from 0
>> 
>>
>> Well, that one is clearly rounding down.
>>
>> What's up, eh, down here?
>
> http://docs.python.org/library/functions.html#round :
> """
> Note: The behavior of round() for floats can be surprising: for
> example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This
> is not a bug: it’s a result of the fact that most decimal fractions
> can’t be represented exactly as a float. See "Floating Point
> Arithmetic: Issues and Limitations"[1] for more information.
> """
> [1]: http://docs.python.org/tutorial/floatingpoint.html
>
> And indeed:
 from decimal import Decimal
 Decimal(2.385)
> Decimal('2.3847868371792719699442386627197265625')
>
> Which, rounded to 2 decimal places, gives us 2.38, which is in turn
> approximated as:

[*whacks forehead hard*]
Nevermind.

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


Re: floating point woes

2011-02-15 Thread Hans-Peter Jansen
On Wednesday 16 February 2011, 01:06:08 Benjamin Kaplan wrote:
> On Tue, Feb 15, 2011 at 6:49 PM, Hans-Peter Jansen  
wrote:
> > Hi,
> >
> > while I usually cope with the woes of floating point issues, this
> > is
> >
> > one, that I didn't expect:
>  round(2.385, 2)
> >
> > 2.3799
> >
> > Doesn't the docs say, it's rounded up for this case?
> >
> > 
> > Values are rounded to the closest multiple of 10 to the power minus
> > n; if two multiples are equally close, rounding is done away from 0
> > 
> >
> > Well, that one is clearly rounding down.
> >
> > What's up, eh, down here?
> >
> > Pete
>
> The number you are rounding is not 2.385. It is not possible to
> represent that number in binary, just like you cannot represent the
> value 1/3 in decimal. So instead, you're using the nearest
> approximation that an IEEE 754 Double-Precision Floating Point number
> can get you, which happens to be about 2.3848. And that
> rounds down to 2.38. Which also cannot be precisely represented in
> binary, so you get 2.3799 instead.

Thanks for the explanation, Benjamin. Not that I like it, but anyway.
If I hadn't quitted smoking a long time ago, I would go and ask, what 
these engineers smoked during the course of inventing this sh*t. Even 
more probably, they took way too much of a special form of lysergic 
acid.

OTOH, cdecimals, as in Stefan Krah's package are long overdue to get 
into the core.

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


Re: floating point woes

2011-02-15 Thread Hans-Peter Jansen
On Wednesday 16 February 2011, 01:24:59 Chris Rebert wrote:
> On Tue, Feb 15, 2011 at 4:09 PM, Chris Rebert  
wrote:
> > On Tue, Feb 15, 2011 at 3:49 PM, Hans-Peter Jansen  
wrote:
> >> Hi,
> >>
> >> while I usually cope with the woes of floating point issues, this
> >> is
> >>
> >> one, that I didn't expect:
> > round(2.385, 2)
> >>
> >> 2.3799
> >>
> >> Doesn't the docs say, it's rounded up for this case?
> >>
> >> 
> >> Values are rounded to the closest multiple of 10 to the power
> >> minus n; if two multiples are equally close, rounding is done away
> >> from 0 
> >>
> >> Well, that one is clearly rounding down.
> >>
> >> What's up, eh, down here?
> >
> > http://docs.python.org/library/functions.html#round :
> > """
> > Note: The behavior of round() for floats can be surprising: for
> > example, round(2.675, 2) gives 2.67 instead of the expected 2.68.
> > This is not a bug: it’s a result of the fact that most decimal
> > fractions can’t be represented exactly as a float. See "Floating
> > Point Arithmetic: Issues and Limitations"[1] for more information.
> > """
> > [1]: http://docs.python.org/tutorial/floatingpoint.html
> >
> > And indeed:
>  from decimal import Decimal
>  Decimal(2.385)
> >
> > Decimal('2.3847868371792719699442386627197265625')
> >
> > Which, rounded to 2 decimal places, gives us 2.38, which is in turn
> > approximated as:

If that only wouldn't be so arkward to use:

>>> from cdecimal import Decimal, ROUND_HALF_UP
>>> d = Decimal("2.385")
>>> d
Decimal('2.385')
>>> d.quantize(Decimal('1.00'))
Decimal('2.38')

hrmpf.

>>> d.quantize(Decimal('1.00'), ROUND_HALF_UP)
Decimal('2.39')

Oh, well. This is a bit too Cobolesque. (Yes, sure, I know, I can define 
any context, I like.)

> [*whacks forehead hard*]
> Nevermind.

Too true.

> - Chris

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


return an object of a different class

2011-02-15 Thread spam

How can I do something like this in python:

#!/usr/bin/python3.1

class MyNumbers:
  def __init__(self, n):
self.original_value = n
if n <= 100:
  self = SmallNumers(self)
else:
  self = BigNumbers(self)

class SmallNumbers:
  def __init__(self, n):
self.size = 'small'

class BigNumbers:
  def __init__(self, n):
self.size = 'big'

t = MyNumbers(200)


When I do type(t) it says MyNumbers, while I'd want it to be BigNumbers, 
because BigNumbers and SmallNumbers will have different methods etc...


Do I need to use metaclasses?

Thanks.
--
Yves.  http://www.SollerS.ca/
   http://blog.zioup.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: return an object of a different class

2011-02-15 Thread MRAB

On 16/02/2011 02:23, s...@uce.gov wrote:

How can I do something like this in python:

#!/usr/bin/python3.1

class MyNumbers:
  def __init__(self, n):
self.original_value = n
if n <= 100:
  self = SmallNumers(self)
else:
  self = BigNumbers(self)

class SmallNumbers:
  def __init__(self, n):
self.size = 'small'

class BigNumbers:
  def __init__(self, n):
self.size = 'big'

t = MyNumbers(200)


When I do type(t) it says MyNumbers, while I'd want it to be BigNumbers,
because BigNumbers and SmallNumbers will have different methods etc...

Do I need to use metaclasses?


Why not just make MyNumbers a function?
--
http://mail.python.org/mailman/listinfo/python-list


Re: return an object of a different class

2011-02-15 Thread Ben Finney
s...@uce.gov writes:

> How can I do something like this in python:
>
> #!/usr/bin/python3.1
>
> class MyNumbers:
>   def __init__(self, n):
> self.original_value = n
> if n <= 100:
>   self = SmallNumers(self)
> else:
>   self = BigNumbers(self)

A class defines a type of object. If you don't actually want instances
of that class, then you don't really want a class.

> class SmallNumbers:
>   def __init__(self, n):
> self.size = 'small'
>
> class BigNumbers:
>   def __init__(self, n):
> self.size = 'big'
>
> t = MyNumbers(200)
>
>
> When I do type(t) it says MyNumbers, while I'd want it to be
> BigNumbers, because BigNumbers and SmallNumbers will have different
> methods etc...
>
> Do I need to use metaclasses?

You could. Or you could simply use a factory function::

def make_number(value):
if value <= 100:
result = SmallNumbers(value)
else:
result = BigNumbers(value)
result.original_value = value
return result

t = make_number(200)

-- 
 \  “Programs must be written for people to read, and only |
  `\incidentally for machines to execute.” —Abelson & Sussman, |
_o__)  _Structure and Interpretation of Computer Programs_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: return an object of a different class

2011-02-15 Thread alex23
On Feb 16, 12:23 pm, s...@uce.gov wrote:
> How can I do something like this in python:
>
> #!/usr/bin/python3.1
>
> class MyNumbers:
>    def __init__(self, n):
>      self.original_value = n
>      if n <= 100:
>        self = SmallNumers(self)
>      else:
>        self = BigNumbers(self)
>
> class SmallNumbers:
>    def __init__(self, n):
>      self.size = 'small'
>
> class BigNumbers:
>    def __init__(self, n):
>      self.size = 'big'
>
> t = MyNumbers(200)
>
> When I do type(t) it says MyNumbers, while I'd want it to be BigNumbers,
> because BigNumbers and SmallNumbers will have different methods etc...

Firstly, does MyNumbers _have_ to be a class? Or would a function
acting as a class factory be sufficient?

Otherwise, you can change the class of an object, even within its own
methods:

class MyNumbers(object):
  def __init__(self, n = 0):
self.original_value = n
self.__class__ = BigNumbers if n > 100 else SmallThing

class BigNumbers(MyNumbers):
  size = 'big'

class SmallNumbers(MyNumbers):
  size = 'small'

>>> from test import *
>>> s = MyNumbers(50)
>>> b = MyNumbers(200)
>>> type(s)

>>> s.size
'small'
>>> type(b)

>>> b.size
'big'

Hope this helps.

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


Re: return an object of a different class

2011-02-15 Thread alex23
alex23  wrote:
>     self.__class__ = BigNumbers if n > 100 else SmallThing

That should, of course, be SmallNumbers :)

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


Re: return an object of a different class

2011-02-15 Thread aitilang

er
I think you need a NumberFactory that makes SmallNumber and BigNumber 
according to the initial value.


?? 2011-2-16 10:23, s...@uce.gov :

How can I do something like this in python:

#!/usr/bin/python3.1

class MyNumbers:
  def __init__(self, n):
self.original_value = n
if n <= 100:
  self = SmallNumers(self)
else:
  self = BigNumbers(self)

class SmallNumbers:
  def __init__(self, n):
self.size = 'small'

class BigNumbers:
  def __init__(self, n):
self.size = 'big'

t = MyNumbers(200)


When I do type(t) it says MyNumbers, while I'd want it to be 
BigNumbers, because BigNumbers and SmallNumbers will have different 
methods etc...


Do I need to use metaclasses?

Thanks.


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


Re: logging module -- better timestamp accuracy on Windows

2011-02-15 Thread Ross Ridge
benhoyt   wrote:
>This works, but as you can see, it's a bit hacky. Is there a better way to =
>fix it? (I'd like the fix to affect all loggers, including the root logger.=
>)

A simpler solution would be to caclulate the time it takes to the handle
the request using time.clock() and include it in the log message.
Something like:

timer = time.time
if sys.platform == 'win32':
timer = time.clock

def handler(...):
start = timer()
...
logging.debug("processing time %.0fms",
  (timer() - start) * 1000)

Saves you from having to do the math in your head when you look at
the logs.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  rri...@csclub.uwaterloo.ca
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: interleave string

2011-02-15 Thread alex23
Andrea Crotti  wrote:
> At the moment I have this ugly inliner
>         interleaved = ':'.join(orig[x:x+2] for x in range(0, len(orig), 2))

I actually prefer this over every other solution to date. If you feel
its too much behaviour in one line, I sometimes break it out into
separate values to provide some in-code documentation:

>>> s = "xxaabbddee"
>>> get_two_chars_at = lambda i: s[i:i+2]
>>> string_index  = xrange(0, len(s), 2)
>>> ':'.join(get_two_chars_at(i) for i in string_index)
'xx:aa:bb:dd:ee'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: floating point woes

2011-02-15 Thread Grant Edwards
On 2011-02-16, Ian Kelly  wrote:
> On Tue, Feb 15, 2011 at 4:49 PM, Hans-Peter Jansen  wrote:
>>
>> while I usually cope with the woes of floating point issues, this is
>> one, that I didn't expect:
>>
> round(2.385, 2)
>> 2.3799
>>
>> Doesn't the docs say, it's rounded up for this case?
[...]

> Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] 
> on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
 2.385
> 2.3848
>
> Looks to me like it's working as expected...

Well, it's working as it's supposed to...

Whether it's working as expected depends on the user. :)

-- 
Grant



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


Re: floating point woes

2011-02-15 Thread Grant Edwards
On 2011-02-16, Hans-Peter Jansen  wrote:

> Thanks for the explanation, Benjamin. Not that I like it, but anyway.
> If I hadn't quitted smoking a long time ago, I would go and ask, what
> these engineers smoked during the course of inventing this sh*t.

Like most tools, IEEE floating point works brilliantly for what it was
intended when used by people who know how to use it.  The problem is
that it's used for all sorts of things it shouldn't be by people who
don't understand how it works (again, like most tools).  The problem
is that it _appears_ easy to use, but it actually takes some study and
effort to use it right.

Back in the days before FP hardware was affordable, it used to be
fairly common for BCD to be the default FP representation in many
non-Fortran languages (BASIC, Pascal, etc.).  I think that probably
provided a lot fewer surprises to most users.

> Even more probably, they took way too much of a special form of
> lysergic acid.
>
> OTOH, cdecimals, as in Stefan Krah's package are long overdue to get 
> into the core.

There probably needs to be some sort of BCD FP option for the casual
user since most people would probably be better off with BCD.  Those
who need HW FP probably know it (and might even know how to use it).

[I may have just barely passed undergrad numerical analysis, but I
learned enough to know how ignorant I was.]

-- 
Grant



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


unicode shutil.copy() changes a file name during copy?

2011-02-15 Thread dave
i'm on windows, using active python 2.7.1

i've written a script to copy a folder of files to dest folder..

one if the files in this folder has the section symbol (§, '\x15') as
part of the file name
shutil.copy(src_file, dst_file) "can't find the file specified" when
it does the os.chmod() part, can't find dest file,
cuz the file got copied with "_" in place of the section symbol.
gar.

Traceback (most recent call last):
  File "../../python/post_build.py", line 159, in 
main(proB, debugB)
  File "../../python/post_build.py", line 105, in main
paths.copy_folder(srcResFolder + 'Export', destRes + '/codecs/
Export')
  File "F:\Users\davec\Developer\depot\kJams\Development\xplat\python
\paths.py", line 77, in copy_folder
copy_folder(srcPath, new_dst_obj)
  File "F:\Users\davec\Developer\depot\kJams\Development\xplat\python
\paths.py", line 80, in copy_folder
copy_file(srcPath, new_dst_obj)
  File "F:\Users\davec\Developer\depot\kJams\Development\xplat\python
\paths.py", line 37, in copy_file
shutil.copy(src_file, dst_file)
  File "C:\Python27\lib\shutil.py", line 117, in copy
copymode(src, dst)
  File "C:\Python27\lib\shutil.py", line 90, in copymode
os.chmod(dst, mode)
WindowsError: [Error 2] The system cannot find the file specified:
'build\\kJams Pro Debug.app/Contents/Resources/codecs/Export/Codec
[MooV]/Animation \xa7 AAC.rtm'

if i replace that with shutil.copyfile(src_file, dst_file) it "works",
again by replacing the section symbol with underbar.
but that leaves me to call os.chmod() myself, which of course fails
because of the character substitution.

i'm gathering the list of files to iterate over the folder via:
fileList = os.listdir(src_dir)
for fileName in fileList:

and yes, src_dir is "unicode".  but the fileName when i print it shows
the degree symbol (°, '\xa7') in place of the section symbol.

i suspect it's a 'dbcs' or 'latin_1' problem?

this same exact python code works on the mac (it's utf8 down to the
metal) and, get this, it works when running Windows under Parallels
Desktop.  It fails only when running Windows natively.  I can't see
how that makes a difference.

i can give a whole lot more info, but i just want to know if i'm
trying to do something impossible.  If this seems strange to y'all
gladly i'll fill in all the details, but hoping it can be short
circuited by someone going "ah hah!  you have to do such and so".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: return an object of a different class

2011-02-15 Thread Richard Thomas
On Feb 16, 2:23 am, s...@uce.gov wrote:
> How can I do something like this in python:
>
> #!/usr/bin/python3.1
>
> class MyNumbers:
>    def __init__(self, n):
>      self.original_value = n
>      if n <= 100:
>        self = SmallNumers(self)
>      else:
>        self = BigNumbers(self)
>
> class SmallNumbers:
>    def __init__(self, n):
>      self.size = 'small'
>
> class BigNumbers:
>    def __init__(self, n):
>      self.size = 'big'
>
> t = MyNumbers(200)
>
> When I do type(t) it says MyNumbers, while I'd want it to be BigNumbers,
> because BigNumbers and SmallNumbers will have different methods etc...
>
> Do I need to use metaclasses?
>
> Thanks.
> --
> Yves.                                                  http://www.SollerS.ca/
>                                                        http://blog.zioup.org/

If you don't want to use a factory function I believe you can do this:

class MyNumber(object):
def __new__(cls, n):
if n <= 100:
cls = SmallNumbers
else:
cls = BigNumbers
return object.__new__(cls, n)
...

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


Re: return an object of a different class

2011-02-15 Thread spam

On 11-02-15 07:45 PM, alex23 wrote:


Firstly, does MyNumbers _have_ to be a class? Or would a function
acting as a class factory be sufficient?


Yes it does. I didn't explain my problem, chose a terrible example. This is 
more what I'm trying to do:


class thingy:
  def __init__(self, athingy):
self.basic_extract()
if self.sortof =

  def basic_extract(self):
do a bunch of things
self.sortof = ..

  def general_method(self)


class ThingyTypeA:
  def __init__(self):
further_extract()

class ThingyTypeB:
  def __init__(self):
further_extract()



Otherwise, you can change the class of an object, even within its own
methods:


And then I just call __init__ method?



class MyNumbers(object):
   def __init__(self, n = 0):
 self.original_value = n
 self.__class__ = BigNumbers if n>  100 else SmallThing

   self.__init__()


class BigNumbers(MyNumbers):

 def __init__(self):

 size = 'big'

   self.newvalue = self.original_value * y



class SmallNumbers(MyNumbers):

 def __init__(self):

 size = 'small'

   self.newvalue = self.original_value * x



Hope this helps.


Yes, thanks!


--
Yves.  http://www.SollerS.ca/
   http://blog.zioup.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: return an object of a different class

2011-02-15 Thread spam
I didn't explain my problem, chose a terrible example. This is more what I'm 
trying to do:


class thingy:
  def __init__(self, athingy):
self.basic_extract()
if self.typeof = A
 .../...

  def basic_extract(self):
# complicated logic to extract data out of the thingy here
# and set a bunch of values base on the data we extract
self.size = xxx
self.typeof = yyy
self.weight = zzz

  def general_method(self)
# Method that can be used on both types of thingy

class ThingyTypeA:
  def __init__(self):
# do some further extraction specific to type A
further_extract()


class ThingyTypeB:
  def __init__(self):
# do some further extraction specific to type B
further_extract()


--
Yves.  http://www.SollerS.ca/
   http://blog.zioup.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Missing SIGCHLD

2011-02-15 Thread Adam Skutt
On Feb 15, 1:28 pm, Dan Stromberg  wrote:
> *ix signals have historically been rather unreliable and troublesome
> when used heavily.
>
> There are BSD signals, SysV signals, and POSIX signals - they all try
> to solve the problems in different ways.

No, there are just signals[1].  There are several different APIs for
handling signals, depending on the situation, but they're all driving
the same functionality underneath the covers. These days, only
sigaction(2) is remotely usable (in C) for installing handlers and all
the other APIs should normally be ignored.

> You might also make sure your SIGCHLD signal handler is not just
> waitpid'ing once per invocation, but rather doing a nonblocking
> waitpid in a loop until no process is found, in case signals are lost
> (especially if/when signals occur during signal handler processing).

This is the most likely the issue.  Multiple instances of the same
pending signals are coalesced together automatically.

It would also help to make sure the signal handler just sets a flag,
within the application's main loop it should then respond to that flag
appropriately.  Running anything inside a signal handler is a recipe
for disaster.

Also, SIGCHLD handlers may not get reinstalled on some operating
systems (even in Python), so the application code needs to reinstall
it.  If not done within the signal handler, this can caused signals to
get "lost".

That being said, I'd just spawn a thread and wait there and avoid
SIGCHLD altogether.  It's typically not worth the hassle.

> Oh, also, signals in CPython will tend to cause system calls to return
> without completing, and giving an EINTR in errno, and not all CPython
> modules will understand what to do with that.  :(  Sadly, many
> application programmers tend to ignore the EINTR possibility.

This can be disabled by signal.siginterrupt().  Regardless, the signal
handling facilities provided by Python are rather poor.

Adam

[1] Ok, I lied, there's regular signals and realtime signals, which
have a few minor differences.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: floating point woes

2011-02-15 Thread Mel
Hans-Peter Jansen wrote:

> Hi,
> 
> while I usually cope with the woes of floating point issues, this is
> one, that I didn't expect:
> 
 round(2.385, 2)
> 2.3799
> 
> Doesn't the docs say, it's rounded up for this case?
> 
> 
> Values are rounded to the closest multiple of 10 to the power minus n;
> if two multiples are equally close, rounding is done away from 0
> 
> 
> Well, that one is clearly rounding down.
> 
> What's up, eh, down here?

2.385 isn't really 2.385:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> repr (2.385)
'2.3848'
>>> 

so it correctly rounded down.  You need to use Decimal numbers if you want 
numbers that behave the way they look.

Mel.

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


Re: return an object of a different class

2011-02-15 Thread Ben Finney
s...@uce.gov writes:

> I didn't explain my problem, chose a terrible example. This is more
> what I'm trying to do:

Unfortunately, it's still very contrived, and the names don't give any
suggestion as to what you're trying to achieve. Can you improve on that?

> class ThingyTypeA:
>   def __init__(self):
> # do some further extraction specific to type A
> further_extract()
>
>
> class ThingyTypeB:
>   def __init__(self):
> # do some further extraction specific to type B
> further_extract()

Perhaps you want those classes to inherit from your base class. Have you
done the Python tutorial? It covers inheritance and how to use it.

-- 
 \ “Are you pondering what I'm pondering?” “I think so, Brain, but |
  `\I don't think Kay Ballard's in the union.” —_Pinky and The |
_o__)   Brain_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Python-GUI Button arrangement Help

2011-02-15 Thread Bugcy 013
Dear all,
I am new to python programming, I am developing some small
application, user agreement using Tkinter ,
totally my application having four buttons AGREE, DISAGREE , QUIT ,NEXT.
AGREE--->>Enable the Next Button
DISAGREE--->> One Waring message will show up yes are no
QUIT >> Quit the application
Next -->>Calling one python script exit the GUI
I have created application all working fine button will show up the
top of the screen..
i want show bottom of the frame... plz... Help me...



#! /usr/bin/python

from Tkinter import Tk, RIGHT, BOTH, RAISED
from ttk import Frame, Button, Style
import sys
import os
sys.path[:0] = ['../../..']
import string
import Tkinter
import Pmw
import wx
from Tkinter import *
import tkMessageBox
import gtk
b1 = 'True'
c1 = 'False'
a1 = 1



class Example(Frame):


   def __init__(self1, parent):
       Frame.__init__(self1, parent)

       self1.parent = parent

       self1.initUI()

       #fixedFont = Pmw.logicalfont('Fixed')
       self1.st = Pmw.ScrolledText(parent,
               labelpos = 'n',
               label_text='User Aggrement',


               usehullsize = 1,
               hull_width = 600,
               hull_height = 400,
               text_wrap='none',
               #text_font = fixedFont,

               text_padx = 4,
               text_pady = 4,
       )
       self1.st.importfile('python.txt');
       self1.st.pack(padx = 5, pady = 5, fill = 'both', expand = 1)

       # Prevent users' modifying text and headers
       self1.st.configure(text_state = 'disabled')

   def initUI(self1):

       self1.parent.title("User Aggrement")
       self1.style = Style()
       self1.style.theme_use("default")

       frame = Frame(self1, relief=RAISED, borderwidth=.5)
       frame.pack(fill=BOTH, expand=1)

       self1.pack(fill=BOTH, expand=1)

       def buttonPress(var):
               #print 'The "%s" button was pressed' % var
               if var == 'ok':
                       #os.system("ls -l") & os.system("man man")
                       widget.configure(state=NORMAL)
               elif var == 'dhana':
                       os.system("top") & exit()
               elif var == 'close':


                       a1 = tkMessageBox.askyesno("DisAgree", "Do you
really wish to Disagree?" )
                       #print a1

               if a1 == 1:
                       exit()

               else:
                       sys.exit


       widget = Tkinter.Button(self1, text='Next',command = lambda
b='dhana':     buttonPress(b) )
       widget.pack(side=RIGHT, padx=5, pady=5)
       widget.configure(state=DISABLED )


       def defaultKey(event):
               def make_widgets(self1):
                       buttonBox.invoke()
                       self1.make_widgets()

               root = Tkinter.tk()

       okButton = Tkinter.Button(self1, text="Quit",command =
sys.exit  , font=('Arial', 10), fg="black")
       okButton.pack(side=RIGHT, padx=5, pady=5)


       CloseButton = Tkinter.Button(self1, text="DisAgree",command =
lambda b='close':     buttonPress(b) , font=('Arial', 10), fg="black")
       CloseButton.pack(side=RIGHT, padx=5, pady=5)

       okButton = Tkinter.Button(self1, text="Agree",command = lambda
b='ok':     buttonPress(b) , font=('Arial', 10), fg="black")
       okButton.pack(side=RIGHT, padx=5, pady=5)
       okButton.focus_force()
       #self1.mainloop()

 

def main():

   root = Tkinter.Tk()
   root.geometry("600x400+30+30")
   app = Example(root)
   root.mainloop()


if __name__ == '__main__':
   main()






--
Did I learn something today? If not, I wasted it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Is this a bug of str.join?

2011-02-15 Thread fireinice
Hi, all
I'm just working around to generate some fake file for parsing. and I
notice some weired thing happen.
time = str(random.randint(1000, ))
s_id = str(random.randint(1000, ))
p_id = str(random.randint(1000, ))
a_id = str(random.randint(1000, ))
s = "test"
a = [time, s_id, p_id, a_id, s]
print '\t'.join(a)

the output is:
31079035823210326101282916386924719897196119318 
1780339444980186test

you can notice that there is no tab between a_id and s
if I switch a_id and p_id, it still happen, but if I delete one of
ids, the problem gone.
I tried this with python2.6 from debian source and python2.3 which I
compiled from source. the result are both the same.
What happened to str.join?
thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Python GUI Tkinter Button arrangement

2011-02-15 Thread Ganesh Kumar
Hi..

I am new to python , i have creating one application user
agreement..using Tkinter, The Content

of the agreement will reading one file...Agree button will click means
enable next button. And activate script,

Quit button for exit the program,, Dis agree means one warning message
will show up..

all are working but one buttons are top of the screen.  i want button
in bottom of the frame plz. help me..

this my source code


Source Code

http://pastebin.com/Lm5teAtS

Thanks in Advance
-Ganesh.

-- 
Did I learn something today? If not, I wasted it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this a bug of str.join?

2011-02-15 Thread fireinice
On Feb 16, 1:24 am, fireinice  wrote:
> Hi, all
> I'm just working around to generate some fake file for parsing. and I
> notice some weired thing happen.
>     time = str(random.randint(1000, ))
>     s_id = str(random.randint(1000, ))
>     p_id = str(random.randint(1000, ))
>     a_id = str(random.randint(1000, ))
>     s = "test"
>     a = [time, s_id, p_id, a_id, s]
>     print '\t'.join(a)
>
> the output is:
> 3107903582321032        6101282916386924        719897196119318 
> 1780339444980186test
>
> you can notice that there is no tab between a_id and s
> if I switch a_id and p_id, it still happen, but if I delete one of
> ids, the problem gone.
> I tried this with python2.6 from debian source and python2.3 which I
> compiled from source. the result are both the same.
> What happened to str.join?
> thanks

I'm sorry, I found it should be the terminal width caused visual
problem, please kindly ignore this post.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this a bug of str.join?

2011-02-15 Thread Stefan Behnel

fireinice, 16.02.2011 07:24:

Hi, all
I'm just working around to generate some fake file for parsing. and I
notice some weired thing happen.
 time = str(random.randint(1000, ))
 s_id = str(random.randint(1000, ))
 p_id = str(random.randint(1000, ))
 a_id = str(random.randint(1000, ))
 s = "test"
 a = [time, s_id, p_id, a_id, s]
 print '\t'.join(a)

the output is:
31079035823210326101282916386924719897196119318 
1780339444980186test

you can notice that there is no tab between a_id and s


Likely just a presentation problem in your terminal. Try with a single 
space instead of tabs and see the difference.


Stefan

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


Re: Is this a bug of str.join?

2011-02-15 Thread Stefan Behnel

fireinice, 16.02.2011 07:32:

On Feb 16, 1:24 am, fireinice  wrote:

Hi, all
I'm just working around to generate some fake file for parsing. and I
notice some weired thing happen.
 time = str(random.randint(1000, ))
 s_id = str(random.randint(1000, ))
 p_id = str(random.randint(1000, ))
 a_id = str(random.randint(1000, ))
 s = "test"
 a = [time, s_id, p_id, a_id, s]
 print '\t'.join(a)

the output is:
31079035823210326101282916386924719897196119318 
1780339444980186test

you can notice that there is no tab between a_id and s
if I switch a_id and p_id, it still happen, but if I delete one of
ids, the problem gone.
I tried this with python2.6 from debian source and python2.3 which I
compiled from source. the result are both the same.
What happened to str.join?
thanks


I'm sorry, I found it should be the terminal width caused visual
problem, please kindly ignore this post.


Well, there's always this that's worth remembering:

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

Stefan

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


Re: return an object of a different class

2011-02-15 Thread spam

I didn't explain my problem, chose a terrible example. This is more
what I'm trying to do:


Basically the subclass I want to use is based on some of the data I extract 
from a blob of data. If I use a function to extract the data before I create 
the objects, then I need to do a bunch of assignments afterwards.




Unfortunately, it's still very contrived, and the names don't give any
suggestion as to what you're trying to achieve. Can you improve on that?


class ThingyTypeA:
   def __init__(self):
 # do some further extraction specific to type A
 further_extract()


class ThingyTypeB:
   def __init__(self):
 # do some further extraction specific to type B
 further_extract()


Perhaps you want those classes to inherit from your base class. Have you
done the Python tutorial? It covers inheritance and how to use it.


Yes, I have done subclasing before, and yes ThingyTypeA and B should be 
subclassing Thingy




--
Yves.  http://www.SollerS.ca/
   http://blog.zioup.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: return an object of a different class

2011-02-15 Thread Ben Finney
s...@uce.gov writes:

> > Perhaps you want those classes to inherit from your base class. Have
> > you done the Python tutorial? It covers inheritance and how to use
> > it.
>
> Yes, I have done subclasing before, and yes ThingyTypeA and B should
> be subclassing Thingy

Then your example still gives no indication why inheritance (allowing
the common behaviour to be in the base class), along with a factory
function (allowing the input data to determine which class gets
instantiated), is not sufficient.

-- 
 \ “When people believe that they have absolute knowledge, with no |
  `\ test in reality, this [the Auschwitz crematorium] is how they |
_o__) behave.” —Jacob Bronowski, _The Ascent of Man_, 1973 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] Accessing query results html frame :The solution

2011-02-15 Thread Karim

On 02/14/2011 01:41 PM, Karim wrote:


Hello,

As I get no response from the tutor python list, I am continuing to 
investigate my problem.


In fact the issue is that there are 2 forms in the interactive page 
and my request does nothing
instead I get the interactive page not the submission I asked (query 
results). The 2 forms are:


   1. 
   2. 

And the parameters for each are:

1)




 
 
 
 
ONCLICK="oncreate()"> 





2)





And I recall my data of the progam below:

data = {
   'init' : "",
   'LastForm': "SavedQuery",
   'prompted': "yes",
   'class': "Development",
   'personalQuery': "DKPV",
   'REMOTE_USER': username,
   'QS': "  -p DKPVALIDATION_PLUGIN \(Class 'isequal' 
"Development" \)",

   'use_field_defs':"false",
   'QueryName': "DKPV",
   'QueryType': "personal",
   'ACTION': "Query"
   }

So the question is how could I specify the correct FORM submission and 
how could I chose the correct action because
there are several TYPE='submit' and I am only interested by this one 
VALUE="Query"?


Regards
Karim

On 02/11/2011 08:51 AM, Karim wrote:


Hello,

In fact as found in the net:

"The concept of browser frames is completely outside the scope of 
HTTP. However, browser frames are defined in HTML, and so is the 
target property on form elements: 
This will make the form submit to the _top frame, which means "use the full browser window" " That means that my post form: ENCTYPE="application/x-www-form-urlencoded" TARGET="rightframe"> has a target property to make the submit to the 'rightframe'. Any ideas how I can modified the code (I think the request data or whatever) below to access without knowing the temporary html file name generically. Regards Karim On 02/10/2011 07:12 PM, Karim wrote: Hello All, I get from Steven an very useful link (void space) for http authentication. I added some codes to be able to POST FORM a query as I do it by clicking a query button to get a list of bug Id on a server. The problem is I get a html page which refers 2 frames. And I am interesting in one particular frame namely for example, http://{server}:{port}/wt/tmp/results:karim.liateni.31_3917.html'.format(server=server, port=port). But this pages is created every times in a tmp directory each time with a different name. 1) How can I get the name of this page because with python the page resulting of my query is not mentionned (hidden like)? Interactively there are 3 frames but only this one is of interest for me. But no name of this page is visible in the main html page. Is there a method to get all the nested frames locations? 2) I can see this page interactively when I click on a submit query button. Do I need to add 'ACTION': "Query" in the query dictionnary to simulate a click for submission (type="submit" button) ? 3) Interactively I see that cgi arg NextForm is empty so I let it like that in my query and LastForm was set to "SavedQuery". I put the same value in my python code. Is this ok? import urllib import urllib2 server='dummy.com' port='8081' username = 'karim.liateni' password = 'dummy_pass' theurl = 'http://{server}:{port}/ddts/ddts_main'.format(server=server, port=port) #theurl = 'http://{server}:{port}:8081/wt/tmp/results:karim.liateni.31_3917.html'.format(server=server, port=port) #MEMO: #ENCTYPE="application/x-www-form-urlencoded" TARGET="rightframe"> data = { 'NextForm': "", 'LastForm': "SavedQuery", 'prompted': "yes", 'class': "Development", 'personalQuery': "DKPV", 'REMOTE_USER': username, 'QS': " -p DKPVALIDATION_PLUGIN \(Class 'isequal' "Development" \)", 'use_field_defs':"false", 'QueryName': "DKPV", 'QueryType': "personal", 'ACTION': "Query" } query = urllib.urlencode(data) request = urllib2.Request(theurl, query) passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, theurl, username, password) authhandler = urllib2.HTTPBasicAuthHandler(passman) opener = urllib2.build_opener(authhandler) urllib2.install_opener(opener) pagehandle = urllib2.urlopen(request) print(pagehandle.read()) ___ Tutor maillist - tu...@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - tu...@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor The solution to handle multiple post forms in a same web page and to submit a given one programmatically is to use this very must have module ClientForm from "http://wwwsearch.sourceforge.net/ClientForm"; and maintained by John J.Lee Example from this module: response = urllib2.urlopen("http://wwwsearch.sourceforge.net/ClientForm/example.html";) forms = ClientForm.ParseRespons