Re: Author of a Python Success Story Needs a Job!

2009-12-29 Thread Diez B. Roggisch

Please, if there is anyone out there who needs a highly creative and
highly skilled software designer for new and completely original work,
then for the love of God I implore you to contact me.


You don't write if you are willing to relocate, and if yes, if outside 
the USA is an option.


We hire skilled python employees in Berlin. Not speaking german is no 
problem, neither at work nor in the city itself.


Take a look:

 http://www.ableton.com/jobs


All the best,


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


Re: (help)Tkinter, how to make labels scrolling?

2009-12-29 Thread Ren Wenshan
It works, Thank you very much.

On Dec 28, 6:38 pm, Francesco Bochicchio  wrote:
>
> Hi,
>
> if you want to realize an 'animated scrolling' effect, you need to
> move the scrolling code out of the start callback
> in a function which is called periodically by the GUI mainloop. In
> Tkinter, you can do that using Toplevel.after to
> have a fuction be called after a timeout. Here is your 'meal' class
> with the modifications needed to make an
> 'animated scroll'. I renamed your start method as _scroll_text and
> wrote  new start and stop methods to start and stop
> the scrolling.
>
> Ciao
> -
> FB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Thanks for the help not given :)

2009-12-29 Thread Ben Finney
J  writes:

> And each time, I started writing a post, complete with code samples
> and my thoughts... and in EVERY case, so far, I've found the answer on
> my own ONLY after writing that post.

> […] actually writing out a post helps me organize my thoughts, the
> problem, and what I've done so far, and usually THAT is when the
> solution actually hits me. Even when I don't send the post, just
> having a target that forces me to actually organize and spell out what
> the problem is helps immensely.

A very common experience, and I'm glad you've found it so consistently
helpful http://en.wikipedia.org/wiki/Rubber_duck_debugging>. Thanks
for telling us how well it works!

-- 
 \  “Our products just aren't engineered for security.” —Brian |
  `\ Valentine, senior vice-president of Microsoft Windows |
_o__)  development |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to write simple code to match strings?

2009-12-29 Thread beginner
Hi Steve,

On Dec 30, 12:01 am, Steven D'Aprano  wrote:
> On Tue, 29 Dec 2009 21:01:05 -0800, beginner wrote:
> > Hi All,
>
> > I run into a problem.  I have a string s that can be a number of
> > possible things. I use a regular expression code like below to match and
> > parse it. But it looks very ugly. Also, the strings are literally
> > matched twice -- once for matching and once for extraction -- which
> > seems to be very slow. Is there any better way to handle this?
>
> The most important thing you should do is to put the regular expressions
> into named variables, rather than typing them out twice. The names
> should, preferably, describe what they represent.
>
> Oh, and you should use raw strings for regexes. In this particular
> example, I don't think it makes a difference, but if you ever modify the
> strings, it will!
>
> You should get rid of the unnecessary double calls to match. That's just
> wasteful. Also, since re.match tests the start of the string, you don't
> need the leading ^ regex (but you do need the $ to match the end of the
> string).
>
> You should also fix the syntax error, where you have "elif s=='-'"
> instead of "elif s='-'".
>
> You should consider putting the cheapest test(s) first, or even moving
> the expensive tests into a separate function.
>
> And don't be so stingy with spaces in your source code, it helps
> readability by reducing the density of characters.
>
> So, here's my version:
>
> def _re_match_items(s):
>     # Setup some regular expressions.
>     COMMON_RE = r'\$?([-+]?[0-9,]*\.?[0-9,]+)'
>     FLOAT_RE = COMMON_RE + '$'
>     BRACKETED_FLOAT_RE = r'\(' + COMMON_RE + r'\)$'
>     DATE_RE = r'\d{1,2}-\w+-\d{1,2}$'
>     mo = re.match(FLOAT_RE, s)  # "mo" short for "match object"
>     if mo:
>         return float(mo.group(1).replace(',', ''))
>     # Otherwise mo will be None and we go on to the next test.
>     mo = re.match(BRACKETED_FLOAT_RE, s)
>     if mo:
>         return -float(mo.group(1).replace(',', ''))
>     if re.match(DATE_RE, s):
>         return dateutil.parser.parse(s, dayfirst=True)
>     raise ValueError("bad string can't be matched")
>
> def convert_data_item(s):
>     if s = '-':
>         return None
>     else:
>         try:
>             return _re_match_items(s)
>         except ValueError:
>             print "Unrecognized format %s" % s
>             return s
>
> Hope this helps.
>
> --
> Steven

This definitely helps.

I don't know if it should be s=='-' or s='-'. I thought == means equal
and = means assignment?

Thanks again,
G



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


Re: detect interactivity

2009-12-29 Thread Dave Angel

Steve Holden wrote:

Roald de Vries wrote:
  

On Dec 30, 2009, at 2:28 AM, Dave Angel wrote:



Roald de Vries wrote:
  


mehow define a different set of functions???
  

I'm using a database, and want to use python interactively to manipulate
it. On the other hand, I also want to be able to use it
non-interactively. In that case, it would be a waste of CPU to load the
function/class definitions meant for interactive use.



This is an extreme case of premature optimization. Write the code and
run it. Do you have any idea how much extra time and memory loading the
additional code will require? If not, it's a waste of your time to even
think about omitting the stuff required for interactive use.

Once you get a handle on the structures and functions required for
interactive vs. non-interactive use you can consider refactoring the
code so that the non-interactive programs don't need to import the stuff
that's exclusively for interactive use. But frankly I wouldn't waste
your time.

regards
 Steve
  


Ron:
You'd be surprised how little additional space and time a few functions 
take up.


But in any case, if (after measurement) you decide you really want them 
to be optional, then just have a different module that the interactive 
users import than the one that you run in production.  Have both modules 
import the bulk of the code, and keep the differences in one place.


It's also possible to build stubs for the missing functions, and import 
them and overwrite the stubs, upon first reference.  I've done that sort 
of thing in other language environments, when it made a definite 
measurable difference (like say 50%)


DaveA

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


Re: TypeError: startView() takes exactly 1 argument (3 given)

2009-12-29 Thread Dave Angel

Ron Croonenberg wrote:

Hello,

I am trying to write a plugin for Rhythmbox in python and run into a 
'strange' problem. For a method (an action for clicking a button) I 
started a method and however many arguments I use, it keeps giving me 
the same error:


'TypeError: startView() takes exactly 1 argument (3 given)'

does someone have any pointers or tips?, thanks;

Ron

here is the code I have the problem with:

import rb
import pygtk
import gtk, gobject


pygtk.require('2.0')



class tb_button (rb.Plugin):

#
# the init thing
#
   def __init__(self):
  rb.Plugin.__init__(self)

#
# the activate thing
#
   def activate(self, shell):
  self.shell = shell

  view_button = """
  

  


  

  
  """

  # create a new action
  action = gtk.Action('viewAction',
_(' _View'),
_('Browse Track '), "")

  # connect it
  action.connect('activate', self.startView, shell)
  action_group = gtk.ActionGroup('NewActionGroup')
  action_group.add_action(action)
  shell.get_ui_manager().insert_action_group(action_group)

  # add it to the toolbar
  ui_manager = shell.get_ui_manager()
  ui_manager.add_ui_from_string(view_button)



#
# Start the  View
#
   def startView(self, widget, shell, se):
# nothing yet
  return


Please give the complete error traceback, and make sure it matches the 
code you post.  I'm guessing that the subset of the error message you're 
quoting occurs when you define startView() as taking only self as a 
parameter.


A quick caveat.  I'm not familiar with GTK in particular, but I 
recognize the paradigm.  You're defining an event handler (startView).  
And you define a certain set of parameters (not arguments), presently 
called self, widge, shell, and se.


But you're not calling it, you're connecting it to an action.  So when 
that action triggers (or event happens), the GUI system will call your 
event handler.  You don't control the arguments it passes, and 
apparently it passes 3.  So you need to change the formal parameters in 
your def to match.


More specifically what are those parameters ?  I don't know, but you 
should be able to tell from sample pyGTK sources, or somebody else can 
chime in.  And maybe I'm totally nuts here.


DaveA

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


Re: How to write simple code to match strings?

2009-12-29 Thread Steven D'Aprano
On Tue, 29 Dec 2009 21:01:05 -0800, beginner wrote:

> Hi All,
> 
> I run into a problem.  I have a string s that can be a number of
> possible things. I use a regular expression code like below to match and
> parse it. But it looks very ugly. Also, the strings are literally
> matched twice -- once for matching and once for extraction -- which
> seems to be very slow. Is there any better way to handle this?

The most important thing you should do is to put the regular expressions 
into named variables, rather than typing them out twice. The names 
should, preferably, describe what they represent.

Oh, and you should use raw strings for regexes. In this particular 
example, I don't think it makes a difference, but if you ever modify the 
strings, it will!

You should get rid of the unnecessary double calls to match. That's just 
wasteful. Also, since re.match tests the start of the string, you don't 
need the leading ^ regex (but you do need the $ to match the end of the 
string).

You should also fix the syntax error, where you have "elif s=='-'" 
instead of "elif s='-'".

You should consider putting the cheapest test(s) first, or even moving 
the expensive tests into a separate function.

And don't be so stingy with spaces in your source code, it helps 
readability by reducing the density of characters.

So, here's my version:

def _re_match_items(s):
# Setup some regular expressions.
COMMON_RE = r'\$?([-+]?[0-9,]*\.?[0-9,]+)'
FLOAT_RE = COMMON_RE + '$'
BRACKETED_FLOAT_RE = r'\(' + COMMON_RE + r'\)$'
DATE_RE = r'\d{1,2}-\w+-\d{1,2}$'
mo = re.match(FLOAT_RE, s)  # "mo" short for "match object"
if mo:
return float(mo.group(1).replace(',', ''))
# Otherwise mo will be None and we go on to the next test.
mo = re.match(BRACKETED_FLOAT_RE, s)
if mo:
return -float(mo.group(1).replace(',', ''))
if re.match(DATE_RE, s):
return dateutil.parser.parse(s, dayfirst=True)
raise ValueError("bad string can't be matched")


def convert_data_item(s):
if s = '-':
return None
else:
try:
return _re_match_items(s)
except ValueError:
print "Unrecognized format %s" % s
return s



Hope this helps.


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


Re: the need for 64 bits

2009-12-29 Thread Cameron Simpson
On 29Dec2009 21:42, Aahz  wrote:
| In article <8950e4a5-f630-4ffb-b7ed-5c539913a...@a6g2000yqm.googlegroups.com>,
| Mensanator   wrote:
| >Ah, the 8 GB Mac wouldn't have helped. Glad I didn't spend the extra
| >$1000.
| 
| It's almost always cheaper to buy your Mac and then upgrade the RAM
| separately.

Unless it's a Macbook Air. Then you're stuck with 2GB max:-(
At least I didn't pay for it:-) It's a nice machine in many respects.
-- 
Cameron Simpson  DoD#743
http://www.cskk.ezoshosting.com/cs/

I am a Bear of Very Little Brain and long words Bother Me.
- Winnie-the-Pooh
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Difference Between Two datetimes

2009-12-29 Thread Stephen Hansen
On Tue, Dec 29, 2009 at 7:21 AM, M.-A. Lemburg  wrote:

> If you want a more human readable, relative format use Age():
>
> >>> Age(bree, nat)
>  0x2b99c6e37ef0>
>
> i.e. 8 years, 4 months, 29 days, 49 minutes, 35 seconds.
>

That is... awesome. I use mx.DateTime all the time, and never knew about the
Age capability.

mx.DateTime wins. I'm sort of curious why Python grew 'datetime' when
mx.DateTime was established already, and its such an excellent library.

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


Re: the need for 64 bits

2009-12-29 Thread Aahz
In article <8950e4a5-f630-4ffb-b7ed-5c539913a...@a6g2000yqm.googlegroups.com>,
Mensanator   wrote:
>
>Ah, the 8 GB Mac wouldn't have helped. Glad I didn't spend the extra
>$1000.

It's almost always cheaper to buy your Mac and then upgrade the RAM
separately.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6 ftplib has timeout parameter, but how to detect a timeout

2009-12-29 Thread Aahz
In article ,
Brendan   wrote:
>
>I was quite happy to see that ftplib in Python 2.6 now has a timeout
>parameter. With large file downloads my script would often hang,
>presumably from timing out. Now that there is a timeout parameter, how
>would I detect when a timeout occurs?

Without looking at code or docs, I assume you get an exception.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: detect interactivity

2009-12-29 Thread Steven D'Aprano
On Wed, 30 Dec 2009 03:33:18 +0100, Roald de Vries wrote:

> I'm using a database, and want to use python interactively to manipulate
> it. On the other hand, I also want to be able to use it non-
> interactively. In that case, it would be a waste of CPU to load the
> function/class definitions meant for interactive use.

Premature optimization is the root of all evil.

The code for interactive use almost certainly won't be a significant 
drain on the computer's resources, unless you're using some sort of 
embedded device. And if it is, then the natural overhead of merely 
running Python at all is almost certainly even more of a drain -- Python 
is not a language designed for the efficiency of the CPU, but for the 
programmer instead.

But even if we give you the benefit of the doubt, and assume that you've 
profiled your code and determined that, in this case, such optimization 
is needed, I see at least two problems with that approach.

Problem #1: the benefit won't be as much as you might expect.

If your approach is the following:

# common code used both interactively and non-interactively
def parrot():
pass

def spanish_inquisition():
pass

# interactive code only:
if interactive():  # however you determine this
def cheeseshop():
pass


then the approach you are trying isn't doing what you think it does. 
Python still has to parse the definition of cheeseshop and compile it 
before running the module code, so the benefit of making it optional is 
minimal.

You might think that the better approach is to move it into another 
module:

if interactive():  # however you determine this
from interactive_code import *


but even this means that the benefit is relatively small, since the 
interactive_code module will be compiled to a .pyc file, and therefore 
most of the effort of parsing it, compiling it etc. will be skipped. And 
now you have to deal with the problem of circular imports.


Problem #2: if you have code that only appears at certain times, how do 
you test it to be sure it works correctly?

Since test code (unit tests, doc tests, etc.) generally are run non-
interactively, your code will be missing all the interactive functions, 
which means you can't test them easily. Any automated test suite will 
skip half your code!



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


Re: detect interactivity

2009-12-29 Thread Steven D'Aprano
On Wed, 30 Dec 2009 03:26:20 +0100, Roald de Vries wrote:

> On Dec 30, 2009, at 1:52 AM, Steven D'Aprano wrote:
>> On Tue, 29 Dec 2009 16:09:58 +0100, Roald de Vries wrote:
>>
>>> Dear all,
>>>
>>> Is it possible for a Python script to detect whether it is running
>>> interactively? It can be useful for e.g. defining functions that are
>>> only useful in interactive mode.
>>
>> Ah, I should have looked more carefully at the docs...
>>
>> http://docs.python.org/library/sys.html#sys.ps1
>>
>> sys.ps1 and sys.ps2 are documented as only existing if you are running
>> interactively.
> 
> This doesn't really work. In ipython, sys.ps1 is not defined.

Then ipython is not a valid implementation of Python, since it breaks a 
promise of the language. You should report this to the ipython people as 
a serious bug.


> But also
> if I run 'python <<< "import sys; print(sys.ps1)"', I get an error.

Of course you do, because you're not running interactively and so sys.ps1 
doesn't exist. You need to check the existence of ps1:

try:
sys.ps1
except AttributeError:
print "Not running interactively."
else:
print "Running interactively."


Alternatively:

if hasattr(sys, 'ps1'):
print "Running interactively."
else:
print "Not running interactively."



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


How to write simple code to match strings?

2009-12-29 Thread beginner
Hi All,

I run into a problem.  I have a string s that can be a number of
possible things. I use a regular expression code like below to match
and parse it. But it looks very ugly. Also, the strings are literally
matched twice -- once for matching and once for extraction -- which
seems to be very slow. Is there any better way to handle this?


  def convert_data_item(s):
if re.match('^\$?([-+]?[0-9,]*\.?[0-9,]+)$',s):
g=re.match('^\$?([-+]?[0-9,]*\.?[0-9,]+)$',s)
v=float(g.group(1).replace(',',''))
elif re.match('^\(\$?([-+]?[0-9,]*\.?[0-9,]+)\)$',s):
g=re.match('^\(\$?([-+]?[0-9,]*\.?[0-9,]+)\)$',s)
v=-float(g.group(1).replace(',',''))
elif re.match('^\d{1,2}-\w+-\d{1,2}$',s):
v=dateutil.parser.parse(s, dayfirst=True)
elif s=='-':
v=None
else:
print "Unrecognized format %s" % s
v=s
return v

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


Re: detect interactivity

2009-12-29 Thread Steve Holden
Roald de Vries wrote:
> 
> On Dec 30, 2009, at 2:28 AM, Dave Angel wrote:
> 
>> Roald de Vries wrote:
>>> On Dec 29, 2009, at 8:34 PM, Dave Angel wrote:
 Antoine Pitrou wrote:
> Le Tue, 29 Dec 2009 16:09:58 +0100, Roald de Vries a écrit :
>
>
>> Dear all,
>>
>> Is it possible for a Python script to detect whether it is running
>> interactively? It can be useful for e.g. defining functions that are
>> only useful in interactive mode.
>>
>
> Try the isatty() method (*) on e.g. stdin:
>
> $ python -c "import sys; print sys.stdin.isatty()"
> True
> $ echo "" | python -c "import sys; print sys.stdin.isatty()"
> False
>
 Your test determines whether input is redirected.  But I think the
 OP was asking how to detect whether the script was being run from an
 interpreter prompt.
>>>
>>> That was my question indeed. Is it possible?
>>>
>>>
>> If I had had a good answer, I would have supplied it in my earlier
>> message.
>>
>> The sneaky answer would be that a script cannot be used interactively,
>> as once you import it from the interpreter, it's a module, not a
>> script.  So you can detect that it's not a script, by examing __name__
>> in the usual way.  If it's a script, it'll have a value of "__main__".
>>
>> But that won't tell you if you're running inside an IDE, or using the
>> -i switch on the Python command line, or probably a bunch of other
>> questions.  I don't know of any "correct" answer, and I'm not sure
>> what the real use case is for knowing.  Are you really going to
>> somehow define a different set of functions???
> 
> I'm using a database, and want to use python interactively to manipulate
> it. On the other hand, I also want to be able to use it
> non-interactively. In that case, it would be a waste of CPU to load the
> function/class definitions meant for interactive use.
> 
This is an extreme case of premature optimization. Write the code and
run it. Do you have any idea how much extra time and memory loading the
additional code will require? If not, it's a waste of your time to even
think about omitting the stuff required for interactive use.

Once you get a handle on the structures and functions required for
interactive vs. non-interactive use you can consider refactoring the
code so that the non-interactive programs don't need to import the stuff
that's exclusively for interactive use. But frankly I wouldn't waste
your time.

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


TypeError: startView() takes exactly 1 argument (3 given)

2009-12-29 Thread Ron Croonenberg

Hello,

I am trying to write a plugin for Rhythmbox in python and run into a 
'strange' problem. For a method (an action for clicking a button) I 
started a method and however many arguments I use, it keeps giving me 
the same error:


'TypeError: startView() takes exactly 1 argument (3 given)'

does someone have any pointers or tips?, thanks;

Ron

here is the code I have the problem with:

import rb
import pygtk
import gtk, gobject


pygtk.require('2.0')



class tb_button (rb.Plugin):

#
# the init thing
#
   def __init__(self):
  rb.Plugin.__init__(self)

#
# the activate thing
#
   def activate(self, shell):
  self.shell = shell

  view_button = """
  

  


  

  
  """

  # create a new action
  action = gtk.Action('viewAction',
_(' _View'),
_('Browse Track '), "")

  # connect it
  action.connect('activate', self.startView, shell)
  action_group = gtk.ActionGroup('NewActionGroup')
  action_group.add_action(action)
  shell.get_ui_manager().insert_action_group(action_group)

  # add it to the toolbar
  ui_manager = shell.get_ui_manager()
  ui_manager.add_ui_from_string(view_button)



#
# Start the  View
#
   def startView(self, widget, shell, se):
# nothing yet
  return

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


Re: Thanks for the help not given :)

2009-12-29 Thread J
On Tue, Dec 29, 2009 at 17:58, Phlip  wrote:
> To the OP - adding "... because Python sucks" to your subject lines will
> increase the quantity of answers - but possibly not the quality.

Unlike Stephan, I hope this was intended in humor/irony rather than
the way it looks, because my OP was meant humorously/ironically.

> You can also learn a little about good questions by answering others's here.

I don't answer questions without having $CLUE, fortunately.  I've been
on lists like this for well over 15 years, going back to when the only
place to find them was usenet, and I've been party to and target of my
fair share of flame wars due to improperly formatted questions or
uninformed answers ;-)

> And I hope you answered your questions here, if no one else did, to avoid
> dead search trails in the archives. You learn by teaching!

Indeed, which is why I teach Linux 101 at the community college level
(credited, not con-ed, an actual, honest to goodness Linux course!!).
I have not answered my own questions here, because the ones that I can
and eventually answer myself, such as the three I mentioned in my OP,
were really so basic as to be just noise on this list (though I guess
this discussion probably borders on it too).  My original POINT was
that the help/answers that I HAVE received here, in addition to the
various threads I read as they come up, has given me enough background
education to really start figuring things out on my own, as opposed to
constantly asking someone else for an answer or trying to grep my way
through various documents/tutorials/HOW-TOs/books/etc.

So it really was meant as a thanks for the people here who do have
$CLUE for helping me start getting one of my own.

> As for me, my questions are usually some combination of hopelessly retarded
> and beyond the blue sky envelope that I take pity on anyone even reading
> them, less answering them...

I sometimes think that of my own questions, though I really do try to
keep the basic questions to a minimum anywhere... then again, we all
have to start somewhere, which is why I try to not haze newbies, even
when that's my first reaction.

> Jon Clements wrote:
>
>> You have a bear that likes a Python? The one I have just keeps going
>> on about Piglet and eating my honey reserves...

As for Jon, and Aahz, I'd try the teddy bear approach, but the last
one I knew led me down the dark path to Perl and thus I try to avoid
them whenever possible ;-)

Cheers,

Jeff

-- 

Jonathan Swift  - "May you live every day of your life." -
http://www.brainyquote.com/quotes/authors/j/jonathan_swift.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: detect interactivity

2009-12-29 Thread Roald de Vries


On Dec 30, 2009, at 2:28 AM, Dave Angel wrote:


Roald de Vries wrote:

On Dec 29, 2009, at 8:34 PM, Dave Angel wrote:

Antoine Pitrou wrote:

Le Tue, 29 Dec 2009 16:09:58 +0100, Roald de Vries a écrit :



Dear all,

Is it possible for a Python script to detect whether it is running
interactively? It can be useful for e.g. defining functions that  
are

only useful in interactive mode.



Try the isatty() method (*) on e.g. stdin:

$ python -c "import sys; print sys.stdin.isatty()"
True
$ echo "" | python -c "import sys; print sys.stdin.isatty()"
False

Your test determines whether input is redirected.  But I think the  
OP was asking how to detect whether the script was being run from  
an interpreter prompt.


That was my question indeed. Is it possible?


If I had had a good answer, I would have supplied it in my earlier  
message.


The sneaky answer would be that a script cannot be used  
interactively, as once you import it from the interpreter, it's a  
module, not a script.  So you can detect that it's not a script, by  
examing __name__ in the usual way.  If it's a script, it'll have a  
value of "__main__".


But that won't tell you if you're running inside an IDE, or using  
the -i switch on the Python command line, or probably a bunch of  
other questions.  I don't know of any "correct" answer, and I'm not  
sure what the real use case is for knowing.  Are you really going to  
somehow define a different set of functions???


I'm using a database, and want to use python interactively to  
manipulate it. On the other hand, I also want to be able to use it non- 
interactively. In that case, it would be a waste of CPU to load the  
function/class definitions meant for interactive use.




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


Re: I think I found a bug in Python 2.6.4 (in the inspect module)

2009-12-29 Thread inhahe
On Tue, Dec 29, 2009 at 6:38 PM, Irmen de Jong  wrote:
> On 29-12-2009 23:22, inhahe wrote:
>
> inspect.getargvalues is used on frames, not on regular code objects.
> Maybe you were looking for inspect.getargspec?
>

That explains it!
I knew I'd done this before, I was just looking at the wrong function name.  thx
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: detect interactivity

2009-12-29 Thread Roald de Vries

On Dec 30, 2009, at 1:52 AM, Steven D'Aprano wrote:

On Tue, 29 Dec 2009 16:09:58 +0100, Roald de Vries wrote:


Dear all,

Is it possible for a Python script to detect whether it is running
interactively? It can be useful for e.g. defining functions that are
only useful in interactive mode.


Ah, I should have looked more carefully at the docs...

http://docs.python.org/library/sys.html#sys.ps1

sys.ps1 and sys.ps2 are documented as only existing if you are running
interactively.


This doesn't really work. In ipython, sys.ps1 is not defined. But also  
if I run 'python <<< "import sys; print(sys.ps1)"', I get an error.



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


Re: detect interactivity

2009-12-29 Thread Dave Angel

Roald de Vries wrote:

On Dec 29, 2009, at 8:34 PM, Dave Angel wrote:

Antoine Pitrou wrote:

Le Tue, 29 Dec 2009 16:09:58 +0100, Roald de Vries a écrit :



Dear all,

Is it possible for a Python script to detect whether it is running
interactively? It can be useful for e.g. defining functions that are
only useful in interactive mode.



Try the isatty() method (*) on e.g. stdin:

$ python -c "import sys; print sys.stdin.isatty()"
True
$ echo "" | python -c "import sys; print sys.stdin.isatty()"
False

Your test determines whether input is redirected.  But I think the OP 
was asking how to detect whether the script was being run from an 
interpreter prompt.


That was my question indeed. Is it possible?



If I had had a good answer, I would have supplied it in my earlier message.

The sneaky answer would be that a script cannot be used interactively, 
as once you import it from the interpreter, it's a module, not a 
script.  So you can detect that it's not a script, by examing __name__ 
in the usual way.  If it's a script, it'll have a value of "__main__".


But that won't tell you if you're running inside an IDE, or using the -i 
switch on the Python command line, or probably a bunch of other 
questions.  I don't know of any "correct" answer, and I'm not sure what 
the real use case is for knowing.  Are you really going to somehow 
define a different set of functions???


But I'm sure someone else will know something more explicitly tied to 
the interactive session.  If that's indeed what you want to test for.


DaveA

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


Re: detect interactivity

2009-12-29 Thread Steven D'Aprano
On Tue, 29 Dec 2009 16:09:58 +0100, Roald de Vries wrote:

> Dear all,
> 
> Is it possible for a Python script to detect whether it is running
> interactively? It can be useful for e.g. defining functions that are
> only useful in interactive mode.

Ah, I should have looked more carefully at the docs...

http://docs.python.org/library/sys.html#sys.ps1

sys.ps1 and sys.ps2 are documented as only existing if you are running 
interactively.


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


Re: detect interactivity

2009-12-29 Thread Steven D'Aprano
On Tue, 29 Dec 2009 16:09:58 +0100, Roald de Vries wrote:

> Dear all,
> 
> Is it possible for a Python script to detect whether it is running
> interactively? It can be useful for e.g. defining functions that are
> only useful in interactive mode.

Check __name__. It's set to '__main__' when running as a (non-
interactive) script, and to the name of the module when imported.

[st...@sylar ~]$ cat interactive.py
print __name__

[st...@sylar ~]$ python interactive.py
__main__
[st...@sylar ~]$ python
Python 2.5 (r25:51908, Nov  6 2007, 16:54:01)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import interactive
interactive
>>>

The only complications are that it doesn't work well with the -i command 
line switch (it still reports that __name__ == '__main__'), and if you 
start an interactive session __name__ is also set to '__main__'.

Sadly, sys.argv doesn't report the switches used, but in Python 2.6 and 
better you can look at sys.flags to see if the -i switch is being used.

http://docs.python.org/library/sys.html#sys.flags


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


Re: Moving from PHP to Python. Is it Possible

2009-12-29 Thread Aaron Watters
Sancar wants to move from PHP to Python.

The following a shameless plug for WHIFF: http://whiff.sourceforge.net
-- I wrote it partially because I wanted PHP-like features using
Python, but better ;).

On Dec 11, 5:26 am, Sancar Saran  wrote:
> Greetings.

> After 3 days of crawling google, diving in python and cursing, now  I can 
> show
> something on my linux/apache/mod_wsgi setup.

It's too bad you didn't find the WHIFF quickstart first :).
   http://whiffdoc.appspot.com/docs/W0500.quickstart

> And i'm struck on something
>
> My design depends on a Global Array. A huge array which store everything about
> requested Web page for a final rendering.
> In PHP accessing globals is easy. You may do direct access or use class
> something like ZEND Registry
> 1-) Can I create Global (read/write access anywhere from my code) Multi
> dimensional, associative array (or hash) and store any kind of variable type.

There are a number of ways to do things like this in WHIFF
-- one way is to use the WSGI environment to store your
"globals" as illustrated in the Mako tutorial:
http://whiffdoc.appspot.com/docs/W1100_1075.MakoGrading

> 2-) Is there any error trigger for mod_wsgi. When something go bad I god
> Internal Server error. Looking for error log was't nice. Is there any way to
> shows errors in the web page ?

Configure your application to display tracebacks on errors.
I need to explicitly add this to the documentation, but here
is an example used by the WHIFF documentation app config:

59 whiffDocumentation = resolver.moduleRootApplication("/", docroot,
60   #exception_middleware=None,
61   environment=environment,
62   exception_middleware=displayTraceback.__middleware__,
63   on_not_found=None, # show traceback (could comment)
64   auto_reload=False,
65 )

lines 62 and 63 from
  
http://aaron.oirt.rutgers.edu/cgi-bin/whiffRepo.cgi/file/4b2cea3d92fc/doc/servedocs.py

> 3-) Any documents books sites about helping moving from php to python

  http://whiffdoc.appspot.com/ (doesn't explicitly mention PHP).

> 4-) In php we had something like
> ob_start(); // start Output buffering
> require('hede.php'); // include phtml similar to psp. mixed language and html
> (to avoiding string replacement (or marker based) html templates)
> $var = ob_get_clean(); // get rendered output and use anywhere
> can find a similar abilities in Python ?

Of course:

See the quoteHtml implementation, for example
http://aaron.oirt.rutgers.edu/cgi-bin/whiffRepo.cgi/file/4b2cea3d92fc/whiff/middleware/quoteHtml.py

> 5-) is there any Python documentation based on examples. When I give up about
> to finding  php's $_REQUEST or $_SERVER equivalents in python some demo code 
> in
> Twisted docs are much helpful than any other words. Me and my kind already
> have  problem with English language. Example code much more helpful than full
> academic description.

  http://whiffdoc.appspot.com (again) there are lots and lots of
examples.

I hope you like it and have a happy new year!  -- Aaron Watters

===
my resolution last year
was not to make any resolutions this year.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I think I found a bug in Python 2.6.4 (in the inspect module)

2009-12-29 Thread Irmen de Jong

On 29-12-2009 23:22, inhahe wrote:

On Tue, Dec 29, 2009 at 5:11 PM, inhahe  wrote:

On Tue, Dec 29, 2009 at 5:10 PM, inhahe  wrote:


So i'm guessing that the attribute has been changed from func_code to
f_code but the inspect module wasn't updated to reflect that.



er i mean from f_code to func_code



f_locals doesn't even seem to exist at all.


[...]

I think there are 2 different things :
f_code : 'the code object being executed in this frame'
func_code : 'The code object representing the compiled function'

That is, one is valid in the context of execution stack frames,
while the other is valid in the context of compiled byte code objects 
that are generated for functions and so on.


inspect.getargvalues is used on frames, not on regular code objects.
Maybe you were looking for inspect.getargspec?

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


Re: I think I found a bug in Python 2.6.4 (in the inspect module)

2009-12-29 Thread Daniel Fetchinson
On 12/29/09, inhahe  wrote:
> Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)]
> on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
 import inspect
 def a(b=1): pass
> ...
 inspect.getargvalues(a)
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "C:\Python26\lib\inspect.py", line 816, in getargvalues
> args, varargs, varkw = getargs(frame.f_code)
> AttributeError: 'function' object has no attribute 'f_code'
 dir(a)
> ['__call__', '__class__', '__closure__', '__code__', '__defaults__',
> '__delattr_
> _', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__',
> '__globa
> ls__', '__hash__', '__init__', '__module__', '__name__', '__new__',
> '__reduce__'
> , '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__',
> '__subcla
> sshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict',
> 'func_doc'
> , 'func_globals', 'func_name']

>
> So i'm guessing that the attribute has been changed from func_code to
> f_code but the inspect module wasn't updated to reflect that.



Please read the documentation for inspect.getargvalues:

"""
inspect.getargvalues(frame)

Get information about arguments passed into a particular frame. A
tuple of four things is returned: (args, varargs, varkw, locals). args
is a list of the argument names (it may contain nested lists). varargs
and varkw are the names of the * and ** arguments or None. locals is
the locals dictionary of the given frame.

Changed in version 2.6: Returns a named tuple ArgInfo(args,
varargs, keywords, locals).
"""

HTH,
Daniel


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


Re: detect interactivity

2009-12-29 Thread Roald de Vries

On Dec 29, 2009, at 8:34 PM, Dave Angel wrote:

Antoine Pitrou wrote:

Le Tue, 29 Dec 2009 16:09:58 +0100, Roald de Vries a écrit :



Dear all,

Is it possible for a Python script to detect whether it is running
interactively? It can be useful for e.g. defining functions that are
only useful in interactive mode.



Try the isatty() method (*) on e.g. stdin:

$ python -c "import sys; print sys.stdin.isatty()"
True
$ echo "" | python -c "import sys; print sys.stdin.isatty()"
False

Your test determines whether input is redirected.  But I think the  
OP was asking how to detect whether the script was being run from an  
interpreter prompt.


That was my question indeed. Is it possible?



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


Re: Another Sets Problem

2009-12-29 Thread Emile van Sebille

On 12/29/2009 12:52 PM Victor Subervi said...

On Tue, Dec 29, 2009 at 4:30 PM, Carsten Haese mailto:carsten.ha...@gmail.com>> wrote:
You need to rethink your priorities. Understanding your code is a
prerequisite, not a luxury. You keep saying that you'll get around to
understanding your code when it's done. My point is that your code will
never be done if you don't take the time to understand it.


I'm trying to understand it, for crying out loud!


You're kidding, right?  When you can identify that your output is wrong, 
correctly identify the three line for loop in your program where the 
error must be occurring, and still not identify the error?


And then, no mea culpa?

Emile

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


Re: Thanks for the help not given :)

2009-12-29 Thread Stefan Behnel

Phlip, 29.12.2009 23:58:
And I hope you answered your questions here, if no one else did, to 
avoid dead search trails in the archives.


You should have read the posting.

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


Re: Thanks for the help not given :)

2009-12-29 Thread Phlip
To the OP - adding "... because Python sucks" to your subject lines will 
increase the quantity of answers - but possibly not the quality.


You can also learn a little about good questions by answering others's here.

And I hope you answered your questions here, if no one else did, to avoid dead 
search trails in the archives. You learn by teaching!


As for me, my questions are usually some combination of hopelessly retarded and 
beyond the blue sky envelope that I take pity on anyone even reading them, less 
answering them...


Jon Clements wrote:


You have a bear that likes a Python? The one I have just keeps going
on about Piglet and eating my honey reserves...


http://zeekland.zeroplayer.com/Pigleg_Too/1
--
http://mail.python.org/mailman/listinfo/python-list


Re: Another Sets Problem

2009-12-29 Thread Stefan Behnel

Victor Subervi wrote:

I'm using python 2.4.3 which apparently requires that I import Set:
from sets import Set


... unless you use "set" instead of "Set".

I've done this. In another script I successfully manipulated MySQL 
sets by so doing. Here's the code snippet from the script where I was 
able to call the elements in a for loop:


  if isinstance(colValue[0], (str, int, float, long, complex, 
unicode, list, buffer, xrange, tuple)):


This line leaves me baffled. I guess a positive list would be less ugly 
here, and some more generic code that handles data values regardless of 
their exact type would be even better.



  html = "%s: " % (col, col)


Note that there are tons of helpful libraries out there for generating HTML 
with Python. While string concatenation works in general, it also makes it 
very hard to get the output right, and to keep the output correct when you 
change minor stuff in your code.


Given that you seem to pull data from a database into a web page, you might 
want to take a look at Django, for example.


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


Re: Which version of MSVC?90.DLL's to distribute with Python 2.6 based Py2exe executables?

2009-12-29 Thread David Bolen
Jonathan Hartley  writes:

> I guess I really need an installer. Oh well.

This need not be that much of a hurdle.  Several solutions exist such
as Inno Setup (my personal preference), NSIS, etc... which are not
hard to create a solid installer with.  I suspect your end users will
appreciate it too since your application (even if trivial) will
install/uninstall just like other standard applications.  Combining
py2exe with such an installer is a solid combination for deployment
under Windows.

It could also help you over time since you'll have better control if
needed over how future versions handle updates, can control menus,
shortcuts, etc..  Even if a start menu shortcut just opens up a
console window with your text based application, it's probably easier
for users then telling them to open such a window manually, switch to
the right directory, and start your script.

You can arrange to have the redist installer run from within your
installation script, so it's a one-time hit rather than each time your
application starts.

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


Re: I think I found a bug in Python 2.6.4 (in the inspect module)

2009-12-29 Thread inhahe
On Tue, Dec 29, 2009 at 5:11 PM, inhahe  wrote:
> On Tue, Dec 29, 2009 at 5:10 PM, inhahe  wrote:
>>
>> So i'm guessing that the attribute has been changed from func_code to
>> f_code but the inspect module wasn't updated to reflect that.
>>
>
> er i mean from f_code to func_code
>

f_locals doesn't even seem to exist at all.

Traceback (most recent call last):
  File "E:\jsterm\specs\test.py", line 6, in 
print inspect.getargvalues(a)
  File "E:\Python26\lib\inspect.py", line 817, in getargvalues
return ArgInfo(args, varargs, varkw, frame.f_locals)
AttributeError: 'function' object has no attribute 'f_locals
>>> dir(a)
['__call__', '__class__', '__closure__', '__code__', '__defaults__',
'__delattr__', '__dict__', '__doc__', '__format__', '__get__',
'__getattribute__', '__globals__', '__
hash__', '__init__', '__module__', '__name__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'func_clo
sure', 'func_code', 'func_defaults', 'func_dict', 'func_doc',
'func_globals', 'func_name']
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I think I found a bug in Python 2.6.4 (in the inspect module)

2009-12-29 Thread inhahe
On Tue, Dec 29, 2009 at 5:10 PM, inhahe  wrote:
>
> So i'm guessing that the attribute has been changed from func_code to
> f_code but the inspect module wasn't updated to reflect that.
>

er i mean from f_code to func_code
-- 
http://mail.python.org/mailman/listinfo/python-list


I think I found a bug in Python 2.6.4 (in the inspect module)

2009-12-29 Thread inhahe
Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import inspect
>>> def a(b=1): pass
...
>>> inspect.getargvalues(a)
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python26\lib\inspect.py", line 816, in getargvalues
args, varargs, varkw = getargs(frame.f_code)
AttributeError: 'function' object has no attribute 'f_code'
>>> dir(a)
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr_
_', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globa
ls__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__'
, '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subcla
sshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc'
, 'func_globals', 'func_name']
>>>

So i'm guessing that the attribute has been changed from func_code to
f_code but the inspect module wasn't updated to reflect that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Thanks for the help not given :)

2009-12-29 Thread Jon Clements
On Dec 29, 9:28 pm, a...@pythoncraft.com (Aahz) wrote:
> In article ,
>
> J   wrote:
>
> >So though I've only posted a small bit here and on python-win, I did
> >want to thank y'all for helping me when you have, and even when you
> >actually haven't!
>
> Get a teddybear, that helps, too.  ;-)  (I.e. try to explain your
> problem to a teddybear.)
> --
> Aahz (a...@pythoncraft.com)           <*>        http://www.pythoncraft.com/

You have a bear that likes a Python? The one I have just keeps going
on about Piglet and eating my honey reserves...

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


Re: Moving from PHP to Python. Is it Possible

2009-12-29 Thread Robert Kern

On 2009-12-29 15:26 PM, Aahz wrote:

In article<4b2602a0$0$30660$426a3...@news.free.fr>,
Bruno Desthuilliers  wrote:

zeph a �crit :


4) It's better to collect all your eventual output into a string that
you print


Yuck ! Definitly one of the worst advises you could give.


By all mean, *DONT* do that. Use a templating system instead.



Because I know Zeph, I know that you two aren't actually disagreeing.  ;-)
Templates are one good way to follow Zeph's advice, but particularly for
small projects they may be overkill.


I find that Ian Bicking's Tempita is small enough (in terms of code and language 
design) to not be overkill for even small tasks.


  http://pythonpaste.org/tempita/

--
Robert Kern

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

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


Re: Thanks for the help not given :)

2009-12-29 Thread Aahz
In article ,
J   wrote:
>
>So though I've only posted a small bit here and on python-win, I did
>want to thank y'all for helping me when you have, and even when you
>actually haven't!

Get a teddybear, that helps, too.  ;-)  (I.e. try to explain your
problem to a teddybear.)
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Moving from PHP to Python. Is it Possible

2009-12-29 Thread Aahz
In article <4b2602a0$0$30660$426a3...@news.free.fr>,
Bruno Desthuilliers   wrote:
>zeph a écrit :
>>
>> 4) It's better to collect all your eventual output into a string that
>> you print
>
>Yuck ! Definitly one of the worst advises you could give.
>
>
>By all mean, *DONT* do that. Use a templating system instead.
>

Because I know Zeph, I know that you two aren't actually disagreeing.  ;-)
Templates are one good way to follow Zeph's advice, but particularly for
small projects they may be overkill.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.
-- 
http://mail.python.org/mailman/listinfo/python-list


Thanks for the help not given :)

2009-12-29 Thread J
I just wanted to take a break from writing some code to thank the list
for all the help you've NOT given me :-)

And I do mean that but I should explain...

At least three times today, I've been working on various bits of code,
and run into a problem that I just could not figure out.

And each time, I started writing a post, complete with code samples
and my thoughts... and in EVERY case, so far, I've found the answer on
my own ONLY after writing that post.  Thankfully, I've not actually
posted them, saving myself from looking like TOO much of an idiot
(especially since one case was a REALLY glaring example of a Logic
Error).

I could say that it's all because I'm learning and figuring things out
on my own, but because I don't want to post poorly formed help
requests on any list I belong to, actually writing out a post helps me
organize my thoughts, the problem, and what I've done so far, and
usually THAT is when the solution actually hits me. Even when I don't
send the post, just having a target that forces me to actually
organize and spell out what the problem is helps immensely.

So though I've only posted a small bit here and on python-win, I did
want to thank y'all for helping me when you have, and even when you
actually haven't!

Cheers
Jeff


-- 

Ted Turner  - "Sports is like a war without the killing." -
http://www.brainyquote.com/quotes/authors/t/ted_turner.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python OOP Problem

2009-12-29 Thread Lie Ryan

On 12/29/2009 3:01 PM, Миклухо wrote:

On 28 дек, 18:29, "Martin v. Loewis"  wrote:

In this case (you just started to learn Python), I recommend to take
an explicit approach. Create a dictionary that maps class names to
classes:

name2class = { "MyObject" : MyObject,
"MyOtherObject" : MyOtherObject,
"Etc" : Etc }

Then, when you receive the string class_name, you do

o = name2class[class_name]
o.myfunction()

HTH,
Martin


Thanks for reply, but it doesn't fit to my task. If I will add later
other objects(and it will be very often) - I should stop the service,
but that would be very bad.


you don't need to stop any service; just add into the dictionary:
name2class['NewObject'] = NewObject


I'm not sure, if this is solution, but test passed:

myimportmod = __import__('ClassName', globals(), locals(),
['ClassName'], -1)
mod = getattr(_myimportmod, 'ClassName')
o = mod();
o.myfunction();


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


Re: clean data [was: Simple distributed example for learning purposes?]

2009-12-29 Thread Lie Ryan

On 12/29/2009 9:14 AM, Ethan Furman wrote:

Lie Ryan wrote:

On 12/28/2009 11:59 PM, Shawn Milochik wrote:

With address data:
one address may have suite data and the other might not
the same city may have multiple zip codes


why is that even a problem? You do put suite data and zipcode into
different database fields right?


The issue here is not proper database design, the issue is users -- not
one user, not two users, but millions of users, with no consistency
amongst them. They bring you their nice tiny list of 10,000 names and
addresses and want you to correct/normalize/mail them, and you have to
be able to break down what they gave you into something usable.

To rephrase, the issue that Shawn is referring to is the huge amount of
data *already out there*, not brand new data.

~Ethan~


The way Shawn describes the problem appears like he has problem with 
"searching the database". I said, given a good index searching should 
never be the problem. To make the "good index", you've got a slightly 
different but easier problem to tackle: parsing. I realize that parsing 
inconsistent data isn't as easy as talking about it; but it's generally 
much easier than trying to fuzzily grep through the raw data.

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


Re: Another Sets Problem

2009-12-29 Thread Victor Subervi
On Tue, Dec 29, 2009 at 4:30 PM, Carsten Haese wrote:

> Victor Subervi wrote:
> > On Tue, Dec 29, 2009 at 3:58 PM, Carsten Haese  > > wrote:
> >
> > Victor Subervi wrote:
> > > You know I did this before, substituting "f" for "field", and it
> > honestly wouldn't print but threw a 500 error. Now it works. I don't
> > understand.
> >
> > That's exactly why you keep running into strange problems. I strongly
> > urge you to learn to understand why your code does what it does. The
> > desire to find out how something works is, in my opinion, an
> essential
> > skill in a programmer, and your "maybe I'll figure it out later"
> > attitude displays a disturbing lack of this skill.
> >
> >
> > Wrong. Prioritization is also important. Don't be so foolish as to think
> > that I don't want to understand why my code does what it does!
>
> You need to rethink your priorities. Understanding your code is a
> prerequisite, not a luxury. You keep saying that you'll get around to
> understanding your code when it's done. My point is that your code will
> never be done if you don't take the time to understand it.
>

I'm trying to understand it, for crying out loud! I'm also trying to eat!
Have a nice day! Goodbye!
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cookies

2009-12-29 Thread Carsten Haese
Victor Subervi wrote:
> Hi;
> I have these lines:
> 
>   cookie = os.environ.get('HTTP_COOKIE')
>   if not cookie:
> cookie = Cookie.SimpleCookie()
> cExpires, cPath, cComment, cDomain, cMaxAge, cVersion = myCookie()
> cookie['lastvisit'] = str(time.time())
> cookie['lastvisit']['expires'] = cExpires
> cookie['lastvisit']['path'] = cPath
> cookie['lastvisit']['comment'] = cComment
> cookie['lastvisit']['domain'] = cDomain
> cookie['lastvisit']['max-age'] = cMaxAge
> cookie['lastvisit']['version'] = cVersion
> cookieFlag = 'new'
>   else:
> cookie = Cookie.SimpleCookie(cookie)
> cookieFlag = 'old'
>   print '''Content-Type: text/html\r\n
> 
> 
> '''
>   print cookieFlag
> 
> cookieFlag prints 'new'. Every time. Even when I refresh. I've imported
> Cookie. I've followed the tutorials :-} I've already been through my
> problem with trying to find the cookies on this computer. The fact that
> I'm using gmail is proof that cookies are enabled. I have also tried:
> cookie = os.environ.has_key('HTTP_COOKIE')
> Please advise.

You apparently haven't followed the tutorials carefully enough. You do
know that a cookie is a piece of information that's stored in your
browser, don't you? So tell me, which of the above lines of code do you
suppose is responsible for informing your browser of the cookie's contents?

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Another Sets Problem

2009-12-29 Thread Carsten Haese
Victor Subervi wrote:
> On Tue, Dec 29, 2009 at 3:58 PM, Carsten Haese  > wrote:
> 
> Victor Subervi wrote:
> > You know I did this before, substituting "f" for "field", and it
> honestly wouldn't print but threw a 500 error. Now it works. I don't
> understand.
> 
> That's exactly why you keep running into strange problems. I strongly
> urge you to learn to understand why your code does what it does. The
> desire to find out how something works is, in my opinion, an essential
> skill in a programmer, and your "maybe I'll figure it out later"
> attitude displays a disturbing lack of this skill.
> 
> 
> Wrong. Prioritization is also important. Don't be so foolish as to think
> that I don't want to understand why my code does what it does!

You need to rethink your priorities. Understanding your code is a
prerequisite, not a luxury. You keep saying that you'll get around to
understanding your code when it's done. My point is that your code will
never be done if you don't take the time to understand it.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Another Sets Problem

2009-12-29 Thread Victor Subervi
On Tue, Dec 29, 2009 at 3:58 PM, Carsten Haese wrote:

> Victor Subervi wrote:
> > You know I did this before, substituting "f" for "field", and it honestly
> wouldn't print but threw a 500 error. Now it works. I don't understand.
>
> That's exactly why you keep running into strange problems. I strongly
> urge you to learn to understand why your code does what it does. The
> desire to find out how something works is, in my opinion, an essential
> skill in a programmer, and your "maybe I'll figure it out later"
> attitude displays a disturbing lack of this skill.
>

Wrong. Prioritization is also important. Don't be so foolish as to think
that I don't want to understand why my code does what it does!
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting name of passed reference

2009-12-29 Thread Dave Angel



Joel Davis wrote:

On Dec 29, 11:21 am, Emile van Sebille  wrote:
  


In an extremely controlled situation you may avoid headaches when
deploying this kind of technique.  Regardless, we all want to make you
aware that this _will_ likely cause headaches, and, idle curiosity
aside, none of us can imagine the problem to which this is the
appropriate solution.

It's fun to work out, but you're probably better served if you describe
the problem you're solving and consider the alternatives suggested.

Dependence on introspection belongs in programming tools, not in
applications deployed across versions and platforms.

Emile



Emile, essentially, the situation is that I'm trying to create an API
for consumption scripting. As it stands now, in initial development
they can pass callback function. The idea was to enable them to pass
variables and have the handling function determine the type and just
drop the value into it instead of calling function with the value as
an argument. The problem with that approach is determining exactly
which variable was passed. My idea was to use this to capture the name
and then modify the globals for the executing frame so that the passed
variable represents the new value.

  
I've never heard of "consumption scripting."  Can you describe it in 
simple terms?


I take it you're publishing a library of code that somebody can call to 
do things.  Can you characterize your users?  Are they programmers, are 
they Python programmers, are they scientists?


Presumably you're trying to define a language (not Python) that these 
users can program in, where you want to achieve call by reference.  I'm 
sure you have some good reason for that, but could we hear it?


When you need to do something like this for programmers, the approach 
might be for them to pass a collection object, and an identifier to 
specify what part of the collection for you to modify.  If the 
collection object is their module, then the identifier could be just the 
name of the identifier they want you to modify.  In this case, the code 
could be robust and readable.


Even better would be for them to pass you an object, and you can call 
methods on that object to modify it in place.  Just provide them a class 
to create such an instance, and they can have as many of them as they like.


DaveA

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


Re: Another Sets Problem

2009-12-29 Thread Carsten Haese
Victor Subervi wrote:
> You know I did this before, substituting "f" for "field", and it honestly 
> wouldn't print but threw a 500 error. Now it works. I don't understand.

That's exactly why you keep running into strange problems. I strongly
urge you to learn to understand why your code does what it does. The
desire to find out how something works is, in my opinion, an essential
skill in a programmer, and your "maybe I'll figure it out later"
attitude displays a disturbing lack of this skill.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: getting name of passed reference

2009-12-29 Thread Martin P. Hellwig

Joel Davis wrote:

I'm just curious if anyone knows of a way to get the variable name of
a reference passed to the function.

Put another way, in the example:

  def MyFunc ( varPassed ):
 print varPassed;

  MyFunc(nwVar)

how would I get the string "nwVar" from inside of "MyFunc"? is it
possible?


Would it be acceptable to require keyword arguments when calling the 
function?


>>> def test(**kwargs):
print(kwargs)

>>> test(x=1)
{'x': 1}
>>>


--
MPH
http://blog.dcuktec.com
'If consumed, best digested with added seasoning to own preference.'
--
http://mail.python.org/mailman/listinfo/python-list


Cookies

2009-12-29 Thread Victor Subervi
Hi;
I have these lines:

  cookie = os.environ.get('HTTP_COOKIE')
  if not cookie:
cookie = Cookie.SimpleCookie()
cExpires, cPath, cComment, cDomain, cMaxAge, cVersion = myCookie()
cookie['lastvisit'] = str(time.time())
cookie['lastvisit']['expires'] = cExpires
cookie['lastvisit']['path'] = cPath
cookie['lastvisit']['comment'] = cComment
cookie['lastvisit']['domain'] = cDomain
cookie['lastvisit']['max-age'] = cMaxAge
cookie['lastvisit']['version'] = cVersion
cookieFlag = 'new'
  else:
cookie = Cookie.SimpleCookie(cookie)
cookieFlag = 'old'
  print '''Content-Type: text/html\r\n


'''
  print cookieFlag

cookieFlag prints 'new'. Every time. Even when I refresh. I've imported
Cookie. I've followed the tutorials :-} I've already been through my problem
with trying to find the cookies on this computer. The fact that I'm using
gmail is proof that cookies are enabled. I have also tried:
cookie = os.environ.has_key('HTTP_COOKIE')
Please advise.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: detect interactivity

2009-12-29 Thread Dave Angel

Antoine Pitrou wrote:

Le Tue, 29 Dec 2009 16:09:58 +0100, Roald de Vries a écrit :

  

Dear all,

Is it possible for a Python script to detect whether it is running
interactively? It can be useful for e.g. defining functions that are
only useful in interactive mode.



Try the isatty() method (*) on e.g. stdin:

$ python -c "import sys; print sys.stdin.isatty()"
True
$ echo "" | python -c "import sys; print sys.stdin.isatty()"
False


(*) http://docs.python.org/library/stdtypes.html#file.isatty


  
Your test determines whether input is redirected.  But I think the OP 
was asking how to detect whether the script was being run from an 
interpreter prompt.



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


Re: Windows, IDLE, __doc_, other

2009-12-29 Thread W. eWatson

Lie Ryan wrote:

On 12/29/2009 5:10 AM, W. eWatson wrote:

Lie Ryan wrote:

If you're on Windows, don't use the "Edit with IDLE" right-click
hotkey since that starts IDLE without subprocess. Use the shortcut
installed in your Start menu.

When I go to Start and select IDLE, Saves or Opens want to go into
C:/Python25. I have to motor over to my folder where I keep the source
code. The code is in a folder about 4 levels below the top. That's a bit
awkward.

Is there a way to go directly to the folder I normally work in?
--
http://mail.python.org/mailman/listinfo/python-list


Re: getting name of passed reference

2009-12-29 Thread MRAB

Joel Davis wrote:

On Dec 29, 11:21 am, Emile van Sebille  wrote:

On 12/29/2009 7:02 AM Joel Davis said...


On Dec 29, 2:29 am, "Gabriel Genellina"
wrote:

I'm sure other limitations apply too -- don't rely on this technique for
anything critical.
--
Gabriel Genellina

Gabriel,
thanks for your input, I had no idea that did that and it could have
been deployed without even being aware of it, caused consternation and
headaches galore.

In an extremely controlled situation you may avoid headaches when
deploying this kind of technique.  Regardless, we all want to make you
aware that this _will_ likely cause headaches, and, idle curiosity
aside, none of us can imagine the problem to which this is the
appropriate solution.

It's fun to work out, but you're probably better served if you describe
the problem you're solving and consider the alternatives suggested.

Dependence on introspection belongs in programming tools, not in
applications deployed across versions and platforms.

Emile


Emile, essentially, the situation is that I'm trying to create an API
for consumption scripting. As it stands now, in initial development
they can pass callback function. The idea was to enable them to pass
variables and have the handling function determine the type and just
drop the value into it instead of calling function with the value as
an argument. The problem with that approach is determining exactly
which variable was passed. My idea was to use this to capture the name
and then modify the globals for the executing frame so that the passed
variable represents the new value.


All I can say is: Yuck! Don't do that! :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: adding python engine into c++ application

2009-12-29 Thread griwes
Great thanks ;) I will try to combine cython and embedding python
interpreter soon.
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: Pymazon 0.1beta released.

2009-12-29 Thread Chris Colbert
I'm happy to announce the first beta release of Pymazon: a Python
implemented alternative to the Amazon mp3 downloader.

Pymazon was created specifically to alleviate the issues surrounding the
Linux version of the Amazon mp3 downloader (though it should run just fine
in Windows too).

Pymazon can be used from the command line, or a gui interface if PyQt4 is
installed.

You can get Pymazon from the cheeseshop using pip (easy_install is not
supported as it breaks the bin script):

$ pip install pymazon

You can read more about Pymazon (screenshots, installation, usage, source
code) at http://code.google.com/p/pymazon/

Cheers!

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


Re: Which version of MSVC?90.DLL's to distribute with Python 2.6 based Py2exe executables?

2009-12-29 Thread Jonathan Hartley

On 29/12/2009 18:31, pyt...@bdurham.com wrote:

Jonathan,


I'm going to try to run vcredist_x86.exe automatically (as opposed to
asking my users to download and run it manually). I don't currently
have any installer, so I'm going to run vcredist_x86.exe on my
application start-up. Some logic like this seems to do this trick:

 if platform.system() == 'Windows':
 command = [path.join('lib', 'vcredist_x86.exe'), '/q']
 retcode = subprocess.call(command)
 if retcode != 0:
 sys.stderr.write(
 'Return value %d from vcredist_x86.exe\n' %
(retcode,))

This seems to work. My py2exe program will now run out of the box on a
bare-bones Windows XP install. (note: running 'vcredist_x86.exe /qu'
will uninstall the DLLs again)


I'm surprised that this technique works because the Python interpreter
itself needs to find the MSVC*90.DLL files before it can startup and run
your program that installs the MSVC*90.DLL files. Sort of a chicken and
egg scenario.

Malcolm

   


Yeah, I was still clearly a little fuzzy-headed from Christmas when I 
even thought to try that. It only appeared to work, I was trying it on 
another machine (not my bare-bones VM) and evidently the required 
msvcr90.dll was already installed elsewhere on that machine.


I'm just going to give in and stick the manifest and dll directly in 
with my application as described by others earlier, from the cheapest 
copy of Visual Studio I can lay my hands on.


Thanks to everyone for their help on this, it's been plaguing me for ages.

Jonathan Hartley  Made of meat.  http://tartley.com
tart...@tartley.com   +44 7737 062 225   twitter/skype: tartley



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


Re: Which version of MSVC?90.DLL's to distribute with Python 2.6 based Py2exe executables?

2009-12-29 Thread python
Jonathan,


I'm going to try to run vcredist_x86.exe automatically (as opposed to
asking my users to download and run it manually). I don't currently
have any installer, so I'm going to run vcredist_x86.exe on my
application start-up. Some logic like this seems to do this trick:

if platform.system() == 'Windows':
command = [path.join('lib', 'vcredist_x86.exe'), '/q']
retcode = subprocess.call(command)
if retcode != 0:
sys.stderr.write(
'Return value %d from vcredist_x86.exe\n' %
(retcode,))

This seems to work. My py2exe program will now run out of the box on a
bare-bones Windows XP install. (note: running 'vcredist_x86.exe /qu'
will uninstall the DLLs again)


I'm surprised that this technique works because the Python interpreter
itself needs to find the MSVC*90.DLL files before it can startup and run
your program that installs the MSVC*90.DLL files. Sort of a chicken and
egg scenario.

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


Re: getting name of passed reference

2009-12-29 Thread Joel Davis
On Dec 29, 11:21 am, Emile van Sebille  wrote:
> On 12/29/2009 7:02 AM Joel Davis said...
>
> > On Dec 29, 2:29 am, "Gabriel Genellina"
> > wrote:
> >> I'm sure other limitations apply too -- don't rely on this technique for
> >> anything critical.
>
> >> --
> >> Gabriel Genellina
>
> > Gabriel,
>
> > thanks for your input, I had no idea that did that and it could have
> > been deployed without even being aware of it, caused consternation and
> > headaches galore.
>
> In an extremely controlled situation you may avoid headaches when
> deploying this kind of technique.  Regardless, we all want to make you
> aware that this _will_ likely cause headaches, and, idle curiosity
> aside, none of us can imagine the problem to which this is the
> appropriate solution.
>
> It's fun to work out, but you're probably better served if you describe
> the problem you're solving and consider the alternatives suggested.
>
> Dependence on introspection belongs in programming tools, not in
> applications deployed across versions and platforms.
>
> Emile

Emile, essentially, the situation is that I'm trying to create an API
for consumption scripting. As it stands now, in initial development
they can pass callback function. The idea was to enable them to pass
variables and have the handling function determine the type and just
drop the value into it instead of calling function with the value as
an argument. The problem with that approach is determining exactly
which variable was passed. My idea was to use this to capture the name
and then modify the globals for the executing frame so that the passed
variable represents the new value.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to iterate the input over a particular size?

2009-12-29 Thread John Posner

On Tue, 29 Dec 2009 01:35:41 -0500, Steven D'Aprano
 wrote:


On Tue, 29 Dec 2009 00:49:50 -0500, John Posner wrote:


On Sun, 27 Dec 2009 09:44:17 -0500, joy99 
wrote:


Dear Group,

I am encountering a small question.

Suppose, I write the following code,

input_string=raw_input("PRINT A STRING:")
string_to_word=input_string.split()
len_word_list=len(string_to_word)
if len_word_list>9:
 rest_words=string_to_word[9:]
 len_rest_word=len(rest_words)
 if len_rest_word>9:
  remaining_words=rest_words[9:]



Here's an issue that has not, I think, been addressed in this thread.
The OP's problem is:

1. Start with an indefinitely long string.

2. Convert the string to a list, splitting on whitespace.

3. Repeatedly return subslices of the list, until the list is exhausted.

This thread has presented one-chunk-at-a-time (e.g. generator/itertools)
approaches to Step #3, but what about Step #2? I've looked in the Python
documentation, and I've done some Googling, but I haven't found a
generator version of the string function split(). Am I missing
something?


"Indefinitely long" doesn't mean you can't use split.

But if you want a lazy splitter, here's a version which should do what
you want:


def lazy_split(text):
accumulator = []
for c in text:
if c in string.whitespace:
if accumulator:
yield ''.join(accumulator)
accumulator = []
else:
accumulator.append(c)
if accumulator:
yield ''.join(accumulator)



Thanks -- I coded a similar generator, too. Yours handles the corner cases
and end-of-string more elegantly, so I won't share mine. :-)



Other alternatives are to use a regex to find runs of whitespace
characters, then yield everything else; or to use the itertools.groupby
function.


Yup, that approach occurred to me as I was falling asleep last night (OMG,
get a life, buddy!):

def groupby_split(text):
whitespace_grouper = itertools.groupby(
text,
lambda(c): c not in string.whitespace)
for boolval, group_iter in itertools.ifilter(
  lambda pair: pair[0] == True,
  whitespace_grouper):
yield "".join(group_iter)

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


Re: How to iterate the input over a particular size?

2009-12-29 Thread John Posner

On Tue, 29 Dec 2009 01:35:41 -0500, Steven D'Aprano
 wrote:


On Tue, 29 Dec 2009 00:49:50 -0500, John Posner wrote:


On Sun, 27 Dec 2009 09:44:17 -0500, joy99 
wrote:


Dear Group,

I am encountering a small question.

Suppose, I write the following code,

input_string=raw_input("PRINT A STRING:")
string_to_word=input_string.split()
len_word_list=len(string_to_word)
if len_word_list>9:
 rest_words=string_to_word[9:]
 len_rest_word=len(rest_words)
 if len_rest_word>9:
  remaining_words=rest_words[9:]



Here's an issue that has not, I think, been addressed in this thread.
The OP's problem is:

1. Start with an indefinitely long string.

2. Convert the string to a list, splitting on whitespace.

3. Repeatedly return subslices of the list, until the list is exhausted.

This thread has presented one-chunk-at-a-time (e.g. generator/itertools)
approaches to Step #3, but what about Step #2? I've looked in the Python
documentation, and I've done some Googling, but I haven't found a
generator version of the string function split(). Am I missing
something?


"Indefinitely long" doesn't mean you can't use split.

But if you want a lazy splitter, here's a version which should do what
you want:


def lazy_split(text):
accumulator = []
for c in text:
if c in string.whitespace:
if accumulator:
yield ''.join(accumulator)
accumulator = []
else:
accumulator.append(c)
if accumulator:
yield ''.join(accumulator)



Thanks -- I coded a similar generator, too. Yours handles the corner cases
and end-of-string more elegantly, so I won't share mine. :-)



Other alternatives are to use a regex to find runs of whitespace
characters, then yield everything else; or to use the itertools.groupby
function.


Yup, that approach occurred to me as I was falling asleep last night (OMG,
get a life, buddy!):

def groupby_split(text):
  whitespace_grouper = itertools.groupby(
  text,
  lambda(c): c not in string.whitespace)
  for boolval, group_iter in itertools.ifilter(
lambda pair: pair[0] == True,
whitespace_grouper):
  yield "".join(group_iter)

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


Re: How to iterate the input over a particular size?

2009-12-29 Thread John Posner
On Tue, 29 Dec 2009 01:35:41 -0500, Steven D'Aprano  
 wrote:



On Tue, 29 Dec 2009 00:49:50 -0500, John Posner wrote:


On Sun, 27 Dec 2009 09:44:17 -0500, joy99 
wrote:


Dear Group,

I am encountering a small question.

Suppose, I write the following code,

input_string=raw_input("PRINT A STRING:")
string_to_word=input_string.split()
len_word_list=len(string_to_word)
if len_word_list>9:
 rest_words=string_to_word[9:]
 len_rest_word=len(rest_words)
 if len_rest_word>9:
  remaining_words=rest_words[9:]



Here's an issue that has not, I think, been addressed in this thread.
The OP's problem is:

1. Start with an indefinitely long string.

2. Convert the string to a list, splitting on whitespace.

3. Repeatedly return subslices of the list, until the list is exhausted.

This thread has presented one-chunk-at-a-time (e.g. generator/itertools)
approaches to Step #3, but what about Step #2? I've looked in the Python
documentation, and I've done some Googling, but I haven't found a
generator version of the string function split(). Am I missing
something?


"Indefinitely long" doesn't mean you can't use split.

But if you want a lazy splitter, here's a version which should do what
you want:


def lazy_split(text):
accumulator = []
for c in text:
if c in string.whitespace:
if accumulator:
yield ''.join(accumulator)
accumulator = []
else:
accumulator.append(c)
if accumulator:
yield ''.join(accumulator)



Thanks -- I coded a similar generator, too. Yours handles the corner cases  
and end-of-string more elegantly, so I won't share mine. :-)




Other alternatives are to use a regex to find runs of whitespace
characters, then yield everything else; or to use the itertools.groupby
function.


Yup, that approach occurred to me as I was falling asleep last night (OMG,  
get a life, buddy!):


def groupby_split(text):
whitespace_grouper = itertools.groupby(
text,
lambda(c): c not in string.whitespace)
for boolval, group_iter in itertools.ifilter(
  lambda pair: pair[0] == True,
  whitespace_grouper):
yield "".join(group_iter)

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


Re: Another Sets Problem

2009-12-29 Thread Victor Subervi
On Tue, Dec 29, 2009 at 1:14 PM, Carsten Haese wrote:

> Victor Subervi wrote:
> > On Tue, Dec 29, 2009 at 12:54 PM, Carsten Haese  > > wrote:
> >
> > Victor Subervi wrote:
> > > Since it is difficult to send the inputs but easy to provide the
> > > outputs, and as opposed to posting the printout, let me direct you
> > here
> > > to see it first-hand:
> > > http://angrynates.com/cart/enterProducts2.py?store=products
> >
> > All right, I've gone to that URL. Now what? I see an HTML table, but
> I
> > can't tell how it differs from what you're expecting, because you
> didn't
> > describe what you're expecting.
> >
> >
> > Sorry. The last two fields have "Set({whatever])" when all I want is the
> > "whatever" :)
>
> All right. I'm assuming that the following snippet of code is
> responsible for that behavior:
>
>  elif types[x][0:3] == 'set':
>for f in field:
>  print '%s\n' % (field)
>
> (It's on lines 134-136 of your script if I copied and pasted it from
> your previous email correctly.)
>
> In that branch of code, <> is the name of a Set object. You're
> iterating over all the elements in that set, giving the name <> to
> the individual elements, but then you don't do anything with <>.
> Instead, you're printing <>! Printing <> instead would seem to
> be a step in the right direction, but I'll readily admit that I didn't
> study your code hard enough to determine whether that's the complete
> solution.
>

You know I did this before, substituting "f" for "field", and it honestly
wouldn't print but threw a 500 error. Now it works. I don't understand. But
thank :-}
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting name of passed reference

2009-12-29 Thread Stephen Hansen
On Tue, Dec 29, 2009 at 8:17 AM, Joel Davis wrote:

> did set the tone and I think I've been more than a little tolerant on
> this. Someone posts a question, responds back with a "n/m I found the
> solution, here it is" and his response is essentially to berate them,
> telling them how crappy their code is and that they should at least
> _try_ the code. Bear in mind that I even told him the reason he wasn't
> able to run it is because he's pasting it into the interactive
> terminal. He then responded back AGAIN with the same insults and the
> same issue that shows he didn't really even read my last response.
>
>
Please reconsider your attitude to this issue; there is no acceptable
defense to your response-- it is flagrantly rude and disrespectful to
someone trying to help you. Perhaps you don't appreciate their perceived
tone when you repeatedly don't listen to people telling you that this just
isn't a place to go, but even if that tone was there, its not even kind of
OK to respond the way you did. You don't really get points for not being an
ass sooner: that's not tolerance.

To your issue, while I don't believe traceback.extract_stack will be going
away anytime soon, the use of it for your purpose is something you can't
rely on. It works, kind of, because exceptions keep a stack of frames which
are examinable -- for the purpose of printing tracebacks.

It might work, kind of. In a strictly controlled set of circumstances (which
Gabriel articulated) that 'kind of' might be good enough for you. If you're
a closed-source or purely internal application in which you have complete
control of the scenarios of use, that might be fine. If you intend for
anyone else to ever use it or to let this code out of strict control though,
then it's an unmitigated mistake to take this approach.

You're working directly *against* the language, its entire design and
function. You can kind of achieve your result: but its a hack. Some hacks
are necessarily evils sometimes, certainly. But they are always fragile.

Instead of insulting Steven D'Aprano, perhaps it would be better to answer
his question. What are you REALLY trying to solve? What are you REALLY
needing to do? Why do you so need to do this?

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


PyCon Early Bird is Ending Soon!

2009-12-29 Thread VanL
Do you have a year-end hole in your training budget? Or will the
improved economy let you finally attend a work conference? Come to sunny
and warm Atlanta in February for PyCon 2010. Early bird registration
ends on January 6.

Register: https://us.pycon.org/2010/register/

See the talks: http://us.pycon.org/2010/conference/talks/
Get trained at a tutorial:  http://us.pycon.org/2010/tutorials/

Also see the five (or more!) talks that people can't miss at PyCon:

PyOraGeek: PyCon pre-favorites


Pyright: PyCon pre-favorites, the Carl T. edition:


Aftermarket Pipes: Five Pycon 2010 Talks I Need to See:


Jessenoller.com: PyCon 2010: Talks I want to see:


The Third Bit: Five PyCon Talks I Want To See:


See you at PyCon!

Register: https://us.pycon.org/2010/register/

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


Re: Another Sets Problem

2009-12-29 Thread Carsten Haese
Victor Subervi wrote:
> On Tue, Dec 29, 2009 at 12:54 PM, Carsten Haese  > wrote:
> 
> Victor Subervi wrote:
> > Since it is difficult to send the inputs but easy to provide the
> > outputs, and as opposed to posting the printout, let me direct you
> here
> > to see it first-hand:
> > http://angrynates.com/cart/enterProducts2.py?store=products
> 
> All right, I've gone to that URL. Now what? I see an HTML table, but I
> can't tell how it differs from what you're expecting, because you didn't
> describe what you're expecting.
> 
> 
> Sorry. The last two fields have "Set({whatever])" when all I want is the
> "whatever" :)

All right. I'm assuming that the following snippet of code is
responsible for that behavior:

  elif types[x][0:3] == 'set':
for f in field:
  print '%s\n' % (field)

(It's on lines 134-136 of your script if I copied and pasted it from
your previous email correctly.)

In that branch of code, <> is the name of a Set object. You're
iterating over all the elements in that set, giving the name <> to
the individual elements, but then you don't do anything with <>.
Instead, you're printing <>! Printing <> instead would seem to
be a step in the right direction, but I'll readily admit that I didn't
study your code hard enough to determine whether that's the complete
solution.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Another Sets Problem

2009-12-29 Thread Victor Subervi
On Tue, Dec 29, 2009 at 12:54 PM, Carsten Haese wrote:

> Victor Subervi wrote:
> > Since it is difficult to send the inputs but easy to provide the
> > outputs, and as opposed to posting the printout, let me direct you here
> > to see it first-hand:
> > http://angrynates.com/cart/enterProducts2.py?store=products
>
> All right, I've gone to that URL. Now what? I see an HTML table, but I
> can't tell how it differs from what you're expecting, because you didn't
> describe what you're expecting.
>

Sorry. The last two fields have "Set({whatever])" when all I want is the
"whatever" :)
Thanks,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting name of passed reference

2009-12-29 Thread Steve Holden
Joel Davis wrote:
> On Dec 29, 10:08 am, Steve Holden  wrote:
>> Joel Davis wrote:
>>> On Dec 29, 2:04 am, Steven D'Aprano
>>>  wrote:
 On Mon, 28 Dec 2009 19:28:32 -0800, Joel Davis wrote:
> my thanks go out to Emile and Mr Hanson for their responses, I think
> I've found the solution, much shorter as well:
> > #!/usr/bin/python
> > import traceback
> > def testing ( varPassed ):
> > print traceback.extract_stack()[0][3]
> > testing("123")
> and it seems the traceback module in general seems to have a lot of
> history to it. This project is for CPython so compatibility with Jython,
> Iron Python, et al isn't really that important right now. So as far as
> functionality and compatibility I think I'm set as long as
> traceback.extract_stack is 3.0 safe.
 I'm afraid that one fails again. Do you actually test your solutions
 before telling us you've solved the problem?
>>> import traceback
>>> def testing ( varPassed ):
 ... print traceback.extract_stack()[0][3]
 ...
>>> testing("123")
 None
>>> x = "123"
>>> testing(x)
 None
 When a "solution" doesn't work under some circumstances (in this case,
 when run in the interactive interpreter) that's a warning that you need
 to understand when and where it will work before using it in production.
 Otherwise, how do you know that it will work under other circumstances?
 Or, find an alternative. What are you actually trying to do? "Get the
 name of a passed reference" is a means to an end. What are you expecting
 to do with it?
 --
 Steven
>>> Steven I don't know what your issue is, but it works for me. If your
>>> having trouble running the code, then that's your issue, and I would
>>> appreciate it if you would just shut up until you know what the hell
>>> you're talking about. I say that because if you paid the slightest
>>> attention my first solution that you found so woefully inept IS
>>> BASICALLY YOUR FIRST SOLUTION RECONFIGURED.
>>> You also apparently can't read.
>> Whereas you appear to have a problem maintaining good manners.
>>
>> regards
>>  Steve
>> --
>> Steve Holden   +1 571 484 6266   +1 800 494 3119
>> PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
>> Holden Web LLChttp://www.holdenweb.com/
>> UPCOMING EVENTS:http://holdenweb.eventbrite.com/
> 
> well not to engage in a he/she said, but in my own defense D'Aprano
> did set the tone and I think I've been more than a little tolerant on
> this. Someone posts a question, responds back with a "n/m I found the
> solution, here it is" and his response is essentially to berate them,
> telling them how crappy their code is and that they should at least
> _try_ the code. Bear in mind that I even told him the reason he wasn't
> able to run it is because he's pasting it into the interactive
> terminal. He then responded back AGAIN with the same insults and the
> same issue that shows he didn't really even read my last response.
> 
> If anything, I should be faulted for actually engaging him and not
> just letting it go.

Yes, that would have been better.

I would be interested to know which response of Steven's you thought
insulting. In reviewing the correspondence the only "insults" I see from
him appear to be (correct) assertions that your code doesn't work under
certain circumstances. Your refutation that "that's probably because it
can't be ran in the interactive terminal" ignores his attempt to help
you avoid real problems, and bypasses his attempt to find out why you
felt it was necessary to obtain the names of things which sometimes
don't have names.

While I have no problem with you ignoring good advice I would prefer it
if you didn't tell knowledgeable and helpful Python programmers to "just
shut up until you know what the hell you are talking about" when they
have already provided long-term evidence by their helpfulness on c.l.py
that they do indeed know what they are talking about. That doesn't
advance any dialog, and isn't normally allowed in the kindergarten
playground, let alone in what purports to be a technical dialog between
responsible adults.

So in future, unless you are *really* sure you are being personally
insulted for no good reason, it would be a much more adult response to
maintain a dignified silence.

Or do you regard this message as insulting also?

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

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


Re: Another Sets Problem

2009-12-29 Thread Carsten Haese
Victor Subervi wrote:
> Since it is difficult to send the inputs but easy to provide the
> outputs, and as opposed to posting the printout, let me direct you here
> to see it first-hand:
> http://angrynates.com/cart/enterProducts2.py?store=products

All right, I've gone to that URL. Now what? I see an HTML table, but I
can't tell how it differs from what you're expecting, because you didn't
describe what you're expecting.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Another Sets Problem

2009-12-29 Thread Victor Subervi
On Tue, Dec 29, 2009 at 12:21 PM, MRAB  wrote:

> Victor Subervi wrote:
>
>  On Tue, Dec 29, 2009 at 6:29 AM, Jean-Michel Pichavant <
>> jeanmic...@sequans.com > wrote:
>>
>>Matt Nordhoff wrote:
>>
>>Victor Subervi wrote:
>>
>>On Mon, Dec 28, 2009 at 1:41 PM, MRAB
>>mailto:pyt...@mrabarnett.plus.com
>> >
>>>>> wrote:
>>
>>DON'T USE BARE EXCEPTS!
>>
>>(There are 2 in your code.)
>>
>>There are times when they are *necessary*.
>>
>>No, there aren't.
>>
>>Even if there were, this is not one of those situations.
>>
>>And to elaborate a little bit, someone said in this list (sorry,
>>don't remember who) that often people think that making their code
>>robust is one of the top priority, especially when you are providing
>>some services to clients. That could be true. The fact is that most
>>newcomers thinks bare try except will do the trick: "look, my server
>>never crashes". Yes it does not crash, but even worse, it handles
>>exception in an inapropriate way that leads the server to behave in
>>a reliable, yet unpredictable, manner. And that is definitely *not*
>>being robust.
>>
>> You all have made very good points about bare excepts. I promise you I
>> will work on this...AFTER I've finished the first working copy of this
>> shopping cart and gotten caught up on my work, and start to clean this
>> shopping cart up to make it truly professional. HOWEVER, there is NO bare
>> except influencing the problem which I am trying to fix. Can we PLEASE set
>> this issue aside and deal with the problem of this post??
>>
> [snip]
>
> Bare excepts hide bugs. It's very easy to catch exceptions properly.


I'll get there.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another Sets Problem

2009-12-29 Thread Victor Subervi
On Tue, Dec 29, 2009 at 12:15 PM, Carsten Haese wrote:

> Victor Subervi wrote:
> > Once again, it seems nobody is bothering to address this issue. Is it
> > beyond your reach as it is beyond mine? I feel compelled to restate the
> > problem once again as I did in my original post, and to once again post
> > the entire code. Hopefully someone will help me see my error.
>
> The reason why nobody is addressing your issue is that merely posting
> your code is not enough to find out what's going wrong. In order to
> diagnose the code, we need to know what inputs it's processing. You're
> not giving us any information about that. Alternatively, it would be
> helpful to see EXACTLY what output the code is producing. You're not
> giving us that either. You're merely giving us a vague description that
> the code doesn't print everything you're expecting.
>
> That leaves us with only your code, which is an impenetrable fortress of
> poorly named variables, import statements you think you need but don't,
> and lots of Python anti-idioms, all of which conspire to make it
> impossible for anybody who is not paid to do this work to put in the
> effort that's necessary to trace your logic and identify the bug.
>
> Please help us help you.
>

Gladly, Carsten, gladly. Thank you for pointing out the deficiencies. Since
it is difficult to send the inputs but easy to provide the outputs, and as
opposed to posting the printout, let me direct you here to see it
first-hand:
http://angrynates.com/cart/enterProducts2.py?store=products
With respect to my poor coding, I intend to use this project as an
opportunity to learn how to properly code. I'm almost done with getting this
shopping cart up and running. And while it looks bad to you, it has certain
genius that will enable me to use it for all my future clients, a difficult
task for a shopping cart since clients' needs are so different. So, please
help me get this working. Next, I need to catch up some other client work,
then I will return to this and start cleaning it up and hopefully learn how
to program better.
Thanks for your help.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which version of MSVC?90.DLL's to distribute with Python 2.6 based Py2exe executables?

2009-12-29 Thread Martin v. Loewis
>> However, this takes a few seconds to run. Is there a sensible way for
>> me to only run this if the required DLL is not already installed? How
>> should I be detecting that?

Look at windows\winsxs\

>> Also: Will this work on 64 bit machines? Or do I not need to worry
>> about that?

If you ship the 32-bit Python DLLs, and have a 32-bit installer, and
install the 32-bit redist, it will work fine on a 64-bit machine as
well.

If one of the components above is 64-bit, all of them will need to
be 64-bit.

> If the DLLs aren't installed, then my program can't be launched, and
> can't bootstrap itself by installing the required DLL's.
> 
> I guess I really need an installer. Oh well.

You can perhaps modify the py2exe launcher to install vc_redist if needed.

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


Re: Another Sets Problem

2009-12-29 Thread Steve Holden
Victor Subervi wrote:
> On Tue, Dec 29, 2009 at 10:16 AM, Steve Holden  > wrote:
> 
> Victor Subervi wrote:
> > On Tue, Dec 29, 2009 at 9:33 AM, Steve Holden  
> > >> wrote:
> >
> > That's a bit like being told you have to produce something
> green, and
> > then when you do, being told "no, not that green, a light
> green". So you
> > produce something a lighter gree and then being told "no, a
> slightly
> > redder green". And so on.
> >
> > In other words, you aren't giving us the whole picture here,
> and without
> > the whole picture you will only ever get bits of the answer.
> >
> >
> > Later on I give you "the whole picture"...which you summarily toss in
> > the garbage can. What am I supposed to do with that??
> >
> That isn't "the whole picture", that's "the Python soup I produced to
> query the SQL soup I produced because I thought it might answer my
> problem".
> 
> >
> >
> > > #  print 'XXX', types[x]
> > >   elif types[x][0:3] == 'set':
> > > for f in field:
> > >   print 'AAA%s\n' % (field)
> > > else:
> > >   print 'YYY'
> > >
> > > 1) If I uncomment the commented line, it throws this error:
> > >
> > What happens if you *don't* uncomment the commented line?
> >
> >
> > As I mentioned, it prints BOTH the AAA and the YYY lines! The AAA is
> > printed with something like this:
> > AAASet([purple:223344])
> >
> Try moving the "else" so it's associated with the "if ... elif" rather
> than the "for". It's currently indented one level too far.
> 
> 
> There is currently an else where you indicate, as one can see in the
> complete code I am once again supplying with this post. That prints out
> pretty much all the other fields and does so just fine.
> 
See, this is another indication of the problem. The code snippet quoted
above *clearly* has the "else" matching the "for" and not the "if" above
it. This is different from the code you quote below.

> Once again, it seems nobody is bothering to address this issue. Is it
> beyond your reach as it is beyond mine? I feel compelled to restate the
> problem once again as I did in my original post, and to once again post
> the entire code. Hopefully someone will help me see my error.
> 
> I'm using python 2.4.3 which apparently requires that I import Set:
> from sets import Set
> I've done this. In another script I successfully manipulated MySQL sets
> by so doing. Here's the code snippet from the script where I was able to
> call the elements in a for loop:
> 
>   if isinstance(colValue[0], (str, int, float, long, complex,
> unicode, list, buffer, xrange, tuple)):
> pass
>   else:
> try:
>   html = "%s: " % (col, col)
>   notSet = 0
>   for itm in colValue[0]:
> try:
>   color, number = itm.split(':')
>   html += "%s" % (itm, color)
> except:
>   html += "%s" % (itm, itm)
>  
> However, when I try that in my current script, the script fails. It
> throws no error, but rather just quits printing to the screen. Here's
> the code snippet:
> 
>   elif types[x][0:3] == 'set':
> for f in field:
>   print '%s\n' % (field)
>   else:
> print '%s\n' % (field)
> 
> Notice that I can slice to determine if it's a set (I've printed
> something after that call to be sure). But once I try to loop through
> the set it quits printing to screen. The entire code follows.
> 
You *say* you can "slice to determine if it's a set", but sets aren't
sliceable, just like they aren't indexable, because no position is
associated with an element of a set (they are like dicts in that respect):

>>> from sets import Set
>>> s = Set("abc")
>>> s
Set(['a', 'c', 'b'])
>>> s[1:2]
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unsubscriptable object
>>>

So whatever it is you think you are looping over, it certainly isn't a set.

It's difficult to help someone whose thinking is so imprecise.

You say your program "stops printing to the screen", but you aren't
printing to the screen in the first place - you are generating output
that a web server is sending across the network, and that output is
being interpreted by a web browser. This has certain implications, whihc
you appear determined to ignore.

> #! /usr/bin/python
> 
> import MySQLdb
> import cgi
> import sys,os
> sys.path.append(os.getcwd())
> from login import login
> from sets import Set
> 
> def enterProducts2():
>   print '''Content-type: text/html
> 
> 
> 

Re: Another Sets Problem

2009-12-29 Thread Emile van Sebille

On 12/29/2009 5:51 AM Victor Subervi said...

 > #  print 'XXX', types[x]
 >   elif types[x][0:3] == 'set':
 > for f in field:
 >   print 'AAA%s\n' % (field)
 > else:
 >   print 'YYY'
 >
 > 1) If I uncomment the commented line, it throws this error:
 >
What happens if you *don't* uncomment the commented line?


As I mentioned, it prints BOTH the AAA and the YYY lines! The AAA is
printed with something like this:
AAASet([purple:223344])


Yes -- that's what a for-else does.  See 
http://www.ibiblio.org/swaroopch/byteofpython/read/for-loop.html for 
example.


Emile

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


Re: Another Sets Problem

2009-12-29 Thread MRAB

Victor Subervi wrote:
On Tue, Dec 29, 2009 at 6:29 AM, Jean-Michel Pichavant 
mailto:jeanmic...@sequans.com>> wrote:


Matt Nordhoff wrote:

Victor Subervi wrote:

On Mon, Dec 28, 2009 at 1:41 PM, MRAB
mailto:pyt...@mrabarnett.plus.com>
>> wrote:

DON'T USE BARE EXCEPTS!

(There are 2 in your code.)

There are times when they are *necessary*.

No, there aren't.

Even if there were, this is not one of those situations.

And to elaborate a little bit, someone said in this list (sorry,
don't remember who) that often people think that making their code
robust is one of the top priority, especially when you are providing
some services to clients. That could be true. The fact is that most
newcomers thinks bare try except will do the trick: "look, my server
never crashes". Yes it does not crash, but even worse, it handles
exception in an inapropriate way that leads the server to behave in
a reliable, yet unpredictable, manner. And that is definitely *not*
being robust.

You all have made very good points about bare excepts. I promise you I 
will work on this...AFTER I've finished the first working copy of this 
shopping cart and gotten caught up on my work, and start to clean this 
shopping cart up to make it truly professional. HOWEVER, there is NO 
bare except influencing the problem which I am trying to fix. Can we 
PLEASE set this issue aside and deal with the problem of this post?? 

[snip]

Bare excepts hide bugs. It's very easy to catch exceptions properly.
--
http://mail.python.org/mailman/listinfo/python-list


Re: getting name of passed reference

2009-12-29 Thread Emile van Sebille

On 12/29/2009 7:02 AM Joel Davis said...

On Dec 29, 2:29 am, "Gabriel Genellina"
wrote:

I'm sure other limitations apply too -- don't rely on this technique for
anything critical.

--
Gabriel Genellina


Gabriel,

thanks for your input, I had no idea that did that and it could have
been deployed without even being aware of it, caused consternation and
headaches galore.


In an extremely controlled situation you may avoid headaches when 
deploying this kind of technique.  Regardless, we all want to make you 
aware that this _will_ likely cause headaches, and, idle curiosity 
aside, none of us can imagine the problem to which this is the 
appropriate solution.


It's fun to work out, but you're probably better served if you describe 
the problem you're solving and consider the alternatives suggested.


Dependence on introspection belongs in programming tools, not in 
applications deployed across versions and platforms.


Emile



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


Re: getting name of passed reference

2009-12-29 Thread Joel Davis
On Dec 29, 10:08 am, Steve Holden  wrote:
> Joel Davis wrote:
> > On Dec 29, 2:04 am, Steven D'Aprano
> >  wrote:
> >> On Mon, 28 Dec 2009 19:28:32 -0800, Joel Davis wrote:
> >>> my thanks go out to Emile and Mr Hanson for their responses, I think
> >>> I've found the solution, much shorter as well:
> >>>     > #!/usr/bin/python
> >>>     > import traceback
> >>>     > def testing ( varPassed ):
> >>>     >         print traceback.extract_stack()[0][3]
> >>>     > testing("123")
> >>> and it seems the traceback module in general seems to have a lot of
> >>> history to it. This project is for CPython so compatibility with Jython,
> >>> Iron Python, et al isn't really that important right now. So as far as
> >>> functionality and compatibility I think I'm set as long as
> >>> traceback.extract_stack is 3.0 safe.
> >> I'm afraid that one fails again. Do you actually test your solutions
> >> before telling us you've solved the problem?
>
> > import traceback
> > def testing ( varPassed ):
> >> ...     print traceback.extract_stack()[0][3]
> >> ...
>
> > testing("123")
> >> None
> > x = "123"
> > testing(x)
> >> None
>
> >> When a "solution" doesn't work under some circumstances (in this case,
> >> when run in the interactive interpreter) that's a warning that you need
> >> to understand when and where it will work before using it in production.
> >> Otherwise, how do you know that it will work under other circumstances?
>
> >> Or, find an alternative. What are you actually trying to do? "Get the
> >> name of a passed reference" is a means to an end. What are you expecting
> >> to do with it?
>
> >> --
> >> Steven
>
> > Steven I don't know what your issue is, but it works for me. If your
> > having trouble running the code, then that's your issue, and I would
> > appreciate it if you would just shut up until you know what the hell
> > you're talking about. I say that because if you paid the slightest
> > attention my first solution that you found so woefully inept IS
> > BASICALLY YOUR FIRST SOLUTION RECONFIGURED.
>
> > You also apparently can't read.
>
> Whereas you appear to have a problem maintaining good manners.
>
> regards
>  Steve
> --
> Steve Holden           +1 571 484 6266   +1 800 494 3119
> PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
> Holden Web LLC                http://www.holdenweb.com/
> UPCOMING EVENTS:        http://holdenweb.eventbrite.com/

well not to engage in a he/she said, but in my own defense D'Aprano
did set the tone and I think I've been more than a little tolerant on
this. Someone posts a question, responds back with a "n/m I found the
solution, here it is" and his response is essentially to berate them,
telling them how crappy their code is and that they should at least
_try_ the code. Bear in mind that I even told him the reason he wasn't
able to run it is because he's pasting it into the interactive
terminal. He then responded back AGAIN with the same insults and the
same issue that shows he didn't really even read my last response.

If anything, I should be faulted for actually engaging him and not
just letting it go.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another Sets Problem

2009-12-29 Thread Carsten Haese
Victor Subervi wrote:
> Once again, it seems nobody is bothering to address this issue. Is it
> beyond your reach as it is beyond mine? I feel compelled to restate the
> problem once again as I did in my original post, and to once again post
> the entire code. Hopefully someone will help me see my error.

The reason why nobody is addressing your issue is that merely posting
your code is not enough to find out what's going wrong. In order to
diagnose the code, we need to know what inputs it's processing. You're
not giving us any information about that. Alternatively, it would be
helpful to see EXACTLY what output the code is producing. You're not
giving us that either. You're merely giving us a vague description that
the code doesn't print everything you're expecting.

That leaves us with only your code, which is an impenetrable fortress of
poorly named variables, import statements you think you need but don't,
and lots of Python anti-idioms, all of which conspire to make it
impossible for anybody who is not paid to do this work to put in the
effort that's necessary to trace your logic and identify the bug.

Please help us help you.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Another Sets Problem

2009-12-29 Thread MRAB

Victor Subervi wrote:
On Mon, Dec 28, 2009 at 4:23 PM, Steve Holden > wrote:



[snip]


Boy, does it! It looks great...on paper. Here's some revised code to debug:

#  print 'XXX', types[x]
  elif types[x][0:3] == 'set':
for f in field:
  print 'AAA%s\n' % (field)
else:
  print 'YYY'
 
1) If I uncomment the commented line, it throws this error:


[Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58]   File 
"/var/www/html/angrynates.com/cart/enterProducts2.py 
", line 138, referer: 
http://angrynates.com/cart/enterProducts.py
[Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58] elif 
types[x][0:3] == 'set':, referer: 
http://angrynates.com/cart/enterProducts.py
[Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58]^, 
referer: http://angrynates.com/cart/enterProducts.py
[Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58] SyntaxError: 
invalid syntax, referer: http://angrynates.com/cart/enterProducts.py
[Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58] Premature end 
of script headers: enterProducts2.py, referer: 
http://angrynates.com/cart/enterProducts.py


Incorrect indentation (later versions of Python give a better error 
message).



2) AAA prints out before the following fields:
AAASet(['Extra-small'])
AAASet(['purple:50404D'])

3) YYY *also* prints out twice!!


[snip]
In a for...else... structure it will execute the 'else' part unless it
'break's out of the 'for' loop, which it doesn't here.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Another Sets Problem

2009-12-29 Thread Victor Subervi
On Tue, Dec 29, 2009 at 10:16 AM, Steve Holden  wrote:

> Victor Subervi wrote:
> > On Tue, Dec 29, 2009 at 9:33 AM, Steve Holden  > > wrote:
> >
> > That's a bit like being told you have to produce something green, and
> > then when you do, being told "no, not that green, a light green". So
> you
> > produce something a lighter gree and then being told "no, a slightly
> > redder green". And so on.
> >
> > In other words, you aren't giving us the whole picture here, and
> without
> > the whole picture you will only ever get bits of the answer.
> >
> >
> > Later on I give you "the whole picture"...which you summarily toss in
> > the garbage can. What am I supposed to do with that??
> >
> That isn't "the whole picture", that's "the Python soup I produced to
> query the SQL soup I produced because I thought it might answer my
> problem".
>
> >
> >
> > > #  print 'XXX', types[x]
> > >   elif types[x][0:3] == 'set':
> > > for f in field:
> > >   print 'AAA%s\n' % (field)
> > > else:
> > >   print 'YYY'
> > >
> > > 1) If I uncomment the commented line, it throws this error:
> > >
> > What happens if you *don't* uncomment the commented line?
> >
> >
> > As I mentioned, it prints BOTH the AAA and the YYY lines! The AAA is
> > printed with something like this:
> > AAASet([purple:223344])
> >
> Try moving the "else" so it's associated with the "if ... elif" rather
> than the "for". It's currently indented one level too far.
>

There is currently an else where you indicate, as one can see in the
complete code I am once again supplying with this post. That prints out
pretty much all the other fields and does so just fine.

Once again, it seems nobody is bothering to address this issue. Is it beyond
your reach as it is beyond mine? I feel compelled to restate the problem
once again as I did in my original post, and to once again post the entire
code. Hopefully someone will help me see my error.

I'm using python 2.4.3 which apparently requires that I import Set:
from sets import Set
I've done this. In another script I successfully manipulated MySQL sets by
so doing. Here's the code snippet from the script where I was able to call
the elements in a for loop:

  if isinstance(colValue[0], (str, int, float, long, complex,
unicode, list, buffer, xrange, tuple)):
pass
  else:
try:
  html = "%s: " % (col, col)
  notSet = 0
  for itm in colValue[0]:
try:
  color, number = itm.split(':')
  html += "%s" % (itm, color)
except:
  html += "%s" % (itm, itm)

However, when I try that in my current script, the script fails. It throws
no error, but rather just quits printing to the screen. Here's the code
snippet:

  elif types[x][0:3] == 'set':
for f in field:
  print '%s\n' % (field)
  else:
print '%s\n' % (field)

Notice that I can slice to determine if it's a set (I've printed something
after that call to be sure). But once I try to loop through the set it quits
printing to screen. The entire code follows.

#! /usr/bin/python

import MySQLdb
import cgi
import sys,os
sys.path.append(os.getcwd())
from login import login
from sets import Set

def enterProducts2():
  print '''Content-type: text/html








'''
  form = cgi.FieldStorage()
  store = form.getfirst('store')
  print "" % store
  user, passwd, db, host = login()
  count = 0
  count2 = 0
  db = MySQLdb.connect(host, user, passwd, db)
  cursor = db.cursor()
  cursor.execute('select ID from %s;' % store)
  test = cursor.fetchall()
  if len(test) > 0:
cursor.execute('show columns from %s;' % store)
colNames = [itm[0] for itm in cursor]
types = [itm[1] for itm in cursor]
colNamesWithCommas = ', '.join(colNames)
try:
  cursor.execute('select ID from %s;' % store)
  ids = cursor.fetchall()
  if store == 'prescriptions':
cursor.execute('show tables like "%PersonalData";')
personalDataTables = [itm[0] for itm in cursor]
  else:
personalDataTables = []
  print '%s\n\n' % (store[0].upper() +
store[1:])
  print 'What do you want to do?\n\n'
  print "Add\n"
  print "Update\n"
  print "Delete\n"
  print '\n\n'
  print '\n'
  print '\n'
  print 'Check\n'
  i = 0
  while i < len(colNames):
if i == 0: # This is the ID field
  print '', colNames[i], '\n'
  try:
cursor.execute('describe relationships%s;' % (store[0].upper() +
store[1:]))
relationshipsDescription = cursor.fetchall()
cursor.execute('select * from relationships%s where %sID="%s";'
% (store[0].upper() + store[1:], store[0].upper() + store[1:], ids[0][0]))

Re: getting name of passed reference

2009-12-29 Thread Steve Holden
Joel Davis wrote:
> On Dec 29, 2:04 am, Steven D'Aprano
>  wrote:
>> On Mon, 28 Dec 2009 19:28:32 -0800, Joel Davis wrote:
>>> my thanks go out to Emile and Mr Hanson for their responses, I think
>>> I've found the solution, much shorter as well:
>>> > #!/usr/bin/python
>>> > import traceback
>>> > def testing ( varPassed ):
>>> > print traceback.extract_stack()[0][3]
>>> > testing("123")
>>> and it seems the traceback module in general seems to have a lot of
>>> history to it. This project is for CPython so compatibility with Jython,
>>> Iron Python, et al isn't really that important right now. So as far as
>>> functionality and compatibility I think I'm set as long as
>>> traceback.extract_stack is 3.0 safe.
>> I'm afraid that one fails again. Do you actually test your solutions
>> before telling us you've solved the problem?
>>
> import traceback
> def testing ( varPassed ):
>> ... print traceback.extract_stack()[0][3]
>> ...
>>
> testing("123")
>> None
> x = "123"
> testing(x)
>> None
>>
>> When a "solution" doesn't work under some circumstances (in this case,
>> when run in the interactive interpreter) that's a warning that you need
>> to understand when and where it will work before using it in production.
>> Otherwise, how do you know that it will work under other circumstances?
>>
>> Or, find an alternative. What are you actually trying to do? "Get the
>> name of a passed reference" is a means to an end. What are you expecting
>> to do with it?
>>
>> --
>> Steven
> 
> Steven I don't know what your issue is, but it works for me. If your
> having trouble running the code, then that's your issue, and I would
> appreciate it if you would just shut up until you know what the hell
> you're talking about. I say that because if you paid the slightest
> attention my first solution that you found so woefully inept IS
> BASICALLY YOUR FIRST SOLUTION RECONFIGURED.
> 
> You also apparently can't read.

Whereas you appear to have a problem maintaining good manners.

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

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


Re: getting name of passed reference

2009-12-29 Thread Francesco Bochicchio
On 29 Dic, 00:54, Joel Davis  wrote:
> I'm just curious if anyone knows of a way to get the variable name of
> a reference passed to the function.
>
> Put another way, in the example:
>
>   def MyFunc ( varPassed ):
>      print varPassed;
>
>   MyFunc(nwVar)
>
> how would I get the string "nwVar" from inside of "MyFunc"? is it
> possible?


The following code shows one way to get both function name and
argument names from inside a function using module inspect in python
2.6:

import inspect

def myfunc(arg1, arg2):
f = inspect.currentframe()
funcname = inspect.getframeinfo(f).function
numargs =  f.f_code.co_argcount
argnames = f.f_code.co_varnames[:numargs]
print funcname, argnames

myfunc(1, "ppp")

NOTE: it does not list parameters passed as list (*args) or as dict
(**kwd).

P.S . I use this to generate automatically trace messages of type
"called myfunc( arg1=1, arg2=ppp" ).
But I currently lack  a way, from inside a method, to determine the
name of the class to which the
method belong, so I could automatically generate trace messages of
type "class.method called etc ...".
Pointers are welcome.

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


Re: More On the Strange Problem

2009-12-29 Thread Albert van der Horst
In article <4b32881...@dnews.tpgi.com.au>,
Lie Ryan   wrote:
>On 12/24/2009 8:00 AM, MRAB wrote:
>>
>>  >>> print first_twin == second_twin
>> True
>
>err... I don't think there is any situation where first_twin ==
>second_twin wouldn't be considered a bug. They look similar, they act
>similar, and they quack the same; though you can almost always treat
>them the same they are still ultimately different person?

They have a different Personal-Identification-Number as required by
the Tax Office, so they are different. Also probably they have
different fingerprints.

Groetjes Albert.

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
alb...@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst

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


Re: Which version of MSVC?90.DLL's to distribute with Python 2.6 based Py2exe executables?

2009-12-29 Thread Jonathan Hartley
On Dec 29, 2:24 pm, Jonathan Hartley  wrote:
> On Dec 27, 1:51 pm, pyt...@bdurham.com wrote:
>
>
>
> > Hi Martin,
>
> > > You'll need to include Microsoft.VC90.CRT.manifest and msvcr90.dll.
>
> > Thank you for your answers. From my research and testing on this topic:
>
> > 1. Can I safely place these 2 files in the same folder as my Py2exe
> > generated EXE file or do I need to place the MSVCR90.DLL file in a
> > specially named sub-folder?
>
> > 2. Do I need to rename the Microsoft.VC90.CRT.manifest file to
> > myapp.exe.manifest or can I leave it named as is?
>
> > 3. Do I need to customize the contents of the
> > Microsoft.VC90.CRT.manifest file for my EXE?
>
> > I've been experimenting with different answers to the above questions
> > and multiple approaches seems to work. I suspect this is because all the
> > workstations I have access to for testing already have the full set of
> > MSVC*90.DLL's installed - and not because my multiple tests really work.
>
> > Thanks so much for your help!
>
> > Malcolm
>
> I just created a VM containing a bare-bones install of Windows XP,
> precisely so that I can reproduce the errors my users see when
> MSVCR90.DLL is not installed.
>
> It sounds like the wisest course of action is for me to use
> vcredist_x86.exe to install the required MSVC runtime on the user's
> machine (as opposed to trying to distribute MSVCR90.DLL with my
> application.) I can be sure that I have rights to distribute this, and
> I don't have to understand side-by-side DLL installation, and I'm
> delegating any tricky decisions to Microsoft, who are presumably best
> qualified to judge things like: what to do if other versions of the
> DLLs are already installed; how to register them to be shared between
> multiple applications; whether to update them if Windows Update
> decrees it, etc)
>
> I'm going to try to run vcredist_x86.exe automatically (as opposed to
> asking my users to download and run it manually). I don't currently
> have any installer, so I'm going to run vcredist_x86.exe on my
> application start-up. Some logic like this seems to do this trick:
>
>     if platform.system() == 'Windows':
>         command = [path.join('lib', 'vcredist_x86.exe'), '/q']
>         retcode = subprocess.call(command)
>         if retcode != 0:
>             sys.stderr.write(
>                 'Return value %d from vcredist_x86.exe\n' %
> (retcode,))
>
> This seems to work. My py2exe program will now run out of the box on a
> bare-bones Windows XP install. (note: running 'vcredist_x86.exe /qu'
> will uninstall the DLLs again)
>
> However, this takes a few seconds to run. Is there a sensible way for
> me to only run this if the required DLL is not already installed? How
> should I be detecting that?
>
> Also: Will this work on 64 bit machines? Or do I not need to worry
> about that?


I was fooling myself with sloppy testing, this doesn't work at all.
Obviously enough.

If the DLLs aren't installed, then my program can't be launched, and
can't bootstrap itself by installing the required DLL's.

I guess I really need an installer. Oh well.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: detect interactivity

2009-12-29 Thread Antoine Pitrou
Le Tue, 29 Dec 2009 16:09:58 +0100, Roald de Vries a écrit :

> Dear all,
> 
> Is it possible for a Python script to detect whether it is running
> interactively? It can be useful for e.g. defining functions that are
> only useful in interactive mode.

Try the isatty() method (*) on e.g. stdin:

$ python -c "import sys; print sys.stdin.isatty()"
True
$ echo "" | python -c "import sys; print sys.stdin.isatty()"
False


(*) http://docs.python.org/library/stdtypes.html#file.isatty

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


Re: Object Relational Mappers are evil (a meditation)

2009-12-29 Thread J Kenneth King
Steven D'Aprano  writes:

> On Wed, 23 Dec 2009 10:55:19 -0500, J Kenneth King wrote:
>
>> Steven D'Aprano  writes:
>> 
>>> On Mon, 21 Dec 2009 11:44:29 -0500, J Kenneth King wrote:
>>>
 A programmer that
 lacks critical thinking is a bad programmer.  The language they use
 has no bearing on such human facilities.
>>>
>>> That's nonsense, and I can demonstrate it by reference to a single
>>> programming language, namely Python.
>>>
>>> For many years, Python had no ternary if operator:
>
> [...]
>
>> But did the lack of ternary encourage Raymond to become a bad
>> programmer?
>
> No, but Raymond started off in a position of being an excellent 
> programmer. A single buggy idiom lead him to be slightly-less excellent 
> than he otherwise would have been. How many buggy idioms would it take to 
> lead him to become a mediocre coder, if he was unable to change languages?
>
> Because Python is generally an excellent language, the harm done by one 
> or two misfeatures is minor. But less excellent languages encourage 
> coding styles, techniques and idioms that encourage the programmer to 
> write poor code: either complicated, baroque, unreadable code; or slow 
> inefficient code; or buggy code. To avoid starting a flame war, I will 
> avoid mentioning PHP. *cough*
>
> Sometimes you know what you need to do to write non-buggy code, but 
> because covering all the corners are just Too Damn Hard in a certain 
> language, you simply lower your expectations. Error checking is tedious 
> and hard to get right in some languages, like C and Pascal, and hence 
> even good programmers can miss some errors.
>
> Different languages encourage different mind-sets in the programmer: C 
> encourages the coder to think at the low level of pointers and addresses, 
> and primarily about machine efficiency; Java encourages the use of big 
> object hierarchies and design patterns (it's hard to write lightweight 
> code in Java, so everything turns into heavyweight code); Perl encourages 
> cleverness and code-golf (writing a program in as few lines or characters 
> as possible); Haskell and Lisp encourage a heavily abstract approach that 
> often requires an elite coder to follow; Forth encourages you to think 
> like Yoda.

If anyone continues to follow bad idioms without questioning their
usefulness from time to time, I'd question their ability as a
programmer.  Critical thinking is important.  Which is why good programs
can be written in PHP, Forth, Lisp, Perl, and anything else.  However,
if a programmer thinks the only language they will ever need to know is
BF, they have a serious screw loose. ;)

> [...]
>> Good tools make all the difference in the world, I'm not arguing that.
>
> You appear to be arguing against that.

Maybe you need to reconsider my arguments.

It takes a good programmer to recognize the values and trade-offs of the
tools they work with.

Ignorance is not an excuse to blame the language.  It's too easy to say,
"Well Perl sucks because it encourages you to be a bad programmer
because it has all these features that let you shoot yourself in the
foot."  In reality, lots of really great programs are written in Perl
all the time and some very smart people write them.  It just so happens
that in hands of the educated, those very features are useful in certain
cases.

Python doesn't "encourage" you to be a better programmer.  It just
enforces particular idioms and conventions in its design.  As long as
the ignorant programmer follows them they should be better off.  Yet if
they are ignorant, no amount of encouragement will get them to think
critically about Python and find bugs in it.  They will have to rely on
the community of developers to do that thinking for them.

>
>> Just that the tools don't use us; we use them.
>
> Nobody said that tools use us.

But it is being suggested that they influence our thinking.

Pretty smart thing for a language to be able to do.

>> Programming in Python
>> doesn't instantly make me a better programmer.
>
> No, not instantly, but I would argue that after many years of coding in 
> Python you will be a better programmer than after the same number of 
> years of coding in PHP or Basic.

And my argument is that the human element is what will determine who is
better.

There are good programmers who can program in PHP.  Some of the biggest
websites on the Internet are programmed in it.  And like any language
I'm sure it has a good number of inefficiencies and bad design decisions
that the programmers using it had to work around.  Yet despite it being
a poor language in your opinion, they built successful programs with
it.  I wouldn't feel right calling them bad programmers.

(large portions of Facebook and Flickr, for example, are written in
PHP.  They used to be written entirely in PHP before migrating the
bottlenecks out to lower-level languages as they scaled up... as is
common in most high-level languages)

> It also depends on what you mean by "better programmer

Re: Difference Between Two datetimes

2009-12-29 Thread M.-A. Lemburg
W. eWatson wrote:
> According to one web source, this program:
> 
> import datetime
> bree = datetime.datetime(1981, 6, 16, 4, 35, 25)
> nat  = datetime.datetime(1973, 1, 18, 3, 45, 50)
> 
> difference = bree - nat
> print "There were", difference, "minutes between Nat and Bree"
> 
> yields:
> There were 3071 days, 0:49:35 minutes between Nat and Bree
> 
> That's fine, but I'd like to start with two dates as strings, as
> "1961/06/16 04:35:25" and "1973/01/18 03:45:50"
> 
> How do I get the strings into a shape that will accommodate a difference?
> 
> For example,
> t1=datetime.datetime.strptime("2009/01/02 13:01:15","%y/%m/%d %H:%M:%S")
> doesn't do it.
> ValueError: time data did not match format:  data=2009/01/02 13:01:15
> fmt=%y/%m/%d %H:%M:%S

Here's how you'd do this with mxDateTime:

http://www.egenix.com/products/python/mxBase/mxDateTime/

>>> from mx.DateTime import *
>>> bree = DateTimeFrom("1981/06/16 04:35:25")
>>> nat = DateTimeFrom("1973/01/18 03:45:50")
>>> bree

>>> nat


Now, let's look at the date/time difference:

>>> bree - nat


i.e. 3071 days, 49 minutes, 35 seconds.

If you want a more human readable, relative format use Age():

>>> Age(bree, nat)


i.e. 8 years, 4 months, 29 days, 49 minutes, 35 seconds.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Dec 29 2009)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


::: Try our new mxODBC.Connect Python Database Interface for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
   http://www.egenix.com/company/contact/
-- 
http://mail.python.org/mailman/listinfo/python-list


detect interactivity

2009-12-29 Thread Roald de Vries

Dear all,

Is it possible for a Python script to detect whether it is running  
interactively? It can be useful for e.g. defining functions that are  
only useful in interactive mode.


Kind regards, Roald


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


Re: getting name of passed reference

2009-12-29 Thread Joel Davis
On Dec 29, 2:29 am, "Gabriel Genellina" 
wrote:
> En Tue, 29 Dec 2009 00:28:32 -0300, Joel Davis   
> escribió:
>
>
>
> > On Dec 28, 9:37 pm, Joel Davis  wrote:
> > my thanks go out to Emile and Mr Hanson for their responses, I think
> > I've found the solution, much shorter as well:
>
> >     > #!/usr/bin/python
>
> >     > import traceback
>
> >     > def testing ( varPassed ):
> >     >         print traceback.extract_stack()[0][3]
>
> >     > testing("123")
>
> > and it seems the traceback module in general seems to have a lot of
> > history to it. This project is for CPython so compatibility with
> > Jython, Iron Python, et al isn't really that important right now. So
> > as far as functionality and compatibility I think I'm set as long as
> > traceback.extract_stack is 3.0 safe.
>
> Test with this:
>
> def f(): return g()
> def g(): return h()
> def h(): testing("123")
> f()
>
> You probably want traceback.extract_stack()[-2][3] instead.
>
> Note that your solution solves a different problem: you asked "the name of  
> the passed object" and testing() above prints "the source line of the  
> previous stack frame". This method may be good enough for you, but you  
> should be aware of its limitations:
>
> - The source code (.py file) of the module containing the calling function  
> must be present (a .pyc file is not enough).
> - It must be a plain text file in the filesystem, directly reachable in a  
> directory along sys.path (it may not be contained in a .zip file, an .egg,  
> or use any other kind of import mechanism).
> - The source retrieval may fail if your program changes the current  
> directory
> - If the calling function is not actually inside a module, you can't  
> retrieve its source (e.g. when using exec/eval, or from inside the  
> interactive interpreter).
> - Only the last line of the function invocation is returned; you miss all  
> its previous lines and/or arguments.
>
> I'm sure other limitations apply too -- don't rely on this technique for  
> anything critical.
>
> --
> Gabriel Genellina

Gabriel,

thanks for your input, I had no idea that did that and it could have
been deployed without even being aware of it, caused consternation and
headaches galore.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting name of passed reference

2009-12-29 Thread Joel Davis
On Dec 29, 2:04 am, Steven D'Aprano
 wrote:
> On Mon, 28 Dec 2009 19:28:32 -0800, Joel Davis wrote:
> > my thanks go out to Emile and Mr Hanson for their responses, I think
> > I've found the solution, much shorter as well:
>
> >     > #!/usr/bin/python
>
> >     > import traceback
>
> >     > def testing ( varPassed ):
> >     >         print traceback.extract_stack()[0][3]
>
> >     > testing("123")
>
> > and it seems the traceback module in general seems to have a lot of
> > history to it. This project is for CPython so compatibility with Jython,
> > Iron Python, et al isn't really that important right now. So as far as
> > functionality and compatibility I think I'm set as long as
> > traceback.extract_stack is 3.0 safe.
>
> I'm afraid that one fails again. Do you actually test your solutions
> before telling us you've solved the problem?
>
> >>> import traceback
> >>> def testing ( varPassed ):
>
> ...     print traceback.extract_stack()[0][3]
> ...
>
> >>> testing("123")
> None
> >>> x = "123"
> >>> testing(x)
>
> None
>
> When a "solution" doesn't work under some circumstances (in this case,
> when run in the interactive interpreter) that's a warning that you need
> to understand when and where it will work before using it in production.
> Otherwise, how do you know that it will work under other circumstances?
>
> Or, find an alternative. What are you actually trying to do? "Get the
> name of a passed reference" is a means to an end. What are you expecting
> to do with it?
>
> --
> Steven

Steven I don't know what your issue is, but it works for me. If your
having trouble running the code, then that's your issue, and I would
appreciate it if you would just shut up until you know what the hell
you're talking about. I say that because if you paid the slightest
attention my first solution that you found so woefully inept IS
BASICALLY YOUR FIRST SOLUTION RECONFIGURED.

You also apparently can't read.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which version of MSVC?90.DLL's to distribute with Python 2.6 based Py2exe executables?

2009-12-29 Thread Jonathan Hartley
On Dec 27, 1:51 pm, pyt...@bdurham.com wrote:
> Hi Martin,
>
> > You'll need to include Microsoft.VC90.CRT.manifest and msvcr90.dll.
>
> Thank you for your answers. From my research and testing on this topic:
>
> 1. Can I safely place these 2 files in the same folder as my Py2exe
> generated EXE file or do I need to place the MSVCR90.DLL file in a
> specially named sub-folder?
>
> 2. Do I need to rename the Microsoft.VC90.CRT.manifest file to
> myapp.exe.manifest or can I leave it named as is?
>
> 3. Do I need to customize the contents of the
> Microsoft.VC90.CRT.manifest file for my EXE?
>
> I've been experimenting with different answers to the above questions
> and multiple approaches seems to work. I suspect this is because all the
> workstations I have access to for testing already have the full set of
> MSVC*90.DLL's installed - and not because my multiple tests really work.
>
> Thanks so much for your help!
>
> Malcolm


I just created a VM containing a bare-bones install of Windows XP,
precisely so that I can reproduce the errors my users see when
MSVCR90.DLL is not installed.

It sounds like the wisest course of action is for me to use
vcredist_x86.exe to install the required MSVC runtime on the user's
machine (as opposed to trying to distribute MSVCR90.DLL with my
application.) I can be sure that I have rights to distribute this, and
I don't have to understand side-by-side DLL installation, and I'm
delegating any tricky decisions to Microsoft, who are presumably best
qualified to judge things like: what to do if other versions of the
DLLs are already installed; how to register them to be shared between
multiple applications; whether to update them if Windows Update
decrees it, etc)

I'm going to try to run vcredist_x86.exe automatically (as opposed to
asking my users to download and run it manually). I don't currently
have any installer, so I'm going to run vcredist_x86.exe on my
application start-up. Some logic like this seems to do this trick:

if platform.system() == 'Windows':
command = [path.join('lib', 'vcredist_x86.exe'), '/q']
retcode = subprocess.call(command)
if retcode != 0:
sys.stderr.write(
'Return value %d from vcredist_x86.exe\n' %
(retcode,))

This seems to work. My py2exe program will now run out of the box on a
bare-bones Windows XP install. (note: running 'vcredist_x86.exe /qu'
will uninstall the DLLs again)

However, this takes a few seconds to run. Is there a sensible way for
me to only run this if the required DLL is not already installed? How
should I be detecting that?

Also: Will this work on 64 bit machines? Or do I not need to worry
about that?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python OOP Problem

2009-12-29 Thread Миклухо
On Dec 29, 7:35 pm, Laszlo Nagy  wrote:
> > Thanks for reply, but it doesn't fit to my task. If I will add later
> > other objects(and it will be very often) - I should stop the service,
> > but that would be very bad.
>
> I think you meant "if you add other classes".> I'm not sure, if this is 
> solution, but test passed:
>
> > myimportmod = __import__('ClassName', globals(), locals(),
> > ['ClassName'], -1)
> > mod = getattr(_myimportmod, 'ClassName')
> > o = mod();
> > o.myfunction();
>
> The same way you can say: this won't work if you need to change your
> 'ClassName' class. That would require restart of your service. Then you
> can use reload(). However, I do not see the big picture. What is your
> program suppose to do?
>
>   L

The program works under apache(mod_wsgi) and receives different
messages, depends upon the message it should give an answer. There are
a lot types of messages(something like service) - and if I change a
'ClassName' class(mostly I don't change - just throw away from db note
about it(if time of service ended))- other modules(for instance
ClassName2 ClassName3 etc.) work. And if I will edit the main class
(which loads them) all services may be down. That's why it is
important to make a generalized loader - which loads another class.
-- 
http://mail.python.org/mailman/listinfo/python-list


python interface to Yahoo groups?

2009-12-29 Thread guthrie
I'm looking for something to monitor & download yahoo group messages
using Python, similar to the Perl module WWW::Yahoo::Groups.

I've seen a few comments (speculations?) that Yahoo groups uses Python
code, but couldn't find any examples of samples of such access tools.

Any references or pointers appreciated.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another Sets Problem

2009-12-29 Thread Steve Holden
Victor Subervi wrote:
> On Tue, Dec 29, 2009 at 9:33 AM, Steve Holden  > wrote:
> 
> That's a bit like being told you have to produce something green, and
> then when you do, being told "no, not that green, a light green". So you
> produce something a lighter gree and then being told "no, a slightly
> redder green". And so on.
> 
> In other words, you aren't giving us the whole picture here, and without
> the whole picture you will only ever get bits of the answer.
> 
> 
> Later on I give you "the whole picture"...which you summarily toss in
> the garbage can. What am I supposed to do with that??
>  
That isn't "the whole picture", that's "the Python soup I produced to
query the SQL soup I produced because I thought it might answer my problem".

> 
> 
> > #  print 'XXX', types[x]
> >   elif types[x][0:3] == 'set':
> > for f in field:
> >   print 'AAA%s\n' % (field)
> > else:
> >   print 'YYY'
> >
> > 1) If I uncomment the commented line, it throws this error:
> >
> What happens if you *don't* uncomment the commented line?
> 
> 
> As I mentioned, it prints BOTH the AAA and the YYY lines! The AAA is
> printed with something like this:
> AAASet([purple:223344])
> 
Try moving the "else" so it's associated with the "if ... elif" rather
than the "for". It's currently indented one level too far.

> 
> > [Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58]   File
> > "/var/www/html/angrynates.com/cart/enterProducts2.py
> 
> > ", line 138, referer:
> > http://angrynates.com/cart/enterProducts.py
> > [Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58] elif
> > types[x][0:3] == 'set':, referer:
> > http://angrynates.com/cart/enterProducts.py
> > [Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58]^,
> > referer: http://angrynates.com/cart/enterProducts.py
> > [Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58] SyntaxError:
> > invalid syntax, referer: http://angrynates.com/cart/enterProducts.py
> > [Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58]
> Premature end
> > of script headers: enterProducts2.py, referer:
> > http://angrynates.com/cart/enterProducts.py
> >
> I am presuming that this is copied from an Apache error log, though you
> don't bother to say so.
> 
> 
> No. I just copied and pasted stuff from a previous post. I did that
> because I've noticed when someone posts something irrelevant, the
> substance of my posts sometimes gets buried. I should have edited this
> garbage out.
> 
> 
> The issue here is that you can't just stick print statements in anywhere
> you like. Consider the following Python:
> 
> if a == 3:
>print "A is 3"
> print "Debugging"
> elif a == 4:
>print "A is 4"
> else:
>print "A is neither 3 nor 4"
> 
> If you comment out the 'print "Debugging"' line you have a perfectly
> acceptable program. If you don't then you have something that is close
> to Python, but not close enough for the interpreter to be able to
> compile it.
> 
> 
> Duh. I might not be too sharp, but give me a little more credit than
> that, Steve. Come on.
> 
So you didn't need any help to spot this problem?

> 
> What's happening with your (CGI?) program is that the syntax error you
> have induced by inserting a random print statement causes an error
> message to be produced instead of your program's output; this doesn't
> look like HTTP headers. So the web server complains that your program
> has produced output that shouldn't be sent to any self-respecting
> browser.
> 
> 
> Perhaps.
> 
> 
> I further presume (though again I don't believe you bother to report it
> anywhere) that you see an "Error 500" or similar message in your web
> browser when you try and access the web page.
> 
> 
> Yes. I believe that's it.
> 
> 
> > 2) AAA prints out before the following fields:
> > AAASet(['Extra-small'])
> > AAASet(['purple:50404D'])
> 
> 
> And the above is the answer to your previous question. This makes me
> think you really rushed through this. You are a very helpful person, but
> please either take the time necessary or don't answer. That is, respond
> only when you have the time to devote to giving a good and thoughtful
> answer. It's evident you didn't do that here...and you're blaming me for
> it. Wrong!
>  
OK, I'll not answer.

regards
 Steve

> 
> >
> > 3) YYY *also* prints out twice!!
> >
> > Here's the complete code once again:
> >
> [complete code snipped]
> >
> > TIA,
> > beno
> >
> Sorry, I don't intend to read all that code when the error you are
> reporting is in fact 

Re: adding python engine into c++ application

2009-12-29 Thread Stefan Behnel

griwes, 29.12.2009 12:25:

Hello, I am going to write an application in C++, application which
should be easy to extend by scripts. I chose python for script
language in this application. I'd like to have own API for python. And
here the question arises: how do I implement a python engine within an
application written in C++?


Since you likely want to establish some kind of Python level API that wraps 
your C++ code (so that Python code can talk to it), you might want to take 
a look at Cython:


http://cython.org

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


Re: Another Sets Problem

2009-12-29 Thread Victor Subervi
On Tue, Dec 29, 2009 at 9:33 AM, Steve Holden  wrote:

> That's a bit like being told you have to produce something green, and
> then when you do, being told "no, not that green, a light green". So you
> produce something a lighter gree and then being told "no, a slightly
> redder green". And so on.
>
> In other words, you aren't giving us the whole picture here, and without
> the whole picture you will only ever get bits of the answer.
>

Later on I give you "the whole picture"...which you summarily toss in the
garbage can. What am I supposed to do with that??


>
> > #  print 'XXX', types[x]
> >   elif types[x][0:3] == 'set':
> > for f in field:
> >   print 'AAA%s\n' % (field)
> > else:
> >   print 'YYY'
> >
> > 1) If I uncomment the commented line, it throws this error:
> >
> What happens if you *don't* uncomment the commented line?
>

As I mentioned, it prints BOTH the AAA and the YYY lines! The AAA is printed
with something like this:
AAASet([purple:223344])


> > [Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58]   File
> > "/var/www/html/angrynates.com/cart/enterProducts2.py
> > ", line 138, referer:
> > http://angrynates.com/cart/enterProducts.py
> > [Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58] elif
> > types[x][0:3] == 'set':, referer:
> > http://angrynates.com/cart/enterProducts.py
> > [Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58]^,
> > referer: http://angrynates.com/cart/enterProducts.py
> > [Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58] SyntaxError:
> > invalid syntax, referer: http://angrynates.com/cart/enterProducts.py
> > [Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58] Premature end
> > of script headers: enterProducts2.py, referer:
> > http://angrynates.com/cart/enterProducts.py
> >
> I am presuming that this is copied from an Apache error log, though you
> don't bother to say so.
>

No. I just copied and pasted stuff from a previous post. I did that because
I've noticed when someone posts something irrelevant, the substance of my
posts sometimes gets buried. I should have edited this garbage out.

>
> The issue here is that you can't just stick print statements in anywhere
> you like. Consider the following Python:
>
> if a == 3:
>print "A is 3"
> print "Debugging"
> elif a == 4:
>print "A is 4"
> else:
>print "A is neither 3 nor 4"
>
> If you comment out the 'print "Debugging"' line you have a perfectly
> acceptable program. If you don't then you have something that is close
> to Python, but not close enough for the interpreter to be able to
> compile it.
>

Duh. I might not be too sharp, but give me a little more credit than that,
Steve. Come on.

>
> What's happening with your (CGI?) program is that the syntax error you
> have induced by inserting a random print statement causes an error
> message to be produced instead of your program's output; this doesn't
> look like HTTP headers. So the web server complains that your program
> has produced output that shouldn't be sent to any self-respecting browser.
>

Perhaps.

>
> I further presume (though again I don't believe you bother to report it
> anywhere) that you see an "Error 500" or similar message in your web
> browser when you try and access the web page.
>

Yes. I believe that's it.

>
> > 2) AAA prints out before the following fields:
> > AAASet(['Extra-small'])
> > AAASet(['purple:50404D'])
>

And the above is the answer to your previous question. This makes me think
you really rushed through this. You are a very helpful person, but please
either take the time necessary or don't answer. That is, respond only when
you have the time to devote to giving a good and thoughtful answer. It's
evident you didn't do that here...and you're blaming me for it. Wrong!


> >
> > 3) YYY *also* prints out twice!!
> >
> > Here's the complete code once again:
> >
> [complete code snipped]
> >
> > TIA,
> > beno
> >
> Sorry, I don't intend to read all that code when the error you are
> reporting is in fact a clear demonstration that you need to further
> understand the principles of both Python and the web before you continue
> on your journey.
>

Again, I know I'm really slow when it comes to this material. But I didn't
start hacking (and it is hacking) Python code yesterday. I'm almost ashamed
to admit it, but I've been at it 10 years. Again, I might be slow, but I
don't think that gives you the right to tell me to go back to kindergarten.
Help me out here. Or maybe somebody else will.

Let me restate the problem:

I'm using python 2.4.3 which apparently requires that I import Set:
from sets import Set
I've done this. In another script I successfully manipulated MySQL sets by
so doing. Here's the code snippet from the script where I was able to call
the elements in a for loop:

  if isinstance(colValue[0], (str, int, float, long, comp

Re: Difference Between Two datetimes

2009-12-29 Thread Steve Holden
W. eWatson wrote:
> Peter Otten wrote:
>> W. eWatson wrote:
>>
>>> This is quirky.
>>>
>>>  >>> t1=datetime.datetime.strptime("20091205_221100","%Y%m%d_%H%M%S")
>>>  >>> t1
>>> datetime.datetime(2009, 12, 5, 22, 11)
>>>  >>> type(t1)
>>> 
>>>  >>>
>>> t1:  2009-12-05 22:11:00 
>>>
>>> but in the program:
>>> import datetime
>>>
>>> t1=datetime.datetime.strptime("20091205_221100","%Y%m%d_%H%M%S")
>>> print "t1: ",t1, type(t1)
>>>
>>> produces
>>> t1:  2009-12-05 22:11:00 
>>>
>>> Where did the hyphens and colons come from?
>>
>> print some_object
>>
>> first converts some_object to a string invoking str(some_object) which
>> in turn calls the some_object.__str__() method. The resulting string
>> is then written to stdout. Quoting the documentation:
>>
>> datetime.__str__()
>> For a datetime instance d, str(d) is equivalent to d.isoformat(' ').
>>
>> datetime.isoformat([sep])
>> Return a string representing the date and time in ISO 8601 format,
>> -MM-DDTHH:MM:SS.mm or, if microsecond is 0,
>> -MM-DDTHH:MM:SS
>>
>> Peter
> So as long as I don't print it, it's datetime.datetime and I can make
> calculations or perform operations on it as though it is not a string,
> but a datetime object?

It's nothing to do with whether you print it or not. When you print it,
an equivalent string is produced, and the string is what gets printed.
This is necessary, because humans only understand character-based output.

>>> type(x)

>>> print x
82.2
>>> type(x)


The type of something is unchanged by printing it. The print statement
merely calls methods of the object to produce strings that it can print.

>>> x.__str__()
'82.2'
>>> x.__repr__()
'82.203'
>>>

People talk loosely about "converting an object to a string", but that
doesn't mean transmogrifying the object to something else, it means
producing an equivalent value of some other type which can be used
instead of the original object for some specific purpose. In this case,
printing.

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

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


Re: Python OOP Problem

2009-12-29 Thread Laszlo Nagy



Thanks for reply, but it doesn't fit to my task. If I will add later
other objects(and it will be very often) - I should stop the service,
but that would be very bad.
  

I think you meant "if you add other classes".

I'm not sure, if this is solution, but test passed:

myimportmod = __import__('ClassName', globals(), locals(),
['ClassName'], -1)
mod = getattr(_myimportmod, 'ClassName')
o = mod();
o.myfunction();
  
The same way you can say: this won't work if you need to change your 
'ClassName' class. That would require restart of your service. Then you 
can use reload(). However, I do not see the big picture. What is your 
program suppose to do?


 L


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


Re: Another Sets Problem

2009-12-29 Thread Steve Holden
Victor Subervi wrote:
> On Mon, Dec 28, 2009 at 4:23 PM, Steve Holden  > wrote:
> 
> There is only one way for the piece of code you quote to print nothing
> (unless you suspect a bug in the Python interpreter, but the probability
> of that is so low compared with the probability of your making a mistake
> in interpretation of the data that I am going to ignore it).
> 
> Hence my deduction. If types[x][0:3] != 'set' then the else clause would
> definitely print something. Hence types[x][0:3] == 'set', and the for
> statement is executing. But again, if field were anything other than an
> empty container it would produce printed output.
> 
> But if it's empty, no printed output would be produced:
> 
> >>> field = set([])
> >>> for f in field:
> ...   print "Steve is wrong"
> ...
> >>>
> 
> Does this make sense?
> 
> 
> Boy, does it! It looks great...on paper. Here's some revised code to debug:
> 
I am unser how you expect anyone to "debug" an isolated piece of code
like this with an incomplete description of the data it's processing.

That's a bit like being told you have to produce something green, and
then when you do, being told "no, not that green, a light green". So you
produce something a lighter gree and then being told "no, a slightly
redder green". And so on.

In other words, you aren't giving us the whole picture here, and without
the whole picture you will only ever get bits of the answer.

> #  print 'XXX', types[x]
>   elif types[x][0:3] == 'set':
> for f in field:
>   print 'AAA%s\n' % (field)
> else:
>   print 'YYY'
>  
> 1) If I uncomment the commented line, it throws this error:
> 
What happens if you *don't* uncomment the commented line?

> [Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58]   File
> "/var/www/html/angrynates.com/cart/enterProducts2.py
> ", line 138, referer:
> http://angrynates.com/cart/enterProducts.py
> [Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58] elif
> types[x][0:3] == 'set':, referer:
> http://angrynates.com/cart/enterProducts.py
> [Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58]^,
> referer: http://angrynates.com/cart/enterProducts.py
> [Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58] SyntaxError:
> invalid syntax, referer: http://angrynates.com/cart/enterProducts.py
> [Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58] Premature end
> of script headers: enterProducts2.py, referer:
> http://angrynates.com/cart/enterProducts.py
> 
I am presuming that this is copied from an Apache error log, though you
don't bother to say so.

The issue here is that you can't just stick print statements in anywhere
you like. Consider the following Python:

if a == 3:
print "A is 3"
print "Debugging"
elif a == 4:
print "A is 4"
else:
print "A is neither 3 nor 4"

If you comment out the 'print "Debugging"' line you have a perfectly
acceptable program. If you don't then you have something that is close
to Python, but not close enough for the interpreter to be able to
compile it.

What's happening with your (CGI?) program is that the syntax error you
have induced by inserting a random print statement causes an error
message to be produced instead of your program's output; this doesn't
look like HTTP headers. So the web server complains that your program
has produced output that shouldn't be sent to any self-respecting browser.

I further presume (though again I don't believe you bother to report it
anywhere) that you see an "Error 500" or similar message in your web
browser when you try and access the web page.

> 2) AAA prints out before the following fields:
> AAASet(['Extra-small'])
> AAASet(['purple:50404D'])
> 
> 3) YYY *also* prints out twice!!
> 
> Here's the complete code once again:
> 
[complete code snipped]
> 
> TIA,
> beno
> 
Sorry, I don't intend to read all that code when the error you are
reporting is in fact a clear demonstration that you need to further
understand the principles of both Python and the web before you continue
on your journey.

You are trying to run before you can walk. Don't be surprised when the
result is an intimate contact between your face and the ground.

The first thing I would suggest is that you learn to write code that
uses multiple layers, calling functions to achieve higher-level ends. At
the moment your code is "monolithic" (a single huge chunk), which makes
it very difficult to separate out the bits that work from the bits that
don't.

This is not "a sets problem", this is a "lack of understanding problem".
Like any skill, programming is a rewarding talent once mastered. Like
most worthwhile achievements it demands a methodical approach and a
rigorous attention to detail if you are to master it properly.

The first thing you *must* do is instil in yourself a b

Re: Another Sets Problem

2009-12-29 Thread Victor Subervi
On Tue, Dec 29, 2009 at 6:29 AM, Jean-Michel Pichavant <
jeanmic...@sequans.com> wrote:

> Matt Nordhoff wrote:
>
>> Victor Subervi wrote:
>>
>>
>>> On Mon, Dec 28, 2009 at 1:41 PM, MRAB >> > wrote:
>>>
>>>
 DON'T USE BARE EXCEPTS!

 (There are 2 in your code.)


>>> There are times when they are *necessary*.
>>>
>>>
>>
>> No, there aren't.
>>
>> Even if there were, this is not one of those situations.
>>
>>
> And to elaborate a little bit, someone said in this list (sorry, don't
> remember who) that often people think that making their code robust is one
> of the top priority, especially when you are providing some services to
> clients. That could be true. The fact is that most newcomers thinks bare try
> except will do the trick: "look, my server never crashes". Yes it does not
> crash, but even worse, it handles exception in an inapropriate way that
> leads the server to behave in a reliable, yet unpredictable, manner. And
> that is definitely *not* being robust.
>

You all have made very good points about bare excepts. I promise you I will
work on this...AFTER I've finished the first working copy of this shopping
cart and gotten caught up on my work, and start to clean this shopping cart
up to make it truly professional. HOWEVER, there is NO bare except
influencing the problem which I am trying to fix. Can we PLEASE set this
issue aside and deal with the problem of this post?? Here it is again:

On Mon, Dec 28, 2009 at 4:23 PM, Steve Holden  wrote:

> There is only one way for the piece of code you quote to print nothing
> (unless you suspect a bug in the Python interpreter, but the probability
> of that is so low compared with the probability of your making a mistake
> in interpretation of the data that I am going to ignore it).
>
> Hence my deduction. If types[x][0:3] != 'set' then the else clause would
> definitely print something. Hence types[x][0:3] == 'set', and the for
> statement is executing. But again, if field were anything other than an
> empty container it would produce printed output.
>
> But if it's empty, no printed output would be produced:
>
> >>> field = set([])
> >>> for f in field:
> ...   print "Steve is wrong"
> ...
> >>>
>
> Does this make sense?
>

Boy, does it! It looks great...on paper. Here's some revised code to debug:

#  print 'XXX', types[x]

  elif types[x][0:3] == 'set':
for f in field:
  print 'AAA%s\n' % (field)
else:
  print 'YYY'

1) If I uncomment the commented line, it throws this error:

[Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58]   File
"/var/www/html/angrynates.com/cart/enterProducts2.py", line 138, referer:
http://angrynates.com/cart/enterProducts.py
[Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58] elif
types[x][0:3] == 'set':, referer:
http://angrynates.com/cart/enterProducts.py
[Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58]^, referer:
http://angrynates.com/cart/enterProducts.py
[Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58] SyntaxError:
invalid syntax, referer: http://angrynates.com/cart/enterProducts.py
[Tue Dec 29 00:58:10 2009] [error] [client 208.84.198.58] Premature end of
script headers: enterProducts2.py, referer:
http://angrynates.com/cart/enterProducts.py

2) AAA prints out before the following fields:
AAASet(['Extra-small'])
AAASet(['purple:50404D'])

3) YYY *also* prints out twice!!

Here's the complete code once again:
- Show quoted text -


#! /usr/bin/python

import MySQLdb
import cgi
import sys,os
sys.path.append(os.getcwd())
from login import login
from sets import Set

def enterProducts2():
  print '''Content-type: text/html








'''
  form = cgi.FieldStorage()
  store = form.getfirst('store')
  print "" % store
  user, passwd, db, host = login()
  count = 0
  count2 = 0
  db = MySQLdb.connect(host, user, passwd, db)
  cursor = db.cursor()
  cursor.execute('select ID from %s;' % store)
  test = cursor.fetchall()
  if len(test) > 0:
cursor.execute('show columns from %s;' % store)
colNames = [itm[0] for itm in cursor]
types = [itm[1] for itm in cursor]
colNamesWithCommas = ', '.join(colNames)
try:
  cursor.execute('select ID from %s;' % store)
  ids = cursor.fetchall()
  if store == 'prescriptions':
cursor.execute('show tables like "%PersonalData";')
personalDataTables = [itm[0] for itm in cursor]
  else:
personalDataTables = []
  print '%s\n\n' % (store[0].upper() +
store[1:])
  print 'What do you want to do?\n\n'
  print "Add\n"
  print "Update\n"
  print "Delete\n"
  print '\n\n'
  print '\n'
  print '\n'
  print 'Check\n'
  i = 0
  while i < len(colNames):
if i == 0: # This is the ID field
  print '', colNames[i], '\n'
  try:
cursor.execute('describe relationships%s;' % (store[0].upper() +
store[1:]))

Re: subprocess returncode is masked

2009-12-29 Thread Steve Holden
Emmanuel wrote:
> MRAB wrote :
>> Emmanuel wrote:
>>> I'm using Python 2.6 and the new subprocess module to get the exit
>>> value of an external executable. It appears the return value given by
>>>  wait() or poll() operations is masked under Unix: I only get the
>>> lower 8 bits. So an exit value of 0x0402 in the C program will be
>>> seen as 0x02 in Python. And this does not happen on Windows... Any
>>> idea why that is ?
>>>
>> I believe that in Unix the exit code is indeed limited to 8 bits.
> Looks like you're right but the info is difficult to find since it is
> implementation dependent. I finally found it on
> http://en.wikipedia.org/wiki/Exit_status. This is very confusing because
> the parameter type of the exit function is an int ?!

Yes, but the parameter type is a superset of the function's domain.
That's not so unusual - consider math.sqrt(), for example. Its parameter
type is float, but what happens when you call math.float(-3.5)?

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


  1   2   >