Re: Why is python not written in C++ ?

2010-08-05 Thread David Cournapeau
On Fri, Aug 6, 2010 at 8:45 AM, Roy Smith  wrote:
> In article ,
>  Lawrence D'Oliveiro  wrote:
>
>> In message , Roy Smith wrote:
>>
>> > C++, for all its flaws, had one powerful feature which made it very
>> > popular.  It is a superset of C.
>>
>> Actually, it never was.
>
> Yes, there are a few corner cases where valid C syntax has different
> semantics in C and C++.  But, they are very few.  Calling C++ a superset
> of C is essentially correct.

This is only true if you limit yourself to C89 (as python seems to
do). If  you start using C99 (and lot of people do, if only because
they don't realize it because gcc is quite relax about it), then
almost no non trivial C code is valid C++ in my experience.

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


Re: Import python modules from sub-directories

2010-08-05 Thread Ralf Schoenian

Navkirat Singh wrote:

Hi guys,

I am new to python and would like to import certain classes in sub-directories 
of the working directory. I was wondering how will I be able to achieve this?

Regards,
Nav


Hi,

put an empty file with the name __init__.py in your subdirectory. I call 
it sub1 here. Assuming your filename is importme.py and your classname 
is Test you can do the following imports:


from sub1.importme import Test
import sub1.importme

You can find further explainations in the official tutorial 
http://docs.python.org/tutorial/modules.html


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


Re: Import python modules from sub-directories

2010-08-05 Thread Navkirat Singh

On 06-Aug-2010, at 10:44 AM, Navkirat Singh wrote:

> Hi guys,
> 
> I am new to python and would like to import certain classes in 
> sub-directories of the working directory. I was wondering how will I be able 
> to achieve this?
> 
> Regards,
> Nav


Thanks. I got it. I just put an empty __init__.py file in the subdirectories 
and it worked.


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


Re: Struggling to convert a mysql datetime object to a python string of a different format

2010-08-05 Thread John Nagle

On 8/4/2010 4:40 PM, Νίκος wrote:


cursor.execute( ''' SELECT host, hits, date FROM visitors WHERE 
page
= '%s' ORDER BY date DESC ''' % (page) )


Don't do string substitution ("%") on SQL statements.  Let MySQLdb do it 
for you, with proper escaping:


   cursor.execute('''SELECT host, hits, date FROM visitors WHERE page=%s
ORDER BY date DESC''', (page,))

The difference is that if some external source can control "page", and
they put in a value like

100 ; DELETE FROM visitors; SELECT * FROM visitors

you just lost your data.

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


Import python modules from sub-directories

2010-08-05 Thread Navkirat Singh
Hi guys,

I am new to python and would like to import certain classes in sub-directories 
of the working directory. I was wondering how will I be able to achieve this?

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


Re: Python Portability--Not very portable?

2010-08-05 Thread geremy condra
On Thu, Aug 5, 2010 at 8:28 PM, W. eWatson  wrote:
> On 8/5/2010 7:45 PM, geremy condra wrote:
>>
>> On Thu, Aug 5, 2010 at 6:50 PM, W. eWatson  wrote:
>>>
>>> In my on-again-off-again experience with Python for 18 months,
>>> portability
>>> seems an issue.
>>>
>>> As an example, my inexperienced Python partner 30 miles away has gotten
>>> out
>>> of step somehow. I think by installing a different version of numpy than
>>> I
>>> use. I gave him a program we both use months ago, and he had no trouble.
>>> (We
>>> both use IDLE on 2.5). I made a one character change to it and sent him
>>> the
>>> new py file. He can't execute it. I doubt he has changed anything in the
>>> intervening period.
>>
>> Portability doesn't mean you can use different versions of your
>> dependencies and be A-OK. It should be fairly obvious that if the
>> behavior of your dependencies changes, your code needs to change to
>> ensure that it demonstrates the same behavior. Portability also
>> doesn't mean that any given one-character change is valid, so that may
>> be your issue as well.
>>
>>> A further example. Months ago I decided to see if I could compile a
>>> program
>>> to avoid such problems as above. I planned to satisfy that need, and see
>>> if
>>> I could distribute some simple programs to non-Python friends. I pretty
>>> well
>>> understand the idea,and got it working with a small program. It seemed
>>> like
>>> a lot of manual labor to do it.
>>
>> What, why were you compiling a program? And why not just use distutils?
>>
>> Geremy Condra
>
> I checked the one char change on my system thoroughly. I looked around on
> some forums and NGs 4 months ago, and found no one even had a simple
> "compiled program" available to even demonstrate some simple example.

That would be because Python is an interpreted language.

> I would think there are some small time and big time Python players who sell
> executable versions of their programs for profit?

Yes. What's your point?

> disutils. Sounds familiar. I'm pretty sure I was using Py2Exe, and disutils
> might have been part of it.

distutils.

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

> So how does one keep a non-Python user in lock step with my setup, so these
> problems don't arise? I don't even want to think about having him uninstall
> and re-install. :-) Although maybe he could do it without making matters
> worse.

That's going to hinge on what your dependencies are.

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


Re: Python Portability--Not very portable?

2010-08-05 Thread W. eWatson

On 8/5/2010 7:45 PM, geremy condra wrote:

On Thu, Aug 5, 2010 at 6:50 PM, W. eWatson  wrote:

In my on-again-off-again experience with Python for 18 months, portability
seems an issue.

As an example, my inexperienced Python partner 30 miles away has gotten out
of step somehow. I think by installing a different version of numpy than I
use. I gave him a program we both use months ago, and he had no trouble. (We
both use IDLE on 2.5). I made a one character change to it and sent him the
new py file. He can't execute it. I doubt he has changed anything in the
intervening period.


Portability doesn't mean you can use different versions of your
dependencies and be A-OK. It should be fairly obvious that if the
behavior of your dependencies changes, your code needs to change to
ensure that it demonstrates the same behavior. Portability also
doesn't mean that any given one-character change is valid, so that may
be your issue as well.


A further example. Months ago I decided to see if I could compile a program
to avoid such problems as above. I planned to satisfy that need, and see if
I could distribute some simple programs to non-Python friends. I pretty well
understand the idea,and got it working with a small program. It seemed like
a lot of manual labor to do it.


What, why were you compiling a program? And why not just use distutils?

Geremy Condra


I checked the one char change on my system thoroughly. I looked around 
on some forums and NGs 4 months ago, and found no one even had a simple 
"compiled program" available to even demonstrate some simple example.


I would think there are some small time and big time Python players who 
sell executable versions of their programs for profit?


disutils. Sounds familiar. I'm pretty sure I was using Py2Exe, and 
disutils might have been part of it.


So how does one keep a non-Python user in lock step with my setup, so 
these problems don't arise? I don't even want to think about having him 
uninstall and re-install. :-) Although maybe he could do it without 
making matters worse.

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


Re: Python Portability--Not very portable?

2010-08-05 Thread geremy condra
On Thu, Aug 5, 2010 at 6:50 PM, W. eWatson  wrote:
> In my on-again-off-again experience with Python for 18 months, portability
> seems an issue.
>
> As an example, my inexperienced Python partner 30 miles away has gotten out
> of step somehow. I think by installing a different version of numpy than I
> use. I gave him a program we both use months ago, and he had no trouble. (We
> both use IDLE on 2.5). I made a one character change to it and sent him the
> new py file. He can't execute it. I doubt he has changed anything in the
> intervening period.

Portability doesn't mean you can use different versions of your
dependencies and be A-OK. It should be fairly obvious that if the
behavior of your dependencies changes, your code needs to change to
ensure that it demonstrates the same behavior. Portability also
doesn't mean that any given one-character change is valid, so that may
be your issue as well.

> A further example. Months ago I decided to see if I could compile a program
> to avoid such problems as above. I planned to satisfy that need, and see if
> I could distribute some simple programs to non-Python friends. I pretty well
> understand the idea,and got it working with a small program. It seemed like
> a lot of manual labor to do it.

What, why were you compiling a program? And why not just use distutils?

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


Re: Why is there no platform independent way of clearing a terminal?

2010-08-05 Thread alex23
Lawrence D'Oliveiro  wrote:
> You’ve got to be kidding. Look at the number of Windows-specific questions
> this groups is already full of.

Are you really unable to tell the difference between questions about
Windows-related modules and snarky, off-topic sniping at Windows
itself?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pre-uninstall script in bdist_wininst

2010-08-05 Thread Mark Hammond

On 6/08/2010 4:26 AM, Nils wrote:

Hi.
I am using a postinstall-script like this:
setup(
 ...
 scripts=['scripts\install.py'],
 options = {
 ...
 "bdist_wininst" : {
 "install_script" : "install.py",
 ...
 },
 }
)

According to the docs in [1] this script is
a) called after install (with the "-install" parameter) - this works
fine for me...
b) called before uninstall (with tho "-remove" parameter) - this
however does not work.


According to a comment in pywin32's post-install script:

elif arg == "-remove":
# bdist_msi calls us before uninstall, so we can undo what we
# previously did.  Sadly, bdist_wininst calls us *after*, so
# we can't do much at all.

So it seems possible your script is failing due to an import error as 
your module has already been removed.  Maybe a .msi would work better 
for you.



btw: With that I am trying to register a com-server on install and de-
register on uninstall - so if other ideas are around I'd love to hear
them, too...


I'd suggest using py2exe to package the object and inno installer or 
similar to handle the install and uninstall parts.


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


Python Portability--Not very portable?

2010-08-05 Thread W. eWatson
In my on-again-off-again experience with Python for 18 months, 
portability seems an issue.


As an example, my inexperienced Python partner 30 miles away has gotten 
out of step somehow. I think by installing a different version of numpy 
than I use. I gave him a program we both use months ago, and he had no 
trouble. (We both use IDLE on 2.5). I made a one character change to it 
and sent him the new py file. He can't execute it. I doubt he has 
changed anything in the intervening period.


A further example. Months ago I decided to see if I could compile a 
program to avoid such problems as above. I planned to satisfy that need, 
and see if I could distribute some simple programs to non-Python 
friends. I pretty well understand the idea,and got it working with a 
small program. It seemed like a lot of manual labor to do it.

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


Re: [Tutor] Finding the version # of a module, and py module problem

2010-08-05 Thread Philip Semanchuk


On Aug 5, 2010, at 8:55 PM, W. eWatson wrote:

It's been awhile since I've used python, and I recall there is a way  
to find the version number from the IDLE command line  prompt. dir,  
help, __version.__?


Hi Wayne,
FYI it's got nothing to do with IDLE, it's just a question of whether  
or not the module in question exposes any kind of a version attribute.  
There's no standard, unfortunately. The most popular convention seems  
to be via an attribute called __version__, but I've also seen  
__VERSION__, VERSION, and version.


Here's some code that I wrote that you might find useful. It's from a  
setup.py and it checks a list of modules on which our project depends  
to see if (a) they're installed and (b) if the version installed is  
adequate. In the snippet below, dependencies is a list of custom  
classes that represent modules we need (e.g. numpy).



# Try each module
for dependency in dependencies:
try:
__import__(dependency.name)
except ImportError:
# Uh oh!
dependency.installed = None
else:
# The module loaded OK. Get a handle to it and try to  
extract

# version info.
# Many Python modules follow the convention of providing  
their

# version as a string in a __version__ attribute.
module = sys.modules[dependency.name]

# This is what I default to.
dependency.installed = "[version unknown]"

for attribute_name in ("__version__", "__VERSION__",  
"VERSION",

   "version"):
if hasattr(module, attribute_name):
dependency.installed = getattr(module,  
attribute_name)

break

Hope this helps a little,
Philip

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


Re: [Tutor] Finding the version # of a module, and py module problem

2010-08-05 Thread W. eWatson

On 8/5/2010 6:23 PM, MRAB wrote:

W. eWatson wrote:

It's been awhile since I've used python, and I recall there is a way
to find the version number from the IDLE command line prompt. dir,
help, __version.__?

I made the most minimal change to a program, and it works for me, but
not my partner. He gets

Traceback (most recent call last):
File "C:\Documents and
Settings\HP_Administrator.DavesDesktop\Desktop\NC-FireballReport20100729.py",
line 40, in 
from scipy import stats as stats # scoreatpercentile
File "C:\Python25\lib\site-packages\scipy\stats\__init__.py", line 7,
in 
from stats import *
File "C:\Python25\lib\site-packages\scipy\stats\stats.py", line 191,
in 
import scipy.special as special
File "C:\Python25\lib\site-packages\scipy\special\__init__.py", line
22, in 
from numpy.testing import NumpyTest
ImportError: cannot import name NumpyTest

Here are the first few lines of code.

import sys, os, glob
import string
from numpy import *
from datetime import datetime, timedelta
import time
from scipy import stats as stats # scoreatpercentile

I'm pretty sure he has the same version of Python, 2.5, but perhaps
not the numpy or scipy modules. I need to find out his version numbers.


Try:

import numpy
help(numpy.version)

BTW, on Python 2.6 I can see that there's "numpytest" but not
"NumpyTest".
I have to stick with 2.5 for comparability with my partner. He's 
non-Python but was able to get Python 2.5 working. I think he somehow 
bumped ahead to a later version of numpy than I have.

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


Re: [Tutor] Finding the version # of a module, and py module problem

2010-08-05 Thread W. eWatson

On 8/5/2010 6:13 PM, Steven D'Aprano wrote:

On Thu, 05 Aug 2010 17:55:30 -0700, W. eWatson wrote:


I'm pretty sure he has the same version of Python, 2.5, but perhaps not
the numpy or scipy modules. I need to find out his version numbers.


It's only a convention, but the usual way is to check the __version__
attribute. It works for Numpy:


import numpy
numpy.__version__

'1.0.3'




It is now written in my Py book. Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: defining, raising and catching exceptions

2010-08-05 Thread Steven D'Aprano
On Fri, 06 Aug 2010 01:37:17 +0100, MRAB wrote:

> The correct way to create your own exceptions is to call the
> superclass's __init__ method:
> 
> 
>  >>> class NetActiveError(RuntimeError):
> ... def __init__(self, error):
> ... RuntimeError.__init__(self, error)

As given, that's pointless since you're neither overriding (replacing) 
nor overloading the base class method. Since NetActiveError inherits ALL 
behaviour and state from RuntimeError, there's no need to overload 
anything at all, so the correct way to subclass is to simply give the 
subclass a name and (optionally) a docstring:

class NetActiveError(RuntimeError):
"""Description of error goes here."""


The only change from the OP's code is that instead of defining a non-
standard error attribute, it uses the standard message and args 
attributes:

>>> e = NetActiveError('network already running')
>>> e.message
'network already running'
>>> e.args
('network already running',)




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


Re: easy question on parsing python: "is not None"

2010-08-05 Thread Steven D'Aprano
On Thu, 05 Aug 2010 12:07:53 -0400, wheres pythonmonks wrote:

> P.S. Sorry for the top-post -- is there a way to not do top posts from
> gmail?  I haven't used usenet since tin.

Er, surely you can just move the cursor before you start typing???



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


Re: defining, raising and catching exceptions

2010-08-05 Thread Chris Hare

On Aug 5, 2010, at 7:37 PM, MRAB wrote:

> Chris Hare wrote:
>> okay - but why does the response come back like
>> No such file or directory
>> def b
>> ('n', 'e', 't', ' ', 'a', 'l', 'r', 'e', 'a', 'd', 'y', ' ', 'r', 'u', 'n', 
>> 'n', 'i', 'n', 'g')
> The class Exception saves its arguments in the 'args' instance
> attribute, and when it prints the exception it prints those arguments:
> 
> 
> >>> e = Exception(1, 2, 3)
> >>> print e.args
> (1, 2, 3)
> >>> print e
> (1, 2, 3)
> >>> print repr(e)
> Exception(1, 2, 3)
> 
> 
> NetActiveError inherits from RuntimeError, and ultimately from
> Exception.
> 
> NetActiveError sets the 'args' attribute to its single string argument,
> and when the exception is printed out it thinks it's the arguments:
> 
> 
> >>> e.args = "string"
> >>> print e
> ('s', 't', 'r', 'i', 'n', 'g')
> >>> print repr(e)
> Exception('s', 't', 'r', 'i', 'n', 'g')
> 
> 
> The correct way to create your own exceptions is to call the
> superclass's __init__ method:
> 
> 
> >>> class NetActiveError(RuntimeError):
> ... def __init__(self, error):
> ... RuntimeError.__init__(self, error)
> ...
> >>> e = NetActiveError("string")
> >>> print e
> string
> >>> print repr(e)
> NetActiveError('string',)
> 
> 
>> On Aug 5, 2010, at 5:49 PM, Benjamin Kaplan wrote:
>>> What makes you think it has to do with user-defined exceptions?
>>> 
>> try :
>>> ...raise Exception("hello")
>>> ... except Exception as (errno, errText) :
>>> ...   print "whatever"
>>> ...
>>> Traceback (most recent call last):
>>> ValueError: need more than 1 values to unpack
>>> 
>>> An Exception is an object, not a tuple of number and text.
>>> 
>>> Raise an instance of the exception, not the class:
>>> 
>>> raise NetActiveError("net already running")
>>> 
>>> And then catch the exception object
>>> 
>>> except NetActiveError as err:
>>>  print err.args
>>> 
>>> On Thu, Aug 5, 2010 at 3:41 PM, Chris Hare  wrote:
 I have a block of test code, where I am trying to raise and catch my own 
 user defined exception
 
 class NetActiveError(RuntimeError):
   def __init__(self,error):
   self.args = error
 
 def a():
   try:
   fh = open("me.txt", "r")
   except Exception as (errno, errText):
   print errText
   try:
   b()
   except NetActiveError as (errono, errText):
   print errno, errText
 
 def b():
   print "def b"
   raise NetActiveError,"net already running"
 
 
 a()
 
 
 When I run it though, I get the following error:
 
 chare$ python z
 No such file or directory
 def b
 Traceback (most recent call last):
 File "z", line 20, in 
   a()
 File "z", line 12, in a
   except NetActiveError as (errono, errText):
 ValueError: too many values to unpack
 
 
 What am I doing wrong here?
 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list

okay - thanks for the tutorial -- you explained what I couldn't find in the 
docs I looked at.  I appreciate your help

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


Re: [Tutor] Finding the version # of a module, and py module problem

2010-08-05 Thread MRAB

W. eWatson wrote:
It's been awhile since I've used python, and I recall there is a way to 
find the version number from the IDLE command line  prompt. dir, help, 
__version.__?


I made the most minimal change to a program, and it works for me, but 
not my partner. He gets


Traceback (most recent call last):
  File "C:\Documents and 
Settings\HP_Administrator.DavesDesktop\Desktop\NC-FireballReport20100729.py", 
line 40, in 

from scipy import stats as stats # scoreatpercentile
  File "C:\Python25\lib\site-packages\scipy\stats\__init__.py", line 7, 
in 

from stats import *
  File "C:\Python25\lib\site-packages\scipy\stats\stats.py", line 191, 
in 

import scipy.special as special
  File "C:\Python25\lib\site-packages\scipy\special\__init__.py", line 
22, in 

from numpy.testing import NumpyTest
ImportError: cannot import name NumpyTest

Here are the first few lines of code.

import sys, os, glob
import string
from numpy import *
from datetime import datetime, timedelta
import time
from scipy import stats as stats # scoreatpercentile

I'm pretty sure he has the same version of Python, 2.5, but perhaps not 
the numpy or scipy modules. I need to find out his version numbers.



Try:

import numpy
help(numpy.version)

BTW, on Python 2.6 I can see that there's "numpytest" but not
"NumpyTest".
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] Finding the version # of a module, and py module problem

2010-08-05 Thread Steven D'Aprano
On Thu, 05 Aug 2010 17:55:30 -0700, W. eWatson wrote:

> I'm pretty sure he has the same version of Python, 2.5, but perhaps not
> the numpy or scipy modules. I need to find out his version numbers.

It's only a convention, but the usual way is to check the __version__ 
attribute. It works for Numpy:

>>> import numpy
>>> numpy.__version__
'1.0.3'



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


Re: [Tutor] Finding the version # of a module, and py module problem

2010-08-05 Thread W. eWatson
It's been awhile since I've used python, and I recall there is a way to 
find the version number from the IDLE command line  prompt. dir, help, 
__version.__?


I made the most minimal change to a program, and it works for me, but 
not my partner. He gets


Traceback (most recent call last):
  File "C:\Documents and 
Settings\HP_Administrator.DavesDesktop\Desktop\NC-FireballReport20100729.py", 
line 40, in 

from scipy import stats as stats # scoreatpercentile
  File "C:\Python25\lib\site-packages\scipy\stats\__init__.py", line 7, 
in 

from stats import *
  File "C:\Python25\lib\site-packages\scipy\stats\stats.py", line 191, 
in 

import scipy.special as special
  File "C:\Python25\lib\site-packages\scipy\special\__init__.py", line 
22, in 

from numpy.testing import NumpyTest
ImportError: cannot import name NumpyTest

Here are the first few lines of code.

import sys, os, glob
import string
from numpy import *
from datetime import datetime, timedelta
import time
from scipy import stats as stats # scoreatpercentile

I'm pretty sure he has the same version of Python, 2.5, but perhaps not 
the numpy or scipy modules. I need to find out his version numbers.


--
   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

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


Re: defining, raising and catching exceptions

2010-08-05 Thread MRAB

Chris Hare wrote:

okay - but why does the response come back like

No such file or directory
def b
('n', 'e', 't', ' ', 'a', 'l', 'r', 'e', 'a', 'd', 'y', ' ', 'r', 'u', 'n', 
'n', 'i', 'n', 'g')


The class Exception saves its arguments in the 'args' instance
attribute, and when it prints the exception it prints those arguments:


>>> e = Exception(1, 2, 3)
>>> print e.args
(1, 2, 3)
>>> print e
(1, 2, 3)
>>> print repr(e)
Exception(1, 2, 3)


NetActiveError inherits from RuntimeError, and ultimately from
Exception.

NetActiveError sets the 'args' attribute to its single string argument,
and when the exception is printed out it thinks it's the arguments:


>>> e.args = "string"
>>> print e
('s', 't', 'r', 'i', 'n', 'g')
>>> print repr(e)
Exception('s', 't', 'r', 'i', 'n', 'g')


The correct way to create your own exceptions is to call the
superclass's __init__ method:


>>> class NetActiveError(RuntimeError):
... def __init__(self, error):
... RuntimeError.__init__(self, error)
...
>>> e = NetActiveError("string")
>>> print e
string
>>> print repr(e)
NetActiveError('string',)




On Aug 5, 2010, at 5:49 PM, Benjamin Kaplan wrote:


What makes you think it has to do with user-defined exceptions?


try :

...raise Exception("hello")
... except Exception as (errno, errText) :
...   print "whatever"
...
Traceback (most recent call last):
ValueError: need more than 1 values to unpack

An Exception is an object, not a tuple of number and text.

Raise an instance of the exception, not the class:

raise NetActiveError("net already running")

And then catch the exception object

except NetActiveError as err:
  print err.args

On Thu, Aug 5, 2010 at 3:41 PM, Chris Hare  wrote:

I have a block of test code, where I am trying to raise and catch my own user 
defined exception

class NetActiveError(RuntimeError):
   def __init__(self,error):
   self.args = error

def a():
   try:
   fh = open("me.txt", "r")
   except Exception as (errno, errText):
   print errText
   try:
   b()
   except NetActiveError as (errono, errText):
   print errno, errText

def b():
   print "def b"
   raise NetActiveError,"net already running"


a()


When I run it though, I get the following error:

chare$ python z
No such file or directory
def b
Traceback (most recent call last):
 File "z", line 20, in 
   a()
 File "z", line 12, in a
   except NetActiveError as (errono, errText):
ValueError: too many values to unpack


What am I doing wrong here?



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


Re: Why is python not written in C++ ?

2010-08-05 Thread Roy Smith
In article ,
 Lawrence D'Oliveiro  wrote:

> In message , Roy Smith wrote:
> 
> > C++, for all its flaws, had one powerful feature which made it very
> > popular.  It is a superset of C.
> 
> Actually, it never was.

Yes, there are a few corner cases where valid C syntax has different 
semantics in C and C++.  But, they are very few.  Calling C++ a superset 
of C is essentially correct.

It is certainly correct from the level of a risk-averse development 
manager deciding if he or she is willing to use C++ for the first time.  
Fear of the unknown is a powerful deterrent.  It's a lot easier to 
accept something like C++ because "it's just a superset of C, and we've 
been using C for years".

I suspect the same effect contributed to Java's success as well.  "Look, 
it's got curly braces and semicolons.  It's just like C!"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Struggling to convert a mysql datetime object to a python string of a different format

2010-08-05 Thread Tim Chase

On 08/05/10 16:01, Νίκος wrote:

On 5 Αύγ, 22:09, Tim Chase  wrote:

dataset = cursor.fetchall()



for row in dataset:
  print ( '''''' )


So, 'dataset' in here is a 'list of tuples' right? and 'row'
in here is a tuple form the above list of tuples right?

Am i understanding this correctly?!

It was a tuple. But it migth as well be a list too?!?!

Could 'dataset' be a 'list of lists' as well?


Pretty much...it's either a list-of-tuples or a list-of-lists 
(I'm not sure if is part of the DB-API spec to mandate one or the 
other).  For the most part, you can treat them as the same thing. 
 However, tuples are immutable, so you can't say


  my_tuple[3] = some_value

but with a list you can:

  my_list[3] = some_value


How one would know in which way the returned mysql data is saved in?


Well, you can ask:

  print type(row)

(I *suspect* it's a tuple) or you can just tell it what to be:

  for row in dataset:
row = list(row)
row[3] = row[3].strftime(...)
for item in row:
  ...

I don't usually have cause to write a value back into the data 
I'm reading from the DB, so it's never really mattered to me 
whether the DB gives me tuples or lists.



Though I think I'd make it a bit clearer by naming the fields:

for host, hits, dt in dataset:
  print ("")
  for item in (host, hits, dt.strftime(...)):
print ("%s" % item)
  print ("")


Cool! I myself like this solution best over the all working other!
very nice approach thank you very much! Is what i anted and couldn't
write myself!

But please tell me if in my example 'row' was a tuple, what kind of
objects is 'host', 'hits', 'dt' here and how do they sore the data?


Python supports "tuple assignment" which means that the following 
are about[*] the same:


  # variant A
  for row in dataset:
host = row[0]
hits = row[1]
dt = row[2]
# rest of your code here

  # variant B
  for row in dataset:
host, hits, dt = row
# rest of your code here

  # variant C
  for host, hits, dt in row:
# rest of your code here

The data-type of the individual values would be whatever comes 
back from the database as translated into Python (string, 
float/Decimal, boolean, datetime, etc).  In your example, it's 
likely a string+integer+datetime as the 3 values.  You can see 
why I prefer the elegance of just performing the assignment in 
the for-loop (variant C).


Hope this helps,

-tkc


[*] "about" the same because in #1 and #2, you also have access 
to the whole row; whereas in #3, you don't have something called 
"row", but you could reassemble it if you needed:


   row = (host, hits, dt)




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


Re: defining, raising and catching exceptions

2010-08-05 Thread Chris Hare
okay - but why does the response come back like

No such file or directory
def b
('n', 'e', 't', ' ', 'a', 'l', 'r', 'e', 'a', 'd', 'y', ' ', 'r', 'u', 'n', 
'n', 'i', 'n', 'g')


On Aug 5, 2010, at 5:49 PM, Benjamin Kaplan wrote:

> What makes you think it has to do with user-defined exceptions?
> 
 try :
> ...raise Exception("hello")
> ... except Exception as (errno, errText) :
> ...   print "whatever"
> ...
> Traceback (most recent call last):
> ValueError: need more than 1 values to unpack
> 
> An Exception is an object, not a tuple of number and text.
> 
> Raise an instance of the exception, not the class:
> 
> raise NetActiveError("net already running")
> 
> And then catch the exception object
> 
> except NetActiveError as err:
>   print err.args
> 
> On Thu, Aug 5, 2010 at 3:41 PM, Chris Hare  wrote:
>> 
>> I have a block of test code, where I am trying to raise and catch my own 
>> user defined exception
>> 
>> class NetActiveError(RuntimeError):
>>def __init__(self,error):
>>self.args = error
>> 
>> def a():
>>try:
>>fh = open("me.txt", "r")
>>except Exception as (errno, errText):
>>print errText
>>try:
>>b()
>>except NetActiveError as (errono, errText):
>>print errno, errText
>> 
>> def b():
>>print "def b"
>>raise NetActiveError,"net already running"
>> 
>> 
>> a()
>> 
>> 
>> When I run it though, I get the following error:
>> 
>> chare$ python z
>> No such file or directory
>> def b
>> Traceback (most recent call last):
>>  File "z", line 20, in 
>>a()
>>  File "z", line 12, in a
>>except NetActiveError as (errono, errText):
>> ValueError: too many values to unpack
>> 
>> 
>> What am I doing wrong here?
>> 
>> 
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: easy question on parsing python: "is not None"

2010-08-05 Thread Rhodri James
On Thu, 05 Aug 2010 17:07:53 +0100, wheres pythonmonks  
 wrote:



Well, I am not convinced of the equivalence of not None and true:


not None

True

3 is True;

False

3 is not None

True




You're not testing for equivalence there, you're testing for identity.   
"is" and "is not" test whether the two objects concerned are (or are not)  
the same object.  Two objects can have the same value, but be different  
objects.  The interpreter can fool you by caching and reusing objects  
which have the same value when it happens to know about it, in particular  
for small integers, but this is just a happy accident of the  
implementation and in no way guaranteed by the language.  For example:



"spam, eggs, chips and spam" is "spam, eggs, chips and spam"

True

a = "spam, eggs, chips and spam"
b = "spam, eggs, chips and spam"
a is b

False

a == b

True

Also, remember that "is not" is a single operator, *not* the concatenation  
of "is" and "not".  Your last test is probably not checking what you think  
it is :-)



3 is (not None)

False

--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-05 Thread Neil Hodgson
Paul Rubin:

> C has all kinds of undefined behavior.  "Might need to rely on" is not
> relevant for this kind of issue.  Ada's designers had the goal that that
> Ada programs should have NO undefined behavior.

   Ada achieves this by describing a long list of implementation defined
behaviour (Annex M).
http://oopweb.com/Ada/Documents/Ada95RM/Volume/m.htm

> As a famous example of C's underspecification, the behavior of
> 
>a[i++] = i;
> 
> is undefined in C99.

   Ada does not define ordering in all cases either. For example the
order of elaboration of library_items (essentially the order in which
modules are run in the absence of explicit declarations) is defined for
GNAT as

"""
first elaborating bodies as early as possible (i.e. in preference to
specs where there is a choice), and second by evaluating the immediate
with clauses of a unit to determine the probably best choice, and third
by elaborating in alphabetical order of unit names where a choice still
remains
"""

   Other compilers use different orders.

   I just love that "probably".

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


Re: defining, raising and catching exceptions

2010-08-05 Thread Benjamin Kaplan
What makes you think it has to do with user-defined exceptions?

>>> try :
...raise Exception("hello")
... except Exception as (errno, errText) :
...   print "whatever"
...
Traceback (most recent call last):
ValueError: need more than 1 values to unpack

An Exception is an object, not a tuple of number and text.

Raise an instance of the exception, not the class:

raise NetActiveError("net already running")

And then catch the exception object

except NetActiveError as err:
   print err.args

On Thu, Aug 5, 2010 at 3:41 PM, Chris Hare  wrote:
>
> I have a block of test code, where I am trying to raise and catch my own user 
> defined exception
>
> class NetActiveError(RuntimeError):
>    def __init__(self,error):
>        self.args = error
>
> def a():
>    try:
>        fh = open("me.txt", "r")
>    except Exception as (errno, errText):
>        print errText
>    try:
>        b()
>    except NetActiveError as (errono, errText):
>        print errno, errText
>
> def b():
>    print "def b"
>    raise NetActiveError,"net already running"
>
>
> a()
>
>
> When I run it though, I get the following error:
>
> chare$ python z
> No such file or directory
> def b
> Traceback (most recent call last):
>  File "z", line 20, in 
>    a()
>  File "z", line 12, in a
>    except NetActiveError as (errono, errText):
> ValueError: too many values to unpack
>
>
> What am I doing wrong here?
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: easy question on parsing python: "is not None"

2010-08-05 Thread Benjamin Kaplan
On Thu, Aug 5, 2010 at 9:07 AM, wheres pythonmonks
 wrote:
> Well, I am not convinced of the equivalence of not None and true:
>
 not None
> True
 3 is True;
> False
 3 is not None
> True

>
> P.S. Sorry for the top-post -- is there a way to not do top posts from
> gmail?  I haven't used usenet since tin.
>

Scroll down in the email and press enter a few times.
-- 
http://mail.python.org/mailman/listinfo/python-list


defining, raising and catching exceptions

2010-08-05 Thread Chris Hare

I have a block of test code, where I am trying to raise and catch my own user 
defined exception

class NetActiveError(RuntimeError):
def __init__(self,error):
self.args = error

def a():
try:
fh = open("me.txt", "r")
except Exception as (errno, errText):
print errText
try:
b()
except NetActiveError as (errono, errText):
print errno, errText

def b():
print "def b"
raise NetActiveError,"net already running"


a()


When I run it though, I get the following error:

chare$ python z
No such file or directory
def b
Traceback (most recent call last):
  File "z", line 20, in 
a()
  File "z", line 12, in a
except NetActiveError as (errono, errText):
ValueError: too many values to unpack


What am I doing wrong here?


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


Re: A useful, but painful, one-liner to edit money amounts

2010-08-05 Thread Peter Otten
Steven D'Aprano wrote:

> On Thu, 05 Aug 2010 00:22:57 -0700, geremy condra wrote:
> 
>> locale.setlocale(locale.LC_ALL, "")
>>> 'de_DE.UTF-8'
>> print locale.currency(13535, grouping=True)
>>> 13.535,00 €
>> print locale.format("%d", 13535, grouping=True)
>>> 13.535
>>>
>>> Peter
>> 
>> I had literally no idea this existed. Thanks.
> 
> I knew it existed, but completely forgot about it.
> 
> Thanks also Peter.

You're welcome!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Struggling to convert a mysql datetime object to a python string of a different format

2010-08-05 Thread Νίκος
>On 5 Αύγ, 22:09, Tim Chase  wrote:
> On 08/05/10 13:52, Νίκος wrote:
>
> > dataset = cursor.fetchall()
>
> > for row in dataset:
> >      print ( '''  ''' )

As i have it the returned 'dataset' is stored line per line to 'row'.

So,
'dataset' in here is a 'list of tuples' right?
and
'row' in here is a tuple form the above list of tuples right?

Am i understanding this correctly?!


> Well, depending on whether "row" is a tuple or a list, you can do
> either

It was a tuple. But it migth as well be a list too?!?!

Could 'dataset' be a 'list of lists' as well?

How one would know in which way the returned mysql data is saved in?

> Though I think I'd make it a bit clearer by naming the fields:
>
>    for host, hits, dt in dataset:
>      print ("")
>      for item in (host, hits, dt.strftime(...)):
>        print ("%s" % item)
>      print ("")

Cool! I myself like this solution best over the all working other!
very nice approach thank you very much! Is what i anted and couldn't
write myself!

But please tell me if in my example 'row' was a tuple, what kind of
objects is 'host', 'hits', 'dt' here and how do they sore the data?

Thanks again for the cool examples!

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


Re: Why is python not written in C++ ?

2010-08-05 Thread Britt
On Aug 1, 9:34 pm, Albert Hopkins  wrote:
> On Mon, 2010-08-02 at 01:08 +0200, candide wrote:
>
> I would propose that in fact most programming languages are implemented
> in C.  Sun's (Oracle's) Java compiler and runtime are written in ANSI C.
> The core of the Gnu Compiler Collection (which includes C++ and
> Objective-C compilers) is written in C.

The open-source GCC Ada compiler (GNAT) is written in Ada. The GPL'd
compiler source code is available at http://libre.adacore.com/libre/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ctypes: pointer to method

2010-08-05 Thread Nobody
On Thu, 05 Aug 2010 10:50:21 -0700, Martin Landa wrote:

> is it possible to pass pointer to a method using ctypes.

I don't know about methods, but it works for functions.

> Sample code:
> 
> ...
> G_set_error_routine(byref(self._print_error))

This won't work; you have to be more explicit, e.g.:

errtype = CFUNCTYPE(c_int, POINTER(c_char), POINTER(c_int))
errfunc = errtype(print_error)
G_set_error_routine(errfunc)

NOTE: be sure to keep a reference to the wrapper, as ctypes doesn't hold
references itself. IOW, you can't replace the above with:

errtype = CFUNCTYPE(c_int, POINTER(c_char), POINTER(c_int))
G_set_error_routine(errtype(print_error))

If you do this, the wrapper is eligible for garbage collection as soon as
G_set_error_routine() returns, and will probably have vanished by the time
that G_fatal_error() gets called.

For more information see:

http://docs.python.org/library/ctypes.html#callback-functions

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


Re: subprocess escaping POpen?!

2010-08-05 Thread Nobody
On Thu, 05 Aug 2010 12:23:35 +0100, Chris Withers wrote:

>>> ...then the output is indeed captured. So, what is svn doing 
>>> differently? How is it escaping its jail?
>> 
>> maybe it does not read from stdin but directly from /dev/tty
> 
> But why only the request for auth credentials?

So that you can do e.g.:

ssh remotehost command arg arg ... outfile

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


Re: Struggling to convert a mysql datetime object to a python string of a different format

2010-08-05 Thread Tim Chase

On 08/05/10 13:52, Νίκος wrote:

dataset = cursor.fetchall()

for row in dataset:
 print ( '''  ''' )

 date = row[2].strftime( '%d %b, %H:%M' )

 print ( '''  %s %s %s  ''' %
( row[0], row[1], date ) )

Unfortunately had to ditch the 'for entry in row' line because
couldn't iterate over the items of the row.

Could you please shoe me how could i do the same thing with
iteration?!


Well, depending on whether "row" is a tuple or a list, you can do 
either


  row[2] = row[2].strftime(...)  # if it's a list
  # the assignment will fail if it's a tuple

or you can just iterate over a predefined list/tuple:

  for row in dataset:
print ("")
for item in (row[0], row[1], row[2].strftime(...)):
  print ("%s")

Though I think I'd make it a bit clearer by naming the fields:

  for host, hits, dt in dataset:
print ("")
for item in (host, hits, dt.strftime(...)):
  print ("%s" % item)
print ("")

Or perhaps even just

print ("".join("%s" % item
  for item in (host, hits, dt.strftime(...))
  )

Whichever you prefer.  I think I'm partial to the 2nd-from-last 
version, especially as the list of fields may grow.


-tkc



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


Re: Struggling to convert a mysql datetime object to a python string of a different format

2010-08-05 Thread Νίκος
Hey i made it! :-)

dataset = cursor.fetchall()

for row in dataset:
print ( '''  ''' )

date = row[2].strftime( '%d %b, %H:%M' )

print ( '''  %s %s %s  ''' %
( row[0], row[1], date ) )

Unfortunately had to ditch the 'for entry in row' line because
couldn't iterate over the items of the row.

Could you please shoe me how could i do the same thing with
iteration?!
Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pre-uninstall script in bdist_wininst

2010-08-05 Thread Nils
On 5 Aug., 20:26, Nils  wrote:
> According to the docs in [1] [...]
and with [1] I meant 
http://docs.python.org/distutils/builtdist.html#the-postinstallation-script

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


Re: A useful, but painful, one-liner to edit money amounts

2010-08-05 Thread John Posner

On 8/5/2010 12:36 PM, MRAB wrote:


You don't need to reverse the string:

def thous_format(integer_string):
   """
   add comma thousands separator(s) to an integer-valued string
   """
   return re.sub(r"(?<=\d)(?=(?:\d\d\d)+$)", ",", integer_string)


Nice! My first encounter with a look-behind! It appears that a slight 
simplification is possible:


 return re.sub(r"(?<=\d)(?=(\d\d\d)+$)", ",", integer_string)

There no harm in putting \d\d\d into a group, though the group is never 
used.


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


pre-uninstall script in bdist_wininst

2010-08-05 Thread Nils
Hi.
I am using a postinstall-script like this:
setup(
...
scripts=['scripts\install.py'],
options = {
...
"bdist_wininst" : {
"install_script" : "install.py",
...
},
}
)

According to the docs in [1] this script is
a) called after install (with the "-install" parameter) - this works
fine for me...
b) called before uninstall (with tho "-remove" parameter) - this
however does not work.

Can someone please point me to the direction on how to get a pre-
uninstall script working?

btw: With that I am trying to register a com-server on install and de-
register on uninstall - so if other ideas are around I'd love to hear
them, too...

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


Re: Why is python not written in C++ ?

2010-08-05 Thread Paul Rubin
Lawrence D'Oliveiro  writes:
> OK, I have a copy of K&R 2nd Ed on a shelf within reach here. Can you point 
> out some behaviour that C programmers might need to rely on, that is not 
> specified in that document?

C has all kinds of undefined behavior.  "Might need to rely on" is not
relevant for this kind of issue.  Ada's designers had the goal that that
Ada programs should have NO undefined behavior. 

As a famous example of C's underspecification, the behavior of

   a[i++] = i;

is undefined in C99.  See:

https://www.securecoding.cert.org/confluence/display/seccode/EXP30-C.+Do+not+depend+on+order+of+evaluation+between+sequence+points
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new to python - trouble calling a function from another function

2010-08-05 Thread Daniel Urban
> I'm building an elevator simulator for a class assignment. I recently ran
> into a roadblock and don't know how to fix it. For some reason, in my
> checkQueue function below, the call to self.goUp() is never executed. It is
> on the last line of code I pasted in. I can put print statements before and
> after the call and I have a print statement in goUp() itself.  Only the
> print statements before and after the call are executed. The one inside
> goUp() is never executed because goUp() never seems to be executed. How can
> that be? I don't get any errors when the script executes. Surely this isn't
> some limitation I'm encountering?

I think the self.goUp() call is executed, the goUp function gets
called, returns a generator object (because goUp is a generator
function), then you don't use that generator object for anything.


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


ctypes: pointer to method

2010-08-05 Thread Martin Landa
Hi,

is it possible to pass pointer to a method using ctypes. Sample code:

...
G_set_error_routine(byref(self._print_error))
...

def _print_error(self, msg, type):
"""!Redirect stderr"""
self.log.write(msg)

gives me

G_set_error_routine(byref(self._print_error))
TypeError: byref() argument must be a ctypes instance, not
'instancemethod'


C function G_set_error_routine is defined as

void G_set_error_routine(int (*error_routine) (const char *, int))

Thanks in advance for any pointers. Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: easy question on parsing python: "is not None"

2010-08-05 Thread Ethan Furman

Roald de Vries wrote:

On Aug 5, 2010, at 5:42 PM, wheres pythonmonks wrote:
How does "x is not None" make any sense?  "not x is None" does make 
sense.


I can only surmise that in this context (preceding is) "not" is not a
unary right-associative operator, therefore:

x is not None === IS_NOTEQ(X, None)

Beside "not in" which seems to work similarly, is there other
syntactical sugar like this that I should be aware of?


'not None' first casts None to a bool, and then applies 'not', so 'x is 
not None' means 'x is True'.


This is not correct.  'is not' is a single operator, and in this case is 
checking that the object 'x' is not the same as the object 'None'.  No 
boolean conversions are done -- False and True have nothing to do with 
this example.


Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
--> x = 5
--> x is not None
True
--> x = True
--> x is not None
True
--> x = ('this','is','a','tuple')
--> x is not None
True
--> x = None
--> x is not None
False

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


Re: easy question on parsing python: "is not None"

2010-08-05 Thread Dave Angel

Roald de Vries wrote:
On Aug 5, 
2010, at 5:42 PM, wheres pythonmonks wrote:
How does "x is not None" make any sense?  "not x is None" does make 
sense.


I can only surmise that in this context (preceding is) "not" is not a
unary right-associative operator, therefore:

x is not None === IS_NOTEQ(X, None)

Beside "not in" which seems to work similarly, is there other
syntactical sugar like this that I should be aware of?


'not None' first casts None to a bool, and then applies 'not', so 'x 
is not None' means 'x is True'.

'not x is None' is the same as 'not (x is None)'

Cheers, Roald


Did you try it?

Python 2.6.4 (r264:75706, Jan 22 2010, 16:41:54) [MSC v.1500 32 bit
win32
Type "help", "copyright", "credits" or "license" for more informatio
>>> 4 is not None
True
>>> True is not None
True
>>> False is not None
True
>>> None is not None
False
>>>

Looks to me like
  x is not None

is equivalent to
  not (x is None)

(I get same results for 3.1)

DaveA

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


Re: A useful, but painful, one-liner to edit money amounts

2010-08-05 Thread MRAB

John Posner wrote:

On 8/5/2010 12:33 AM, John Nagle wrote:

There's got to be a better way to do this:


def editmoney(n) :
return((",".join(reduce(lambda lst, item : (lst + [item]) if
item else lst,
re.split(r'(\d\d\d)',str(n)[::-1]),[])))[::-1])



Here's a more elegant variant, using regexp lookahead:

def thous_format(integer_string):
"""
add comma thousands separator(s) to an integer-valued string
"""
return re.sub(r'(\d{3})(?=\d)', r'\1,', integer_string[::-1])[::-1]

I *thought* that I had found this on python-list on or about July 5, but 
I didn't find the thread after a search through the archives.



You don't need to reverse the string:

def thous_format(integer_string):
"""
add comma thousands separator(s) to an integer-valued string
"""
return re.sub(r"(?<=\d)(?=(?:\d\d\d)+$)", ",", integer_string)
--
http://mail.python.org/mailman/listinfo/python-list


Re: easy question on parsing python: "is not None"

2010-08-05 Thread Roald de Vries

On Aug 5, 2010, at 6:11 PM, Chris Rebert wrote:
On Thu, Aug 5, 2010 at 8:56 AM, Roald de Vries   
wrote:

On Aug 5, 2010, at 5:42 PM, wheres pythonmonks wrote:
How does "x is not None" make any sense?  "not x is None" does  
make sense.


I can only surmise that in this context (preceding is) "not" is  
not a

unary right-associative operator, therefore:

x is not None === IS_NOTEQ(X, None)

Beside "not in" which seems to work similarly, is there other
syntactical sugar like this that I should be aware of?


'not None' first casts None to a bool, and then applies 'not', so  
'x is not

None' means 'x is True'.


Absolutely incorrect. Read the final paragraph of
http://docs.python.org/reference/expressions.html#notin


Oops, sorry :$.

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


Re: A portable LISP interpreter that includes all the major list-processing functions is described. A complete, annotated listing of the program's code, written in PASCAL, is included.

2010-08-05 Thread fortunatus
On Jul 24, 6:42 pm, Emmy Noether  wrote:
> I have already spent 4 hours scanning/processing to a stage where I
> got a decent OCR which needs hand-verification of pages. I need 4 or 8
> volunteers depending on whether one want to do two pages each or 1
> page each. Its an hour of joyful work each for two pages.

Sheesh, if you just focussed on typing in, you could be done by now
instead of fooling around with OCR and enlisting volunteers for
something that amounts to the same beginner experiment that has been
done 10,000 times: a fundamental Lisp interpreter.

Don't get me wrong, it's a good experiment, but it really needn't
require so much trouble...

For that matter, why not write your own?  Start by replicating
McCarthy's group's initial interpreter...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Struggling to convert a mysql datetime object to a python string of a different format

2010-08-05 Thread Νίκος
On 5 Αύγ, 11:55, Dennis Lee Bieber  wrote:
> On Wed, 4 Aug 2010 16:40:45 -0700 (PDT), Íßêïò
>  declaimed the following in
> gmane.comp.python.general:
>
> >                    for entry in row:
> >                            entry = datetime.datetime.strftime( entry, '%d 
> > %b, %H:%M' ) #!!!
> > this is wrong!
> >                            print ( '''  %s  ''' % entry )
>
> > Apart from that i don't know how iam supposed to print it, because the
> > date string is the 3rd string in every row of the dataset.
>
>         As you state, it is the third item in each returned row... So why
> are you trying to treat EVERY item in the row as a date?

Because when i try to prin the 3 items liek that

print row[0], row[1], row[2]

it gives me an error, so i dont knwo how to tell it how to print the
3rd item differently.



>
>         Since MySQLdb appears to return datetime objects (my quick test is
> showing datetime.date for dates in a test database) you should be
> probably be using
>
>         formatted_entry = entry.strftime("%d... %M")

I tried that myself yesterday but look it fails to the following
message

 /home/webville/public_html/cgi-bin/index.py
   63
   64 for entry in row:
   65 formatted_entry =
entry.strftime('%d %b, %H:%M')
   66 print ( '''  %s  ''' %
entry )
   67
formatted_entry undefined, entry = '178-124-186.dynamic.cyta.gr',
entry.strftime undefined
AttributeError: 'str' object has no attribute 'strftime'
  args = ("'str' object has no attribute 'strftime'",)

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


Re: easy question on parsing python: "is not None"

2010-08-05 Thread Chris Rebert
On Thu, Aug 5, 2010 at 8:42 AM, wheres pythonmonks
 wrote:
> How does "x is not None" make any sense?  "not x is None" does make sense.
>
> I can only surmise that in this context (preceding is) "not" is not a
> unary right-associative operator, therefore:
>
> x is not None === IS_NOTEQ(X, None)
>
> Beside "not in" which seems to work similarly, is there other
> syntactical sugar like this that I should be aware of?

It's not quite the same type of sugar as that, but people sometimes
forget that comparisons can be chained:

if x < y <= z:

Same as:

if x < y and y <= z:
# but y is only evaluated once

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


Re: simple integer subclass

2010-08-05 Thread Andreas Pfrengle
Hello everyone,

thanks for all the suggestions. I did effort to redesign parts of the
data structure the last days, but not all (only those I could easily
keep track of in my code).
For the rest I add +1 before the presentation and comment it. Seems
the easiest way now.

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


Re: easy question on parsing python: "is not None"

2010-08-05 Thread Chris Rebert
On Thu, Aug 5, 2010 at 8:56 AM, Roald de Vries  wrote:
> On Aug 5, 2010, at 5:42 PM, wheres pythonmonks wrote:
>> How does "x is not None" make any sense?  "not x is None" does make sense.
>>
>> I can only surmise that in this context (preceding is) "not" is not a
>> unary right-associative operator, therefore:
>>
>> x is not None === IS_NOTEQ(X, None)
>>
>> Beside "not in" which seems to work similarly, is there other
>> syntactical sugar like this that I should be aware of?
>
> 'not None' first casts None to a bool, and then applies 'not', so 'x is not
> None' means 'x is True'.

Absolutely incorrect. Read the final paragraph of
http://docs.python.org/reference/expressions.html#notin

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


Re: easy question on parsing python: "is not None"

2010-08-05 Thread Carey Tilden
On Thu, Aug 5, 2010 at 8:42 AM, wheres pythonmonks
 wrote:
> How does "x is not None" make any sense?  "not x is None" does make sense.
>
> I can only surmise that in this context (preceding is) "not" is not a
> unary right-associative operator, therefore:
>
> x is not None === IS_NOTEQ(X, None)
>
> Beside "not in" which seems to work similarly, is there other
> syntactical sugar like this that I should be aware of?

In addition to all the other fine responses, you also might want to
take a look at the python grammar [1].  The relevant line is:

  comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'

Cheers,
Carey

[1] http://docs.python.org/reference/grammar.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: easy question on parsing python: "is not None"

2010-08-05 Thread wheres pythonmonks
Well, I am not convinced of the equivalence of not None and true:

>>> not None
True
>>> 3 is True;
False
>>> 3 is not None
True
>>>

P.S. Sorry for the top-post -- is there a way to not do top posts from
gmail?  I haven't used usenet since tin.

On Thu, Aug 5, 2010 at 11:56 AM, Roald de Vries  wrote:
> On Aug 5, 2010, at 5:42 PM, wheres pythonmonks wrote:
>>
>> How does "x is not None" make any sense?  "not x is None" does make sense.
>>
>> I can only surmise that in this context (preceding is) "not" is not a
>> unary right-associative operator, therefore:
>>
>> x is not None === IS_NOTEQ(X, None)
>>
>> Beside "not in" which seems to work similarly, is there other
>> syntactical sugar like this that I should be aware of?
>
> 'not None' first casts None to a bool, and then applies 'not', so 'x is not
> None' means 'x is True'.
> 'not x is None' is the same as 'not (x is None)'
>
> Cheers, Roald
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: easy question on parsing python: "is not None"

2010-08-05 Thread Ben Finney
wheres pythonmonks  writes:

> How does "x is not None" make any sense?

In two ways: partly from the fact that Python syntax is preferentially
designed to be reasonably readable to a native English reader; and
partly because it makes for more obvious semantics.

‘is not’ is a single operator which makes operator precedence clear, and
also “x is not None” is gramatically good English.

> "not x is None" does make sense.

It unfortunately makes for awkward English, and it also makes for two
separate operators and hence non-obvious operator precedence.

> I can only surmise that in this context (preceding is) "not" is not a
> unary right-associative operator

Rather than surmise, you can read the language reference
http://docs.python.org/reference/expressions.html#isnot> which
makes clear that ‘is not’ is one operator.

-- 
 \   “I am amazed, O Wall, that you have not collapsed and fallen, |
  `\since you must bear the tedious stupidities of so many |
_o__)  scrawlers.” —anonymous graffiti, Pompeii, 79 CE |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: easy question on parsing python: "is not None"

2010-08-05 Thread Jean-Michel Pichavant

wheres pythonmonks wrote:

How does "x is not None" make any sense?  "not x is None" does make sense.

I can only surmise that in this context (preceding is) "not" is not a
unary right-associative operator, therefore:

x is not None === IS_NOTEQ(X, None)

Beside "not in" which seems to work similarly, is there other
syntactical sugar like this that I should be aware of?

W
  

x is not None === not (x is None).

"is not" is an operator, not the combination of 2.


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


Re: easy question on parsing python: "is not None"

2010-08-05 Thread Roald de Vries

On Aug 5, 2010, at 5:42 PM, wheres pythonmonks wrote:
How does "x is not None" make any sense?  "not x is None" does make  
sense.


I can only surmise that in this context (preceding is) "not" is not a
unary right-associative operator, therefore:

x is not None === IS_NOTEQ(X, None)

Beside "not in" which seems to work similarly, is there other
syntactical sugar like this that I should be aware of?


'not None' first casts None to a bool, and then applies 'not', so 'x  
is not None' means 'x is True'.

'not x is None' is the same as 'not (x is None)'

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


Re: new to python - trouble calling a function from another function

2010-08-05 Thread Neil Cerutti
On 2010-08-05, Brandon McCombs  wrote:
> class Elevator(Process):
> def __init__(self,name):
>   Process.__init__(self,name=name)
>   self.numPassengers = 0
>   self.passengerList = []
>   self.passengerWaitQ = []
>   self.currentFloor = 1
>   self.idle = 1
>   self.newPassengers = 0
> def goUp(self):
>   print "here"
>   bubbleSort(self.passengerList, len(self.passengerList))
>   self.currentFloor += 1
>   if len(self.passengerList) > 0:
>  for p in self.passengerList:
> if self.currentFloor == p.destination:
>   yield (p.destination - self.currenteFloor) * TRAVELTIME, self
>   reactivate(p)
>   p.inBuilding()
> else:
>   self.goUp()
>
> def checkQueue(self):
>   if (len(self.passengerWaitQ)) > 0 and len(self.passengerList) < 
> MAXCAPACITY:
>   if len(self.passengerWaitQ) < MAXCAPACITY:
>   self.newPassengers = len(self.passengerWaitQ)
>   else:
>  self.newPassengers = MAXCAPACITY - len(self.passengerList)
>   for i in range(0,self.newPassengers):
> self.passengerList.append(self.passengerWaitQ.pop())
>   self.goUp()


Does your program call checkQueue?

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


easy question on parsing python: "is not None"

2010-08-05 Thread wheres pythonmonks
How does "x is not None" make any sense?  "not x is None" does make sense.

I can only surmise that in this context (preceding is) "not" is not a
unary right-associative operator, therefore:

x is not None === IS_NOTEQ(X, None)

Beside "not in" which seems to work similarly, is there other
syntactical sugar like this that I should be aware of?

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


Re: new to python - trouble calling a function from another function

2010-08-05 Thread Tommy Grav

On Aug 5, 2010, at 11:20 AM, Brandon McCombs wrote:
> so I missed a few lines, so sue me.

The problem is that when you don't post a self contained example
there is no proper way to answer your question, since the problem
could be outside the part you posted.

> already aware. I reformatted tabs to reduce the line wrap so it was easier 
> for readers to read it.

Never format code after you copy-paste it to your browser. This
may change the behavior of your example making it impossible for
people to help you. 

> either one of those should still execute self.goUp(). I'm not getting 
> anything though no matter where I place the function call.

Like someone said before. Try to create the smallest subset of your code
that shows this behavior and copy-paste it to the list and people will 
try to help. Right now there is no clear answer from what you posted.

Tommy

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


Re: Why is python not written in C++ ?

2010-08-05 Thread Edward Diener

On 8/2/2010 5:42 PM, Mark Lawrence wrote:

On 02/08/2010 00:08, candide wrote:

Python is an object oriented langage (OOL). The Python main
implementation is written in pure and "old" C90. Is it for historical
reasons?

C is not an OOL and C++ strongly is. I wonder if it wouldn't be more
suitable to implement an OOL with another one.

Has it ever been planned to rewrite in C++ the historical implementation
(of course in an object oriented design) ?


I can't understand why any serious programmer mentions C++. As soon as I
read it, I have to rush either to the kitchen to find a bowl to throw up
in, or head for the toilet so I can talk to the great white telephone.


It must be because we can not be as phenomenally intelligent as you 
evidently are from your comment.

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


Re: new to python - trouble calling a function from another function

2010-08-05 Thread Brandon McCombs

Ulrich Eckhardt wrote:

Brandon McCombs wrote:

I'm building an elevator simulator for a class assignment. I recently
ran into a roadblock and don't know how to fix it. For some reason, in
my checkQueue function below, the call to self.goUp() is never executed.

[...]

sorry about the formatting


While I can certainly forgive you the formatting (my problem is rather that
you didn't reduce the code to the smallest possible example


so I missed a few lines, so sue me.

), Python wont.

Python is a language where whitespace is significant and can subtly change
the meaning of your code.

Example:


for i in range(0,self.newPassengers):
self.passengerList.append(self.passengerWaitQ.pop())
self.goUp()


The formatting here is completely removed, but there are two conceivable
ways this could be formatted:


already aware. I reformatted tabs to reduce the line wrap so it was 
easier for readers to read it.




# variant 1
for i in range(0,self.newPassengers):
self.passengerList.append(self.passengerWaitQ.pop())
self.goUp()

#variant 2
for i in range(0,self.newPassengers):
self.passengerList.append(self.passengerWaitQ.pop())
self.goUp()


either one of those should still execute self.goUp(). I'm not getting 
anything though no matter where I place the function call.




Someone already mentioned PEP 8 (search the web!). These PEPs could be
called the standards governing Python behaviour, and PEP 8 actually defines
several things concerning the formatting of sourcecode. Apply it unless you
have a good reason not to.


Further, you should run Python with "-t" as argument on the commandline.
This will give you warnings when it encounters inconsistent tab/spaces
usage. This can make a difference.


Yeah I already tried that using 'tabnanny' I think it was called to 
diagnose one function that I decided to create and the -t option gave me 
false information. I determined that I had a tab in front of the 
function name (just like many others) however the actual fix was to put 
in spaces until it lined up with all the other 'def' lines.




Example:

#variant 3
for i in range(0,self.newPassengers):
self.passengerList.append(self.passengerWaitQ.pop())
self.goUp()

If your editor is set to four spaces per tab, this will look like variant 2,
with 8 spaces it will look like variant 1. I don't know (and don't care,
since PEP-8 mandates four spaces) which interpretation Python actually
uses.


Lastly, you can simplify your check_queue() function. First, determine the
number of free places inside the elevator. Then, you simply append that
many passengers from the waiting list to the passenger list:

  free = MAX_CAPACITY - len(self.passengers)
  new_passengers = self.passenger_wait_queue[:free]
  self.passenger_wait_queue = self.passenger_wait_queue[free:]
  self.passengers += new_passengers

This uses the fact that list indices are automatically truncated to a valid
range, so requesting the elements 0 to 10 from a 5-element list will only
yield those five elements, not raise an exception. It's up to you though
which version is clearer to you. I would perhaps bail out if "free == 0"
and then also not call go_up() lateron.




so you made other recommendations but didn't address my original 
question unless I missed it somewhere.

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


Re: new to python - trouble calling a function from another function

2010-08-05 Thread Brandon McCombs

Jon Clements wrote:

On 5 Aug, 08:25, Brandon McCombs  wrote:

Hello,

I'm building an elevator simulator for a class assignment. I recently
ran into a roadblock and don't know how to fix it. For some reason, in
my checkQueue function below, the call to self.goUp() is never executed.
It is on the last line of code I pasted in. I can put print statements
before and after the call and I have a print statement in goUp() itself.
  Only the print statements before and after the call are executed. The
one inside goUp() is never executed because goUp() never seems to be
executed. How can that be? I don't get any errors when the script
executes. Surely this isn't some limitation I'm encountering?

thanks

sorry about the formatting

-
class Elevator(Process):
def __init__(self,name):
Process.__init__(self,name=name)
self.numPassengers = 0
self.passengerList = []
self.passengerWaitQ = []
self.currentFloor = 1
self.idle = 1
self.newPassengers = 0
def goUp(self):
print "here"
bubbleSort(self.passengerList, len(self.passengerList))
self.currentFloor += 1
if len(self.passengerList) > 0:
   for p in self.passengerList:
  if self.currentFloor == p.destination:
yield (p.destination - self.currenteFloor) * TRAVELTIME, self
reactivate(p)
p.inBuilding()
  else:
self.goUp()

def checkQueue(self):
if (len(self.passengerWaitQ)) > 0 and len(self.passengerList) <
MAXCAPACITY:
if len(self.passengerWaitQ) < MAXCAPACITY:
self.newPassengers = len(self.passengerWaitQ)
else:
 self.newPassengers = MAXCAPACITY - len(self.passengerList)
for i in range(0,self.newPassengers):
  self.passengerList.append(self.passengerWaitQ.pop())
self.goUp()


Hi Brandon,

Nice one at having a good crack at coding before posting!

From your posted code, I'm struggling to see what's trying to be
taught to you for this class assignment.


not relevant at this point



As a note it'll be worth reading PEP 8 regarding naming conventions,
because it looks very Java-ish to me!


ok but not relevant



(I might be taking too much a real-world approach in the following,
but do with it as you will...)

I'm assuming that MAXCAPACITY and TRAVELTIME are globals somewhere.
Although what I'm thinking is that different Elevators will have
different capacities and different floors they service. An Elevator is
*not* going to know its number of passengers (the most it could do is
capacity based on weight restrictions) therefore it's not going to
know the number of new passengers on each floor either.


okay but not relevant to the problem at hand



A couple of things that'd be worthwhile:

1) Post the requirements for your assignment - what's it supposed to
output etc...


that isn't relevant for determining at the python level why a function 
simply isn't being called



2) Go find an elevator, take a pen and pad with you, and stand in it
for 30 mins or so, and see how the real thing deals with situations
and make notes. ie, does it queue requests, or decide to take the next
nearest floor, when does it stop and open etc...?

hth

Jon.



actually it doesn't help at all since you decided to focus on everything 
but my actual question of why a function call wasn't working but rather 
question the validity of the program itself

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


Are you Searching for a New IT or Telecoms Job?

2010-08-05 Thread hrdublin
Then start your Search here at JobPIMP

JobPIMP is a Customised Search Engine that is crawling over 800+ Local
and International Job Boards so you don't have to.

JobPIMP is searching well known mainstream, niche, and less well known
specialist job portals
(your search results on one page).

Click Link and Try JobPIMP Today 
http://www.directsource-network.com/jobpimphome.html

It is 100% FREE!!!

Or do a Google Search for "jobpimp"

Find Us on Facebook http://www.facebook.com/DSN.ExpatJobs
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A new syntax for writing tests

2010-08-05 Thread jfine
On 5 Aug, 14:52, Jean-Michel Pichavant  wrote:
> jfine wrote:
> > On 5 Aug, 10:17, Jean-Michel Pichavant  wrote:
>
> >> Jonathan Fine wrote:
>
> >>> Hi
>
> >>> I just discovered today anewsyntaxfor writing tests.  The basic
> >>> idea is to write a function that contains some statements, and run it
> >>> via a decorator.  I wonder if anyone had seen this pattern before, and
> >>> how you feel about it.  For myself, I quite like it.
>
> >>> Let's suppose we want to test this trivial (of course) class.
> >>>     class Adder(object):
>
> >>>         def __init__(self):
> >>>             self.value = 0
>
> >>>         def plus(self, delta):
> >>>             self.value += delta
>
> >>> The test the class you need a runner.  In this case it is quite simple.
>
> >>>     def runner(script, expect):
> >>>         '''Create an adder, run script, expect value.'''
>
> >>>         adder = Adder()
> >>>         script(adder)
> >>>         return adder.value
>
> >>> We can now create (and run if we wish) a test.  To do this we write
>
> >>>     @testit(runner, 4)
> >>>     def whatever(a):
> >>>         '''Two plus two is four.'''
>
> >>>         a.plus(2)
> >>>         a.plus(2)
>
> >>> Depending on the exact value of the testit decorator (which in the end
> >>> is up to you) we can store the test, or execute it immediately, or do
> >>> something else.
>
> >>> The simplest implementation prints:
> >>>     OK: Two plus two is four.
> >>> for this passing test, and
> >>>     Fail: Two plus four is five.
> >>>       expect 5
> >>>       actual 6
> >>> for a test that fails.
>
> >>> Here is the testit decorator used to produce the above output:
>
> >>>     def testit(runner, expect):
> >>>         '''Test statements decorator.'''
>
> >>>         def next(script):
> >>>             actual = runner(script, expect)
> >>>             if actual == expect:
> >>>                 print 'OK:', script.__doc__
> >>>             else:
> >>>                 print 'Fail:', script.__doc__
> >>>                 print '  expect', expect
> >>>                 print '  actual', actual
>
> >>>         return next
>
> >>> You can pick this code, for at least the next 30 days, at
> >>>    http://dpaste.com/hold/225056/
>
> >>> For me the key benefit is that writing the test is really easy.  
> >>> Here's a test I wrote earlier today.
>
> >>> @testit(runner, '')
> >>> def whatever(tb):
> >>>     tb.start('a', {'att': 'value'})
> >>>     tb.start('b')
> >>>     tb.end('b')
> >>>     tb.end('a')
>
> >>> If the test has a set-up and tear-down, this can be handled in the
> >>> runner, as can the test script raising an expected or unexpected
> >>> exception.
>
> >> Hi,
>
> >> "The unittest module provides a rich set of tools for constructing and
> >> running tests. This section demonstrates that a small subset of the
> >> tools suffice to meet the needs of most users."
>
> >> sourcehttp://docs.python.org/library/unittest.html
>
> >> As you can see, a much more featured test framework already exists.
>
> >> There's nothing wrong in anewtest framework, but it has to be better
> >> than the existing one in some situations.
>
> > Chalk and cheese.
>
> > My concern is to make tests easy to write, and that is something that
> > unittest is, in my view, not good at.  It is, as you say, a *test
> > framework*.
>
> > I've not written a test framework.  I've found what seems to be anew
> > *syntax* for writing tests.  Tests written in thenewsyntaxcan be
> > run in the unittest (or any other) framework.
>
> > --
> > Jonathan
>
> Well, I never used unittest, but the given example in the doc is pretty
> much simple.
> I'm still scratching my head.

I think you'd understand better if you used unittest.  For example,
try coding my test (with say 10 distinct tests of a class more
complicated than Adder) using unittest.  I think you'll see the point
when you get to number 5.

Here, for reference, is my complete code for one test.  See how it
scales.
 http://dpaste.com/hold/225056/  (available for at least 30
days).

--
Jonathan

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


Re: assigning variables from list data

2010-08-05 Thread Tim Chase

On 08/05/10 09:26, Chris Hare wrote:

I have a database query result (see code below). In PHP, I
would have said

list(var1,var2,var) = $result

and each element in the list would be assigned to each of the
named variables. I have my data coming out of the database,
and I can see it is a list. so my question is, instead of
having to do the variable assignment as I have it here, is
there a way more like PHP or am I stuck with it?

cursor.execute('select * from net where NetNumber> 0')
list = cursor.fetchone()


First off, I'd not mask the built-in "list", but you can use

  row = cursor.fetchone()
  if row:
(netNumber, netType, netCond, netStLo, NCS, NCS1) = row
  else:
print "No results"

(just add in the right number of variables to which you want to 
assign to)


-tkc

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


Re: subprocess escaping POpen?!

2010-08-05 Thread Tim Golden

On 05/08/2010 15:56, Chris Withers wrote:

Tim Golden wrote:

On 05/08/2010 15:49, Chris Withers wrote:

Tim Golden wrote:

See http://pexpect.sf.net for a python version.


...which doesn't work on Windows.


There is a winpexpect:

http://pypi.python.org/pypi/winpexpect/1.3


Are the two api-identical?


From the bitbucket page:

http://bitbucket.org/geertj/winpexpect/wiki/Home

"""
The API of winpexpect is identical to that of pexpect.
The only difference is that you must use the class "winspawn"
instead of "spawn"


...then why aren't they in the same fs&@ing package? ;-)


He does explain there that he hopes to have the changes merged
upstream. Presumably it hasn't happened yet...

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


Re: subprocess escaping POpen?!

2010-08-05 Thread Chris Withers

Tim Golden wrote:

On 05/08/2010 15:49, Chris Withers wrote:

Tim Golden wrote:

See http://pexpect.sf.net for a python version.


...which doesn't work on Windows.


There is a winpexpect:

http://pypi.python.org/pypi/winpexpect/1.3


Are the two api-identical?


 From the bitbucket page:

 http://bitbucket.org/geertj/winpexpect/wiki/Home

"""
The API of winpexpect is identical to that of pexpect.
The only difference is that you must use the class "winspawn"
instead of "spawn"


...then why aren't they in the same fs&@ing package? ;-)

Chris

--
Simplistix - Content Management, Batch Processing & Python Consulting
- http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: assigning variables from list data

2010-08-05 Thread Benjamin Kaplan
On Thu, Aug 5, 2010 at 7:26 AM, Chris Hare  wrote:
>
> I have a database query result (see code below).  In PHP, I would have said
>
> list(var1,var2,var) = $result
>
> and each element in the list would be assigned to each of the named 
> variables.  I have my data coming out of the database, and I can see it is a 
> list.  so my question is, instead of having to do the variable assignment as 
> I have it here, is there a way more like PHP or am I stuck with it?
>
> import sqlite3 as sqlite
>
> try:
>        print "connecting to disk db ..."
>        conn = sqlite.connect("netcomm.db")
> except:
>        print "oops"
>
> print "retrieving data"
> cursor = conn.cursor()
> cursor.execute('select * from net where NetNumber > 0')
> list = cursor.fetchone()
> print list
> print len(list)
> for item in list:
>    print item
> netNumber = list[0]
> netType = list[1]
> netConditions = list[2]
> netStartLocal = list[3]
> NCS = list[4]
> NCS1 = list[5]
> RADAR = list[6]
> NetFreq = list[7]
> Repeater = list[8]
> Notes = list[9]
> --

netNumber, netType, netConditions, netStartLocal, NCS, NCS1, RADAR,
NetFreq, Repeater, Notes = list

by the way, don't call the list "list". It will hide the built-in with
the same name.

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


Re: subprocess escaping POpen?!

2010-08-05 Thread Tim Golden

On 05/08/2010 15:49, Chris Withers wrote:

Tim Golden wrote:

See http://pexpect.sf.net for a python version.


...which doesn't work on Windows.


There is a winpexpect:

http://pypi.python.org/pypi/winpexpect/1.3


Are the two api-identical?


From the bitbucket page:

 http://bitbucket.org/geertj/winpexpect/wiki/Home

"""
The API of winpexpect is identical to that of pexpect.
The only difference is that you must use the class "winspawn"
instead of "spawn"
"""

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


Re: subprocess escaping POpen?!

2010-08-05 Thread Chris Withers

Tim Golden wrote:

See http://pexpect.sf.net for a python version.


...which doesn't work on Windows.


There is a winpexpect:

http://pypi.python.org/pypi/winpexpect/1.3


Are the two api-identical?


Chris

--
Simplistix - Content Management, Batch Processing & Python Consulting
- http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess escaping POpen?!

2010-08-05 Thread Tim Golden

On 05/08/2010 15:38, Chris Withers wrote:

Kushal Kumaran wrote:


- Original message -
> Wolfgang Rohdewald wrote:
> > On Donnerstag 05 August 2010, Chris Withers wrote:
> > > But why only the request for auth credentials?
> >
> > for security reasons I suppose - make sure a human enters
> > the password
>
> Well yes, but what if you actually want to script it?
>

Then you use expect.

See http://pexpect.sf.net for a python version.


...which doesn't work on Windows.


There is a winpexpect:

http://pypi.python.org/pypi/winpexpect/1.3

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


Re: subprocess escaping POpen?!

2010-08-05 Thread Chris Withers

Kushal Kumaran wrote:


- Original message -
 > Wolfgang Rohdewald wrote:
 > > On Donnerstag 05 August 2010, Chris Withers wrote:
 > > > But why only the request for auth credentials?
 > >
 > > for security reasons I suppose - make sure a human enters
 > > the password
 >
 > Well yes, but what if you actually want to script it?
 >

Then you use expect.

See http://pexpect.sf.net for a python version.


...which doesn't work on Windows.

Chris

--
Simplistix - Content Management, Batch Processing & Python Consulting
- http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: Fascinating interview by Richard Stallman on Russia TV

2010-08-05 Thread nanothermite911fbibustards
On Jul 18, 4:48 am, Richard Heathfield  wrote:

> Richard Heathfield 
> Email: -http://www. +rjh@
> "Usenet is a strange place" - dmr 29 July 1999
> Sig line vacant - apply within

http://www.youtube.com/watch?v=JYpkWbdOvrM&feature=related
http://www.youtube.com/watch?v=0y-Ct1NpxWA&feature=related

http://www.youtube.com/watch?v=u7dKl-T6ZFA&feature=related
http://www.youtube.com/watch?v=1DtUtvDrbIM&feature=related

http://www.youtube.com/watch?v=pOESV8kg1JE&feature=related
http://www.youtube.com/watch?v=lUCQRdVL9Pw&feature=related

http://www.youtube.com/watch?v=f5ZbDIUvsNA&NR=1
http://www.youtube.com/watch?v=L-RT_NeKkos&feature=related
http://www.youtube.com/watch?v=eVJxzJAU0nE

The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE
is UNACCEPTABLE.

=

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

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

http://www.youtube.com/watch?v=tXJ-k-iOg0M

Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ?
Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did
you release the 5 dancing Israelis compromising the whole 911
investigation ? If the Dubai Police can catch Mossad Murderers and put
the videos and Iranian Police can why cant you put the Pentagon
Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and
puting on INTERNATIONAL MEDIA a day after catching him without
TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did
you have to LIE about Dr Afiya Siddiqui and torture that Innocent
little mother of 3 and smashing the skull of her one child ?

http://www.youtube.com/watch?v=DhMcii8smxk
http://www.youtube.com/watch?v=0SZ2lxDJmdg

There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian
courts.

FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but
only because he was a white. They got away with MURDER of thousands of
Non-whites in all parts of the world.

Daily 911 news : http://911blogger.com

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

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

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

Conclusion : FBI bustards are RACIST and INcompetent. They could
neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they
cover them up - whichever was their actual goal or task.

SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across
tbe board, esp the whites/jew on the top.

FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and
UNPATRIOTIC Act
FBI bustards failed to prevent ROMAN POLANSKY from absconding to
europe and rapes.
FBI bustards failed to prevent OKLAHOMA

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


assigning variables from list data

2010-08-05 Thread Chris Hare

I have a database query result (see code below).  In PHP, I would have said

list(var1,var2,var) = $result

and each element in the list would be assigned to each of the named variables.  
I have my data coming out of the database, and I can see it is a list.  so my 
question is, instead of having to do the variable assignment as I have it here, 
is there a way more like PHP or am I stuck with it?

import sqlite3 as sqlite

try:
print "connecting to disk db ..."
conn = sqlite.connect("netcomm.db")
except:
print "oops"

print "retrieving data"
cursor = conn.cursor()
cursor.execute('select * from net where NetNumber > 0')
list = cursor.fetchone()
print list
print len(list)
for item in list:
print item
netNumber = list[0]
netType = list[1]
netConditions = list[2]
netStartLocal = list[3]
NCS = list[4]
NCS1 = list[5]
RADAR = list[6]
NetFreq = list[7]
Repeater = list[8]
Notes = list[9]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A portable LISP interpreter that includes all the major list-processing functions is described. A complete, annotated listing of the program's code, written in PASCAL, is included.

2010-08-05 Thread nanothermite911fbibustards
On Jul 24, 3:42 pm, Emmy Noether  wrote:
> On Jul 23, 9:27 pm, TheFlyingDutchman  wrote:
>
>
>
> > On Jul 23, 12:06 pm, Emmy Noether  wrote:
>
> > > Title   PortableLISPinterpreter
> > > Creator/Author  Cox, L.A. Jr. ; Taylor, W.P.
> > > Publication Date        1978 May 31
> > > OSTI Identifier OSTI ID: 7017786
> > > Report Number(s)        UCRL-52417
> > > DOE Contract Number     W-7405-ENG-48
> > > Resource Type   Technical Report
> > > Research Org    California Univ., Livermore (USA). Lawrence Livermore
> > > Lab.
> > > Subject 99 GENERAL AND MISCELLANEOUS//MATHEMATICS, COMPUTING, AND
> > > INFORMATION SCIENCE; COMPUTER CODES; L CODES; COMPUTERS; PROGRAMMING;
> > > PROGRAMMING LANGUAGES
> > > Description/Abstract    A portableLISPinterpreter that includes all the
> > > major list-processing functions is described. A complete, annotated
> > > listing of the program's code, written inPASCAL, is included.
> > > Country of Publication  United States
> > > Language        English
> > > Format  Medium: X; Size: Pages: 21
> > > Availability    Dep. NTIS, PC A02/MF A01.
> > > System Entry Date       2008 Feb 12
>
> > Is this available online? If only in hardcopy form, do they lend it
> > out?
>
> I am glad to share with everyone. However its useless without the
> ability to compile and run. Also with text, its easy to read and
> discuss the code which has a listing of 900 lines.
>
> I have already spent 4 hours scanning/processing to a stage where I
> got a decent OCR which needs hand-verification of pages. I need 4 or 8
> volunteers depending on whether one want to do two pages each or 1
> page each. Its an hour of joyful work each for two pages. Explanation
> are good quality. We will re-write to C, python etc.
>
> It must be edited in emacs in fundamental mode to overridepascalmode
> indentation. Go topascalmode periodically to colorize to indicate
> errors, and then revert before inserting anything. Stay close to the
> original page.
>
> Email me to receive image and initial ocr and lots of fixes I did by
> hand for more than 4hrs. Send only plain text message or it goes to
> spam.
>
> Then we share with everyone here or put it on some site.
>
> E.N.

http://www.youtube.com/watch?v=JYpkWbdOvrM&feature=related
http://www.youtube.com/watch?v=0y-Ct1NpxWA&feature=related

http://www.youtube.com/watch?v=u7dKl-T6ZFA&feature=related
http://www.youtube.com/watch?v=1DtUtvDrbIM&feature=related

http://www.youtube.com/watch?v=pOESV8kg1JE&feature=related
http://www.youtube.com/watch?v=lUCQRdVL9Pw&feature=related

http://www.youtube.com/watch?v=f5ZbDIUvsNA&NR=1
http://www.youtube.com/watch?v=L-RT_NeKkos&feature=related
http://www.youtube.com/watch?v=eVJxzJAU0nE

The FAT per DIEM FBI bustards use our TAX PAYER MONEY and INCOMPETENCE
is UNACCEPTABLE.

=

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

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

http://www.youtube.com/watch?v=tXJ-k-iOg0M

Hey Racist and INcompetent FBI Bustards, where is the ANTHRAX Mailer ?
Where are the 4 blackboxes ? Where are the Pentagon Videos ? Why did
you release the 5 dancing Israelis compromising the whole 911
investigation ? If the Dubai Police can catch Mossad Murderers and put
the videos and Iranian Police can why cant you put the Pentagon
Videos ? If Iran police can put the AMERICAN TERRORIST, Riggi and
puting on INTERNATIONAL MEDIA a day after catching him without
TORTURE, why cant you put the INNOCENT patsies on the MEDIA. Why did
you have to LIE about Dr Afiya Siddiqui and torture that Innocent
little mother of 3 and smashing the skull of her one child ?

http://www.youtube.com/watch?v=DhMcii8smxk
http://www.youtube.com/watch?v=0SZ2lxDJmdg

There are CRIMINAL cases against CIA CRIMINAL Bustards in Italian
courts.

FBI bustards paid a penalty of $5.8 million to Steven Hatfill, but
only because he was a white. They got away with MURDER of thousands of
Non-whites in all parts of the world.

Daily 911 news : http://911blogger.com

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

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

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

Conclusion : FBI bustards are RACIST and INcompetent. They could
neither catch the ANTHRAX or 911 YANK/Jew criminals nor could they
cover them up - whichever was their actual goal or task.

SLASH the SALARIES of FBI/CIA/NSA etc BUSTARDS into half all across
tbe board, esp the whites/jew on the top.

FBI Bustards failed to Catch BERNARD MADOFF even after that RACIST and
UNPATRIOTIC Act
FBI bustards failed to prevent ROMAN POLANSKY from absconding to
europe and rapes.
FBI bustards failed to prevent OKLAHOMA

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


Re: A useful, but painful, one-liner to edit money amounts

2010-08-05 Thread John Posner

On 8/5/2010 12:33 AM, John Nagle wrote:

There's got to be a better way to do this:


def editmoney(n) :
return((",".join(reduce(lambda lst, item : (lst + [item]) if
item else lst,
re.split(r'(\d\d\d)',str(n)[::-1]),[])))[::-1])



Here's a more elegant variant, using regexp lookahead:

def thous_format(integer_string):
"""
add comma thousands separator(s) to an integer-valued string
"""
return re.sub(r'(\d{3})(?=\d)', r'\1,', integer_string[::-1])[::-1]

I *thought* that I had found this on python-list on or about July 5, but 
I didn't find the thread after a search through the archives.


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


Re: A new syntax for writing tests

2010-08-05 Thread Jean-Michel Pichavant

jfine wrote:

On 5 Aug, 10:17, Jean-Michel Pichavant  wrote:
  

Jonathan Fine wrote:


Hi
  
I just discovered today anewsyntaxfor writing tests.  The basic

idea is to write a function that contains some statements, and run it
via a decorator.  I wonder if anyone had seen this pattern before, and
how you feel about it.  For myself, I quite like it.
  
Let's suppose we want to test this trivial (of course) class.

class Adder(object):
  
def __init__(self):

self.value = 0
  
def plus(self, delta):

self.value += delta
  
The test the class you need a runner.  In this case it is quite simple.
  
def runner(script, expect):

'''Create an adder, run script, expect value.'''
  
adder = Adder()

script(adder)
return adder.value
  
We can now create (and run if we wish) a test.  To do this we write
  
@testit(runner, 4)

def whatever(a):
'''Two plus two is four.'''
  
a.plus(2)

a.plus(2)
  
Depending on the exact value of the testit decorator (which in the end

is up to you) we can store the test, or execute it immediately, or do
something else.
  
The simplest implementation prints:

OK: Two plus two is four.
for this passing test, and
Fail: Two plus four is five.
  expect 5
  actual 6
for a test that fails.
  
Here is the testit decorator used to produce the above output:
  
def testit(runner, expect):

'''Test statements decorator.'''
  
def next(script):

actual = runner(script, expect)
if actual == expect:
print 'OK:', script.__doc__
else:
print 'Fail:', script.__doc__
print '  expect', expect
print '  actual', actual
  
return next
  
You can pick this code, for at least the next 30 days, at

   http://dpaste.com/hold/225056/
  
For me the key benefit is that writing the test is really easy.  
Here's a test I wrote earlier today.
  
@testit(runner, '')

def whatever(tb):
tb.start('a', {'att': 'value'})
tb.start('b')
tb.end('b')
tb.end('a')
  
If the test has a set-up and tear-down, this can be handled in the

runner, as can the test script raising an expected or unexpected
exception.
  

Hi,

"The unittest module provides a rich set of tools for constructing and
running tests. This section demonstrates that a small subset of the
tools suffice to meet the needs of most users."

sourcehttp://docs.python.org/library/unittest.html

As you can see, a much more featured test framework already exists.

There's nothing wrong in anewtest framework, but it has to be better
than the existing one in some situations.



Chalk and cheese.

My concern is to make tests easy to write, and that is something that
unittest is, in my view, not good at.  It is, as you say, a *test
framework*.

I've not written a test framework.  I've found what seems to be a new
*syntax* for writing tests.  Tests written in the new syntax can be
run in the unittest (or any other) framework.

--
Jonathan

  


Well, I never used unittest, but the given example in the doc is pretty 
much simple.

I'm still scratching my head.


JM

PS : I think your usage of 'syntax' is inapropriate.
--
http://mail.python.org/mailman/listinfo/python-list


abstract metaclass

2010-08-05 Thread Roald de Vries

Hi all,

I'm trying to create a metaclass that keeps track of its objects, and  
implement this as a collections.MutableMapping. That is, something  
like this:



class type2(type, MutableMapping):
...

/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/ 
python2.6/abc.pyc in __new__(mcls, name, bases, namespace)
 83  if getattr(value,  
"__isabstractmethod__", False))

 84 for base in bases:
---> 85 for name in getattr(base, "__abstractmethods__",  
set()):

 86 value = getattr(cls, name, None)
 87 if getattr(value, "__isabstractmethod__",  
False):


TypeError: Error when calling the metaclass bases
'getset_descriptor' object is not iterable


Anybody knows why? Every type is just an object, isn't it?

Thanks in advance, cheers,

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


Re: subprocess escaping POpen?!

2010-08-05 Thread Kushal Kumaran

- Original message -
> Wolfgang Rohdewald wrote:
> > On Donnerstag 05 August 2010, Chris Withers wrote:
> > > But why only the request for auth credentials?
> > 
> > for security reasons I suppose - make sure a human enters
> > the password
> 
> Well yes, but what if you actually want to script it?
> 

Then you use expect.

See http://pexpect.sf.net for a python version.

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


Re: Why is python not written in C++ ?

2010-08-05 Thread Tim Chase

On 08/05/10 05:33, Lawrence D'Oliveiro wrote:

OK, I have a copy of K&R 2nd Ed on a shelf within reach here. Can you point
out some behaviour that C programmers might need to rely on, that is not
specified in that document?


"need to" is considerably different from "might".  Size of an 
int, assumptions that int=pointer, evaluation order of postfix 
increment/decrement...


http://stackoverflow.com/questions/625333/how-to-limit-the-impact-of-implementation-dependent-language-features-in-c

or http://tinyurl.com/263jayy if mailers between here & there 
break the URL)


Just because facilities (macros, best-practices, etc) have been 
established for some of these things doesn't mean a programmer 
will reach for them if their code happens to work locally without 
them.  Trust me...I've encountered PLENTY of such code in 
production before I left behind (for the most part) the world of C.


-tkc




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


Re: simple (I hope!) problem

2010-08-05 Thread samwyse
On Aug 5, 4:32 am, Jean-Michel Pichavant 
wrote:
> samwyse wrote:
> > On Aug 3, 1:20 am, Steven D'Aprano  > t...@cybersource.com.au> wrote:
>
> >> On Mon, 02 Aug 2010 17:19:46 -0700, samwyse wrote:
>
> >>> Fortunately, I don't need the functionality of the object, I just want
> >>> something that won't generate an error when I use it.  So, what is the
> >>> quickest way to to create such an object (replacing the 'pass' in my
> >>> first snippet).  My solution is this:
>
> >>>     class C:
> >>>         def filter(self, *args, **kwds):
> >>>             pass
> >>>     register = C()
>
> >>> but it seems like I should be able to do something "better", as measured
> >>> by lines of code, faking more than just a 'filter' method, or both.  Any
> >>> ideas?  Thanks!
>
> >> You want a variation on the Null Object design pattern.
>
> >> class NullWithMethods(object):
> >>     def __getattr__(self, name):
> >>         return self
> >>     def __call__(self, *args, **kwargs):
> >>         pass
>
> >> And in action:
>
> > c = NullWithMethods()
> > c.spam("hello", "world")
> > c.something_completely_unlikely.spam.ham("hello", "world", foo=42)
>
> >> --
> >> Steven
>
> > JM emailed me a good solution, but yours is great! Thanks!
>
> The version I gave you overrides __getattribute__. To be honest,
> overriding __getattr__ is a better solution.Just in case you don't know
> the difference, __getattr__ is called only if the attribute is not found
> while __getattribute__ is actually called to find the attribute.
>
> JM

I have to apologize for not replying as soon as I got your email.  It
did everything I needed, so I implemented it in my code and went to
town.  Then, when I did finally return to the c.l.py, there was an
solution that exceeded my needs by letting me chain together arbitrary
lists of attributes.  Now that I've slept on it, I've come up with a
solution that I like even more:

>>> class Placeholder(object):
def __getattr__(self, name):
return self
def __getitem__(self, index):
return self
def __call__(self, *args, **kwargs):
return self

>>> x = Placeholder()
>>> x('hello, world').y[42].z
<__main__.Placeholder object at 0x01E46490>

Yes, running it from the prompt looks ugly, but within a program the
return value is silently discarded.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess escaping POpen?!

2010-08-05 Thread Jean-Michel Pichavant

Chris Withers wrote:

Jean-Michel Pichavant wrote:
You did not redirect stdin, so it is expected you can still read 
input from the console. 


Okay, so if I definitely wanted no input, what should I pass as the 
stdin parameter to the POpen constructor?

You do want an input don't you ? 'cause there is a password to enter.

from subprocess doc page:
"Note that if you want to send data to the process’s stdin, you need to 
create the Popen object with stdin=PIPE."



And it looks like svn is writting the credentials prompt on stderr.


...which, as you can see from the code I posted, is piped to STDOUT, 
which is then PIPE'd through to the calling python so that 
communicate()'s return value will contain the output.


As I explained, I can't reproduce this by replacing svn with a simple 
python script that writes to stderr. So, what is svn doing?
You're right, then that means than svn is writing credentials neither on 
stdout nor stderr.





You may want to look at http://pysvn.tigris.org/docs/pysvn.html though.


Yeah, we were using that, but found it excruciatingly painful due to 
its dependency on a subversion source install due to its c extension.

I can't argue with that.


cheers,

Chris



If you want to scriptly interract with svn or anything else, you may 
look at the pexpect module.


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


Re: subprocess escaping POpen?!

2010-08-05 Thread Grant Edwards
On 2010-08-05, Chris Withers  wrote:
> Wolfgang Rohdewald wrote:
>> On Donnerstag 05 August 2010, Chris Withers wrote:
>>> But why only the request for auth credentials?
>> 
>> for security reasons I suppose - make sure a human enters
>> the password
>
> Well yes, but what if you actually want to script it?

Scripting passwords is considered a huge security hole, so people who
care about security try to prevent it by doing things like reading
passwords from /dev/tty instead of stdin.

-- 
Grant Edwards   grant.b.edwardsYow! I want my nose in
  at   lights!
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A new syntax for writing tests

2010-08-05 Thread jfine
On 5 Aug, 10:17, Jean-Michel Pichavant  wrote:
> Jonathan Fine wrote:
> > Hi
>
> > I just discovered today anewsyntaxfor writing tests.  The basic
> > idea is to write a function that contains some statements, and run it
> > via a decorator.  I wonder if anyone had seen this pattern before, and
> > how you feel about it.  For myself, I quite like it.
>
> > Let's suppose we want to test this trivial (of course) class.
> >     class Adder(object):
>
> >         def __init__(self):
> >             self.value = 0
>
> >         def plus(self, delta):
> >             self.value += delta
>
> > The test the class you need a runner.  In this case it is quite simple.
>
> >     def runner(script, expect):
> >         '''Create an adder, run script, expect value.'''
>
> >         adder = Adder()
> >         script(adder)
> >         return adder.value
>
> > We can now create (and run if we wish) a test.  To do this we write
>
> >     @testit(runner, 4)
> >     def whatever(a):
> >         '''Two plus two is four.'''
>
> >         a.plus(2)
> >         a.plus(2)
>
> > Depending on the exact value of the testit decorator (which in the end
> > is up to you) we can store the test, or execute it immediately, or do
> > something else.
>
> > The simplest implementation prints:
> >     OK: Two plus two is four.
> > for this passing test, and
> >     Fail: Two plus four is five.
> >       expect 5
> >       actual 6
> > for a test that fails.
>
> > Here is the testit decorator used to produce the above output:
>
> >     def testit(runner, expect):
> >         '''Test statements decorator.'''
>
> >         def next(script):
> >             actual = runner(script, expect)
> >             if actual == expect:
> >                 print 'OK:', script.__doc__
> >             else:
> >                 print 'Fail:', script.__doc__
> >                 print '  expect', expect
> >                 print '  actual', actual
>
> >         return next
>
> > You can pick this code, for at least the next 30 days, at
> >    http://dpaste.com/hold/225056/
>
> > For me the key benefit is that writing the test is really easy.  
> > Here's a test I wrote earlier today.
>
> > @testit(runner, '')
> > def whatever(tb):
> >     tb.start('a', {'att': 'value'})
> >     tb.start('b')
> >     tb.end('b')
> >     tb.end('a')
>
> > If the test has a set-up and tear-down, this can be handled in the
> > runner, as can the test script raising an expected or unexpected
> > exception.
>
> Hi,
>
> "The unittest module provides a rich set of tools for constructing and
> running tests. This section demonstrates that a small subset of the
> tools suffice to meet the needs of most users."
>
> sourcehttp://docs.python.org/library/unittest.html
>
> As you can see, a much more featured test framework already exists.
>
> There's nothing wrong in anewtest framework, but it has to be better
> than the existing one in some situations.

Chalk and cheese.

My concern is to make tests easy to write, and that is something that
unittest is, in my view, not good at.  It is, as you say, a *test
framework*.

I've not written a test framework.  I've found what seems to be a new
*syntax* for writing tests.  Tests written in the new syntax can be
run in the unittest (or any other) framework.

--
Jonathan

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


*** Project for New American Python, Scheme, Emacs, Unix Century - TUTORIAL VIDEOS ***

2010-08-05 Thread small Pox


http://www.youtube.com/watch?v=JYpkWbdOvrM&feature=related
http://www.youtube.com/watch?v=0y-Ct1NpxWA&feature=related

http://www.youtube.com/watch?v=u7dKl-T6ZFA&feature=related
http://www.youtube.com/watch?v=1DtUtvDrbIM&feature=related

http://www.youtube.com/watch?v=pOESV8kg1JE&feature=related
http://www.youtube.com/watch?v=lUCQRdVL9Pw&feature=related

http://www.youtube.com/watch?v=f5ZbDIUvsNA&NR=1
http://www.youtube.com/watch?v=L-RT_NeKkos&feature=related
http://www.youtube.com/watch?v=eVJxzJAU0nE


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


Re: subprocess escaping POpen?!

2010-08-05 Thread Chris Withers

Wolfgang Rohdewald wrote:

On Donnerstag 05 August 2010, Chris Withers wrote:

But why only the request for auth credentials?


for security reasons I suppose - make sure a human enters
the password


Well yes, but what if you actually want to script it?

Chris

--
Simplistix - Content Management, Batch Processing & Python Consulting
- http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyInt_FromLong gives segfault on small numbers (<257)

2010-08-05 Thread Antoine Pitrou
On Thu, 5 Aug 2010 05:04:36 -0700 (PDT)
Marcos Prieto  wrote:
> Hi,
> 
> I'm trying to call python (python 2.6) functions from C++ using MS VC+
> + 6.0 and any calls to PyInt_FromLong with numbers below 257 give me
> exceptions, no problems with bigger numbers
> 
> PyObject *pValue;
> 
> pValue = PyInt_FromLong(1L); (or pValue = PyInt_FromLong(1);

Have you called Py_Initialize() before?



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


Re: A useful, but painful, one-liner to edit money amounts

2010-08-05 Thread Peter Otten
Chris Withers wrote:

> Peter Otten wrote:
> locale.setlocale(locale.LC_ALL, ("en_US", "UTF-8"))
>> 'en_US.UTF8'
> print locale.currency(13535, grouping=True)
>> $13,535.00
> 
> Okay, so if I'm writing a wsgi app, and I want to format depending on
> the choices of the currently logged in users, what would you recommend?
> 
> I can't do setlocale, since that would affect all users, and in a
> mult-threaded environment that would be bad.
> 
> Does that mean the whole locale package is useless to all web-app

Blame it on the C guys ;)

I've seen 

http://babel.edgewall.org/wiki/Documentation/intro.html
http://babel.edgewall.org/wiki/ApiDocs/babel.numbers
http://babel.edgewall.org/wiki/BabelFaq#WhatalternativesexistforPythonprojects

mentioned here but not yet tried it myself.

Peter

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


Re: subprocess escaping POpen?!

2010-08-05 Thread Wolfgang Rohdewald
On Donnerstag 05 August 2010, Chris Withers wrote:
> But why only the request for auth credentials?

for security reasons I suppose - make sure a human enters
the password

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


Re: subprocess escaping POpen?!

2010-08-05 Thread Ryan Kelly
On Thu, 2010-08-05 at 12:58 +0100, Chris Withers wrote:
> Jean-Michel Pichavant wrote:
> > You did not redirect stdin, so it is expected you can still read input 
> > from the console. 
> 
> Okay, so if I definitely wanted no input, what should I pass as the 
> stdin parameter to the POpen constructor?

The cross-platform equivalent of /dev/null:

   Popen(...,stdin=open(os.devnull,"r")...)

> > And it looks like svn is writting the credentials 
> > prompt on stderr.
> 
> ...which, as you can see from the code I posted, is piped to STDOUT, 
> which is then PIPE'd through to the calling python so that 
> communicate()'s return value will contain the output.
> 
> As I explained, I can't reproduce this by replacing svn with a simple 
> python script that writes to stderr. So, what is svn doing?

Many programs prompt for auth credentials on the controlling tty instead
of standard input/output.  I believe SSH also does this, which suggests
that it's considered more secure.  No idea why, but I trust the authors
of SSH to know their stuff in this regard.


  Cheers,

 Ryan
-- 
Ryan Kelly
http://www.rfk.id.au  |  This message is digitally signed. Please visit
r...@rfk.id.au|  http://www.rfk.id.au/ramblings/gpg/ for details


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


Re: Why is python not written in C++ ?

2010-08-05 Thread Paul Rudin
Lawrence D'Oliveiro  writes:

> In message , Roy Smith wrote:
>
>> C++, for all its flaws, had one powerful feature which made it very
>> popular.  It is a superset of C.
>
> Actually, it never was.

Wondering off topic a bit - I am reminded of something I once read in
some MS blurb... it described something as an "extended subset" of some
standard or another. (Think about it :))
-- 
http://mail.python.org/mailman/listinfo/python-list


PyInt_FromLong gives segfault on small numbers (<257)

2010-08-05 Thread Marcos Prieto
Hi,

I'm trying to call python (python 2.6) functions from C++ using MS VC+
+ 6.0 and any calls to PyInt_FromLong with numbers below 257 give me
exceptions, no problems with bigger numbers

PyObject *pValue;

pValue = PyInt_FromLong(1L); (or pValue = PyInt_FromLong(1);


Any ideas of what can I be doing wrong?

Thanks,

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


Re: Why is python not written in C++ ?

2010-08-05 Thread Christoffer Viken
C++ is actually not that bad.
Can't compare it to C, but nothing compares to C...
I think the bad reputation it got (and still has) is from Microsoft's visual
studio IDE (that was and still is horrible)
A lot of good applications are written in C++, but many bad ones as well.

Sorry for swearing in the church, but I'm pulling out PHP as an example.
Easy on beginners, the fat that you can jump in and out of PHP mode helps
too. It attracts a lot of beginner developers, and most of them write bad
code. It does not make the language a bad language, in fact PHP5 is pretty
good, but it means that there is a lot of bad code out there, but then we
have gems like MediaWiki and Drupal that is really good software.

You can write bad code in any language, and many languages get a bad
reputation because a lot of bad code is written in it.
The real test is not how bad code you can write, but the limit for how good
code you can write without jumping trough (too manny) hoops.

On Thu, Aug 5, 2010 at 12:34 PM, Lawrence D'Oliveiro
 wrote:

> In message , Roy Smith wrote:
>
> > C++, for all its flaws, had one powerful feature which made it very
> > popular.  It is a superset of C.
>
> Actually, it never was.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
--Desktop Browser, Google Apps -
Christoffer Viken / CVi

i=0

str="kI4dJMtXAv0m3cUiPKx8H"

while i<=20:

if i%3 and not i%4:

print str[i],

i=i+1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A useful, but painful, one-liner to edit money amounts

2010-08-05 Thread DarkBlue
On Aug 5, 7:06 pm, Chris Withers  wrote:
> Peter Otten wrote:
>  locale.setlocale(locale.LC_ALL, ("en_US", "UTF-8"))
> > 'en_US.UTF8'
>  print locale.currency(13535, grouping=True)
> > $13,535.00
>
> Okay, so if I'm writing a wsgi app, and I want to format depending on
> the choices of the currently logged in users, what would you recommend?
>
> I can't do setlocale, since that would affect all users, and in a
> mult-threaded environment that would be bad.
>
> Does that mean the whole locale package is useless to all web-app builders?
>
> Chris

from re import *

class editmoney(float):
def __init__(self,mymoney):
self.mymoney = mymoney
def __str__(self):
temp = "%.2f" % self.mymoney
profile = compile(r"(\d)(\d\d\d[.,])")
while 1:
temp, count = subn(profile,r"\1,\2",temp)
if not count: break
return temp
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess escaping POpen?!

2010-08-05 Thread Chris Withers

Jean-Michel Pichavant wrote:
You did not redirect stdin, so it is expected you can still read input 
from the console. 


Okay, so if I definitely wanted no input, what should I pass as the 
stdin parameter to the POpen constructor?


And it looks like svn is writting the credentials 
prompt on stderr.


...which, as you can see from the code I posted, is piped to STDOUT, 
which is then PIPE'd through to the calling python so that 
communicate()'s return value will contain the output.


As I explained, I can't reproduce this by replacing svn with a simple 
python script that writes to stderr. So, what is svn doing?



You may want to look at http://pysvn.tigris.org/docs/pysvn.html though.


Yeah, we were using that, but found it excruciatingly painful due to its 
dependency on a subversion source install due to its c extension.


cheers,

Chris

--
Simplistix - Content Management, Batch Processing & Python Consulting
- http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess escaping POpen?!

2010-08-05 Thread Jean-Michel Pichavant

Chris Withers wrote:

Hi All,

I have a script that does the following:

from subprocess import Popen,PIPE,STDOUT

def execute(command,cwd):
return Popen(
command,
stderr=STDOUT,
stdout=PIPE,
universal_newlines=True,
cwd=cwd,
shell=True,
).communicate()[0]

captured = execute('svn up .')

Now, if the subversion update requires authentication credentials, it 
manages to write to the console running the above script, *and* read 
input from it too.


This is a bit baffling to me, I thought Popen.communicate() was 
happily hoovering all the output to stdout and stderr into the result 
returned from communicate?


And, indeed, if I change the script instead to do:

import sys
f = open('test.py','w')
f.write('import sys; sys.stderr.write("Hello!\\n")')
f.close()
captured = execute('test.py')

...then the output is indeed captured. So, what is svn doing 
differently? How is it escaping its jail?


Chris

You did not redirect stdin, so it is expected you can still read input 
from the console. And it looks like svn is writting the credentials 
prompt on stderr.


You may want to look at http://pysvn.tigris.org/docs/pysvn.html though.

JM


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


Re: subprocess escaping POpen?!

2010-08-05 Thread Wolfgang Rohdewald
On Donnerstag 05 August 2010, Chris Withers wrote:
> ...then the output is indeed captured. So, what is svn doing 
> differently? How is it escaping its jail?

maybe it does not read from stdin but directly from /dev/tty


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


Re: subprocess escaping POpen?!

2010-08-05 Thread Chris Withers

Wolfgang Rohdewald wrote:

On Donnerstag 05 August 2010, Chris Withers wrote:
...then the output is indeed captured. So, what is svn doing 
differently? How is it escaping its jail?


maybe it does not read from stdin but directly from /dev/tty


But why only the request for auth credentials?

Chris

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


subprocess escaping POpen?!

2010-08-05 Thread Chris Withers

Hi All,

I have a script that does the following:

from subprocess import Popen,PIPE,STDOUT

def execute(command,cwd):
return Popen(
command,
stderr=STDOUT,
stdout=PIPE,
universal_newlines=True,
cwd=cwd,
shell=True,
).communicate()[0]

captured = execute('svn up .')

Now, if the subversion update requires authentication credentials, it 
manages to write to the console running the above script, *and* read 
input from it too.


This is a bit baffling to me, I thought Popen.communicate() was happily 
hoovering all the output to stdout and stderr into the result returned 
from communicate?


And, indeed, if I change the script instead to do:

import sys
f = open('test.py','w')
f.write('import sys; sys.stderr.write("Hello!\\n")')
f.close()
captured = execute('test.py')

...then the output is indeed captured. So, what is svn doing 
differently? How is it escaping its jail?


Chris

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


Re: A useful, but painful, one-liner to edit money amounts

2010-08-05 Thread Chris Withers

Peter Otten wrote:

locale.setlocale(locale.LC_ALL, ("en_US", "UTF-8"))

'en_US.UTF8'

print locale.currency(13535, grouping=True)

$13,535.00


Okay, so if I'm writing a wsgi app, and I want to format depending on 
the choices of the currently logged in users, what would you recommend?


I can't do setlocale, since that would affect all users, and in a 
mult-threaded environment that would be bad.


Does that mean the whole locale package is useless to all web-app builders?

Chris

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


  1   2   >