Re: from datetime.datetime import today not working. python2.6.4 on windows

2010-01-06 Thread Joshua Kordani

Gary Herron wrote:

Joshua Kordani wrote:

Greetings all!

So I'm reading through the manual and I get to the point where it 
talks about packages and how to import them.  namely section 6.4 in 
the tutorial.  I wont repeat the section here, but I want to 
understand whats going on in the following (as typed on my computer).


Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit 
(Intel)] on

win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dir(datetime)
['MAXYEAR', 'MINYEAR', '__doc__', '__name__', '__package__', 'date', 
'datetime',

 'datetime_CAPI', 'time', 'timedelta', 'tzinfo']
>>> dir(datetime.datetime)
['__add__', '__class__', '__delattr__', '__doc__', '__eq__', 
'__format__', '__ge
__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', 
'__lt__', '
__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', 
'__repr__', '__rs
ub__', '__setattr__', '__sizeof__', '__str__', '__sub__', 
'__subclasshook__', 'a
stimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fromordinal', 
'fromtimest
amp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 
'microsecond', 'm
in', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 
'strftime', 's
trptime', 'time', 'timetuple', 'timetz', 'today', 'toordinal', 
'tzinfo', 'tzname
', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 
'weekday', 'year']


>>> from datetime.datetime import today
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named datetime
>>>

so dir on datetime shows symbols date, time, datetime,etc
dir on datetime shows today, now, etc

lets say for arguments sake that I want to just import the today 
function, according to the documentation, the line should be:

from datetime.datetime import today.

as you can see, that didn't work.  why not?


Just a little confusion on your part.

datetime is a module, so you can import it (as you did) and objects from it

datetime.datetime is a type (like a class is a type) not a module so you 
cannot import from it.



So you can
 import datetime
and you can
 from datetime import 
but that's all the further you can go with imports.

Some of the confusion may be from having a class (well actually it's a 
type) with the same name as its module.  This is now considered bad form.


You might achieve the effect you were you were trying for like this:
 import datetime
 today = datetime.datetime.today
or
 from datetime import datetime
 today = datetime.today
Then you'll be able to call
 today()
at any time.

Gary Herron




Josh




@ All thanks for the responses!  That was the key bit I was missing.

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


Re: How to reduce the memory size of python

2010-01-06 Thread Steve Holden
Mishra Gopal-QBX634 wrote:
> Hi,
>  
> When i write following pyhon program and execute it in linux machine,
>  
> if __name__=='__main__':
> while True:
>   pass
>  
> When i check the VmRSS size, it shows 2956 KB in size.
>  
> Is there any way to reduce the memory size taken by python.
>  
> I am working in flash memory devices.
>  
> Any suggession is highly helpfull to me.
>  
It would not be easy to reduce the size of the standard interpreter, but
there are various implementations for embedded devices. You may get some
help from

  http://wiki.python.org/moin/Tiny%20Python

and

  http://wiki.python.org/moin/Tiny%20Python

A company called Synapse has a working cut-down Python implementation
that they embed in their 802.15 wireless mesh devices, which IIRC
occupies less than 128K.

There is a lot in the standard interpreter that you won't need - many
embedded systems don't need floating point arithmetic, for example.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Steve Holden
r0g wrote:
> r0g wrote:
>> Steven D'Aprano wrote:
>>> On Wed, 06 Jan 2010 23:58:21 +, r0g wrote:
>>>
 Steven D'Aprano wrote:
> On Wed, 06 Jan 2010 22:46:33 +, r0g wrote:
>
>> Grant Edwards wrote:
>>> On 2010-01-06, r0g  wrote:
 See? Spoiling for an argument even now! I never said you weren't allowed
 to butt in, just that you did. Butting in is fine, that's half the point
> 
>> detect no background seething at all here.
>>
>> Roger.
>>
> 
> 
> Actually guys I've just reread this thread from the start and I clearly
> did overreact, sorry about that. In fact it reminded me of this comic...
> 
> http://xkcd.com/481/
> 
> Time to smoke a joint and get a half decent nights sleep I think!
> 
> Roger.

Brilliant. It takes a real whole human being to make an admission like
that (or even to bother to question their own behavior sufficiently to
bother re-reading the thread). I think a lot more of you for the admission.

Not that you really need care one way or the other what *I* think ...

We all have off-days. About three years ago I went completely apeshit at
someone in a fit of tiredness-induced pique, as was at one point amply
evidenced by

http://mail.python.org/pipermail/python-list/2007-August/thread.html#454510

Strangely the universe conspired to stamp on that thread, and it appears
to have been lost to the python.org archives. A Google search for "Steve
Holden" and "not a fucking computer", however, reveals that my shame has
not been totally expunged.

[If only I could rickroll those links ... :)]

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: Python interactive terminal in Ubuntu Linux : some keys fouled up

2010-01-06 Thread t r z e w i c z e k

On Thu, 07 Jan 2010 01:09:08 +0100, casevh  wrote:


On Jan 6, 2:40 pm, pdlem...@earthlink.net wrote:

