Book recommendations
Can someone recommend a Python book for a newbie and perhaps you have a used one for sale? Thank you. Cordially, west -- http://mail.python.org/mailman/listinfo/python-list
Re: Create a new class on the fly
Alex Martelli wrote: > > Thanks for snipping all the actual helpful stuff I posted, it makes SO > much easier for me to be snide! > > You can find a few examples of me demonstrating the subject of your > interest by searching for my name e.g. on video.google.com; searching > for my name on Amazon will show some books using similar techniques, and > searching for my name on groups.google.com will find about 50,000 posts > many of which exhibit essentially the same approach. Unfortunately, I > can't currently offer such courses commercially while staying employed > as Uber Tech Lead for Google, Inc, but if the monies on offer make it > worth my while for me to drop million bucks worth of stock options, plus > a vigorish for my other comp package _and_ the incredible amount of > happiness I get every day from my job (where I get to interact with > truly brlliant people, who, if and when they "leave an erroneous snippet > in", are GRATEFUL to me for pointing it out, rather than RESENTFUL and > DEFENSIVE), I'll surely consider that most seriously (as long as the > monies in question are in escrow for my personal reassurance). > > Until such conditions should obtain, I'll just have to keep freely > helping the people who are WORTH helping, and poking sarcastic funs at > those who prove themselves ot be a waste of oxygen instead. > > > May you have the life you deserve, I'm new to all this, but I didn't get the impression that sickeningly smug self-satisfaction was a "pythonic" characteristic. Let's hope for a Waco (cults, siege, bloodbath) style conclusion to the Google story. That would be truly (Monty) Pythonic. > Alex > -- http://mail.python.org/mailman/listinfo/python-list
Proxying every function in a module
Hello
I've got a web application with the following structure:
1) module of 100 functions corresponding to user actions (e.g.
"update_profile()", "organisations_list()")
2) a wsgi callable which maps urls to functions eg
/organisations/list/?sort=date_created is mapped to
organisations_list("dateCreated")
3) mapping is performed using inspect.getargspec()
4) a bunch of html generating templates
In the templates I want to generate urls by referencing the function to
which they map, rather than the url, e.g.
Sort By Date Created
In other words, I want to always refer to functions, rather than mixing
up function calls and urls
I would like a class that proxies all the 100 functions in the user
actions module. When a proxied function is called via this class it
should return the url to which it is mapped rather than executing the
user action function.
Sort By Date
Created
should produce:
Sort By Date Created
Obviously, I don't want to write and maintain copies of these 100
functions in another class.
My question is therefore: what is the best way to proxy these 100 functions?
Thanks
Tim Arnold wrote:
> Hi, I'm using ElementTree which is wonderful. I have a need now to write out
> an XML file with these two headers:
>
>
>
> My elements have the root named tocbody and I'm using:
> newtree = ET.ElementTree(tocbody)
> newtree.write(fname)
>
> I assume if I add the encoding arg I'll get the xml header:
> newtree = ET.ElementTree(tocbody)
> newtree.write(fname,encoding='utf-8')
>
> but how can I get the into the tree?
>
> python2.4.1,hpux10,ElementTree1.2.6
>
> thanks,
> --Tim
>
>
>
--
http://mail.python.org/mailman/listinfo/python-list
Proxying every function in a module
Kind and wise fellows,
I've got a web application with the following structure:
1) module of 100 functions corresponding to user actions (e.g.
"update_profile()", "organisations_list()")
2) a wsgi callable which maps urls to functions eg
/organisations/list/?sort=date_created is mapped to
organisations_list("dateCreated")
3) mapping is performed using inspect.getargspec()
4) a bunch of html generating templates
In the templates I want to generate urls by referencing the function to
which they map, rather than the url, e.g.
Sort By Date Created
In other words, I want to always refer to functions, rather than mixing
up function calls and urls
I would like a class that proxies all the 100 functions in the user
actions module. When a proxied function is called via this class it
should return the url to which it is mapped rather than executing the
user action function.
Sort By Date
Created
should produce:
Sort By Date Created
Obviously, I don't want to write and maintain copies of these 100
functions in another class.
My question is therefore: what is the best way to proxy these 100 functions?
Thanks
Tim Arnold wrote:
> Hi, I'm using ElementTree which is wonderful. I have a need now to write out
> an XML file with these two headers:
>
>
>
> My elements have the root named tocbody and I'm using:
> newtree = ET.ElementTree(tocbody)
> newtree.write(fname)
>
> I assume if I add the encoding arg I'll get the xml header:
> newtree = ET.ElementTree(tocbody)
> newtree.write(fname,encoding='utf-8')
>
> but how can I get the into the tree?
>
> python2.4.1,hpux10,ElementTree1.2.6
>
> thanks,
> --Tim
>
>
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Proxying every function in a module
>
> First off, don't attempt to start a new thread by replying to a previous
> one. Many newsreaders will merge the two, confusing the hell out of
> everyone and generally not helping.
>
Ahh, yes. I see what you mean. Explains why it didn't appear the first
time I posted (until later..).
Sorry for bother and thanks for the advice.
> Second, what makes you think you need a module? I'd have thought an
> instance of some user-defined class would have been better, as that way
> you can redefine the __getattr__() method to return appropriate functions.
>
The functions are ported from a java class static methods. I was trying
to be "pythonic" - since my 100 functions don't share state, I thought
they should be packaged as a module rather than as a class of bunch of
effectively static methods.
> This seems to work, though I haven't tested it extensively (i.e. I have
> called one instance precisely once ;-)
>
> >>> import re
> >>> pat = re.compile("([a-z]+)(.+)")
> >>> class myRewriter:
> ... def srt(self, s):
> ... m = pat.match(s)
> ... if not m: raise ValueError(s)
> ... return m.group(1), m.group(2).lower()
> ... def __getattr__(self, name):
> ... n1, n2 = name.split("_")
> ... def f(val):
> ... s1, s2 = self.srt(val)
> ... return "/%s/%s/?sort=%s_%s" % \
> ... (n1, n2, s1, s2)
> ... return f
> ...
> >>> r = myRewriter()
> >>> r.organisations_list('dateCreated')
> '/organisations/list/?sort=date_created'
> >>>
>
> regards
> Steve
>
Genius! Embarrassingly, I hadn't realised that __getattr__() is called
when a method is invoked, thus making the method name (attribute name)
so easily available as a string. I was therefore thinking in terms of
gnarly introspection/reflection things. This is much better.
Thanks very much
--
http://mail.python.org/mailman/listinfo/python-list
Finding decorators in a file
Probably a bit of weird question. I realise decorators shouldn't be executed until the function they are defined with are called, but is there anyway for me to find all the decorates declared in a file when I import it? Or perhaps anyway to find the decorators by loading the file by other methods (with out simply parsing it by hand). Basically what I'm looking for is a way to, given a python file, look through that file and find all the decorators and the associated functions, that includes any arguments that the decorator has. Sorry if this has been asked before but I've googled no end and come up with nothing so far. -- http://mail.python.org/mailman/listinfo/python-list
SMTPLIB & email.MIMEText : Certain charaters in the body stop mail from arriving. Why?
Hello Sending mail with certain characters in the body causes mail never to arrive. Why? e.g if body text has a fullstop "." mail never arrives. I'm using python 4.2 on windows. Harvey # import smtplib from email.MIMEText import MIMEText def mail(serverURL=None, sender='', to='', subject='', text=''): COMMASPACE = ', ' to = COMMASPACE.join(to) msg = MIMEText(text) msg['Subject'] = subject msg['From'] = sender msg['To'] = to mailServer = smtplib.SMTP(serverURL, 25) mailServer.sendmail(sender, to, msg.as_string()) mailServer.quit() print msg.as_string() # Output Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: "Information from ost-cs-emma" From: [EMAIL PROTECTED] To: [EMAIL PROTECTED] Some text Some more text in body - Information in this email including any attachments may be privileged, confidential and is intended exclusively for the addressee. The views expressed may not be official policy, but the personal views of the originator. If you have received it in error, please notify the sender by return e-mail and delete it from your system. You should not reproduce, distribute, store, retransmit, use or disclose its contents to anyone. Please note we reserve the right to monitor all e-mail communication through our internal and external networks. SKY and the SKY marks are trade marks of British Sky Broadcasting Group plc and are used under licence. British Sky Broadcasting Limited (Registration No. 2906991), Sky Interactive Limited (Registration No. 3554332), Sky-In-Home Service Limited (Registration No. 2067075) and Sky Subscribers Services Limited (Registration No. 2340150) are direct or indirect subsidiaries of British Sky Broadcasting Group plc (Registration No. 2247735). All of the companies mentioned in this paragraph are incorporated in England and Wales and share the same registered office at Grant Way, Isleworth, Middlesex TW7 5QD. -- http://mail.python.org/mailman/listinfo/python-list
Python trig precision problem
Hello all, having a small problem with a trig routine using python math module. This code is designed to convert geodetic coordinates to lambert conformal conic coordinates. It implements the formulas found at http://mathworld.wolfram.com/LambertConformalConicProjection.html . The problem is that, at least on my machine, the precision is off to the tune of around 1 km, which is unacceptable. (using the calculator found at http://www.deh.gov.au/erin/tools/geo2lam-gda.html ) Anyone have any ideas? here is the offending code. from math import * def lambert(lat,lon,ref_lat,ref_lon,st_parallel_1,st_parallel_2): earth_radius= 6371.9986 lon*=pi/180.0 lat *=pi/180.0 ref_lon*=pi/180.0 ref_lat *=pi/180.0 st_parallel_1 *=pi/180.0 st_parallel_2 *=pi/180.0 def sec(theta): return 1.0/cos(theta) def cot(theta): return 1.0/tan(theta) n = log( cos( st_parallel_1 ) * sec( st_parallel_2 ) ) / ( log( tan ( pi / 4.0 + st_parallel_2 / 2.0 ) * cot( pi / 4.0 + st_parallel_1 / 2.0 ) ) ) F = ( cos( st_parallel_1 ) * tan ( pi / 4.0 + st_parallel_1 / 2.0 ) ** n ) / n rho = F * ( cot ( pi / 4.0 + lat / 2.0 ) ** n ) ref_rho = F * ( cot ( pi / 4.0 + ref_lat / 2.0 ) ** n ) x = rho * sin( n * ( lon-ref_lon ) ) y = ref_rho - ( rho * cos( n * ( lon-ref_lon ) ) ) return earth_radius*x,earth_radius*y ### lat,lon=35,-90 print lambert(lat,lon,40,-97,33,45) -- http://mail.python.org/mailman/listinfo/python-list
Recommendation for Web Framework
Let me explain my situation a bit. I've been contracted to develop an ecommerce site. It's nothing too huge but requires a lot of custom development that's not typical for your run of the mill webstore. I've got about three weeks to get the project delivered and I've written quite a bit of code already. I'd like to find some sort of tool to generate some of the repetative bits like data management (think phpMyAdmin but for Python) so I don't have to write a stupid mangement script for every single module (users, customers, inventory, etc). I know there's tools out there that will do this for ASP code with a SQL server backend, but I haven't seen anything for Python outside of the web application frameworks. Ideally, I'd like something like Ruby on Rails that would provide scaffolding support so I can bootstrap the system, so to speak. I've looked at Django, but the client is only running Apache 1.x and Python 2.3. I've given Turbo Gears a try, but couldn't get SQLObject to run (threw an error that I didn't have time to struggle with). So basically I need something with low dependencies, easy to develop in, and releatively easy to deploy. Anyone have any recommendations? I really need something on which I can ramp up quickly to get this project out of the door fast. I'm also a framework newbie, so I know there's a learning curve. Any input is appreciated, thank you. - james -- http://mail.python.org/mailman/listinfo/python-list
CTYPES structure passing
Hi
I'm hoping someone here can tell me what I'm doing wrong as I've spent
the best part of three days reading docs and trying code.
I want to port a windows DLL that controls a USB camera to Python
using C types. I've happily converted a lot of the functions but am
stuck with one vital function that requires a structure to be passed
to the DLL for filling with data.
I have the C declarations
CAM_API BOOL LUCAM_EXPORT LucamGetFormat(HANDLE hCamera,
LUCAM_FRAME_FORMAT *pFormat, FLOAT *pFrameRate);
where the LUCAM_FRAME_FORMAT is defined as
typedef struct {
ULONG xOffset; // x coordinate on imager of top left corner of
subwindow in pixels
ULONG yOffset; // y coordinate on imager of top left corner of
subwindow in pixels
ULONG width; // width in pixels of subwindow
ULONG height;// height in pixels of subwindow
ULONG pixelFormat; // pixel format for data
union
{
USHORT subSampleX;// sub-sample ratio in x direction in pixels
(x:1)
USHORT binningX; // binning ratio in x direction in pixels (x:1)
};
USHORT flagsX; // LUCAM_FRAME_FORMAT_FLAGS_*
union
{
USHORT subSampleY; // sub-sample ratio in y direction in pixels
(y:1)
USHORT binningY; // binning ratio in y direction in pixels (y:1)
};
USHORT flagsY; // LUCAM_FRAME_FORMAT_FLAGS_*
} LUCAM_FRAME_FORMAT;
In my Python code I have
#- Frame format
class FRAME_FORMAT_UNION(Union):
__fields__ = [("subSample", c_ushort), # sub-sample ratio in x
direction in pixels (x:1)
("binning", c_ushort )]# binning ratio in x
direction in pixels (x:1)
class LUCAM_FRAME_FORMAT(Structure):
__fields__ = [( "xOffset", c_ulong), # x coordinate on imager of
top left corner of subwindow in pixels
( "yOffset", c_ulong), # y coordinate on imager of
top left corner of subwindow in pixels
( "width", c_ulong), # width in pixels of
subwindow
( "height", c_ulong),# height in pixels of
subwindow
( "pixelFormat", c_ulong), #pixel format for data
( "XUnion", FRAME_FORMAT_UNION),
( "flagsX", c_ushort), # LUCAM_FRAME_FORMAT_FLAGS_*
( "YUnion", FRAME_FORMAT_UNION),
( "flagsY", c_ushort)]
LP_FRAME_FORMAT = POINTER(LUCAM_FRAME_FORMAT)
and make the call like this
FrameRate = c_float(0)
FrameFormat = LUCAM_FRAME_FORMAT()
FrameFormat.xOffset = 0
FrameFormat.yOffset = 0
FrameFormat.width = 0
FrameFormat.height = 0
FrameFormat.pixelFormat = 0
FrameFormat.XUnion = 0
FrameFormat.flagsX = 0
FrameFormat.YUnion = 0
FrameFormat.flagsY = 0
lucam = windll.lucamapi
error = bool()
GetFormat = lucam.LucamGetFormat
GetFormat.argtypes = ( HANDLE, LP_FRAME_FORMAT, POINTER(c_float) )
GetFormat.restype = BOOL
error = GetFormat (hCamera, FrameFormat, FrameRate )
On return the FrameRate parameter is correct but the FrameFormat
structure no longer has the any field attributes. Further more it
often generates an access violation, apparently in python26.dll. I
guess the call is writing to unallocated memory but I have no idea
why.
Can anyone help?
--
http://mail.python.org/mailman/listinfo/python-list
Python 3.5 Cross Compile for ARM
Hi. Can anyone point me to documentation/instructions for cross compiling Python 3.5? I'm trying to compile Python for an ARM processor. It seems like something broke with cross compilation in 3.5 and a patch was created (https://bugs.python.org/issue22359), but I don't even know where to begin with this. If anyone could help me out, I would appreciate it. Thanks. -- https://mail.python.org/mailman/listinfo/python-list
Re: Division issue with 3.8.2 on AIX 7.1
I need off this list please. I don’t even have this. On Wed, Jun 3, 2020 at 11:30 PM Albert Chin < [email protected]> wrote: > On Wed, Jun 03, 2020 at 08:11:17PM -0400, Dennis Lee Bieber wrote: > > On Tue, 2 Jun 2020 12:26:16 -0500, Albert Chin > > declaimed the following: > > > > >I've built Python 3.8.2 on AIX 5.2, 5.3, 6.1, and 7.1. I am seeing > > >different results for the following Python program: > > > $ python3 -c "eps = 2.0 ** -53.0; tiny = 2.0 ** -1022.0; \ > > >print ((1.0 - eps) / tiny * 4.0)" > > > > > >I get the correct result, 1.7976931348623157e+308, on AIX 5.2, 5.3, > > >and 6.1. But, on 7.1, I get "inf". > > > > > >Anyone know where can I look in the Python source code to investigate > > >this? > > > > Have you considered that it might be something in an underlying C > > library (especially for the double-precision exponentiation)? > > On Wed, Jun 03, 2020 at 08:44:47PM -0700, Miki Tebeka wrote: > > > Anyone know where can I look in the Python source code to investigate > > > this? > > > > Probably around > > https://github.com/python/cpython/blob/master/Objects/floatobject.c > > Thanks to both of you. I applied some updated OS patches and the > problem went away. > > -- > albert chin ([email protected]) > -- > https://mail.python.org/mailman/listinfo/python-list > -- Mrs. Sherry West Owens Cross Roads Elementary -- https://mail.python.org/mailman/listinfo/python-list
ooopy: newbie cannot get basic functionality to work
Hi list,
I am new to python and old to coding (as in I did it a long time
ago). I've got a task that cries out for a scripted solution --
importing chunks of ASCII data dumps from a point-of-sale system into
an openoffice.org spreadsheet. What a great chance for me to get my
coding skills back and learn python too!
I have attempted to get ooopy to work for me and have run into
problems at the first step. Google returns not much on ooopy and the
common example, from help (OOoPy) is:
| from OOoPy import OOoPy
| >>> o = OOoPy (infile = 'test.sxw', outfile = 'out.sxw')
| >>> e = o.read ('content.xml')
| >>> e.write ()
| >>> o.close ()
okay here goes:
>>> from OOoPy import OOoPy
Traceback (most recent call last):
File "", line 1, in ?
ImportError: No module named OOoPy
hmm... okay how about:
>>> from ooopy import OOoPy
>>> dir (OOoPy)
['ElementTree', 'OOoElementTree', 'OOoPy', 'StringIO', 'VERSION',
'ZIP_DEFLATED', 'ZipFile', '__builtins__', '__doc__', '__file__',
'__name__', '_autosuper', 'autosuper', 'fromstring', 'mkstemp', 'os']
okay that works. now:
>>> o = OOoPy (infile='/home/andrew/monthly.ods')
Traceback (most recent call last):
File "", line 1, in ?
TypeError: 'module' object is not callable
>>>
that's not good. at this point, I'm stuck. I've tried various
permutations of this with no other results. It also fails on the
sample file provided with ooopy, test.sxw.
I have seen one solution using zip to get the contents of the oo.o
file which would probably work but would like to figure this out.
I have installed ooopy using setup.py provided with the package on
debian sid, up-to-date. And I've tried it using python 2.3 and 2.4.
any help appreciated. thanks
A
>>>import sys
>>> sys.path
['', '/usr/lib/python24.zip', '/usr/lib/python2.4',
'/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk',
'/usr/lib/python2.4/lib-dynload',
'/usr/local/lib/python2.4/site-packages',
'/usr/lib/python2.4/site-packages',
'/usr/lib/python2.4/site-packages/PIL',
'/var/lib/python-support/python2.4']
>>> sys.modules
{'tokenize': , 'copy_reg': , 'sre_compile': ,
'ooopy.StringIO': None, '_sre': ,
'__main__': , 'ooopy.os': None, 'site':
, '__builtin__':
, 'elementtree.ElementTree': ,
'encodings': , 'array': , 'pydoc': , 'posixpath': , '_random':
,
'imp': , 'tempfile': , 'errno': , 'binascii': , 'encodings.codecs':
None, 'sre_constants': , 're': , 'encodings.latin_1': ,
'collections': , 'os.path': , '_codecs':
, 'opcode': , 'encodings.exceptions': None, 'sre':
, 'math': , 'fcntl':
,
'stat': ,
'zipimport': , 'string': , 'inspect': , 'warnings': , 'encodings.types':
None, 'UserDict': , 'ooopy.Version': ,
'zipfile': ,
'repr': , 'sys':
, 'ooopy.elementtree': None,
'ooopy.tempfile': None, 'itertools': , 'codecs': , 'readline': ,
'elementtree': ,
'ooopy.OOoPy': , 'types': , 'struct': , 'elementtree.string':
None, 'thread': , 'StringIO': , 'ooopy.zipfile':
None, 'strop': , 'signal': , 'zlib': , 'elementtree.ElementPath':
,
'random':
signature.asc
Description: Digital signature
--
http://mail.python.org/mailman/listinfo/python-list
Re: ooopy: newbie cannot get basic functionality to work
On Sat, Dec 09, 2006 at 09:42:40PM -0600, Paul Watson wrote: > Andrew Sackville-West wrote: > > Hi list, > > > > I am new to python and old to coding (as in I did it a long time > > ago). I've got a task that cries out for a scripted solution -- > > importing chunks of ASCII data dumps from a point-of-sale system into > > an openoffice.org spreadsheet. What a great chance for me to get my > > coding skills back and learn python too! > > The openoffice.org spreadsheet tool can read a CSV file. How about > producing that first, just so you have something that works. I agree, > this sounds like a nice way to dive into Python, but you might want > something that works first, even if it is not elegant. absolutely a good idea. I'm just thinking back to when I automated this under windows/quattro pro/whatever-corel's-script is and wanted to return those blissful days. But I suppose, modularising the thing properly, I could but whatever "backend" into it I want. (seems funny to use the idea of a backend with something so trivial. And I still want to get ooopy working. I feel there is something simple and fundamental I am missing here in getting this working at the most basic level. thanks A signature.asc Description: Digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: ooopy: newbie cannot get basic functionality to work
On Sat, Dec 09, 2006 at 09:30:32PM -0800, John Machin wrote: > > Andrew Sackville-West wrote: > > > > >>> o = OOoPy (infile='/home/andrew/monthly.ods') > > Traceback (most recent call last): > > File "", line 1, in ? > > TypeError: 'module' object is not callable > > >>> > > OK, so that tells you that ooopy.OOoPy is a *module*, and it contains > *another* gizmoid named OOoPy. ah ha! I knew it was something fundamental. its those technical terms that throw me ;-) (gizmoid). > > [snip] > > >>> sys.modules > [snip] > > 'ooopy.OOoPy': > '/usr/lib/python2.4/ooopy/OOoPy.py'>, > > Uh-huh. Confirmation that ooopy.OOoPy is a module. > > Try: > > from ooopy import OOoPy > o = OOoPy.OOoPy(infile='/home/andrew/monthly.ods') > > BTW, is that package being maintained? Did you ask the maintainer? Any > response? > I wondered about that when I was looking at it. It was last updated about a year ago which isn't bad as far as some projects go... heh. No I didn't go after the maintainer. I'm also looking at maybe using ElementTree directly as ooopy is a pretty thin wrapper anyway. anyway, thanks for the help. I can now do fun things like for n in o.getiterator(): and so forth. A signature.asc Description: Digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: speed of python vs matlab.
On Wed, Dec 13, 2006 at 04:07:20PM -0800, Chao wrote: > I've been trying to develop some numerical codes with python, however > got disappointed. > > A very simple test, > > a = 1.0 > > for i in range(1000): > for j in range(1000): >a = a+1 > > unfortunately, it took 4.5 seconds to finish(my machines is fine. P4 > 3.0G, 1G RAM, it varies according to machine configuration, but should > be in the same level) somethings not right there. [EMAIL PROTECTED]:~$ cat pytimetest.py a=1.0 for i in range (1000): for j in range (1000): a=a+1 [EMAIL PROTECTED]:~$ time python pytimetest.py real0m0.534s user0m0.528s sys 0m0.000s [EMAIL PROTECTED]:~$ cat /proc/cpuinfo | grep name model name : Intel(R) Celeron(R) CPU 2.53GHz [EMAIL PROTECTED]:~$ uname -a Linux debian 2.6.18-3-686 #1 SMP Mon Dec 4 16:41:14 UTC 2006 i686 GNU/Linux A signature.asc Description: Digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: automatically grading small programming assignments
On Fri, Dec 15, 2006 at 06:44:37AM +, Dennis Lee Bieber wrote: > On Thu, 14 Dec 2006 12:27:07 -0500, Brian Blais <[EMAIL PROTECTED]> > declaimed the following in gmane.comp.python.general: > > > > I envision a number of possible solutions. In one solution, I provide a > > function > > template with a docstring, and they have to fill it in to past a doctest. > > Is there a > > good (and safe) way to do that online? Something like having a student > > post code, > > and the doctest returns. I'd love to allow them to submit until they get > > it, logging > > each attempt. > > > I have some problems with the concept behind the last sentence... It > encourages brute-force trial&error coding (unless you are going to tell > them that each submittal gets logged, AND that multiple submittals will > reduce the final score they get for the assignment). its been decades since I was in a programming course... salt accordingly. Whenever I learn a new language, I spend a LOT of time just hacking stuff and seeing what it does -- learning syntax and effects by trial and error. Since I already know (okay, knew) good coding practice, the resulting code would not look like it had been hacked together in such a manner, but if I was graded on how many times I executed a bit of code, I'd fail right out. Now, maybe in the second or third semester of a particular language, that might make sense -- the student should already understand syntax and effects well enough to avoid that stuff. .02 from a python newb. A signature.asc Description: Digital signature -- http://mail.python.org/mailman/listinfo/python-list
MySQLdb, lots of columns and newb-ness
Hi list,
I've tried, lots of interpreter testing and google grepping to figure
this out and I think I'm missing something fundamental.
I have an ascii data dump from a POS system that has 131 fields in a
single column in a flat file. I can easily open the file, read in the
data and assemble it into various formats. okay. what I *want* to do
is insert each of these fields into a mysql database that has 132
columns that correspond to the 131 fields in the ascii file (plus one
for the date).
I can successfully connect to mysql and do stuff to my tables my
specific problem is how to efficiently put those 132 fields into the
thing. All I have been able to figure out is really ugly stuff like:
build the mysql statement out of various pieces with appropriate
commas and quote included. stuff like (not tested)
for field in f.read():
row+=field[:-2]+", "
stmt="insert into daily values "+row")"
cursor.execute(stmt)
(the slice is to kill a cr/lf on each one)
that seems really kludgey to me.
I've also tried building tuples and lists and then using this
cursor.execute("insert into daily values (%s)", values)
with no luck. it appears to me that I have to put in all 132 '%s' in
order to make that work and that just seems stupid.
I suppose I could build a list of the column names:
columns=('Asales', 'Bsales', 'Csales' ...)
and bring in the data as a list and then
for col in range(len(columns)):
cursor.execute("insert into daily (%s) values (%s)",
(columns[col], data[col]))
but again, that doesn't seem too pythonic.
any suggestions are greatly appreciated.
A
signature.asc
Description: Digital signature
--
http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb, lots of columns and newb-ness
On Tue, Dec 19, 2006 at 07:34:58PM -0800, Todd Neal wrote:
> Andrew Sackville-West wrote:
> >
> > I can successfully connect to mysql and do stuff to my tables my
> > specific problem is how to efficiently put those 132 fields into the
> > thing. All I have been able to figure out is really ugly stuff like:
> > build the mysql statement out of various pieces with appropriate
> > commas and quote included. stuff like (not tested)
> >
>
> I just started looking into Python myself, so someone can probably
> clean this up or suggest a better way, but this may work:
okay, let me run through this and see if I understand:
>
>
> import MySQLdb
>
> fields = ["field1\r\n","field2\r\n","field3\r\n"]
build a list of data fields to be inserted (whatever method)
>
> def escapeAndQuote(x):
> return "\"%s\"" % MySQLdb.escape_string(x)
not at the right machine to read up on this but obviously it cleans up
the strings and inserts the quotes around each field.
>
> values = ", ".join([escapeAndQuote(f[:-2]) for f in fields])
crap. I knew about .join. that was really the part I was missing.
> q = "insert into daily values(%s)" % values
>
make the query statement.
>
> In testing I got:
>
> >>> fields = ["field1\r\n","field2\r\n","field3\r\n"]
> >>> values = ", ".join([escapeAndQuote(f[:-2]) for f in fields])
> >>> values
> '"field1", "field2", "field3"'
> >>> q = "insert into daily values(%s)" % values
> 'insert into daily values("field1", "field2", "field3")'
>
cool! thanks Todd.
A
>
>
> Todd
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
signature.asc
Description: Digital signature
--
http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb, lots of columns and newb-ness
On Wed, Dec 20, 2006 at 07:00:38AM -0800, Ant wrote: > > > On Dec 20, 5:20 am, Andrew Sackville-West <[EMAIL PROTECTED]> > wrote: > > > >>> values = ", ".join([escapeAndQuote(f[:-2]) for f in fields]) > > Obviously this is the appropriate choice since this is a database app. > In general the strip() group of string methods do what you want in a > safe way - assuming you don't care about whitespace: > > >>> s = " test \r\n" > >>> s.strip() > 'test' perfect! [...] > > This way it doesn't matter what your line endings are - you won't be > surprised by missing characters if the data dump changes for any > reason. well, no great chance of the data dump changing, but its a good point. thanks A signature.asc Description: Digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb, lots of columns and newb-ness
On Wed, Dec 20, 2006 at 09:22:59AM +0100, Fredrik Lundh wrote:
> Andrew Sackville-West wrote:
>
> > I've also tried building tuples and lists and then using this
> >
> > cursor.execute("insert into daily values (%s)", values)
> >
> > with no luck. it appears to me that I have to put in all 132 '%s' in
> > order to make that work and that just seems stupid.
>
> on the other hand, hackers just *love* people who think they're too
> clever to do things in a safe and robust way:
>
>http://en.wikipedia.org/wiki/SQL_injection
good point. when I go for world domination and put this thing on the
web, I'll watch for that ;-). seriously though, this is merely an
internal operation in my one man show where I can more easily access
historical sales data.
>
> using parameterized inserts also speeds things up for many databases,
> since the database engine don't have to parse and and analyze the sql
> statement over and over and over again.
>
> to quickly generate the parameter list, use string repeat to create the
> parameter list:
>
>params = "(" + ",".join(["%s"]*len(values)) + ")"
>cursor.execute("insert into daily values " + params, values)
>
okay. this is great. thanks!
> you probably want to do some normalization work on your database too,
> but that's another story.
>
indeed. there is definitely some duplicated data, or rather derived
data (if that's the right term), but not a whole lot. I suppose I will
get to that sooner or later. first thing, for me, is to get the data
into something more useable than a bunch of flat files on another
machine on my lan.
thanks a bunch for your pointers.
A
signature.asc
Description: Digital signature
--
http://mail.python.org/mailman/listinfo/python-list
