Re: Which way is best to execute a Python script in Excel?

2012-07-05 Thread Mark Shroyer
On Thu, Jul 05, 2012 at 03:22:01AM -0400, Maurizio Spadaccino wrote:
> Hi all
> 
> I'm new to Python but soon after a few days of studying its features I
> find it my favourite mean of programming scripts to allow for data
> storing and mining. My idea would be to inplement python scripts from
> inside an excel sheet that would store and fetch data from a Mysql
> database. So i need the script to be launched, say, by pressing a
> button in excel and, for instance, retrieve immediately data from the
> mysql table. For what I found in the net, it seems there are three
> ways to control python from excel: 1) run my python script via shell
> using the Run command in VBA, which seems to me the easiest (but maybe
> slower?) way; 2) creating a COM server, for which I need more training
> since it doesnt appear that easy; 3) via Microsoft Script Control, for
> which I saw some example around where It looks like I can 'simulate' a
> python shell via the 'executeStatement' command.
> 
> What would you suggest would be the more performing way to achieve my
> goals as described above?

One thing you could check out is IronSpread: http://www.ironspread.com/

(Despite the name, it's based on CPython rather than IronPython.)

It presents a simplified interface for communicating with Excel compared
to what you get with win32com / plain OLE automation.  I'm a little hazy
on whether the Python scripts created with this plugin are saved within
the Excel file or somewhere on the local system, though...
-- 
http://mail.python.org/mailman/listinfo/python-list


Problem using py-bt, py-locals, etc. during GDB debugging

2012-12-06 Thread Mark Shroyer
I'm having trouble with the py-bt, py-locals, etc. GDB commands (from
Python's python-gdb.py) while using GDB 7.4 to debug Python 2.7.3; I was
wondering if anyone here could offer advice.

Briefly, py-bt seems to identify the python stack frames correctly, but
shows "(unable to read python frame information)" for each, and likewise
py-locals fails with "Unable to read information on python frame".

The full GDB session is shown here:

https://gist.github.com/4228342#file_gdb_output.txt

My test script is as follows:

from __future__ import print_function
from os import kill, getpid
from signal import SIGINT

def factorial(n):
if n == 0:
# Break into GDB
kill(getpid(), SIGINT)
return 1
else:
return n * factorial(n-1)

if __name__ == "__main__":
n = 10
print("factorial({0}) = {1}".format(n, factorial(n)))

And I'm seeing this with both the following sets of software:

 1. Ubuntu 12.04's python-dbg 2.7.3 and GDB 7.4 packages

 2. Freshly-built copies of GDB 7.5 and Python 2.7.3 (the latter built
with -O0 -g3 in Ubuntu's GCC 4.6.3), after loading that Python's own
copy of python-gdb.py into GDB.

Any ideas?  Thanks...
Mark

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


Re: Problem using py-bt, py-locals, etc. during GDB debugging [solved]

2012-12-06 Thread Mark Shroyer
On Thu, Dec 06, 2012 at 04:39:41PM -0500, Mark Shroyer wrote:
> I'm having trouble with the py-bt, py-locals, etc. GDB commands (from
> Python's python-gdb.py) while using GDB 7.4 to debug Python 2.7.3; I was
> wondering if anyone here could offer advice.
> 
> Briefly, py-bt seems to identify the python stack frames correctly, but
> shows "(unable to read python frame information)" for each, and likewise
> py-locals fails with "Unable to read information on python frame".

OK, I took a closer look at this and I've identified the issue; posting
my fix here in case someone else Googles this.

The problem in my case was that the python-gdb.py extension makes some
fragile assumptions about the format of values it receives from GDB, and
I had the line "set output-radix 16" in my .gdbinit, ultimately
resulting in the extension attempting to convert the string
representation of a hexadecimal number into an integer.

So there are two easy workarounds:

 1. set output-radix 10 in GDB, or

 2. Patch Python 2.7.3's python-gdb.py as follows:

=== 8< =

--- python-gdb.py.orig  2012-12-06 15:12:18.666760664 -0500
+++ python-gdb.py   2012-12-06 19:17:19.588356874 -0500
@@ -1074,7 +1074,11 @@
 
 
 def int_from_int(gdbval):
-return int(str(gdbval))
+int_str = str(gdbval)
+if int_str.startswith("0x"):
+return int(int_str[2:], 16)
+else:
+return int(int_str)
 
 
 def stringify(val):

=== 8< =

I haven't checked to see whether this also applies to the GDB extension
for Python 3, though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem using py-bt, py-locals, etc. during GDB debugging [solved]

2012-12-06 Thread Mark Shroyer
On Thu, Dec 06, 2012 at 07:37:22PM -0500, MRAB wrote:
> On 2012-12-07 00:22, Mark Shroyer wrote:
> >
> > [...]
> >
> >   2. Patch Python 2.7.3's python-gdb.py as follows:
> >
> > === 8< =
> >
> > --- python-gdb.py.orig  2012-12-06 15:12:18.666760664 -0500
> > +++ python-gdb.py   2012-12-06 19:17:19.588356874 -0500
> > @@ -1074,7 +1074,11 @@
> >
> >
> >   def int_from_int(gdbval):
> > -return int(str(gdbval))
> > +int_str = str(gdbval)
> > +if int_str.startswith("0x"):
> > +return int(int_str[2:], 16)
> > +else:
> > +return int(int_str)
> >
> >
> >   def stringify(val):
> >
> > === 8< =
> >
> > I haven't checked to see whether this also applies to the GDB extension
> > for Python 3, though.
> >
> A shorter fix would be:
> 
> def int_from_int(gdbval):
>  return int(str(gdbval), 0)
> 
> 
> Some examples:
> 
>  >>> # Decimal
>  >>> int("12", 0)
> 12
>  >>> # Hexadecimal
>  >>> int("0x12", 0)
> 18
>  >>> # Octal
>  >>> int("012", 0)
> 10
>  >>> # Octal
>  >>> int("0o12", 0)
> 10
>  >>> # Binary
>  >>> int("0b11", 0)
> 3

Nice, I didn't know about that... thanks!

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


RE: How to automatically get the indent level from code?

2013-03-16 Thread Mark Shroyer
I realize this isn't yet precisely what you're asking for, but look at the 
inspect and ast modules:

import ast, inspect

def indent_level():
lineno = inspect.currentframe().f_back.f_lineno

with open(__file__) as source_file:
tree = ast.parse(source_file.read(), filename=__file__)

for node in ast.walk(tree):
if hasattr(node, 'lineno') and node.lineno == lineno:
return node.col_offset

def example_usage():
print("first indent_level() = {0}".format(indent_level()))
if True:
print("second indent_level() = {0}".format(indent_level()))

if __name__ == '__main__':
example_usage()

The indent_level function above returns the textual column offset rather than 
the logical block level you're asking for, e.g.:

first indent_level() = 4
second indent_level() = 8

But hopefully it's a start.

Mark

-Original Message-
From: Python-list 
[mailto:python-list-bounces+mshroyer=awaredigital@python.org] On Behalf Of 
Peng Yu
Sent: Sunday, March 17, 2013 12:53 AM
To: python-list@python.org
Subject: How to automatically get the indent level from code?

Hi,

I want to get the indent level within the code. For example, I want to
print 1 within the while loop as the line is indented 1 level. Is it
possible to get it within python?

while 1:
   #print the level of indent, which is 1 here.

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


Portrait of a "real life" __metaclass__

2007-11-09 Thread Mark Shroyer
I guess this sort of falls under the "shameless plug" category, but
here it is: Recently I used a custom metaclass in a Python program
I've been working on, and I ended up doing a sort of write-up on it,
as an example of what a "real life" __metaclass__ might do for those
who may never have seen such a thing themselves.

http://markshroyer.com/blog/2007/11/09/tilting-at-metaclass-windmills/

So what's the verdict?  Incorrect?  Missed the point completely?
Needs to get his head checked?  I'd love to hear what
comp.lang.python has to (anthropomorphically) say about it.

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


Re: Portrait of a "real life" __metaclass__

2007-11-10 Thread Mark Shroyer
On 2007-11-10, Jonathan Gardner <[EMAIL PROTECTED]> wrote:
> On Nov 9, 7:12 pm, Mark Shroyer <[EMAIL PROTECTED]> wrote:
>> I guess this sort of falls under the "shameless plug" category, but
>> here it is: Recently I used a custom metaclass in a Python program
>> I've been working on, and I ended up doing a sort of write-up on it,
>> as an example of what a "real life" __metaclass__ might do for those
>> who may never have seen such a thing themselves.
>>
>> http://markshroyer.com/blog/2007/11/09/tilting-at-metaclass-windmills/
>>
>> So what's the verdict?  Incorrect?  Missed the point completely?
>> Needs to get his head checked?  I'd love to hear what
>> comp.lang.python has to (anthropomorphically) say about it.
>>
>
> Kinda wordy.

Yeah, my fingers sort of latch onto the keyboard sometimes and just
won't let go.  Sorry about that ;)

> Let me see if I got the point:
>
> - You already had a bunch of classes that did age matching on date
> time objects.
>
> - You were building a class that matched emails.
>
> - You wanted to reuse the code for age matching to do email matching
> (based on the message's age)
>
> - So you wrote a metaclass that replaced the match() method with a
> proxy that would either dispatch to the old match() method (if it was
> a datetime object) or dispatch to the new match() method (which
> matched based on the message's date.)

Close, but not quite.  The proxy *always* dispatches to
AgeSpec.match(), but if the result of that method is an AgeSpec
itself, then the proxy wraps the result back up in a Matcher, which
works out rather conveniently for the rest of the application.

> Sounds Java-y, if that's even a word.

Yeah, you pretty much nailed my original background right there.  On
the other hand, I've also done a lot of work in Perl and C, and
pride myself on striving not to resort to OO patterns where they
aren't really useful.  So let me try to defend my reasoning, if it
is in fact defensible...

> Too many classes, not enough functions. You can tell you are doing
> Java in Python when you feel the urge to give everything a name
> that is a noun, even if it is completely based of a verb, such as
> "matcher". My opinion is that if you want to talk about doing
> something in Python such as matching, starting writing functions
> that match and forget the classes. Classes are for real nouns,
> nouns that can do several distinct things.
>
> What would I have done? I wouldn't have had an age matching class. I
> would have had a function that, given the datetime and a range
> specification, would return true or false. Then I would've written
> another function for matching emails. Again, it takes a specification
> and the email and returns true or false.

There isn't much difference between

  match_calendar_month(2007, 11, message)

and

  m = CalendarMonthMatcher(2007, 11)
  m.match(message)

so of course you're right that, were that all I'm doing with these
matchers, it would be a waste to implement them as classes.  But
take for example two of my app's mailbox actions -- these aren't
their real names, but for clarity let's call them ArchiveByMonth and
SaveAttachmentsByMonth.  The former moves messages from previous
months into an archival mbox file ./archives//MM.mbox
corresponding to each message's month, and the latter saves message
attachments into a directory ./attachments//MM/.  Each of these
actions would work by using either match_calendar_month() or
CalendarMonthMatcher().match() to perform its action on all messages
within a given month; then it iterates through previous months and
repeats until there are no more messages left to be processed.

In my object-oriented implementation, this iteration is performed by
calling m.previous() on the current matcher, much like the
simplified example in my write-up.  Without taking the OO approach,
on the other hand, both types of actions would need to compute the
previous month themselves; sure that's not an entirely burdensome
task, but it really seems like the wrong place for that code to
reside.  (And if you tackle this by writing another method to return
the requisite (year, month) tuple, and apply that method alongside
wherever match_calendar_month() is used...  well, at that point
you're really just doing object-oriented code without the "class"
keyword.)

Furthermore, suppose I want to save attachments by week instead of
month: I could then hand the SaveAttachmentsByPeriod action a
WeekMatcher instead of a MonthMatcher, and the action, using the
matcher's common interface, does the job just as expected.  (This is
an actual configuration file option in the application; the nice
thing about taking

Re: Portrait of a "real life" __metaclass__

2007-11-11 Thread Mark Shroyer
 "syntactic sugar" is, in this case, a means of
organizing my application's behavior into meaningful, simply
understood, and easily adapted units.  A monolithic "match" function
with an ever-increasing number of arguments as I cram in more and
more classes of matching logic?  *That* is what's bound to become
incomprehensible.

> No, you're arguing about the thing I wanted to argue about, so you see
> the point I am trying to make.
>
> It's painful to realize that all those years learning OO design and
> design patterns just to make Java usable are wasted in the world of
> Python. I understand that because I've invested years mastering C++
> and perl before discovering Python. Your solace comes when you embrace
> that and see how much simpler life really is when the language gets
> out of your way.

It's just as harmful as to ignore the occasional usefulness of
object-oriented patterns as it is to abuse them left and right.  My
approach on this project feels right, it produces legible and easily
extensible code, it's been a breeze to test and maintain so far...
if implementing different types of matching logic as classes here is
"wrong" by Python convention (and that would come as a rather big
surprise to me), then I don't want to be right.

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


Re: IronPython faster than CPython?

2007-12-18 Thread Mark Shroyer
In article <[EMAIL PROTECTED]>,
 "Jack" <[EMAIL PROTECTED]> wrote:

> I learned a lot from the other thread 'Is a "real" C-Python possible?' about 
> Python performance and optimization. I'm almost convinced that Python's 
> performance is pretty good for this dynamic language although there are 
> areas to improve, until I read some articles that say IronPython is a few 
> times faster. I find it amazing that something that's written in C and runs 
> on hardware is slower than a .NET app that runs on CLR as managed code:
> 
> http://www.python.org/~jeremy/weblog/031209a.html
> http://blogs.msdn.com/jasonmatusow/archive/2005/03/28/402940.aspx 

You might argue that Python programs executed using CPython "run on 
hardware" to a *lesser* extent than they do when run in IronPython.  In 
either case, your program is parsed and compiled into bytecode (Python 
bytecode or MSIL), then loaded by the Python virtual machine or the .NET 
VM, respectively.  But whereas the Python VM is a bytecode interpreter, 
the .NET VM, like Java, uses just-in-time compilation to translate MSIL 
bytecode to optimized machine code for more efficient execution.  This 
is probably the most important factor in the performance difference 
demonstrated in the above links.

The fact that the IronPython compiler is written in C# and therefore 
runs from the VM, whereas the CPython compiler is compiled straight to 
machine code, is unimportant.  Even if a significant performance 
difference did result from this, keep in mind that the bulk of the 
execution time of any Python app worth profiling is going to be after 
this initial Python-to-bytecode compilation, during the execution of the 
program's bytecode itself.

-- 
Mark Shroyer
http://markshroyer.com/contact/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What can we do about all the spam that the list is getting?

2008-04-16 Thread Mark Shroyer
In article 
<[EMAIL PROTECTED]>,
 Mensanator <[EMAIL PROTECTED]> wrote:

> On Apr 16, 12:01 pm, [EMAIL PROTECTED] wrote:
> > What can we do about all the spam that comp.lang.python is getting?
> > Things are getting pretty bad.
> 
> Buy Google and make them fix it.

I've had pretty good luck with MT-NewsWatcher, a freeware Mac newsreader 
that performs Bayesian spam filtering.  Thunderbird's Usenet reader also 
offers Bayesian filtering, which presumably works just as well for 
classifying Usenet spam as it does at handling email spam.

So download a "real" NNTP client for whatever platform you're on and 
give its spam filter a shot; clearly Google is not interested in 
fighting spam itself.

-- 
Mark Shroyer
http://markshroyer.com/contact/
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: What can we do about all the spam that the list is getting?

2008-04-17 Thread Mark Shroyer
In article <[EMAIL PROTECTED]>,
 Grant Edwards <[EMAIL PROTECTED]> wrote:

> On 2008-04-16, Mark Shroyer <[EMAIL PROTECTED]> wrote:
> > In article 
> ><[EMAIL PROTECTED]>,
> >  Mensanator <[EMAIL PROTECTED]> wrote:
> >
> >> On Apr 16, 12:01?pm, [EMAIL PROTECTED] wrote:
> >> > What can we do about all the spam that comp.lang.python is getting?
> >> > Things are getting pretty bad.
> >> 
> >> Buy Google and make them fix it.
> >
> > I've had pretty good luck with MT-NewsWatcher, a freeware Mac
> > newsreader that performs Bayesian spam filtering.
> > Thunderbird's Usenet reader also offers Bayesian filtering,
> > which presumably works just as well for classifying Usenet
> > spam as it does at handling email spam.
> >
> > So download a "real" NNTP client for whatever platform you're
> > on and give its spam filter a shot; clearly Google is not
> > interested in fighting spam itself.
> 
> Plonking anything posted via google.groups is the simplest
> answer.

Yes, but it's hard to give him that advice with a straight face until 
I've convinced him to stop using Google Groups to begin with ;)

-- 
Mark Shroyer
http://markshroyer.com/contact/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inheritance confusion

2008-04-19 Thread Mark Shroyer
In article <[EMAIL PROTECTED]>,
 Hook <[EMAIL PROTECTED]> wrote:

> Hi,
> 
> I'm having a problem with multiple inheritance - it's clearly something 
> I've missed, but the web pages and books that I've consulted aren't 
> helping, so I'll throw myself on the mercy and collective wisdom of 
> Usenet!
> 
> I've got 4 files (what I'll show has the active content removed for 
> brevity):
> 
> Errors_m.py
> ~~~
> class Errors (object) :
> def __init__ (self, params) :
> pass
> 
> def Error (self, string) :
> return 100
> 
> DT_m.py
> ~~~
> class DT (object) :
> def __init__ (self, params) :
>   pass
> 
> def Date (self, epoch, pattern = 'd mmm ') :
> dt = datetime.datetime.fromtimestamp (epoch)
> 
> Hook_m.py
> ~
> from DT_m import DT
> from Error_m import Errors
> 
> class Hook (Errors, DT) :
> def __init__ (self, params) :
> DT.__init__ (self, params)
> Errors.__init__ (self, params)
> 
> DB_m.py
> ~~~
> from Hook_m import Hook
> 
> class DB (Hook) :
> def __init__ (self, params) :
> Hook.__init__ (self, params)
> 
> 
> And a test script:
> 
> #!/usr/bin/python
> 
> import os
> import re
> import string
> import sys
> 
> from DB_m import DB
> 
> Dict = dict ()
> Dict ['logdir'] = '/tmp/log'
> Dict ['diag']   = 1
> 
> Obj = DB (Dict)
> print dir (Obj)
> Obj.Connect ('Database')
> 
> 
> When I run the script I get this:
> 
> Traceback (most recent call last):
>   File "./3.py", line 20, in 
> Obj.Connect ('Database')
>   File "/mnt/isis/Projects/Python/Learning/DB_m.py", line 102, in Connect
> self.TRACE ("DB::Connect (" + database + "," + mode)
>   File "/mnt/isis/Projects/Python/Learning/Hook_m.py", line 314, in TRACE
> self.DailyLog (msg)
>   File "/mnt/isis/Projects/Python/Learning/Hook_m.py", line 98, in 
> DailyLog
> dt  = self.Date (time ())
> TypeError: 'module' object is not callable
> 
> 
> Googling the "TypeError" message suggests that I've got a module and 
> class with the same name, but I can't see that I have.

For what it's worth, modules actually *are* allowed to contain a class 
of the same name: for example, datetime.datetime.

Anyway, what this error message is actually trying to tell you is that 
you are attempting to call a module as a function somewhere -- and in 
this particular case, I think it's referring to the time module.  Are 
you sure that line 98 in Hook_m.py should not instead be:

dt = self.Date(time.time())

The time module contains a function, time(), which returns the current 
Unix time (another example of a module containing an object of the same 
name, incidentally); but you'll need to call this function as 
"time.time()" unless you have prefaced your code with

from time import time

or

from time import *

Otherwise, the token "time" refers to the time module, which is not 
callable, and not the desired function therein.

-- 
Mark Shroyer, http://markshroyer.com/contact/

   Due to extreme spam, I block all articles originating from Google
 Groups.  If you want your postings to be seen by more readers you will
  need to find a different means of posting on Usenet.
   http://improve-usenet.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is massive spam coming from me on python lists?

2008-04-21 Thread Mark Shroyer
In article <[EMAIL PROTECTED]>,
 Brian Vanderburg II <[EMAIL PROTECTED]> wrote:

> I've recently gotten more than too many spam messages and all say 
> Sender: [EMAIL PROTECTED]  I'm wondering 
> if my mail list registration is now being used to spam myself and 
> others.  If so, sorry, but I'm not the one sending messages if other are 
> getting them even though Sender seems to include my address (I'm not 
> sure about mail headers so I don't know how From: is different than 
> Sender:)  Anyway, it seems to be a bunch of spam emails about cracks and 
> stuff.
> 
> Brian Vanderburg II


Nah, if anyone owes anybody an apology, then whatever mail server admins 
decided that it would be a good idea to accept SMTP messages before 
actually determining that the RCPT TO address is, in fact, deliverable, 
thereby creating a deluge of backscatter and filling up your inbox, 
should be groveling on their knees and begging *you* for forgiveness. ;)

(I haven't seen any such spam messages myself; but the way I'm set up, I 
wouldn't receive them even if that is the case.)

-- 
Mark Shroyer, http://markshroyer.com/contact/
 I have joined others in blocking Google Groups due to excessive
spam.  If you want more people to see your posts, you should use
 another means of posting to Usenet.  http://improve-usenet.org/
-- 
http://mail.python.org/mailman/listinfo/python-list