Have recently moved from XP to Ubuntu Linux.
Successfully installed Python 3.1.1 in the Ubuntu 9.04
release on my desktop.
Problem is the python interactive terminal  >>> .
Many of the keys now do not work.
eg pressing left-arrow yields  ^[[D
right-arrow ^[[C
Home  ^[OH
Del  ^[[3~
up-arrow^[[A  
Frustrating as I use all these , esp  up-arrow to

repeat recent lines.  Found the same thing on
my sons MacBook.

This is not mentioned in two recent Python books
or one on Ubuntu. Nor could I found help on the www.

Is there any work-around  ?  Should I just forget
the python prompt >>>   ?  
Thanks, Davepdlem...@earthlink.net


Assuming you compiled the source code, you will also need to install
"libreadline5-dev" via Synaptic or apt-get.

casevh



Or you can use Idle instead of terminal. It works kind of different.

sudo apt-get install idle-python3.1

will do the thing!

cheers,
trzewiczek


--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Validating cells of a table PyQt

2010-01-06 Thread t r z e w i c z e k

On Thu, 07 Jan 2010 01:37:05 +0100, Zabin  wrote:


Hey!

I am new PyQT programmer. I am trying to create a table in which cells
only take in numeric data. I am unable to use setValidator on table
cells. Looking around i found some material on the editor attribute
but I dont know how to apply this. Any help will be appreciated

Cheers!



Hi,

I'm not an expert but could you write, why you can't use validators on the  
cells? There is this free ebook of first edition of "C++ GUI Programming  
with Qt 4" that has an excel like application as an example and I remember  
there was a part with validators that looked pretty nice. You can easly  
and legally download this book from various sites.


Best from Poland,
trzewiczek




--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
--
http://mail.python.org/mailman/listinfo/python-list


How to reduce the memory size of python

2010-01-06 Thread Mishra Gopal-QBX634
Hi,
 
When i write following pyhon program and execute it in linux machine,
 
if __name__=='__main__':
while True:
  pass
 
When i check the VmRSS size, it shows 2956 KB in size. 
 
Is there any way to reduce the memory size taken by python.
 
I am working in flash memory devices.
 
Any suggession is highly helpfull to me.
 
Thanks,
Gopal
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread r0g
r0g wrote:
> Steven D'Aprano wrote:
>> On Wed, 06 Jan 2010 23:58:21 +, r0g wrote:
>>
>>> Steven D'Aprano wrote:
 On Wed, 06 Jan 2010 22:46:33 +, r0g wrote:

> Grant Edwards wrote:
>> On 2010-01-06, r0g  wrote:
>>> See? Spoiling for an argument even now! I never said you weren't allowed
>>> to butt in, just that you did. Butting in is fine, that's half the point

> detect no background seething at all here.
> 
> Roger.
> 


Actually guys I've just reread this thread from the start and I clearly
did overreact, sorry about that. In fact it reminded me of this comic...

http://xkcd.com/481/

Time to smoke a joint and get a half decent nights sleep I think!

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


Re: Pass multidimensional array (matrix) to c function using ctypes

2010-01-06 Thread Mark Tolonen


"Daniel Platz"  wrote in message 
news:63ac1a01-8491-4885-bae7-cb884abb5...@34g2000yqp.googlegroups.com...

Hello,

I would like to pass a two dimensional array to C function in a dll. I
use ctypes to call the function.

I compile the dll with visual studio 2008 express and my C source code
looks like this.

#include 
#ifdef __cplusplus
extern "C" {  // only need to export C interface if
 // used by C++ source code
using namespace std;
#endif


__declspec(dllexport) int print(double** ptr, int ny, int nx)
{
int i, j;
for(i=0; i

Furthermore, I am wondering if there is a fast way to use a numpy 2D
array instead or alternatively to cast the ctypes array into a numpy
array.

Has someone an idea to help me?


A two-dimentional array is not equivalent to a double**, so depending on 
what your requirements are there are two solutions.


1.  To work with your original matrix.c code above, some Python code that 
works is:


-
import ctypes as ct

# I like C types in caps
DOUBLE = ct.c_double
PDOUBLE = ct.POINTER(DOUBLE)
PPDOUBLE = ct.POINTER(PDOUBLE)
INT = ct.c_int

matrix = ct.cdll.LoadLibrary('matrix.dll')
print_matrix = getattr(matrix,'print')

# An array of doubles can be passed to a function that takes double*.
DBL5ARR = DOUBLE * 5
# An array of double* can be passed to your function as double**.
PDBL4ARR = PDOUBLE * 4

# Declare double* array.
ptr = PDBL4ARR()
for i in range(4):
   # fill out each pointer with an array of doubles.
   ptr[i] = DBL5ARR()
   for j in range(5):
   ptr[i][j] = i + j  # just to initialize the actual doubles.

print_matrix(ptr,4,5)
---


2.  In C, multidimensional arrays are really just single dimentional arrays 
where the compiler does the math for you, so if you declare your matrix 
print function like this:


- matrix2.c ---
#include 
#ifdef __cplusplus
extern "C" {  // only need to export C interface if
 // used by C++ source code
#endif

__declspec(dllexport) int print(double* ptr, int ny, int nx)
{
   int i, j;
   for(i=0; ihttp://mail.python.org/mailman/listinfo/python-list


Re: from datetime.datetime import today not working. python2.6.4 on windows

2010-01-06 Thread Gary Herron

Joshua Kordani wrote:

Greetings all!

So I'm reading through the manual and I get to the point where it 
talks about packages and how to import them.  namely section 6.4 in 
the tutorial.  I wont repeat the section here, but I want to 
understand whats going on in the following (as typed on my computer).


Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit 
(Intel)] on

win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dir(datetime)
['MAXYEAR', 'MINYEAR', '__doc__', '__name__', '__package__', 'date', 
'datetime',

 'datetime_CAPI', 'time', 'timedelta', 'tzinfo']
>>> dir(datetime.datetime)
['__add__', '__class__', '__delattr__', '__doc__', '__eq__', 
'__format__', '__ge
__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', 
'__lt__', '
__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', 
'__repr__', '__rs
ub__', '__setattr__', '__sizeof__', '__str__', '__sub__', 
'__subclasshook__', 'a
stimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fromordinal', 
'fromtimest
amp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 
'microsecond', 'm
in', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 
'strftime', 's
trptime', 'time', 'timetuple', 'timetz', 'today', 'toordinal', 
'tzinfo', 'tzname
', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 
'weekday', 'year']


>>> from datetime.datetime import today
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named datetime
>>>

so dir on datetime shows symbols date, time, datetime,etc
dir on datetime shows today, now, etc

lets say for arguments sake that I want to just import the today 
function, according to the documentation, the line should be:

from datetime.datetime import today.

as you can see, that didn't work.  why not?


Just a little confusion on your part.

datetime is a module, so you can import it (as you did) and objects from it

datetime.datetime is a type (like a class is a type) not a module so you 
cannot import from it.



So you can
 import datetime
and you can
 from datetime import 
but that's all the further you can go with imports.

Some of the confusion may be from having a class (well actually it's a 
type) with the same name as its module.  This is now considered bad form.


You might achieve the effect you were you were trying for like this:
 import datetime
 today = datetime.datetime.today
or
 from datetime import datetime
 today = datetime.today
Then you'll be able to call
 today()
at any time.

Gary Herron




Josh


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


Re: from datetime.datetime import today not working. python2.6.4 on windows

2010-01-06 Thread Steve Holden
Joshua Kordani wrote:
> Greetings all!
> 
> So I'm reading through the manual and I get to the point where it talks
> about packages and how to import them.  namely section 6.4 in the
> tutorial.  I wont repeat the section here, but I want to understand
> whats going on in the following (as typed on my computer).
> 
> Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit
> (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
 import datetime
 dir(datetime)
> ['MAXYEAR', 'MINYEAR', '__doc__', '__name__', '__package__', 'date',
> 'datetime',
>  'datetime_CAPI', 'time', 'timedelta', 'tzinfo']
 dir(datetime.datetime)
> ['__add__', '__class__', '__delattr__', '__doc__', '__eq__',
> '__format__', '__ge
> __', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__',
> '__lt__', '
> __ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__',
> '__repr__', '__rs
> ub__', '__setattr__', '__sizeof__', '__str__', '__sub__',
> '__subclasshook__', 'a
> stimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fromordinal',
> 'fromtimest
> amp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max',
> 'microsecond', 'm
> in', 'minute', 'month', 'now', 'replace', 'resolution', 'second',
> 'strftime', 's
> trptime', 'time', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo',
> 'tzname
> ', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday',
> 'year']
> 
 from datetime.datetime import today
> Traceback (most recent call last):
>   File "", line 1, in 
> ImportError: No module named datetime

> 
> so dir on datetime shows symbols date, time, datetime,etc
> dir on datetime shows today, now, etc
> 
> lets say for arguments sake that I want to just import the today
> function, according to the documentation, the line should be:
> from datetime.datetime import today.
> 
> as you can see, that didn't work.  why not?
> 

Because datetime is a module, but datetime.datetime is a class. You can
import individual names from a module, but a class is a monolithic
all-or-nothing chunk.

There's the potential for confusion because Python also has "packages",
which are like modules but more structured: you can import a module from
a package:

>>> from xml import etree

or import the package module directly:

>>> import xml.etree)

You can also import a submodule from the module:

>>> from xml.etree import cElementTree

or import the submodule directly

>>> import xml.etree.cElementTree

You can even import a class from the submodule:

>>> from xml.etree.cElementTree import Element

but what you *can't* do is import the submodule's class directly:

>>> import xml.etree.cElementTree.Element
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named Element

However, what you did was import the datetime module (which is not a
package, and does not therefore contains submodules), and reference the
datetime class within that module (datetime.datetime), which is all OK.
But datetime.datetime is a class, not a module, so you can't import
anything from it. Neither can you import it directly:

>>> import datetime.datetime
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named datetime

(in the last line, the name "datetime" refers to the class, not themodule.

Hope this helps. You may learn a bit more by actually looking at the
source of the module, which probably lives in

C:\Python26\Lib\datetime.py

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: from datetime.datetime import today not working. python2.6.4 on windows

2010-01-06 Thread Benjamin Kaplan
On Thu, Jan 7, 2010 at 12:07 AM, Joshua Kordani  wrote:
> Greetings all!
>
> So I'm reading through the manual and I get to the point where it talks
> about packages and how to import them.  namely section 6.4 in the tutorial.
>  I wont repeat the section here, but I want to understand whats going on in
> the following (as typed on my computer).
>
> Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)]
> on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
 import datetime
 dir(datetime)
> ['MAXYEAR', 'MINYEAR', '__doc__', '__name__', '__package__', 'date',
> 'datetime',
>  'datetime_CAPI', 'time', 'timedelta', 'tzinfo']
 dir(datetime.datetime)
> ['__add__', '__class__', '__delattr__', '__doc__', '__eq__', '__format__',
> '__ge
> __', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__',
> '__lt__', '
> __ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__',
> '__rs
> ub__', '__setattr__', '__sizeof__', '__str__', '__sub__',
> '__subclasshook__', 'a
> stimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fromordinal',
> 'fromtimest
> amp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max',
> 'microsecond', 'm
> in', 'minute', 'month', 'now', 'replace', 'resolution', 'second',
> 'strftime', 's
> trptime', 'time', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo',
> 'tzname
> ', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday',
> 'year']
>
 from datetime.datetime import today
> Traceback (most recent call last):
>  File "", line 1, in 
> ImportError: No module named datetime

>
> so dir on datetime shows symbols date, time, datetime,etc
> dir on datetime shows today, now, etc
>
> lets say for arguments sake that I want to just import the today function,
> according to the documentation, the line should be:
> from datetime.datetime import today.
>
> as you can see, that didn't work.  why not?
>

>>> import datetime
>>> type(datetime.datetime)


datetime.datetime is a type (so it's a class), not a module and today
is an attribute of that type. You can't import from a class.
-- 
http://mail.python.org/mailman/listinfo/python-list


from datetime.datetime import today not working. python2.6.4 on windows

2010-01-06 Thread Joshua Kordani

Greetings all!

So I'm reading through the manual and I get to the point where it talks 
about packages and how to import them.  namely section 6.4 in the 
tutorial.  I wont repeat the section here, but I want to understand 
whats going on in the following (as typed on my computer).


Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit 
(Intel)] on

win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dir(datetime)
['MAXYEAR', 'MINYEAR', '__doc__', '__name__', '__package__', 'date', 
'datetime',

 'datetime_CAPI', 'time', 'timedelta', 'tzinfo']
>>> dir(datetime.datetime)
['__add__', '__class__', '__delattr__', '__doc__', '__eq__', 
'__format__', '__ge
__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', 
'__lt__', '
__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', 
'__repr__', '__rs
ub__', '__setattr__', '__sizeof__', '__str__', '__sub__', 
'__subclasshook__', 'a
stimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fromordinal', 
'fromtimest
amp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 
'microsecond', 'm
in', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 
'strftime', 's
trptime', 'time', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo', 
'tzname
', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday', 
'year']


>>> from datetime.datetime import today
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named datetime
>>>

so dir on datetime shows symbols date, time, datetime,etc
dir on datetime shows today, now, etc

lets say for arguments sake that I want to just import the today 
function, according to the documentation, the line should be:

from datetime.datetime import today.

as you can see, that didn't work.  why not?

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


RE: lxml 2.2.4 on python3.1, Windows XP gives importerror

2010-01-06 Thread VYAS ASHISH M-NTB837
Processor is Intel Pentium 32 bit. 

import platform
print (platform.architecture()) gives -> ('32bit', 'WindowsPE')


Regards,
Ashish Vyas
 

-Original Message-
From: Sridhar Ratnakumar [mailto:sridh...@activestate.com] 
Sent: Wednesday, January 06, 2010 10:15 PM
To: VYAS ASHISH M-NTB837
Cc: python-list@python.org
Subject: Re: lxml 2.2.4 on python3.1, Windows XP gives importerror

On 1/5/2010 1:38 AM, VYAS ASHISH M-NTB837 wrote:
> Dear All
> I have Python 3.1 installed on Windows XP and Works nice.
> I downloaded lxml 2.2.4 (lxml-2.2.4.win32-py3.1.exe) from pypi.
> When I try:
> from lxml import etree
> I get:
> ImportError: DLL load failed: This application has failed to start 
> because the application configuration is incorrect. Reinstalling the 
> application may fix this problem.

Are you by any chance running 64-bit Python (whereas the lxml binary you
have installed is 32-bit)?

C:> python -c "import platform; print platform.architecture()"

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


Re: Assertions, challenges, and polite discourse

2010-01-06 Thread r0g
alex23 wrote:
> r0g  wrote:
>> Well I think sometimes, for the sake of expediency and overall
>> pleasantness, it's better to let the smaller things go: and if you just
>> can't let them go then at least try and issue corrections in a friendly
>> manner rather than a cold or pious one.
> 
> The irony, it is too rich...

Hi Alex, I didn't think anyone else would still be reading this thread!

The above was in the context of people who have done nothing to warrant
coldness and piety. Sadly we seem to have gotten way beyond that. You
are right though, in retrospect I should have let this slip, clearly no
minds have been changed by not doing :/

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


Re: GUI for multiplatform multimedia project

2010-01-06 Thread r0g
Philip Semanchuk wrote:
> 
> On Jan 6, 2010, at 4:53 PM, 
>  wrote:
> 
>> Hi everyone,
>>
>> I posted that question on a python-forum, but got answer, so I ask here.
>>
>> I'm working on an artistic project and I'm looking for the best
>> cross-platform GUI solution. The problem is that it's gonna be a tool
>> that
>> will have to be double-click installable/runnable and pre-installation of
>> any libraries for end-users is very much like an evil. It really has
>> to be
>> double-click tool
>>
>> My first thought was PyQt, because it's a real framework with a lot of
>> stuff inside (including Phonon) and I know some cross-platform media
>> software written in C++ QT (like VLC). But on the other hand I've heard
>> that it's not that easy to make it "double-clicky" multi-platform. Is
>> that
>> true?
>>
>> Another thing that matters for me is ease of integration with libraries
>> like OpenCV.
>>
>> I will be VERY thankful for any help. I'm SO tired googling the problem
>> (it's like weeks now!!)
> 
> Cześć trzewiczek,
> I'm not well qualified to answer your question but since no one else has
> I'll make a stab at it. I'm interested because I'll have to solve the
> same problem in some months time with a suite of wxPython-based apps
> that rely on a lot of libraries.
> 


Actually the one I wouldn't recommend for the OP is wxPython. It's very
good and I use it almost exclusively but as the OP has an "artistic
project" I'm not sure it would be ideal. wxPython works by leveraging
the runtime platform's native toolkit so your apps are very portable and
fit in nicely with the look and feel of whatever system they're on but...

Sometimes that can make it hard to do very precise layouts that look the
same across platforms. Sometimes it doesn't manifest and the times where
it does wont be a problem for the vast majority of apps but if you
require very granular control you may be better off picking one toolkit
and sticking to it. I'd pick QT over GTK if I had to make a choice and
also I agree with the last poster that packaging any of them (for
windows at least) will require a fair degree of faff.

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


Re: GUI for multiplatform multimedia project

2010-01-06 Thread Philip Semanchuk


On Jan 6, 2010, at 4:53 PM,  > wrote:



Hi everyone,

I posted that question on a python-forum, but got answer, so I ask  
here.


I'm working on an artistic project and I'm looking for the best
cross-platform GUI solution. The problem is that it's gonna be a  
tool that
will have to be double-click installable/runnable and pre- 
installation of
any libraries for end-users is very much like an evil. It really has  
to be

double-click tool

My first thought was PyQt, because it's a real framework with a lot of
stuff inside (including Phonon) and I know some cross-platform media
software written in C++ QT (like VLC). But on the other hand I've  
heard
that it's not that easy to make it "double-clicky" multi-platform.  
Is that

true?

Another thing that matters for me is ease of integration with  
libraries

like OpenCV.

I will be VERY thankful for any help. I'm SO tired googling the  
problem

(it's like weeks now!!)


Cześć trzewiczek,
I'm not well qualified to answer your question but since no one else  
has I'll make a stab at it. I'm interested because I'll have to solve  
the same problem in some months time with a suite of wxPython-based  
apps that rely on a lot of libraries.


When you say "cross platform" I assume you mean OS X, Linux and  
Windows. All three of those require a different technique to create a  
double-clickable app, so in a way you have three problems to solve,  
not just one. For instance, py2exe is a popular solution for building  
monolithic application blobs for Windows, while py2app does the same  
for the Mac.


It might be true that PyQt isn't all that easy to cram into a "double- 
clicky" application blob. But I don't know that e.g. wxPython will be  
any easier. Bundling a Python GUI app is non-trivial. I think that's  
exactly why you've been able to spend weeks googling -- there's no  
easy, obvious, this-is-it, canonical solution. Different people use  
different techniques.


So to get back to your original question, although I don't know if one  
GUI toolkit is easier to bundle than another, I suspect that none of  
them are easy. I would pick the GUI toolkit based on what suits your  
technical & licensing needs best and worry about distribution later.


That's one man's opinion. I hope someone else with more practical  
experience in the matter can offer you some advice.


Good luck
Philip





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


Re: TypeError

2010-01-06 Thread Steve Holden
John Machin wrote:
> On Jan 7, 1:38 pm, Steve Holden  wrote:
>> John Machin wrote:
>>
>> [...]> I note that in the code shown there are examples of building an SQL
>>> query where the table name is concocted at runtime via the %
>>> operator ... key phrases: "bad database design" (one table per
>>> store!), "SQL injection attack"
>> I'm not trying to defend the code overall, but most databases won't let
>> you parameterize the table or column names, just the data values.
> 
> That's correct, and that's presumably why the OP is constructing whole
> SQL statements on the fly e.g.
> 
> cursor.execute('select max(ID) from %sCustomerData;' % store)
> 
Well yes, but that is just a symptom of the real disease, which is that
he has very little idea what he is doing.

> What is the reason for "but" in "but most databases won't ..."? What
> are you rebutting?
> 
I was simply pointing out that the OP had chosen the only available way
of generating variable table names. The bad database design has been
discussed,if not ad infinitum then certainly ad nauseam. All advice has
been ignored.

> Let me try again: One table per store is bad design. The
> implementation of that bad design may use:
> 
> cursor.execute('select max(ID) from %sCustomerData;' % store)
> or (if available)
> cursor.execute('select max(ID) from ?CustomerData;', (store, ))
> but the implementation means is irrelevant.

[Do you know any database on which the latter technique will work? I
realise I said "most", but I suspect I should have said "all" - at least
I can't think of a counterexample now I have put myself on the spot].

I pointed this out to the OP some time ago. It won't make any
difference. In the particular code you mention the tables didn't seem to
be constructed from  user input, thereby removing much of the danger of
SQL injection exploits, but I could be wrong - reading it made me feel
squeamish so I didn't analyze it thoroughly.

The whole thing is a hodge-podge of Python and HTML produced by an
individual who appears to feel it isn't necessary to understand either
HTTP or HTML in order to produce dynamic web sites, whose grasp of
Python itself is slight and whose response to constructive criticism is
to defer acting on it until it is no longer going to be helpful.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: Astronomy--Programs to Compute Siderial Time?

2010-01-06 Thread W. eWatson

John Machin wrote:

On Jan 7, 11:40 am, "W. eWatson"  wrote:

W. eWatson wrote:

Is there a smallish Python library of basic astronomical functions?
There are a number of large such libraries that are crammed with
excessive functions not needed for common calculations.

It looks like I've entered a new era in my knowledge of Python.


Mild curiosity: this would be a wonderful outcome, but what makes it
look so?
I actually need to learn how to make a module that can be imported, 
which in the short interlude I have done. Also looked into docstrings 
and docs, which I now have a decent grasp of. Never really used either 
doc info or writing my own module before. Easy.



I found
a module somewhat like I want, siderial.py. You can see an intro to it
at .
It appears that I can get the code for it through section 1.2, near the
bottom. I scooped it siderial.py up, and placed it in a corresponding
file of the same name and type via NotePad. However, there is a xml file
below it. I know little about it. I thought maybe I could do the same,
but Notepad didn't like some characters in it. As I understand Python
doc files are useful. So how do I get this done, and where do I put the
files?


The file you need is sidereal.py, not your twice-mentioned siderial.py
(the existence of which on the referenced website is doubtful).
How right you are. I misspelled it twice, and quickly found that out 
when I tried to use the [side][real] (easy mnemonic, two words) module. 
sidereal.


What you have been reading is the "Internal maintenance
specification" (large font, near the top of the page) for the module.
The xml file is the source of the docs, not meant to be user-legible.

What is it used for? Do I need it?

A very tiny amount of googling "sidereal.py" (quotes included) leads
to the user documentation at 
http://infohost.nmt.edu/tcc/help/lang/python/examples/sidereal/

Found that too as I cruised around.


Where do you put the files? Well, we're now down to only one file,
sidereal.py, and you put it wherever you'd put any other module that
you'd like to call ... if there's only going to be one caller, put it
in the same directory as that caller's code. More generally, drop it
in /Lib/site-packages
Again in my "learning about modules", discovered that too. I think I'm 
on my way. Thanks.

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


Re: QDoubleValidator

2010-01-06 Thread John Posner

On Wed, 06 Jan 2010 17:47:37 -0500, Zabin  wrote:


On Jan 7, 10:23 am, Zabin  wrote:

Hey!

I am new PyQt programmer and want to restrict users to allow only
numeric values into a table and lineedit boxes. I found the
QDoubleValidator class but am unsure as to how to implement it. (I am
a little shaky on the concept of parent and how to define them). Any
help would be much appreciated!


You'll probably get more help in these Qt-specific forums:

   http://lists.trolltech.com/mailman/listinfo/qt-interest

   http://www.riverbankcomputing.com/mailman/listinfo/pyqt

Good luck,
John

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


Re: TypeError

2010-01-06 Thread John Machin
On Jan 7, 1:38 pm, Steve Holden  wrote:
> John Machin wrote:
>
> [...]> I note that in the code shown there are examples of building an SQL
> > query where the table name is concocted at runtime via the %
> > operator ... key phrases: "bad database design" (one table per
> > store!), "SQL injection attack"
>
> I'm not trying to defend the code overall, but most databases won't let
> you parameterize the table or column names, just the data values.

That's correct, and that's presumably why the OP is constructing whole
SQL statements on the fly e.g.

cursor.execute('select max(ID) from %sCustomerData;' % store)

What is the reason for "but" in "but most databases won't ..."? What
are you rebutting?

Let me try again: One table per store is bad design. The
implementation of that bad design may use:

cursor.execute('select max(ID) from %sCustomerData;' % store)
or (if available)
cursor.execute('select max(ID) from ?CustomerData;', (store, ))
but the implementation means is irrelevant.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess.Popen does not close pipe in an error case

2010-01-06 Thread Steven K. Wong
Well, the example code at 
http://www.python.org/doc/2.6.2/library/subprocess.html#replacing-shell-pipeline
has the same issue:

output=`dmesg | grep hda`
==>
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

After communicate() returns, if you wait for p1 to finish (by calling
p1.poll() repeatedly or p1.wait()), you can hang if the conditions
described in the original post are true, i.e. p1 wrote lots of data to
the pipe and p2 failed without reading much data from the pipe.

Perhaps the doc can be improved to remind folks to close p1.stdout if
the calling process doesn't need it, unless wait() is changed to close
it and p1.wait() is called.

Am I making any sense here?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Assertions, challenges, and polite discourse

2010-01-06 Thread alex23
r0g  wrote:
> Well I think sometimes, for the sake of expediency and overall
> pleasantness, it's better to let the smaller things go: and if you just
> can't let them go then at least try and issue corrections in a friendly
> manner rather than a cold or pious one.

The irony, it is too rich...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError

2010-01-06 Thread Steve Holden
Steve Holden wrote:
> John Machin wrote:
> [...]
>> I note that in the code shown there are examples of building an SQL
>> query where the table name is concocted at runtime via the %
>> operator ... key phrases: "bad database design" (one table per
>> store!), "SQL injection attack"
>>
> I'm not trying to defend the code overall, but most databases won't let
> you parameterize the table or column names, just the data values.
> 
And, apropos of nothing in particular, here's a completely gratuitous
additional chance to tell me off again for spamming the list about a
conference:

http://holdenweb.blogspot.com/2010/01/register-for-pycon-or-kitten-gets-it.html

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: TypeError

2010-01-06 Thread Steve Holden
John Machin wrote:
[...]
> I note that in the code shown there are examples of building an SQL
> query where the table name is concocted at runtime via the %
> operator ... key phrases: "bad database design" (one table per
> store!), "SQL injection attack"
> 
I'm not trying to defend the code overall, but most databases won't let
you parameterize the table or column names, just the data values.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread r0g
Steven D'Aprano wrote:
> On Wed, 06 Jan 2010 23:58:21 +, r0g wrote:
> 
>> Steven D'Aprano wrote:
>>> On Wed, 06 Jan 2010 22:46:33 +, r0g wrote:
>>>
 Grant Edwards wrote:
> On 2010-01-06, r0g  wrote:
>> See? Spoiling for an argument even now! I never said you weren't allowed
>> to butt in, just that you did. Butting in is fine, that's half the point
>> of public groups after all but it's also besides the point. I was merely
>> explaining to Grant that I hadn't posed a yes/no question to anyone, let
>> alone you.
> 
> I quote from your very next post:
> 
> 
> [quote]
> Well I think sometimes, for the sake of expediency and overall
> pleasantness, it's better to let the smaller things go: and if you just
> can't let them go then at least try and issue corrections in a friendly
> manner rather than a cold or pious one.
> [end quote]
> 
> 


I did answer HIM in a friendly manner, to you I'm merely responding in kind.

Anyway I got upset at Ben's comments for several reasons which I
explained at length in that very post (and several subsequent ones) so I
won't rehash them any further here. The "No" in question was merely the
straw that broke the camels back and triggered my admittedly undignified
outburst. I have just seen too many supercilious replies beginning "No,
" in this forum and so yes, it p* me off - I can happily admit it.

Of course clearly you're too cool to ever get p* off yourself, I
detect no background seething at all here.

Roger.

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


Re: Astronomy--Programs to Compute Siderial Time?

2010-01-06 Thread John Machin
On Jan 7, 11:40 am, "W. eWatson"  wrote:
> W. eWatson wrote:
> > Is there a smallish Python library of basic astronomical functions?
> > There are a number of large such libraries that are crammed with
> > excessive functions not needed for common calculations.
>
> It looks like I've entered a new era in my knowledge of Python.

Mild curiosity: this would be a wonderful outcome, but what makes it
look so?

> I found
> a module somewhat like I want, siderial.py. You can see an intro to it
> at .
> It appears that I can get the code for it through section 1.2, near the
> bottom. I scooped it siderial.py up, and placed it in a corresponding
> file of the same name and type via NotePad. However, there is a xml file
> below it. I know little about it. I thought maybe I could do the same,
> but Notepad didn't like some characters in it. As I understand Python
> doc files are useful. So how do I get this done, and where do I put the
> files?

The file you need is sidereal.py, not your twice-mentioned siderial.py
(the existence of which on the referenced website is doubtful).

What you have been reading is the "Internal maintenance
specification" (large font, near the top of the page) for the module.
The xml file is the source of the docs, not meant to be user-legible.
A very tiny amount of googling "sidereal.py" (quotes included) leads
to the user documentation at 
http://infohost.nmt.edu/tcc/help/lang/python/examples/sidereal/

Where do you put the files? Well, we're now down to only one file,
sidereal.py, and you put it wherever you'd put any other module that
you'd like to call ... if there's only going to be one caller, put it
in the same directory as that caller's code. More generally, drop it
in /Lib/site-packages
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Astronomy--Programs to Compute Siderial Time?

2010-01-06 Thread W. eWatson

Roy Smith wrote:

In article ,
 "W. eWatson"  wrote:

Is there a smallish Python library of basic astronomical functions? 
There are a number of large such libraries that are crammed with 
excessive functions not needed for common calculations.


FWIW, if you have any interest in this kind of stuff, you must read the 
classic book on the subject:


http://www.amazon.com/Astronomical-Formulae-Calculators-Jean-Meeus/dp/094339
6220

This is not some textbook which takes graduate level physics to understand.  
It's a straight-forward primer for people who want to use calculators to 
compute phase of the moon and stuff like that.
Thanks, but I'm quite familiar with it. My copy is some 10-15 years old. 
 I suspect he never wrote a newer edition for any computer language. I 
do have access to a C++ library, but I don't think that's going to do me 
much good with Python.


My problem at the moment is finding either someone who has implemented 
it or another similar module.


Note I posted just before you that I have found a siderial.py module, 
but am not familiar with how one installs them or the doc mechanism.

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


Re: Assertions, challenges, and polite discourse

2010-01-06 Thread r0g
Ben Finney wrote:
> r0g  writes:
> 
>> Ben Finney wrote:
>>> People sometimes get upset — on an immediate, irrational level —
>>> when their assertions are challenged. There's no denying that
>>> emotions entangle our discourse, and our interpretation of the
>>> discourse of others.
>> That's truer than most people appreciate, to the extent that it's a
>> good idea to tread very lightly when correcting strangers if you want
>> rational discourse to continue. Even small amounts of negativity
>> commonly provoke large threat responses in people which in turn
>> inhibit rational thinking...
> 
> I prefer the strategy of acknowledging and desensitising this irrational
> response, by making it obvious that every assertion expressed is
> inevitably an exposure of that assertion to challenge and criticism.


I see what you're saying but the "tough love" approach has been shown to
be ineffective in many of the situations it has been tried in, it's
something people instinctively think ought to work but rarely does in
the modern world. Anyway, it's only an irrational response in the sense
that it is likely to provoke irrationality in your counterpart which
isn't a good outcome for either of you.

To our brains it is a very natural and powerful response. That it's
emotional doesn't necessarily make it irrational. Bear in mind that
evolution is the distilled rationality of countless generations and to
fight it is to engage in a very one sided battle. Seriously, watch that
video I recommended, it's very interesting and delves into the neurology
of this exact subject.


> 
> Challenging assertions and criticising reasoning are both healthy and in
> insufficient supply, and I want them to be normal and routine. I try to
> act accordingly.
> 


OK that's fair enough as a general principle but I disagree we are
insufficiently supplied with either here on usenet. I reckon we have too
much if anything. I do understand that a balance must be struck and the
bar ought to err on the high side after, all this group isn't yahoo
answers but neither is it a peer reviewed journal or a legal proceeding.

And anyway, my main point was concerning the tone used when challenging
(perceived) falsehoods rather than the rationale behind challenging
(perceived) falsehoods. Naturally it's right to correct non-trivial
technical falsehoods in the context of this group.

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


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Steven D'Aprano
On Wed, 06 Jan 2010 23:58:21 +, r0g wrote:

> Steven D'Aprano wrote:
>> On Wed, 06 Jan 2010 22:46:33 +, r0g wrote:
>> 
>>> Grant Edwards wrote:
 On 2010-01-06, r0g  wrote:

> NO! It's a rude way to start a sentence don't you think?
 No.  When somebody asks a yes/no question, answering yes or no seems
 quite polite to me.  Following the yes/no answer with an explanation
 of the answer is always nice, and I've little doubt that's what
 happened.


>>> Well actually I hadn't asked a question and I hadn't been talking to
>>> him, he just butted in with it. Otherwise yes I agree completely.
>> 
>> 
>> It's a public forum. You're talking to the whole world.
>
> 
> See? Spoiling for an argument even now! I never said you weren't allowed
> to butt in, just that you did. Butting in is fine, that's half the point
> of public groups after all but it's also besides the point. I was merely
> explaining to Grant that I hadn't posed a yes/no question to anyone, let
> alone you.

I quote from your very next post:


[quote]
Well I think sometimes, for the sake of expediency and overall
pleasantness, it's better to let the smaller things go: and if you just
can't let them go then at least try and issue corrections in a friendly
manner rather than a cold or pious one.
[end quote]


Perhaps you should consider taking your own advice instead of lecturing 
us in an unpleasant, aggressive manner about how horrible we are for 
answering your questions with things you don't want to hear?

BTW, you were actually talking about Ben butting in -- it was Ben's 
answer that started with "No" that triggered this series of complaints 
from you:

[quote]
I might have let it slip had you not started your reply with the word 
"No", that just p* me off.
[end quote]


And the offending, dastardly comment from Ben?

[r0g]
Yes, it returns a tuple if you return more than one value, it just has
a lovely syntax for it.
[ben] 
No, there is nothing inherent to the ‘return’ statement for dealing with
multiple values.


The word "No" was clearly and obviously a response to the previous 
sentence that started "Yes". If this is all it takes to put you in a 
temper ("p* me off") then I suggest you need to look at your own 
behaviour and stop blaming others.





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


Re: TypeError

2010-01-06 Thread John Machin
On Jan 7, 11:14 am, John Machin  wrote:
> On Jan 7, 3:29 am, MRAB  wrote:
>
> > Victor Subervi wrote:
> > > ValueError: unsupported format character '(' (0x28) at index 54
> > >       args = ("unsupported format character '(' (0x28) at index 54",)
>
> > > Apparently that character is a "file separator", which I presume is an
> > > invisible character. I tried retyping the area in question, but with no
> > > avail (threw same error). Please advise. Complete code follows.
>
> OP is barking up the wrong tree. "file separator" has ordinal 28
> DECIMAL. Correct tree contains '(' (left parenthesis, ordinal 0x28
> (HEX)) as the error message says.

It took a bit of mucking about to get an example of that error message
(without reading the Python source code):

|>>> anything = object()

\|>>> "foo%(" % anything
Traceback (most recent call last):
  File "", line 1, in 
TypeError: format requires a mapping

|>>> "foo%(" % {}
Traceback (most recent call last):
  File "", line 1, in 
ValueError: incomplete format key

|>>> "foo%2(" % anything
Traceback (most recent call last):
  File "", line 1, in 
ValueError: unsupported format character '(' (0x28) at index 5

FWIW, the OP's message subject is "TypeError" but the reported message
contains ValueError ... possibly indicative of code that first builds
a format string (incorrectly) and then uses it with error messages
that can vary from run to run depending on exactly what was stuffed
into the format string.

I note that in the code shown there are examples of building an SQL
query where the table name is concocted at runtime via the %
operator ... key phrases: "bad database design" (one table per
store!), "SQL injection attack"

A proper traceback would be very nice ... at this stage it's not
certain what was the line of source that triggers the exception.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Astronomy--Programs to Compute Siderial Time?

2010-01-06 Thread Roy Smith
In article ,
 "W. eWatson"  wrote:

> Is there a smallish Python library of basic astronomical functions? 
> There are a number of large such libraries that are crammed with 
> excessive functions not needed for common calculations.

FWIW, if you have any interest in this kind of stuff, you must read the 
classic book on the subject:

http://www.amazon.com/Astronomical-Formulae-Calculators-Jean-Meeus/dp/094339
6220

This is not some textbook which takes graduate level physics to understand.  
It's a straight-forward primer for people who want to use calculators to 
compute phase of the moon and stuff like that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: parsing an Excel formula with the re module

2010-01-06 Thread John Machin
On Jan 6, 6:54 am, vsoler  wrote:
> On 5 ene, 20:21, vsoler  wrote:
>
>
>
> > On 5 ene, 20:05, Mensanator  wrote:
>
> > > On Jan 5, 12:35 pm, MRAB  wrote:
>
> > > > vsoler wrote:
> > > > > Hello,
>
> > > > > I am acessing an Excel file by means of Win 32 COM technology.
> > > > > For a given cell, I am able to read its formula. I want to make a map
> > > > > of how cells reference one another, how different sheets reference one
> > > > > another, how workbooks reference one another, etc.
>
> > > > > Hence, I need to parse Excel formulas. Can I do it by means only of re
> > > > > (regular expressions)?
>
> > > > > I know that for simple formulas such as "=3*A7+5" it is indeed
> > > > > possible. What about complex for formulas that include functions,
> > > > > sheet names and possibly other *.xls files?
>
> > > > > For example    "=Book1!A5+8" should be parsed into ["=","Book1", "!",
> > > > > "A5","+","8"]
>
> > > > > Can anybody help? Any suggestions?
>
> > > > Do you mean "how" or do you really mean "whether", ie, get a list of the
> > > > other cells that are referred to by a certain cell, for example,
> > > > "=3*A7+5" should give ["A7"] and "=Book1!A5+8" should give ["Book1!A5]
>
> > > Ok, although "Book1" would be the default name of a workbook, with
> > > default
> > > worksheets labeled "Sheet1". "Sheet2", etc.
>
> > > If I had a worksheet named "Sheety" that wanted to reference a cell on
> > > "Sheetx"
> > > OF THE SAME WORKBOOK, it would be =Sheet2!A7. If the reference was to
> > > a completely
> > > different workbook (say Book1 with worksheets labeled "Sheet1",
> > > "Sheet2") then
> > > the cell might have =[Book1]Sheet1!A7.
>
> > > And don't forget the $'s! You may see =[Book1]Sheet1!$A$7.
>
> > Yes, Mensanator, but...  what re should I use? I'm looking for the re
> > statement. No doubt you can help!
>
> > Thank you.
>
> Let me give you an example:
>
> >>> import re
> >>> re.split("([^0-9])", "123+456*/")
>
> [’123’, ’+’, ’456’, ’*’, ’’, ’/’, ’’]
>
> I find it excellent that one single statement is able to do a lexical
> analysis of an expression!

That is NOT lexical analysis.
>
> If the expression contains variables, such as A12 or B9, I can try
> another re expression. Which one should I use?
>
> And if my expression contains parenthesis?   And the sin() function?

 You need a proper lexical analysis, followed by a parser. What you
are trying to do can NOT be accomplished in any generality with a
single regex. The Excel formula syntax has several tricky bits. E.g.
IIRC whether TAX09 is a (macro) name or a cell reference depends on
what version of Excel you are targetting but if it appears like TAX09!
A1:B2 then it's a sheet name.

The xlwt package (of which I am the maintainer) has a lexer and parser
for a largish subset of the syntax ... see  http://pypi.python.org/pypi/xlwt

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


Re: Assertions, challenges, and polite discourse

2010-01-06 Thread Ben Finney
r0g  writes:

> Ben Finney wrote:
> > People sometimes get upset — on an immediate, irrational level —
> > when their assertions are challenged. There's no denying that
> > emotions entangle our discourse, and our interpretation of the
> > discourse of others.
>
> That's truer than most people appreciate, to the extent that it's a
> good idea to tread very lightly when correcting strangers if you want
> rational discourse to continue. Even small amounts of negativity
> commonly provoke large threat responses in people which in turn
> inhibit rational thinking...

I prefer the strategy of acknowledging and desensitising this irrational
response, by making it obvious that every assertion expressed is
inevitably an exposure of that assertion to challenge and criticism.

Challenging assertions and criticising reasoning are both healthy and in
insufficient supply, and I want them to be normal and routine. I try to
act accordingly.

-- 
 \  “Nothing is more sacred than the facts.” —Sam Harris, _The End |
  `\   of Faith_, 2004 |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: please help shrink this each_with_index() implementation

2010-01-06 Thread Carl Banks
On Jan 6, 12:12 pm, Phlip  wrote:
> Nobody wrote:
> > Writing robust software from the outset puts you at a competitive
> > disadvantage to those who understand how the system works.
>
> And I, not my language, should pick and chose how to be rigorous. The language
> should not make the decision for me.

Oh well, your language does.  Deal with it, or pick another language.


Carl Banks

P.S. Actually, Python has ways to request no expection when it's
actually useful, e.g. the get method of dicts, but not when it's
ridiculous and stupid like int() returning zero on error.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File transfer with python

2010-01-06 Thread alex23
Valentin de Pablo Fouce  wrote:
> My intention is to be able to transfer files from one computer to
> another in this environment.
>
> Looking (and surfing) at internet the only suggestion given is to use
> low level sockets for this file transfer. Is there another way to do
> it, is there any top level library that helps you to do that?

If your computers are distributed across many networks, and they all
have internet access, Richard Jones' GmailFS[1] might give you some
ideas. It uses the Python bindings for FUSE to create a local
filestore that's a wrapper around the Gmail API, stashing the actual
data on Google's servers. It's out of date now, but it shouldn't be
much of an effort to update to the latest Gmail API, or to replace
with any other backend data store you like. Google App Engine[2]
provides a hefty amount of free storage to developers, so that's
another option.

1: http://richard.jones.name/google-hacks/gmail-filesystem/gmail-filesystem.html
2: http://code.google.com/appengine/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Astronomy--Programs to Compute Siderial Time?

2010-01-06 Thread W. eWatson

W. eWatson wrote:
Is there a smallish Python library of basic astronomical functions? 
There are a number of large such libraries that are crammed with 
excessive functions not needed for common calculations.
It looks like I've entered a new era in my knowledge of Python. I found 
a module somewhat like I want, siderial.py. You can see an intro to it 
at .
It appears that I can get the code for it through section 1.2, near the 
bottom. I scooped it siderial.py up, and placed it in a corresponding 
file of the same name and type via NotePad. However, there is a xml file 
below it. I know little about it. I thought maybe I could do the same, 
but Notepad didn't like some characters in it. As I understand Python 
doc files are useful. So how do I get this done, and where do I put the 
files?

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


Validating cells of a table PyQt

2010-01-06 Thread Zabin
Hey!

I am new PyQT programmer. I am trying to create a table in which cells
only take in numeric data. I am unable to use setValidator on table
cells. Looking around i found some material on the editor attribute
but I dont know how to apply this. Any help will be appreciated

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


Re: Assertions, challenges, and polite discourse

2010-01-06 Thread r0g
Ben Finney wrote:
> In fairness, the “No” was in response, not to an explicit question, but
> to an assertion.
> 
> Every assertion expressed, though, implies the question “is this
> assertion true?”. It was that question that was answered “No” (followed
> by an explanation of why the assertion was not true).
> 


That's a fair point I had never really considered. I'd wouldn't have
been nearly as upset if you'd started your sentence with AssertionError :)


> People sometimes get upset — on an immediate, irrational level — when
> their assertions are challenged. There's no denying that emotions
> entangle our discourse, and our interpretation of the discourse of
> others.


That's truer than most people appreciate, to the extent that it's a good
idea to tread very lightly when correcting strangers if you want
rational discourse to continue. Even small amounts of negativity
commonly provoke large threat responses in people which in turn inhibit
rational thinking... Have a watch of this Google Tech Talk if you have
time, it's really quite enlightening...

http://www.youtube.com/watch?v=XeJSXfXep4M



> 
> That's not something I'd ever want to eradicate. I ask only that, rather
> than decrying that assertions be challenged per se, the challenge be
> assessed to see whether it's valid.
> 


Well I think sometimes, for the sake of expediency and overall
pleasantness, it's better to let the smaller things go: and if you just
can't let them go then at least try and issue corrections in a friendly
manner rather than a cold or pious one. As this thread is demonstrating
endless checking of every detail of every assertion leads to very long
execution times and on balance I'm not sure we benefit from these extra
digits of precision.

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


Re: please help shrink this each_with_index() implementation

2010-01-06 Thread alex23
Phlip  wrote:
> And I, not my language, should pick and chose how to be rigorous. The language
> should not make the decision for me.

Since you seem unwilling to put the minimal effort into producing the
support code you'd need to work with Python the way you want, perhaps
Perl might be more to your liking?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 3 byte network ordered int, How To ?

2010-01-06 Thread John Machin
On Jan 7, 5:33 am, Matthew Barnett 
wrote:
> mudit tuli wrote:
> > For a single byte, struct.pack(')
> > For two bytes, struct.pack(')
> > what if I want three bytes ?
>
> Four bytes and then discard the most-significant byte:
>
> struct.pack(')[ : -1]

AARRGGHH! network ordering is BIGendian, struct.pack('<. is
LITTLEendian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError

2010-01-06 Thread John Machin
On Jan 7, 3:29 am, MRAB  wrote:
> Victor Subervi wrote:

> > ValueError: unsupported format character '(' (0x28) at index 54
> >       args = ("unsupported format character '(' (0x28) at index 54",)
>
> > Apparently that character is a "file separator", which I presume is an
> > invisible character. I tried retyping the area in question, but with no
> > avail (threw same error). Please advise. Complete code follows.
>

OP is barking up the wrong tree. "file separator" has ordinal 28
DECIMAL. Correct tree contains '(' (left parenthesis, ordinal 0x28
(HEX)) as the error message says.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: suds problem

2010-01-06 Thread Fencer

On 2010-01-06 20:02, Fencer wrote:

On 2010-01-06 19:33, Fencer wrote:

Hello, I just started using suds to use web services. First I tried suds
with a very simple web service I had written and was running myself.
That worked fine. Then I tried to use the web services provided by KEGG:
http://soap.genome.jp/KEGG.wsdl
But I get a SAXParseException due to a supposed mis-matched tag when I
try to consume that wsdl with suds. I checked the wsdl in oxygene and it
claims it's valid. What is the problem here? My test program is below
and it's very simple:
from suds.client import Client

url = 'http://soap.genome.jp/KEGG.wsdl'

client = Client(url)

print client

- Fencer


Same problem with reactome:
http://www.reactome.org:8080/caBIOWebApp/services/caBIOService?wsdl

I suppose I'm mis-using suds, maybe some setting that wasn't needed for
my simple web service but is needed for kegg and reactome.

- Fencer


Seems to be a known problem regarding suds. :( A work-around was 
suggested to remove some cache files but that didn't solve it for me. 
Appreciate other ideas!


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


Re: Python interactive terminal in Ubuntu Linux : some keys fouled up

2010-01-06 Thread casevh
On Jan 6, 2:40 pm, pdlem...@earthlink.net wrote:
> Have recently moved from XP to Ubuntu Linux.
> Successfully installed Python 3.1.1 in the Ubuntu 9.04
> release on my desktop.
> Problem is the python interactive terminal  >>> .
> Many of the keys now do not work.
> eg pressing left-arrow yields  ^[[D
>                     right-arrow         ^[[C
>                     Home                  ^[OH
>                     Del                      ^[[3~
>                     up-arrow            ^[[A                  
>
> Frustrating as I use all these , esp  up-arrow to
> repeat recent lines.  Found the same thing on
> my sons MacBook.
>
> This is not mentioned in two recent Python books
> or one on Ubuntu. Nor could I found help on the www.
>
> Is there any work-around  ?  Should I just forget
> the python prompt >>>   ?                  
>
> Thanks,             Dave        pdlem...@earthlink.net

Assuming you compiled the source code, you will also need to install
"libreadline5-dev" via Synaptic or apt-get.

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


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread r0g
Steven D'Aprano wrote:
> On Wed, 06 Jan 2010 22:46:33 +, r0g wrote:
> 
>> Grant Edwards wrote:
>>> On 2010-01-06, r0g  wrote:
>>>
 NO! It's a rude way to start a sentence don't you think?
>>> No.  When somebody asks a yes/no question, answering yes or no seems
>>> quite polite to me.  Following the yes/no answer with an explanation of
>>> the answer is always nice, and I've little doubt that's what happened.
>>>
>>>
>> Well actually I hadn't asked a question and I hadn't been talking to
>> him, he just butted in with it. Otherwise yes I agree completely.
> 
> 
> It's a public forum. You're talking to the whole world.
> 
> 
> 
> 


See? Spoiling for an argument even now! I never said you weren't allowed
to butt in, just that you did. Butting in is fine, that's half the point
of public groups after all but it's also besides the point. I was merely
explaining to Grant that I hadn't posed a yes/no question to anyone, let
alone you.

Roger.

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


Assertions, challenges, and polite discourse (was: Exception as the primary error handling mechanism?)

2010-01-06 Thread Ben Finney
Grant Edwards  writes:

> Answering a yes/no question with "no" doesn't seem to me to be
> combative if the correct answer is indeed "no".  But I've lost
> track of the post you found objectionable...

In fairness, the “No” was in response, not to an explicit question, but
to an assertion.

Every assertion expressed, though, implies the question “is this
assertion true?”. It was that question that was answered “No” (followed
by an explanation of why the assertion was not true).

People sometimes get upset — on an immediate, irrational level — when
their assertions are challenged. There's no denying that emotions
entangle our discourse, and our interpretation of the discourse of
others.

That's not something I'd ever want to eradicate. I ask only that, rather
than decrying that assertions be challenged per se, the challenge be
assessed to see whether it's valid.

-- 
 \   “Everything you read in newspapers is absolutely true, except |
  `\for that rare story of which you happen to have first-hand |
_o__) knowledge.” —Erwin Knoll |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python xmlrpc client with ssl client certificates and standard modules

2010-01-06 Thread Martin v. Loewis
> My next task is how to find out at the client side, that the server
> certificate is a properly signed one.

As Heikki says, you'll need Python 2.6 for that. You'll probably need to
extend your transport implementation.

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


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Steven D'Aprano
On Wed, 06 Jan 2010 22:46:33 +, r0g wrote:

> Grant Edwards wrote:
>> On 2010-01-06, r0g  wrote:
>> 
>>> NO! It's a rude way to start a sentence don't you think?
>> 
>> No.  When somebody asks a yes/no question, answering yes or no seems
>> quite polite to me.  Following the yes/no answer with an explanation of
>> the answer is always nice, and I've little doubt that's what happened.
>> 
>> 
> Well actually I hadn't asked a question and I hadn't been talking to
> him, he just butted in with it. Otherwise yes I agree completely.


It's a public forum. You're talking to the whole world.




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


Re: please help shrink this each_with_index() implementation

2010-01-06 Thread Antoine Pitrou
Le Wed, 06 Jan 2010 12:12:08 -0800, Phlip a écrit :
> 
> And I, not my language, should pick and chose how to be rigorous. The
> language should not make the decision for me.

And that's why there is the "try: ... except: ..." construct.
Your rant is getting tiring.


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


Re: Mencoder and creating videos

2010-01-06 Thread r0g
Emile van Sebille wrote:
> On 1/6/2010 12:44 PM aditya shukla said...
>> Hello Guys,
>>
>> I have a multiprocessing script which downloads images from 5 urls to 5
>> directories(usinf multiprocess in python 2.6).The download is for 5
>> mins.My aim is to create a video for every minute for each directory and
>> dump the images as the video is created. My question are , should i use
>> _*mencoder.exe*_ to create the videos?
> 

Ffmpeg will do multiprocessor encoding too if the compression codec
supports it. It will also compile stills into video as long as you are
careful to number the file names sequentially. There's no "official"
windows build of it but there's various 3rd party builds floating around
the web, or you can build it yourself.

Roger,

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


Re: TypeError

2010-01-06 Thread r0g
MRAB wrote:
> Victor Subervi wrote:
>> Hi;
>> I get this error:
>>
>>  /var/www/html/angrynates.com/christians/cart/simplemail/mail.py
>> 
>>   153 
>>   154 '''
>>   155 commitSale()
>>   156 myMail()
>>   157 print '''
>> commitSale = 
>>  /var/www/html/angrynates.com/christians/cart/simplemail/mail.py
>>  in
>> commitSale()
>>98 cursor.execute('select max(ID) from %sCustomerData;' % store)
>>99 custID = cursor.fetchone()[0]
>>   100   customerData(store, tmpTable, custID, patientID)
>>   101
>>   102 def myMail():
>> global customerData = , global store =
>> 'products', tmpTable = 'tem12627568064', custID = 1, global patientID
>> = 'None'
>>  /var/www/html/angrynates.com/christians/cart/customerData.py
>>  in
>> customerData(store='products', tmpTable='tem12627568064', custID=1,
>> patientID='None')
>>39 
>>40 """
>>41   print """
>>42   print '%s Customer Data' %
>> (store[0].upper() + store[1:])
>>43   cursor.execute('describe %sCustomerData' % store)
>> store = 'products'
>>
>> ValueError: unsupported format character '(' (0x28) at index 54
>>   args = ("unsupported format character '(' (0x28) at index 54",)
>>
>> Apparently that character is a "file separator", which I presume is an
>> invisible character. I tried retyping the area in question, but with
>> no avail (threw same error). Please advise. Complete code follows.
>>
> Please provide the actual code (and, preferably, an easier-to-understand
> traceback, like what CPython does!). What you supplied isn't runnable.



Oh and, it's probably not a good idea to post things that identify the
site you're working on, especially if you're fairly new to programming
and you're doing a shopping cart! Hackers have been known to trawl
google looking for mention of novice coders websites, giving them domain
names, internal paths, table names etc might well help them hack you!

Cheers & good luck,

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


GUI for multiplatform multimedia project

2010-01-06 Thread trzewiczek
Hi everyone,

I posted that question on a python-forum, but got answer, so I ask here. 

I'm working on an artistic project and I'm looking for the best
cross-platform GUI solution. The problem is that it's gonna be a tool that
will have to be double-click installable/runnable and pre-installation of
any libraries for end-users is very much like an evil. It really has to be
double-click tool 

My first thought was PyQt, because it's a real framework with a lot of
stuff inside (including Phonon) and I know some cross-platform media
software written in C++ QT (like VLC). But on the other hand I've heard
that it's not that easy to make it "double-clicky" multi-platform. Is that
true? 

Another thing that matters for me is ease of integration with libraries
like OpenCV. 

I will be VERY thankful for any help. I'm SO tired googling the problem
(it's like weeks now!!)

Best from Poland, 
trzewiczek
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File transfer with python

2010-01-06 Thread r0g
Valentin de Pablo Fouce wrote:
> Hi there,
> 
> I hope this is the rigth place, if not please, tell me which is the
> right dicussion place. I apologize in such case.
> 
> Ok, I am trying to do a very quick application (is "home based" so is
> not a big deal...). My intention is to transfer files from one
> computer to another.
> 
> I am using several OS (Linux and Windows basicly, but potentially in
> the future Mac too), and the computers won't be potentially in the
> same network (ok, the most times will... but there will be
> exceptions).
> 
> My intention is to be able to transfer files from one computer to
> another in this environment.
> 
> Looking (and surfing) at internet the only suggestion given is to use
> low level sockets for this file transfer. Is there another way to do
> it, is there any top level library that helps you to do that?
> 
> That's a lot!


Well there's several file transfer protocols you could use, TFTP, FTP,
SFTP and you can do SCP and Rysnc over SSH.

AFAIK there's python libs that handle all of those. Unless you need very
high performance I'd suggest using SFTP (Secure file transfer protocol).

Lookup the Paramiko library, it does this and other SSH based stuff.

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


Problem with multiprocessing managers

2010-01-06 Thread Metalone
>From the documentation for Using a remote manager there is the
following example code:

from multiprocessing.managers import BaseManager
import Queue
queue = Queue.Queue()
class QueueManager(BaseManager): pass
QueueManager.register('get_queue', callable=lambda:queue)
m = QueueManager(address=('', 5), authkey='abracadabra')
s = m.get_server()
s.serve_forever()

I don't know how to stop the server.
The documentation states that to call shutdown(), start() must be used
instead of server_forever().
If I use m.start() instead of m.get_server().server_forever() I
receive a PicklingError.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: QDoubleValidator

2010-01-06 Thread Zabin
On Jan 7, 10:23 am, Zabin  wrote:
> Hey!
>
> I am new PyQt programmer and want to restrict users to allow only
> numeric values into a table and lineedit boxes. I found the
> QDoubleValidator class but am unsure as to how to implement it. (I am
> a little shaky on the concept of parent and how to define them). Any
> help would be much appreciated!

I managed to get it going for the line edit- but am stuck with
checking a cell in a table as cells do not have the set validator
attribute- here's the code i had for the line edit:

 self.ui.Thickness_datum.setValidator(QtGui.QDoubleValidator(-999.0,
999.0, 2, self.ui.Thickness_datum))

for the table i thought it would be:

self.ui.table_process.item(row,2).setValidator(QtGui.QDoubleValidator
(-999.0, 999.0, 2, self.ui.table_process.item(row,2)))

Any help would be appreciated
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread r0g
Grant Edwards wrote:
> On 2010-01-06, r0g  wrote:
> 
>> NO! It's a rude way to start a sentence don't you think?
> 
> No.  When somebody asks a yes/no question, answering yes or no
> seems quite polite to me.  Following the yes/no answer with an
> explanation of the answer is always nice, and I've little doubt
> that's what happened.
> 

Well actually I hadn't asked a question and I hadn't been talking to
him, he just butted in with it. Otherwise yes I agree completely.

Roger.

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


Python interactive terminal in Ubuntu Linux : some keys fouled up

2010-01-06 Thread pdlemper
Have recently moved from XP to Ubuntu Linux.
Successfully installed Python 3.1.1 in the Ubuntu 9.04
release on my desktop.
Problem is the python interactive terminal  >>> .
Many of the keys now do not work.
eg pressing left-arrow yields  ^[[D
right-arrow ^[[C
Home  ^[OH
Del  ^[[3~
up-arrow^[[A  
  
Frustrating as I use all these , esp  up-arrow to
repeat recent lines.  Found the same thing on 
my sons MacBook.

This is not mentioned in two recent Python books
or one on Ubuntu. Nor could I found help on the www.

Is there any work-around  ?  Should I just forget 
the python prompt >>>   ?  

Thanks, Davepdlem...@earthlink.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread r0g
Ben Finney wrote:
> r0g  writes:
> 
>> NO! It's a rude way to start a sentence don't you think?
> 
> Shouting is usually rude, yes.
> 
>> Just because you're correcting someone doesn't mean you have to be
>> combative and try and make them feel small.
> 
> Again, you're reading something that isn't there. I utterly deny the
> motives you're imputing.
> 
>> I can't imagine why I expect good manners on usenet though, AFAICT
>> it's never been like that (well not since I got on it anyway).
> 
> I'll reiterate that you can address this by paying more attention to
> what is actually written, and endeavouring to avoid finding emotions or
> motives that are likely not in the message.
> 


Both you and Steve are routinely harsh is all I'm saying, although he's
worse than you.

I'm sure you're both very good programmers who don't have the time to
tread carefully around those who come in, often under prepared, seeking
advice. Fair enough you don't tolerate fools lightly, I can respect that
(within reason) and you contribute a lot to the group so you're perhaps
owed a bit more slack than your average Joe but... There's a difference
between that and repeatedly seeking out reasons to stick your boot in -
and to my mind you seem to do that.

Maybe it's just me, but have you considered that maybe it's not?... Most
of the time when I see an extremely blunt, overly harsh response to a
question on here I know if I glance up to the name field I'll find one
of your names there (as I say, probably Steve more often that yourself).
I'm sure you think I'm making this up but many passive aggressive don't
realise how they're acting - can't see the wood for the trees and all that.

Anyway I'm going to butt out now, I'm sure everyone is getting
thoroughly bored of the OT noise.

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


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Michi
On Jan 5, 9:44 am, Steven D'Aprano  wrote:
>
> I'm glad we agree on that, but I wonder why you previously emphasised
> machine efficiency so much, and correctness almost not at all, in your
> previous post?

Uh… Because the original poster quoted one small paragraph out of a
large article and that paragraph happened to deal with this particular
(and minor) point of API design?

> If all you're argument is that we shouldn't write crappy APIs, then I
> agree with you completely.

Well, yes: the article was precisely about that. And the point about
exception efficiency was a minor side remark in that article.

> Your argument seems to be
> that we should avoid exceptions by default, and only use them if
> unavoidable. I think that is backwards.

I never made that argument. After 25 years as a software engineer, I
well and truly have come to appreciate exceptions as a superior form
of error handling. I simply stated that throwing an exception when
none should be thrown is a pain and often inefficient on top of that.
That's all, really.

> I wouldn't say that's normal. If you don't care about the function's
> result, why are you calling it? For the side-effects?

printf returns a value that is almost always ignored. And, yes, a
function such as printf is inevitable called for its side effects. We
could argue that printf is misdesigned (I would): the return value is
not useful, otherwise it would be used more. And if printf threw an
exception when something didn't work, that would be appropriate
because it fails so rarely that, if it does fail, I probably want to
know.

> > However, if a function throws instead of
> > returning a value, ignoring that value becomes more difficult for the
> > caller and can extract a performance penalty that may be unacceptable to
> > the caller.
>
> There's that premature micro-optimization again.

Let's be clear here: the entire discussion is about *inappropriate*
use of exceptions. This isn't a premature optimisation. It's about
deciding when an exception is appropriate and when not. If I throw an
exception when I shouldn't, I make the API harder to use *and* less
efficient. The real crime isn't the loss of efficiency though, it's
the inappropriate exception.

> I've been wondering when you would reach the conclusion that an API
> should offer both forms. For example, Python offers both key-lookup that
> raises exceptions (dict[key]) and key-lookup that doesn't (dict.get(key)).
>
> The danger of this is that it complicates the API, leads to a more
> complex implementation, and may result in duplicated code (if the two
> functions have independent implementations).

Offering a choice in some form can be appropriate for some APIs. I'm
not advocating it as a panacea, and I'm aware of the down-side in
increased complexity, learning curve, etc. (BTW, the article discusses
this issue in some detail.)

> Well, obviously I agree that you should only make things be an exception
> if they actually should be an exception. I don't quite see where the
> implication is

In the context of the original article, I argued that throwing
exceptions that are inappropriate is one of the many things that API
designers get wrong. To many people, that's stating the obvious. The
number of APIs that still make exactly this mistake suggests that the
point is worth making though.

Anyway, some of the early posts implied that I was arguing against
exception handling per-se because exceptions can be less efficient. I
responded to correct that misconception. What the article really said
is that throwing an exception when none should be thrown is bad API
design, and inefficient to boot. I stand by that statement.

Cheers,

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


Re: File transfer with python

2010-01-06 Thread Emile van Sebille

On 1/6/2010 10:00 AM Valentin de Pablo Fouce said...

Hi there,

I hope this is the rigth place, if not please, tell me which is the
right dicussion place. I apologize in such case.

Ok, I am trying to do a very quick application (is "home based" so is
not a big deal...). My intention is to transfer files from one
computer to another.

I am using several OS (Linux and Windows basicly, but potentially in
the future Mac too), and the computers won't be potentially in the
same network (ok, the most times will... but there will be
exceptions).


cygwin + scp or rsync are other options.

Emile




My intention is to be able to transfer files from one computer to
another in this environment.

Looking (and surfing) at internet the only suggestion given is to use
low level sockets for this file transfer. Is there another way to do
it, is there any top level library that helps you to do that?

That's a lot!



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


Re: creating tar file and streaming it over HTTP?

2010-01-06 Thread Steve Holden
r0g wrote:
> pbienst wrote:
>> I would like to bundle up a number of files in a tar file and send it
>> over a HTTP connection, but I would like to do this without creating
>> the tar file on disk first.
>>
> 
> Stringio lets you treat a strings as a files...
> 
> http://docs.python.org/library/stringio.html
> 
> Roger.

... though that does mean that the whole tar file has to be created
before it can be sent, I suspect. If it will comfortably fit into memory
that shouldn't matter, of course.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mencoder and creating videos

2010-01-06 Thread Emile van Sebille

On 1/6/2010 12:44 PM aditya shukla said...

Hello Guys,

I have a multiprocessing script which downloads images from 5 urls to 5
directories(usinf multiprocess in python 2.6).The download is for 5
mins.My aim is to create a video for every minute for each directory and
dump the images as the video is created. My question are , should i use
_*mencoder.exe*_ to create the videos?


I did something similar but on linux and used mencoder -- I'm guessing 
you can do the same on windows.



and how should i create the
videos without interrupting the download.


In my situation I'd set up an ftp server and had webcams sending images 
once a second there.  I'd also set up a cron job (scheduled task on 
windows systems) to create the video and archive the images.


Emile

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


Re: creating tar file and streaming it over HTTP?

2010-01-06 Thread r0g
pbienst wrote:
> I would like to bundle up a number of files in a tar file and send it
> over a HTTP connection, but I would like to do this without creating
> the tar file on disk first.
> 

Stringio lets you treat a strings as a files...

http://docs.python.org/library/stringio.html

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


Re: File transfer with python

2010-01-06 Thread Jan Kaliszewski

Valentin de Pablo Fouce  wrote:


Ok, I am trying to do a very quick application (is "home based" so is
not a big deal...). My intention is to transfer files from one
computer to another.



My intention is to be able to transfer files from one computer to
another in this environment.

Looking (and surfing) at internet the only suggestion given is to use
low level sockets for this file transfer. Is there another way to do
it, is there any top level library that helps you to do that?


Python standard library offers tools for HTTP communication (rather easy  
to use) -- see:

http://docs.python.org/library/simplehttpserver.html
http://docs.python.org/library/cgihttpserver.html
http://docs.python.org/library/basehttpserver.html
-- as well as:
http://docs.python.org/library/urllib.html
http://docs.python.org/library/urllib2.html

Cheers,
*j

--
Jan Kaliszewski (zuo) 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Steve Holden
Phlip wrote:
> On Jan 6, 10:23 am, Lie Ryan  wrote:
>> On 1/7/2010 3:41 AM, Phlip wrote:
>>
>>> Steve Holden wrote:
 y'all just keep defending the approach to programming that
 *you* think is best.
>>> Speak for yourself...
>> Everyone speaks for themselves, is that a problem?
> 
> Of course not. I was pointing out that Steve is telling me not to
> force my programming opinions on everyone...
> 
> ...while defending Python enforcing programming opinions on everyone.
> 
That's because Python is not a person, and Guido is a better language
designer than both of us put together. No languagecan be all things to
all programmers, and Python represents a set of pragmatic and useful
choices.

> And now, if everyone will excuse me, I have to get back to writing a
> unit-test-to-code ratio of 2:1. Have fun being rigorous, everyone!

Consider yourself excused ;-)

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


QDoubleValidator

2010-01-06 Thread Zabin
Hey!

I am new PyQt programmer and want to restrict users to allow only
numeric values into a table and lineedit boxes. I found the
QDoubleValidator class but am unsure as to how to implement it. (I am
a little shaky on the concept of parent and how to define them). Any
help would be much appreciated!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: please help shrink this each_with_index() implementation

2010-01-06 Thread Steven D'Aprano
On Wed, 06 Jan 2010 12:12:08 -0800, Phlip wrote:

> And I, not my language, should pick and chose how to be rigorous. The
> language should not make the decision for me.

All languages make that decision for you by making some thing possible 
and other things not. The language designer, not the programmer, decides 
what syntactic features to allow and disallow, what programming styles to 
include, and what functionality to provide as primitives.




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


Re: Introspection

2010-01-06 Thread Jason Scheirer
On Jan 6, 8:38 am, Steven D'Aprano  wrote:
> On Wed, 06 Jan 2010 06:53:40 -0800, m...@infoserv.dk wrote:
> > I'm looking for a way to make a list of string literals in a class.
>
> > Example:
>
> > class A:
> >    def method(self):
> >        print 'A','BC'
>
>  ExtractLiterals(A)
> > ['A','BC']
>
> > Is this possible? Can anyone point me in the right direction?
>
> class A:
>     def extract_literals(self):
>         return "A BC".split()
>     def method(self):
>         print self.extract_literals()
>
> a = A()
> a.extract_literals()
>
> --
> Steven

Slightly more robust than Miki's solution insofar as it doesn't
require the source to exist in a .py file:

import types
def extract_literals(klass):
for attr in (getattr(klass, item) for item in dir(klass)):
if isinstance(attr, types.MethodType):
for literal in attr.im_func.func_code.co_consts:
if isinstance(literal, basestring):
yield literal

class full_of_strings(object):
def a(self):
return "a", "b", "c"
def b(self):
"y", "z"

print list(extract_literals(full_of_strings))
['a', 'b', 'c', 'y', 'z']

print list(extract_literals(full_of_strings()))
['a', 'b', 'c', 'y', 'z']

Note that this is evil and should be avoided.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Steven D'Aprano
On Wed, 06 Jan 2010 12:39:36 -0800, Phlip wrote:

> And now, if everyone will excuse me, I have to get back to writing a
> unit-test-to-code ratio of 2:1.

In my experience, that's about half as many unit-tests as needed for full 
code coverage for even a simple class. If you're trying to impress us, 
you have failed.


> Have fun being rigorous, everyone!

You say that as if writing correct code was a bad thing.



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


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Terry Reedy

On 1/6/2010 1:20 PM, Lie Ryan wrote:


Python decided that the default behavior should be raising exception and
sentinel have to use the dict.get() method. Simple and clear. The other
possible behavior (i.e. slicing returns a sentinel while dict.get()
raises an exception) is arguably just as simple and just as clear; but
python doesn't do it that way. Why? Because it's part of what makes
python Python[1].


The altermatives are not quite equivalent. The current way lets one 
specify the sentinel whereas the alternative does not. There is hardly 
any reason to specify the exception.


tjr

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


Mencoder and creating videos

2010-01-06 Thread aditya shukla
Hello Guys,

I have a multiprocessing script which downloads images from 5 urls to 5
directories(usinf multiprocess in python 2.6).The download is for 5 mins.My
aim is to create a video for every minute for each directory and dump the
images as the video is created. My question are , should i use *mencoder.exe
* to create the videos?  and how should i create the videos without
interrupting the download.

Thanks

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


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Phlip
On Jan 6, 10:23 am, Lie Ryan  wrote:
> On 1/7/2010 3:41 AM, Phlip wrote:
>
> > Steve Holden wrote:
>
> >> y'all just keep defending the approach to programming that
> >> *you* think is best.
>
> > Speak for yourself...
>
> Everyone speaks for themselves, is that a problem?

Of course not. I was pointing out that Steve is telling me not to
force my programming opinions on everyone...

...while defending Python enforcing programming opinions on everyone.

And now, if everyone will excuse me, I have to get back to writing a
unit-test-to-code ratio of 2:1. Have fun being rigorous, everyone!
-- 
http://mail.python.org/mailman/listinfo/python-list


an't start a thread Pool from another thread

2010-01-06 Thread Glazner
Hi all,
I hope someone can help me with this issue
I see that i can't start a thread Pool from another thread, why?

running python 2.6.4 windowsXP
>>> import multiprocessing.dummy as threads
>>> def makePool():
threads.Pool(3)

>>> makePool()
>>> import thread
>>> thread.start_new(makePool,())
Unhandled exception in thread started by 
6960
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: please help shrink this each_with_index() implementation

2010-01-06 Thread Phlip

Nobody wrote:

On Tue, 05 Jan 2010 19:46:01 -0800, alex23 wrote:


They will tell me how to use except: (which is a good example why a
program should not use exceptions for its normal control flow if at
all possible).

Really? Magic functions that coerce and eat errors are a better coding
technique than exceptions and explicit handling?

What kool-aid have you been drinking?


Maybe he's doing it for a living?

Contract programming seems to work on the basis that the ultimate
requirement is for the client to hand over the money. If, at that point,
the program is still full of bugs, you get to charge extra for "upgrades".


Uh, no, right now I'm working with the long-term goal of creating useful modules 
that sustain us equitably.



Writing robust software from the outset puts you at a competitive
disadvantage to those who understand how the system works.


And I, not my language, should pick and chose how to be rigorous. The language 
should not make the decision for me.

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


The END (of PyCon early bird registration) is NEAR!

2010-01-06 Thread VanL
Today is the last day of registration for PyCon 2010 at the early bird
rate. Registration at the early bird rate is still good as long as it is
January 6 somewhere in the world.

Register now!  - https://us.pycon.org/2010/register/

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


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Grant Edwards
On 2010-01-06, Lie Ryan  wrote:
> On 1/7/2010 3:41 AM, Phlip wrote:
>> Steve Holden wrote:
>>
>>> y'all just keep defending the approach to programming that
>>> *you* think is best.
>>
>> Speak for yourself...
>
> Everyone speaks for themselves, [...]

Except for the Lorax.  He speaks for the trees.

-- 
Grant Edwards   grante Yow! The SAME WAVE keeps
  at   coming in and COLLAPSING
   visi.comlike a rayon MUU-MUU ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess.Popen does not close pipe in an error case

2010-01-06 Thread Steven K. Wong
On Jan 6, 10:30 am, Nobody  wrote:
> I think that you should close prog1.stdout here. Otherwise, there will
> be two readers on the pipe (the calling process and prog2). Even if one of
> them dies, there's always the possibility that the caller might eventually
> decide to read prog1.stdout itself. If you close it in the caller, when
> prog2 terminates there will be no readers, and prog1 will get SIGPIPE (or
> write() will fail with EPIPE if SIGPIPE is handled).

Thanks for raising a great point, that prog1.stdout is also readable
by the calling process, not just by prog2. Therefore, I agree it makes
sense to explicitly call prog1.stdout.close() in the given code (say
right after the creation of prog2).

Suppose now all the prog1.poll() calls/loop are replaced by a single
prog1.wait(). Without the explicit prog1.stdout.close(), prog1.wait()
will not return, so the calling process still hangs. Because calling
prog1.wait() means that the calling process will naturally never read
prog1.stdout, I would argue that prog1.wait() should close the pipe
before actually waiting for prog1 to exit. Makes sense?
-- 
http://mail.python.org/mailman/listinfo/python-list


Need help with multiprocessing.manager and passing the manager a multiprocessing.Connection

2010-01-06 Thread Metalone
The following code snippet is taken from the Python 2.6
multiprocessing documentation with a simple change and this change
does not work.  I would like to know how to make it work or something
similar.
I want to pass a Connection object to the MathsClass.
I get the following error on Windows:

Traceback (most recent call last):
  File "c:\apps\python26\lib\multiprocessing\managers.py", line 214,
in serve_cl
ient
request = recv()
TypeError: Required argument 'handle' (pos 1) not found


from multiprocessing.managers import BaseManager
from multiprocessing import Pipe# I added this

class MathsClass(object):
def set(self, conn):  # I added the set() function
self.conn = conn
def add(self, x, y):
return x + y
def mul(self, x, y):
return x * y

class MyManager(BaseManager):
pass

MyManager.register('Maths', MathsClass)

if __name__ == '__main__':
parent_conn, child_conn = Pipe()# I added this
manager = MyManager()
manager.start()
maths = manager.Maths()
print maths.add(4, 3) # prints 7
print maths.mul(7, 8) # prints 56
maths.set(child_conn)   # I added this, error is thrown here
-- 
http://mail.python.org/mailman/listinfo/python-list


Astronomy--Programs to Compute Siderial Time?

2010-01-06 Thread W. eWatson
Is there a smallish Python library of basic astronomical functions? 
There are a number of large such libraries that are crammed with 
excessive functions not needed for common calculations.

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


Re: getfirst and re

2010-01-06 Thread Victor Subervi
On Wed, Jan 6, 2010 at 3:09 PM, Carsten Haese wrote:

> Victor Subervi wrote:
> > I have an automatically generated HTML form from which I need to extract
> > data to the script which this form calls (to which the information is
> > sent).
>
> Ideally, the script that receives the submitted fields should know how
> the form was generated, so it knows what fields to expect. Failing that,
>  you should realize that getfirst() is not the only way to access the
> contents of a cgi.FieldStorage object.
>
> If you need to know the values of all fields whose names obey a certain
> pattern, I recommend you start with a list of all field names in the
> FieldStorage object and pick out the ones whose names obey that pattern.
> To get the list of field names, you should consider using the .keys()
> method of the FieldStorage object.
>

Cool. Thanks!
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getfirst and re

2010-01-06 Thread Carsten Haese
Victor Subervi wrote:
> I have an automatically generated HTML form from which I need to extract
> data to the script which this form calls (to which the information is
> sent).

Ideally, the script that receives the submitted fields should know how
the form was generated, so it knows what fields to expect. Failing that,
 you should realize that getfirst() is not the only way to access the
contents of a cgi.FieldStorage object.

If you need to know the values of all fields whose names obey a certain
pattern, I recommend you start with a list of all field names in the
FieldStorage object and pick out the ones whose names obey that pattern.
To get the list of field names, you should consider using the .keys()
method of the FieldStorage object.

-Carsten

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


Re: suds problem

2010-01-06 Thread Fencer

On 2010-01-06 19:33, Fencer wrote:

Hello, I just started using suds to use web services. First I tried suds
with a very simple web service I had written and was running myself.
That worked fine. Then I tried to use the web services provided by KEGG:
http://soap.genome.jp/KEGG.wsdl
But I get a SAXParseException due to a supposed mis-matched tag when I
try to consume that wsdl with suds. I checked the wsdl in oxygene and it
claims it's valid. What is the problem here? My test program is below
and it's very simple:
from suds.client import Client

url = 'http://soap.genome.jp/KEGG.wsdl'

client = Client(url)

print client

- Fencer


Same problem with reactome:
http://www.reactome.org:8080/caBIOWebApp/services/caBIOService?wsdl

I suppose I'm mis-using suds, maybe some setting that wasn't needed for 
my simple web service but is needed for kegg and reactome.


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


Re: Python books, literature etc

2010-01-06 Thread J
A good point was brought up to me privately, and I agree completely,
that the OP should re-state the request with a bit more specifics...

Since the OP says he is at least familiar with Python, does he need
info on beginner level books that are general purpose, or is he
interested in resources that are more specific (e.g. geared toward web
programming, mathematical analysis, data modeling, etc)

My suggestions were meant just as an example of what I use in the
course of learning something at the basic and intermediate level, once
it goes beyond that, it's useful to know WHAT you intend to do so you
can find the right resources to go in that direction.

Just want to make sure I am not misunderstood or anything :-)

For what it's worth, I also tend to collect technical books for some
reason... My wife is just barely tolerant of my bookshelf full of
things on various computer topics, astronomy, photography, radio and
antenna theory and so forth ;-)  I just let her keep her shoe
collection, and we have a quid pro quo.

Cheers
Jeff



-- 

Mike Ditka  - "If God had wanted man to play soccer, he wouldn't have
given us arms." -
http://www.brainyquote.com/quotes/authors/m/mike_ditka.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File transfer with python

2010-01-06 Thread Lie Ryan

On 1/7/2010 5:00 AM, Valentin de Pablo Fouce wrote:

My intention is to be able to transfer files from one computer to
another in this environment.


Do you have a USB flashdrive?


Looking (and surfing) at internet the only suggestion given is to use
low level sockets for this file transfer. Is there another way to do
it, is there any top level library that helps you to do that?


Networked file system (e.g. Samba/SMB), File Transfer Protocol (FTP), 
whatever works for you. pysamba is available from sourceforge and there 
is ftplib in the standard library. For most purposes though, you could 
just setup a network shared directory and drag and drop files from the 
file manager.

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


Re: python xmlrpc client with ssl client certificates and standard modules

2010-01-06 Thread Heikki Toivonen
News123 wrote:
> This will probably work, but it requires the module M2Crypto.
> 
> In order to avoid installing M2Crypto an all hosts that want to run the
> script I wondered, whether there is no other solution.
> 
> I can do xmlrpc over ssl WITHOUT certificates with following code:
[...]

Please note that if you just use the stdlib it is not secure out of the
box. With Python 2.6 and the ssl module you can make it so, but it
requires some work on your part. See for example
http://www.heikkitoivonen.net/blog/2008/10/14/ssl-in-python-26/

-- 
  Heikki Toivonen - http://heikkitoivonen.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess.Popen does not close pipe in an error case

2010-01-06 Thread Nobody
On Tue, 05 Jan 2010 15:50:39 -0800, Steven K. Wong wrote:

> Below, I have a Python script that launches 2 child programs, prog1
> and prog2, with prog1's stdout connected to prog2's stdin via a pipe.
> (It's like executing "prog1 | prog2" in the shell.)
> 
> If both child programs exit with 0, then the script runs to
> completion. But if prog2 exits with non-0, prog1 does not exit and the
> script hangs (i.e. prog1.poll() always returns None) -- unless I
> uncomment the 2 lines marked by XXX to close prog1.stdout.
> 
> I was expecting that I don't have to explicitly close prog1.stdout,
> whether prog2 succeeds or fails. Is the current behavior a bug in the
> subprocess module or is it expected? Or am I doing something wrong?
> 
> Thanks.
> 
> import subprocess
> import time
> 
> # prog1: a program that writes lots of data to the pipe
> cmd = ['zcat', '--force', 'a_large_file']
> prog1 = subprocess.Popen(cmd, bufsize=-1, stdout=subprocess.PIPE)
> 
> # prog2: a program that fails without reading much data from the pipe
> cmd = ['python', '-c', 'import time; time.sleep(10); asdf']
> prog2 = subprocess.Popen(cmd, bufsize=-1, stdin=prog1.stdout,
> stdout=open('popen.out', 'w'))

I think that you should close prog1.stdout here. Otherwise, there will
be two readers on the pipe (the calling process and prog2). Even if one of
them dies, there's always the possibility that the caller might eventually
decide to read prog1.stdout itself. If you close it in the caller, when
prog2 terminates there will be no readers, and prog1 will get SIGPIPE (or
write() will fail with EPIPE if SIGPIPE is handled).


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


Re: 3 byte network ordered int, How To ?

2010-01-06 Thread Matthew Barnett

mudit tuli wrote:

For a single byte, struct.pack(')
For two bytes, struct.pack(')
what if I want three bytes ?


Four bytes and then discard the most-significant byte:

struct.pack(')[ : -1]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Lie Ryan

On 1/7/2010 3:41 AM, Phlip wrote:

Steve Holden wrote:


y'all just keep defending the approach to programming that
*you* think is best.


Speak for yourself...


Everyone speaks for themselves, is that a problem?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Lie Ryan

On 1/7/2010 2:12 AM, Phlip wrote:

On Jan 5, 10:54 pm, Benjamin Kaplan  wrote:


{41: None}[41] ?

In cases where None is a valid result, you can't use it to signal failure..


Asked and answered. You change the "sentinel" in .fetch to something
else.


I believe Ben Kaplan's point is that if dict slicing returns sentinel 
for missing keys, the slicing syntax would be unusable to differentiate 
{41: sentinel} and {}; if the default sentinel had been None, that would 
make it too easy to forget to reset the sentinel and wrote a buggy code.



But y'all keep on defending the language making your programming
decisions for you!


When designing a language, there are two different ways to signal a 
missing key in a dict: 1) raise an exception or 2) return a sentinel. 
Both are useful for different purpose. One or the other must be the 
default behavior, and the other must give way.


Python decided that the default behavior should be raising exception and 
sentinel have to use the dict.get() method. Simple and clear. The other 
possible behavior (i.e. slicing returns a sentinel while dict.get() 
raises an exception) is arguably just as simple and just as clear; but 
python doesn't do it that way. Why? Because it's part of what makes 
python Python[1].



But y'all keep on defending the language making your programming
decisions for you!


Indeed, the language makes decisions for you; why would you want to use 
a language that nags you for every possible different behavior? I want a 
reasonable default and I want a reasonably easy way to access the 
non-default behaviors.


[1] the essence of which is emboldened as the Zen, which is the broad 
design guideline for both python's syntax and codes written in python. 
Specifically, "Errors should never pass silently" because missing key 
indicates a possible error and "Simple is better than complex" because 
returning sentinel for missing keys implies the need for an interface to 
change the sentinel[2].
[2] or become like Java, whose HashMap cannot reliably store null and 
doesn't allow you to specify the sentinel.

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


Re: please help shrink this each_with_index() implementation

2010-01-06 Thread Nobody
On Tue, 05 Jan 2010 19:46:01 -0800, alex23 wrote:

>> They will tell me how to use except: (which is a good example why a
>> program should not use exceptions for its normal control flow if at
>> all possible).
> 
> Really? Magic functions that coerce and eat errors are a better coding
> technique than exceptions and explicit handling?
> 
> What kool-aid have you been drinking?

Maybe he's doing it for a living?

Contract programming seems to work on the basis that the ultimate
requirement is for the client to hand over the money. If, at that point,
the program is still full of bugs, you get to charge extra for "upgrades".

Writing robust software from the outset puts you at a competitive
disadvantage to those who understand how the system works.

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


Re: please help shrink this each_with_index() implementation

2010-01-06 Thread Carl Banks
On Jan 5, 2:40 pm, Phlip  wrote:
> On Jan 5, 1:10 pm, Antoine Pitrou  wrote:
>
> >http://docs.python.org/library/functions.html
>
> > Don't forget that the Python documentation is rich and structured.
> > And good luck.
>
> Does it say how to convert a string containing either an integer
> representation, or something alphabetic, into an integer, or a zero,
> in like 1 method call?


No, as he said, it only describes the most important functions.


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


File transfer with python

2010-01-06 Thread Valentin de Pablo Fouce
Hi there,

I hope this is the rigth place, if not please, tell me which is the
right dicussion place. I apologize in such case.

Ok, I am trying to do a very quick application (is "home based" so is
not a big deal...). My intention is to transfer files from one
computer to another.

I am using several OS (Linux and Windows basicly, but potentially in
the future Mac too), and the computers won't be potentially in the
same network (ok, the most times will... but there will be
exceptions).

My intention is to be able to transfer files from one computer to
another in this environment.

Looking (and surfing) at internet the only suggestion given is to use
low level sockets for this file transfer. Is there another way to do
it, is there any top level library that helps you to do that?

That's a lot!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getfirst and re

2010-01-06 Thread Victor Subervi
On Wed, Jan 6, 2010 at 1:59 PM, Tim Chase wrote:

> Victor Subervi wrote:
>
>> On Wed, Jan 6, 2010 at 1:27 PM, Tim Chase > >wrote:
>>
>>  But if you're using it on HTML form text, regexps are usually the wrong
>>> tool, and you should be using an HTML parser (such as BeautifulSoup) that
>>> knows how to handle odd text and escapings better and more robustly than
>>> regexps will
>>>
>>
>> I have an automatically generated HTML form from which I need to extract
>> data to the script which this form calls (to which the information is
>> sent).
>> I believe BeautifulSoup is geared to scraping pages that exist permanently
>> on the web. By the time BeautifulSoup was called, this page would be gone.
>>
>
> BeautifulSoup takes string data fed to it, and builds a structure that can
> be neatly navigated.  That string data can come from a web page, from a
> disk, or even a serial port, a random-character-generator, or just from HTML
> that's built up in memory and never sees a network or a disk.  It's worth
> reading its documentation[1] and trying its examples to get familiar with
> it.
>

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


3 byte network ordered int, How To ?

2010-01-06 Thread mudit tuli
For a single byte, struct.pack(')
For two bytes, struct.pack(')
what if I want three bytes ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: please help shrink this each_with_index() implementation

2010-01-06 Thread Nobody
On Tue, 05 Jan 2010 12:20:58 -0800, Marco Nawijn wrote:

> You could use the build-in function enumerate inside a list
> comprehension.
> 
 seq = range(5)
 [ (i,s) for i,s in enumerate(seq) ]
> [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

Just use list(), i.e. "list(enumerate(seq))".

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


Re: getfirst and re

2010-01-06 Thread Tim Chase

Victor Subervi wrote:

On Wed, Jan 6, 2010 at 1:27 PM, Tim Chase wrote:


But if you're using it on HTML form text, regexps are usually the wrong
tool, and you should be using an HTML parser (such as BeautifulSoup) that
knows how to handle odd text and escapings better and more robustly than
regexps will


I have an automatically generated HTML form from which I need to extract
data to the script which this form calls (to which the information is sent).
I believe BeautifulSoup is geared to scraping pages that exist permanently
on the web. By the time BeautifulSoup was called, this page would be gone.


BeautifulSoup takes string data fed to it, and builds a structure 
that can be neatly navigated.  That string data can come from a 
web page, from a disk, or even a serial port, a 
random-character-generator, or just from HTML that's built up in 
memory and never sees a network or a disk.  It's worth reading 
its documentation[1] and trying its examples to get familiar with it.


-tkc


[1]
http://www.crummy.com/software/BeautifulSoup/documentation.html



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


Re: getfirst and re

2010-01-06 Thread Victor Subervi
On Wed, Jan 6, 2010 at 1:27 PM, Tim Chase wrote:

> But if you're using it on HTML form text, regexps are usually the wrong
> tool, and you should be using an HTML parser (such as BeautifulSoup) that
> knows how to handle odd text and escapings better and more robustly than
> regexps will.
>

I have an automatically generated HTML form from which I need to extract
data to the script which this form calls (to which the information is sent).
I believe BeautifulSoup is geared to scraping pages that exist permanently
on the web. By the time BeautifulSoup was called, this page would be gone.
Any other ideas?
TIA
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Pass multidimensional array (matrix) to c function using ctypes

2010-01-06 Thread Daniel Platz
Hello,

I would like to pass a two dimensional array to C function in a dll. I
use ctypes to call the function.

I compile the dll with visual studio 2008 express and my C source code
looks like this.

#include 
#ifdef __cplusplus
extern "C" {  // only need to export C interface if
  // used by C++ source code
using namespace std;
#endif


__declspec(dllexport) int print(double** ptr, int ny, int nx)
{
int i, j;
for(i=0; i

Furthermore, I am wondering if there is a fast way to use a numpy 2D
array instead or alternatively to cast the ctypes array into a numpy
array.

Has someone an idea to help me?

Thank you very much

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


Re: getfirst and re

2010-01-06 Thread Tim Chase

I need to do something like the following:

pat = re.compile('edit[0-9]*:[0-9]*')
check = form.getfirst(pat)

(to check things like 'edit0:1') How do I do this?


Well, you can do it either as

  check = pat.search(string_to_search)

which is pretty plainly detailed in the help for the "re" module, 
both under the search() function and under the "8.2.2 Matching 
vs. Searching" section.


Alternatively, if you plan to get the others too, you can use

  fi = pat.finditer(string_to_search)
  check = fi.next().group(0) # beware this may throw
  # a StopIteration if there are no more matches.

which would usually be done inside a loop where the StopIteration 
does the Right Thing(tm).


But if you're using it on HTML form text, regexps are usually the 
wrong tool, and you should be using an HTML parser (such as 
BeautifulSoup) that knows how to handle odd text and escapings 
better and more robustly than regexps will.


-tkc



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


Python tk Listbox: -listvariable

2010-01-06 Thread Looney, James B
Yesterday, I searched all over trying to figure out how to properly use the 
"listvariable" argument with tk's Listbox class.  Unfortunately, no amount of 
searching (online) could come up with anything more useful than telling me the 
variable needed to be a list, and nothing built-in exists.

I finally came across a way of using it that I consider fairly simple, and 
wanted to toss it out there for everyone else.  One post I saw mentioned using 
StringVar.  That just didn't work well in my head, so instead I used its parent 
class: Variable.  Apparently, the trick is to use tuples.  If I use a list, 
string, etc - the Listbox seems to split the content based on spaces.  Not the 
behavior I was looking for as I have spaces in the strings I wish to display.

If anyone has better suggestions, I'd love to hear them.  (I thought about a 
ListVar class, but haven't made it much beyond the thought).  Regardless, I 
hope the following code helps others avoid the confusion I went through.

Sample code:
import Tkinter, tkSimpleDialog
from Tkconstants import *

class ListboxTest( tkSimpleDialog.Dialog ):
   #
   def __init__( self, master, tupleItems = () ):
  self.myVar = Tkinter.Variable()
  self.myVar.set( tupleItems )

  tkSimpleDialog.Dialog.__init__( self, master, "Listbox testing" )

   #
   def body( self, master ):
  lbox = Tkinter.Listbox( master, listvariable = self.myVar )
  lbox.grid( row = 0, column = 0, sticky = N + W )
  self.myVar.set( self.myVar.get() + tuple( [ "* Final string being 
added *" ] ) )
  print type( self.myVar.get() ), self.myVar.get()

if( "__main__" == __name__ ):
   tk = Tkinter.Tk()
   lt = ListboxTest( tk, tuple( [ "String 1 - with some spaces", "String 2 - 
with more spaces" ] ) )
-- 
http://mail.python.org/mailman/listinfo/python-list


getfirst and re

2010-01-06 Thread Victor Subervi
Hi;
I need to do something like the following:

pat = re.compile('edit[0-9]*:[0-9]*')
check = form.getfirst(pat)

(to check things like 'edit0:1') How do I do this?
TIA,
beno

-- 
The Logos has come to bear
http://logos.13gems.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >