Re: [Tutor] Looking for HOWTO's
Maybe this is Off-Topic but I found recently a perfect repository of python tutorials at: http://www.awaretek.com/tutorials.html Ced. -- Cedric BRINER ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] interactif or not
hi, How can I know if a script is launched interactively or not because I'd like to make a script verbose or not depending if it is executed as interactive or not. eg. If I invoke it in a shell.. then it can be verbose If it is launched from a crontab.. then it is less verbose. Ced. -- Cedric BRINER ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Postgresql+Python -tutorial?
Hi! I've been using MySQL up this day, but would like to convert my program to use Postgresql. There seems to be awful lots of tutorials for MySQL+Python, but not so many for Postgresql+Python. Where should I start? I'm not very good at database things, but have written some little programs with MySQL+Python/Php/Java. So, if you have some good tutorials or something else info, I'd be glad to know! Oh, I can install additional modules, but it would be great if Ubuntu had them... Thanks! -- Olli Rajala <>< Tampere, Finland http://www.students.tut.fi/~rajala37/ "In theory, Theory and Practice should be the same. But in practice, they aren't." - Murphy's Proverbs ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Py2exe Problem
Traceback (most recent call last): > File "NovusExtension.pyw", line 8, in ? > File "Pmw\__init__.pyc", line 28, in ? > WindowsError: [Errno 3] El sistema no puede hallar la ruta especificada: this: > WindowsError: [Errno 3] El sistema no puede hallar la ruta especificada: is spanish for: WindowsErrorL [Errno 3] The system can not find the file/directory specified. There are better ways of saying that.. but that's simple enough, is it? Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Py2exe Problem
Hey Thanks for the docs I finally was able to make a good compilation After I freezed Pmw into pmw.py I had to restart Python (Ctrl-Alt-Del and terminate all python process that were running, by the way why they still stay there and how can I terminate them?) and only then the compilation didn't include the Pmw library inside the dist folder that py2exe creates. But I made a compilation a few months before (I didn't remember how to compile with Pmw) and I remembered that I had to copy inside the dist folder all the images I was using and of course de pmw.py and pmwblt.py and pmwcolor.py also This is in case you want to make a compilation and you have the same problems I had Best Regards to all Alberto >From: [EMAIL PROTECTED] >To: "tutor@python.org" >Subject: Re: [Tutor] Py2exe Problem >Date: Fri, 03 Jun 2005 10:06:18 +1200 (NZST) > >Quoting Alberto Troiano <[EMAIL PROTECTED]>: > > > I'm having a problem with Py2exe. > > I created the executable but when I try to execute it it gives the > > following > > error: > > > > Traceback (most recent call last): > > File "NovusExtension.pyw", line 8, in ? > > File "Pmw\__init__.pyc", line 28, in ? > > WindowsError: [Errno 3] El sistema no puede hallar la ruta especificada: > > > > 'C:\\Documents and > > Settings\\percy.IMPOR-FERNANDO\\Escritorio\\NovExt\\dist\\library.zip\ > > \Pmw/*.*' > >It might help if you translated that error message :-) > >But, I will make one guess, since I see the problem is to do with Pmw: > > >From this page: http://pmw.sourceforge.net/doc/dynamicloader.html > >""" > When Pmw is first imported, an instance of PmwLoader is created and >placed into >sys.modules['Pmw']. From that point on, any reference to attributes of the >Pmw >'module' is handled by the loader. The real Pmw package is stored in >sys.modules['_Pmw']. > >... > > Freezing Pmw > >Since the dynamic loader requires that Pmw be installed at run time, it can >not >be used when freezing Pmw. In this case, a single module containing all Pmw >code >is required, which can then be frozen with the rest of the application's >modules. The bundlepmw.py script in the Pmw bin directory can be used to >create >such a file. This script concatenates (almost) all Pmw megawidget files >into a >single file, Pmw.py, which it writes to the current directory. The script >is >called like this: > > bundlepmw.py [-noblt] [-nocolor] /path/to/Pmw/Pmw_X_X_X/lib > >The last argument should be the path to the lib directory of the required >version of Pmw. By default, the Pmw.py file imports the PmwBlt and PmwColor >modules and so, to freeze an application using Pmw, you will need to copy >the >files PmwBlt.py and PmwColor.py to the application directory before >freezing. > >If you are sure that your application does not use any of the Pmw.Blt or >Pmw.Color functions, you can use the -noblt or -nocolor options. In this >case >Pmw.py will be modified so that it does not import these module(s) and so >will >not need to be included when freezing the application. > >If your application only uses a few Pmw megawidgets, you can remove the >references to the usused ones in the files list in the bundlepmw.py code. >To >make the change, take a copy of the script and modify it. This will make >the >Pmw.py file smaller. However, be sure that you do not delete megawidgets >that >are components or base classes of megawidgets that you use. >""" > >If you haven't done this, you will need to, otherwise Pmw won't work with >py2exe. > >-- >John. >___ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about "hiding" a function/method in a class
I haven't done much OO in Python yet. For various web apps we write, we usually write up a DB schema in a spreadsheet. Then we write the sql script that would create the tables in the database. I thought it would be neat to save the spreadsheet as a csv file and have python write the sql script. So I started to write the Python program. - #!/usr/bin/env python """ SQLGEN takes a csv file of a database schema and writes the sql script that will create the tables and fields in the database Mike Hansen Jun 2005 """ class DBField(object): def __init__(self, fieldName): self.fieldName = fieldName self.type = "" self.size = 0 self.notNull = False self.unique = False self.references = "" self.default = "" def printField(self): self.fieldStr = "%s %s" %(self.fieldName, self.type) if self.size > 0: self.fieldStr = "%s(%s)" %(self.fieldStr, self.size) if self.notNull: self.fieldStr = "%s NOT NULL" %self.fieldStr if self.unique: self.fieldStr = "%s UNIQUE" %self.fieldStr if self.default: self.fieldStr = "%s DEFAULT %s" %(self.fieldStr, self.default) # if self.references return self.fieldStr def __getattr__(self, attrname): if attrname == "fieldStr": return self.printField() else: raise AttributeError, attrname def main(): pass def test(): areas = DBField("area") areas.type = "VARCHAR" areas.size = 80 areas.notNull = True areas.unique = True print areas.fieldStr stuff = DBField("stuff") stuff.type = "INTEGER" stuff.notNull = True print stuff.fieldStr if __name__ == "__main__": # main() test() --- I was wondering if I should "hide" the printField function, so I or someone else won't do x.printField() in the main program but use the x.fieldStr attribute. If so, how would I do that, def __printField(self):? How would I call it from __getattr__? I know I'm not really hiding it ;just mangling it. On the other hand, I guess it doesn't matter. What do you think? Mike ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about "hiding" a function/method in a class
Mike Hansen wrote: > class DBField(object): > def __init__(self, fieldName): > self.fieldName = fieldName > self.type = "" > self.size = 0 > self.notNull = False > self.unique = False > self.references = "" > self.default = "" > > def printField(self): > self.fieldStr = "%s %s" %(self.fieldName, self.type) > if self.size > 0: > self.fieldStr = "%s(%s)" %(self.fieldStr, self.size) > if self.notNull: > self.fieldStr = "%s NOT NULL" %self.fieldStr > if self.unique: > self.fieldStr = "%s UNIQUE" %self.fieldStr > if self.default: > self.fieldStr = "%s DEFAULT %s" %(self.fieldStr, self.default) > # if self.references > return self.fieldStr > > def __getattr__(self, attrname): > if attrname == "fieldStr": > return self.printField() > else: > raise AttributeError, attrname > --- > > I was wondering if I should "hide" the printField function, so I or someone > else > won't do x.printField() in the main program but use the x.fieldStr attribute. > If > so, how would I do that, def __printField(self):? How would I call it from > __getattr__? I know I'm not really hiding it ;just mangling it. On the other > hand, I guess it doesn't matter. What do you think? Python programmers tend to take the attitude "We're all adults here" towards things like this. We use conventions to put warning labels where appropriate, then trust the client programmer to do what is right for them. So, to answer your direct question, yes, you could call the method __printField(), which nominally hides the name from other modules, or _printField(), which by convention marks the method as for internal use only (a warning label). You would call it from __getattr__() as __printField() or _printField(). (A quick experiment would have answered this part of the question.) However, for your particular usage of dynamically computing the value of a field, there is a better way to do this - use a property. class DBField(object): def _printField(self): ... # Create a read-only fieldStr attribute whose value is computed by _printField() fieldStr = property(_printField) # Remove _printField so it can't be called directly del _printField A few more comments: - The name _printField() is a bit of a misnomer since nothing is printed; _getFieldStr() might be a better name. - Another, simpler way to do this is to define __str__() instead of _printField() and fieldStr; then clients can just call str(field) to get the string representation. This will work well if you don't need any other string representation. - Of course you could also just define getFieldStr() and forget about the fieldStr attribute entirely. This is also a very simple, straightforward approach. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Database connections don't stay alive
Well, I asked about tutorials, but maybe this was not so good day, because it has been quite "silent". :) So, good tutorials are still welcome, though I know now how to connect to the Postgresql database. I just have some problems, though. With MySQL I can do like this: import MySQLdb def connectDB(): try: db = MySQLdb.connect(host='localhost', user='user', db='pictures', passwd='passwd') cursor = db.cursor() return cursor except: print 'Error' cursor = connectDB() cursor.execute('SELECT * FROM categories') print cursor.fetchall() And everything works as I thought. But with Postgre, it seems that the connection don't stay alive. I mean, with the same kind of code: from pyPgSQL import PgSQL def connectDB(): try: db = PgSQL.connect(host='localhost', database='pictures', user='user', password='passwd') return db.cursor() except: print "Error" cursor = connectDB() cursor.execute("SELECT * FROM categories") print cursor.fetchall() The result is: Traceback (most recent call last): File "test.py", line 23, in ? cursor.execute("SELECT * FROM categories") File "/usr/lib/python2.4/site-packages/pyPgSQL/PgSQL.py", line 2992, in execute raise InterfaceError, "execute failed - the cursor is closed." libpq.InterfaceError: execute failed - the cursor is closed. So, what's the solution for this? I saw somewhere some mentions about 'connection pooling', what's that and how I'm supposed to use that? It's quite hard to code when you don't have good manuals and have to put together information from very different sources and try to make it work... For example, this is from a manual I've used: 2.1.3.1 PQconnectdb Syntax: c = PQconnectdb(conninfo) Where conninfo is a string containing connection information. What the heck is 'conninfo', I mean, what's it's syntax? Yeah, I was finally able to figure it out, but it took hours googling, trying and stumbling. Okay, okay, back to business. Hope that someone will be able to help me. :) Yours sincerely, -- Olli Rajala <>< Tampere, Finland http://www.students.tut.fi/~rajala37/ "In theory, Theory and Practice should be the same. But in practice, they aren't." - Murphy's Proverbs ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Database connections don't stay alive
Olli Rajala wrote: > Well, I asked about tutorials, but maybe this was not so good day, > because it has been quite "silent". :) > > So, good tutorials are still welcome, though I know now how to connect > to the Postgresql database. I just have some problems, though. You might want to try asking on the DB-SIG mailing list... http://www.python.org/sigs/db-sig/ Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] insering into lists through slices
Hi, I am a newbie to Python (that's very guessable). I simply fail to understand the semantics of the following piece of code. #assuming ls=[1,2,3,4] >>>ls[1:1]=[5,6] #then ls becomes >>> ls [1, 5, 6, 2, 3, 4] i would be happy to know how it works. Basically, ls[1:1] returns an empty list and assigning [5,6] to it, actually inserts the elements... but how? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] insering into lists through slices
when you operate slice be carefull of the position of pointer which slice the list: L = [0 , 1 , 2 , 3] ^ ^ pos 0 1 That's why : L = [1,2,3] L[0:1] = [7] print L # will replace element 1 L = [1,2,3] L[1:1] = [7] print L # will insert 7 between element 1 and 2 pujo On 6/3/05, venkata subramanian <[EMAIL PROTECTED]> wrote: > Hi, > I am a newbie to Python (that's very guessable). > I simply fail to understand the semantics of the following piece of code. > #assuming ls=[1,2,3,4] > >>>ls[1:1]=[5,6] > #then ls becomes > >>> ls > [1, 5, 6, 2, 3, 4] > > i would be happy to know how it works. > > Basically, ls[1:1] returns an empty list and assigning [5,6] to it, > actually inserts the elements... but how? > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Webbrowser module
I am using the webbrowser module to open a URL in Mozilla. My question is what happens when I exit from Mozilla. I have a script running on a Desktop with WindowsXP and a Laptop also with windowsXP In the first case return from Mozilla is to the function containing the webbrowser command ,in the other case it restarts the whole script. mike p ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] interactif or not
> If I invoke it in a shell.. then it can be verbose > > If it is launched from a crontab.. then it is less verbose. You need to check who the process owner is. That can be done on *Nix by reading the USER environment variable. Cron jobs are usually run under the 'cron' user I believe. Hoever that won;t work if the python script is executed in a shell script that is then executed by a user. Its usually better to make verbosity controllable by a flag - traditionally -v. Thus the default is non verbode and verbosity can be switched on(or even given any one of several levels) as desired. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] insering into lists through slices
On Fri, 3 Jun 2005, venkata subramanian wrote: > I am a newbie to Python (that's very guessable). > I simply fail to understand the semantics of the following piece of code. > #assuming ls=[1,2,3,4] > >>>ls[1:1]=[5,6] > #then ls becomes > >>> ls > [1, 5, 6, 2, 3, 4] > > i would be happy to know how it works. > > Basically, ls[1:1] returns an empty list and assigning [5,6] to it, > actually inserts the elements... but how? Hi Venkata, Actually, this is a gotcha. Usually, when we are doing assignments (=), the left hand side has to be a variable name. For example: ## >>> x = 42 >>> def double(x): ... return x * 2 ... >>> double(3) = 42 SyntaxError: can't assign to function call >>> 2**3 = 8 SyntaxError: can't assign to operator ## So we're not allowed to just put anything on the left hand side, since that wouldn't fit well with the concept of assignment. When we're assigning, we're trying to bind some value to some name or place or thing. The reason that we get those SyntaxErrors about in the example above is because the left hand side wasn't describing a valid place for storing things. With that in mind, let's go back to: ls[1:1] = [5,6] This is a kind of assignment that Python does allow. It doesn't mean to take the left hand side and evaluate it, but instead, it means to squeeze the elements of the right hand side into the place described by the left hand side. This is list slice assignment, and it's a special case. (For the gory details on what is allowed on the right hand side of an assignment, you can take a quick look at the Reference Manual: http://docs.python.org/ref/assignment.html but I wouldn't recommend focusing on it too much.) Anyway, hope that makes some sense. Please feel free to ask more questions. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building an SQL query
On Thu, Jun 02, 2005 at 10:41:20PM +0100, Alan G wrote: > Why not convert the list to a tuple before applying str(): > > str(tuple(ids_to_process)) I'm just getting started with Python and PostgreSQL but I found that str(tuple(valueList)) wouldn't work for me because I had a few values with apostrophes. PostgreSQL needed 'Lion''s Mane' but Python was sending it "Lion's Mane", so I ended up writing this little function: def sqlNice(valueList): count = 1 y = '(' for x in valueList: x = x.replace("'", "''") y = y + "'" + x + "'" if count < len(valueList): y = y + ', ' count = count + 1 y = y + ')' y = y.replace("'NULL'", 'NULL') return y Does anyone see any major stumbling blocks in that? On a side note, I've struggled with PyGreSQL. At first I was using the pg module, but I switched to pgdb when insert() wasn't working for me and I thought I would have less trouble using something that's DB-API compliant. There seemed to be more documentation there, and I figured it's a good idea to go with the standard. However, it does seem like I'm covering ground I'm sure someone else has already crossed when I create these re functions to manipulate queries. For inserts, at least, it seems a Python dictionary should be able to do the job nicely. gabe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] insering into lists through slices
> (For the gory details on what is allowed on the right hand side of an ^ > assignment, you can take a quick look at the Reference Manual: Hi Venkata, Gaaa, I don't know my left from my right. *grin* I meant to say "left" hand side, since that's the target of the assignment. There's no restriction on what can be on the right hand side, except that it needs to be an expression. Best of wishes! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building an SQL query
On Fri, 3 Jun 2005, Gabriel Farrell wrote: > def sqlNice(valueList): > count = 1 > y = '(' > for x in valueList: > x = x.replace("'", "''") > y = y + "'" + x + "'" > if count < len(valueList): > y = y + ', ' > count = count + 1 > y = y + ')' > y = y.replace("'NULL'", 'NULL') > return y > > Does anyone see any major stumbling blocks in that? Hi Gabriel, Hmmm... there's got be something already in PyGreSQL that does most of that, and if there is, let's avoid reinventing the wheel. Let me check... ok, there is an undocumented function in pg.py that does the individual value quotation in pgdb._quote(). It looks like you might be able to get away with: ## def sqlNice(valueList): quotedValues = [str(pgdb._quote(x)) for x in valueList] return '(' + ','.join(quotedValues) + ')' ## That being said, I feel nervous about advocating using an underscored function, since that's a hint that it's not a part of the interface to the pydb module. Maybe you can contact the author and ask if '_quote()' could be renamed to 'quote()', or at least to provide some kind of official access to the quote function. ... Wait a minute. According to the content of the _quote() function, it handles tuples and lists properly: ### pgdb.py, from PyGreSQL-3.6.2 ### def _quote(x): if isinstance(x, DateTime.DateTimeType): x = str(x) elif isinstance(x, unicode): x = x.encode( 'utf-8' ) if isinstance(x, types.StringType): x = "'" + string.replace( string.replace(str(x), '\\', ''), "'", "''") + "'" elif isinstance(x, (types.IntType, types.LongType, types.FloatType)): pass elif x is None: x = 'NULL' elif isinstance(x, (types.ListType, types.TupleType)): x = '(%s)' % string.join(map(lambda x: str(_quote(x)), x), ',') elif hasattr(x, '__pg_repr__'): x = x.__pg_repr__() else: raise InterfaceError, 'do not know how to handle type %s' % type(x) return x ## So you should be able to pass lists without any problems. Can you show us what some of your SQL execution statements have looked like? You should be able to do something like: ## cursor.execute("select name from foo where id in %s", ([1, 2, 3, 4, 5]) ## Best of wishes! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] python and apache....
How do I execute a python script on my apache server? *(I am attempting to install google’s sitemap generator… thanks Chris STATEMENT OF CONFIDENTIALITY:The information contained in this electronic message is intended for the exclusive use of the addressee(s) and may contain confidential information. If you are not the intended recipient of this email, be advised you have received this message in error and that any use, dissemination, forwarding, printing, or copying is strictly prohibited. Please notify TradePoint Systems LLC immediately at (603) 889-3200 and destroy all copies of this message and any attachments. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about "hiding" a function/method in a class
> Subject: > Re: [Tutor] question about "hiding" a function/method in a class > From: > Kent Johnson <[EMAIL PROTECTED]> > Date: > Fri, 03 Jun 2005 09:45:20 -0400 > > CC: > tutor@python.org > > > Mike Hansen wrote: > >> class DBField(object): >> def __init__(self, fieldName): >> self.fieldName = fieldName >> self.type = "" >> self.size = 0 >> self.notNull = False >> self.unique = False >> self.references = "" >> self.default = "" >> >> def printField(self): >> self.fieldStr = "%s %s" %(self.fieldName, self.type) >> if self.size > 0: >> self.fieldStr = "%s(%s)" %(self.fieldStr, self.size) >> if self.notNull: >> self.fieldStr = "%s NOT NULL" %self.fieldStr >> if self.unique: >> self.fieldStr = "%s UNIQUE" %self.fieldStr >> if self.default: >> self.fieldStr = "%s DEFAULT %s" %(self.fieldStr, >> self.default) >> # if self.references >> return self.fieldStr >> >> def __getattr__(self, attrname): >> if attrname == "fieldStr": >> return self.printField() >> else: >> raise AttributeError, attrname >> --- >> >> I was wondering if I should "hide" the printField function, so I or >> someone else won't do x.printField() in the main program but use the >> x.fieldStr attribute. If so, how would I do that, def >> __printField(self):? How would I call it from __getattr__? I know I'm >> not really hiding it ;just mangling it. On the other hand, I guess it >> doesn't matter. What do you think? > > > Python programmers tend to take the attitude "We're all adults here" > towards things like this. We use conventions to put warning labels where > appropriate, then trust the client programmer to do what is right for them. > > So, to answer your direct question, yes, you could call the method > __printField(), which nominally hides the name from other modules, or > _printField(), which by convention marks the method as for internal use > only (a warning label). You would call it from __getattr__() as > __printField() or _printField(). (A quick experiment would have answered > this part of the question.) > > However, for your particular usage of dynamically computing the value of > a field, there is a better way to do this - use a property. > > class DBField(object): > def _printField(self): >... > > # Create a read-only fieldStr attribute whose value is computed by > _printField() > fieldStr = property(_printField) > > # Remove _printField so it can't be called directly > del _printField > > > A few more comments: > - The name _printField() is a bit of a misnomer since nothing is > printed; _getFieldStr() might be a better name. > - Another, simpler way to do this is to define __str__() instead of > _printField() and fieldStr; then clients can just call str(field) to get > the string representation. This will work well if you don't need any > other string representation. > - Of course you could also just define getFieldStr() and forget about > the fieldStr attribute entirely. This is also a very simple, > straightforward approach. > > Kent > Doh, I forgot about properties! If I had read a little more in Learning Python on the page with __getattr__, I might have noticed properties. I might go with the "Simple is better than complex" approach using getFieldStr(). I agree that printField wasn't sounding like a good name. Thanks for the comments. Mike ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Postgresql+Python -tutorial?
> I've been using MySQL up this day, but would like to convert > my program to use Postgresql. I'm curious. Why? Is there some advantage to Postgres over MySql? The reason I ask is that I am torn between these two for my own use. Up until now I've been a happy user of Intebase on both Windows and Linux but I'd like to move my Linux DB to an Opensource one and although Firebird is the obvious choice one of the big two would offer good experience(*). But which one? Oh, I can install additional modules, but it would be great if Ubuntu had them... Ubuntu??? A linux distro maybe? (*) I'm currently using SqlLite for my online tutorial on database programming but the more I use it the less I like it! To the extent that I might change to one of the others even though it means a re-write of the tutorial topic... Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about "hiding" a function/method in a class
> I haven't done much OO in Python yet. For various web apps we write, we usually > write up a DB schema in a spreadsheet. Wow! How exactly do you represent a schema in a spreadsheet? I confess I cannot conceive of such a thing. Can you send a representative sample to illustrate? > create the tables in the database. I thought it would be neat to save the > spreadsheet as a csv file and have python write the sql script. So I started to > write the Python program. You do know that there are lots of ERD programs that allow you to draw the schema as an ERD and generate the SQL DDL directly? In fact even Visio can do that. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] insering into lists through slices
> I simply fail to understand the semantics of the following piece of code. > #assuming ls=[1,2,3,4] > >>>ls[1:1]=[5,6] > #then ls becomes > >>> ls > [1, 5, 6, 2, 3, 4] > Basically, ls[1:1] returns an empty list and assigning [5,6] to > it, actually inserts the elements... but how? ls[1:1] returns whatever lies between ls item 1 and ls item 1 which is nothing. ls[1:1] = [5.6] inserts the contents of [5,6] between ls item 1 and ls item 1 - in other words at index 1 - which results in [1,5,6,2,3,4] So the behaviour of [1:1] is consistent, it refers to the items between index 1 and 1. Similarly ls[2:3] refers to whats between 2 and 3 which is 3 ls[2,3 = [5,6] replaces whats between 2 and 3 with 5,6 so the result is: [1,2,5,6,4] Note that the numbers in a slice refer to the commas not the list indexes (to take a simplistic view, for a more accurate one read the docs onslicing!) HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about "hiding" a function/method in a class
Alan G wrote: >>I haven't done much OO in Python yet. For various web apps we write, > > we usually > >>write up a DB schema in a spreadsheet. > > > Wow! How exactly do you represent a schema in a spreadsheet? > I confess I cannot conceive of such a thing. Can you send a > representative sample to illustrate? > Maybe it's not a "schema" exactly. |Table Name|Fields |Type |Size|Primary Key|Not Null|Unique|Foreign Key| ... |areas |area_id |serial ||x |x |x | | | |area|varchar|80 | |x |x | | | |enabled |boolean|| |x | | | |'s represent each cell. It's just a way to organize your thoughts, and have something a little more readable than an SQ script for a DB schema. There's been less than 20 tables in a database for most of these applications that we write. It's clear enough to see the relations(there's another column references). > >>create the tables in the database. I thought it would be neat to > > save the > >>spreadsheet as a csv file and have python write the sql script. So I > > started to > >>write the Python program. > > > You do know that there are lots of ERD programs that allow you to draw > the schema as an ERD and generate the SQL DDL directly? In fact even > Visio > can do that. > > Alan G. > Can you point me to some Open Source/Free ERD programs that work with Postgre?(I'll google after I send this message.) I'd certainly would like to look at ways to do this better. Last time I looked at Visio which was Visio 2000, the ERD stuff cost extra and was very unstable. Mike ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Postgresql+Python -tutorial?
I said: > > I've been using MySQL up this day, but would like to convert > > my program to use Postgresql. And then Alan G replied: > I'm curious. Why? > Is there some advantage to Postgres over MySql? Well, I'm not 100% sure. I've been using MySql some years now. It may sound that I know much, but I've done only some very basic programs, so... But I know something about the differences. Quite many system administrator don't think MySQL as Real SQL(tm) database. It has been improved during last years, but it doesn't meet the SQL standards (yet) but Postgresql does that. That's probably the biggest reason. If you want to do it by easy way, use MySQL, there just is so much more tutorials and other info around the Net, but if you want to get system that meet standards, try Postgresql. Oh, and thanks for the guy who suggested me the other list concentrating for databases. I got there the info I needed and now my program is under total refactoring. At least the sql side... ;) > Ubuntu??? A linux distro maybe? Yep. The best of the best of the best. :) http://www.ubuntulinux.org For those who know something about Linux, it's 'Debian loaded with current software'. ;) I mean, it's based on Debian, but the dev cycle is much faster than with Debian. Yours, -- Olli Rajala <>< Tampere, Finland http://www.students.tut.fi/~rajala37/ "In theory, Theory and Practice should be the same. But in practice, they aren't." - Murphy's Proverbs ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building an SQL query (Gabriel Farrell)
The code to update the database should look something like: the_cursor.execute( sql_cmd, data) I am not using postgresql so I do not know the place-holder mark for your module. You can get that from the module documentation. So sql_cmd could be something like "UPDATE my_table SET title= where record_id=" If data gets passed as a tuple (some modules support dict), data is ("Lion's Mane", 12345) For mysql the place-holder is %s, and the code would be the_cursor.execute("UPDATE my_table SET title=%s where record_id=%s", ("Lion's Mane", 12345) ) > I'm just getting started with Python and PostgreSQL but I found that > str(tuple(valueList)) wouldn't work for me because I had a few values > with apostrophes. PostgreSQL needed 'Lion''s Mane' but Python was > sending it "Lion's Mane", so I ended up writing this little function: > > def sqlNice(valueList): > count = 1 > y = '(' > for x in valueList: > x = x.replace("'", "''") > y = y + "'" + x + "'" > if count < len(valueList): > y = y + ', ' > count = count + 1 > y = y + ')' > y = y.replace("'NULL'", 'NULL') > return y > > Does anyone see any major stumbling blocks in that? > > On a side note, I've struggled with PyGreSQL. At first I was using > the pg module, but I switched to pgdb when insert() wasn't working for > me and I thought I would have less trouble using something that's > DB-API compliant. There seemed to be more documentation there, and I > figured it's a good idea to go with the standard. However, it does > seem like I'm covering ground I'm sure someone else has already > crossed when I create these re functions to manipulate queries. For > inserts, at least, it seems a Python dictionary should be able to do > the job nicely. > > gabe -- Lloyd Kvam Venix Corp -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python and apache....
On Fri, 3 Jun 2005, Taylor, Chris wrote: > How do I execute a python script on my apache server? > > *(I am attempting to install google's sitemap generator... Hi Chris, This is more of an Apache configuration question, so you may get better help by asking on an Apache-specific forum. It's not that we don't like getting questions, but we want to keep the content on Tutor focused on learning Python. In any case, here are details on setting up Apache support for Python: http://httpd.apache.org/docs/misc/FAQ.html#CGIoutsideScriptAlias http://httpd.apache.org/docs-2.0/howto/cgi.html The second link, in particular, should be really helpful; when the documentation refers to '.pl', add a '.py' in there too, and you should be ok. *grin* If you have more questions on setting up Apache, again, you'll probably get better answers by asking on a forum like: http://httpd.apache.org/userslist.html Best of wishes to you. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Postgresql+Python -tutorial?
On Fri, 3 Jun 2005, Alan G wrote: > > I've been using MySQL up this day, but would like to convert my > > program to use Postgresql. > > I'm curious. Why? > Is there some advantage to Postgres over MySql? Hi Alan, Yes. The 'MySQL Gotchas' page details specifically some of the tricky areas that are MySQL-specific: http://sql-info.de/mysql/gotchas.html Postgres behaves a lot like Python in that it'll die early rather than try to guess at what the user means. Postgres handles bad data much more responsibly, and usually doesn't quietly fail the way that MySQL does. Best of wishes! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [Pythoncard-users] TextField bug?
What's tfStudy? I assume it's your textfield.What are the attributes of your text field in the resource file? If you copy and post your code and resource file somewhere like this - http://www.rafb.net/paste/ it'd be a lot easier to figure out. On 6/4/05, John Henry <[EMAIL PROTECTED]> wrote: Thanks for the reply."What's the platform ?"Windows XP fp 2"Version of wxPython"wxPython2.5-win32-unicode-2.5.4.1-py23.exe"and of Python ?"2.3.5 "Do the Pythoncard samples work OK ?"Yes."How about the wxPython demos ?"I don't see any demo ap in the wxPython directory.I am beginning to wonder if it has to do with the keyPress event I am trying. This is what I am doing:#*def on_tfStudy_keyPress(self, event):keyCode = event.keyCodeif keyCode==13 :...some processing code... else:event.skip()#*Without this event, the program doesn't crash.Thanks,--John-Original Message-From: [EMAIL PROTECTED][mailto:[EMAIL PROTECTED]]On Behalf Of Liam ClarkeSent: Friday, June 03, 2005 4:57 AM To: [EMAIL PROTECTED]Subject: Re: [Pythoncard-users] TextField bug?On 6/3/05, Alex Tweedly < [EMAIL PROTECTED]> wrote:[EMAIL PROTECTED] wrote:>Hello list,>>I am having touble with textfield objects in>Pythoncard - I am using the latest version downloaded >from www.pythoncard.org (ver 0.81?).>>I have a no-brainer application and when I run it,the>moment I hit a key when inside a textfield, I get an >exception in class point within _core.py, method>__getitem__. The code says:>>def __getitem__(self, index):>return self.Get()[index]>>and it's choking on indexing out-of-range. >>I've checked and the size of self.Get() is 2 and the>value of index is 2 and that's why it crashed.>>As I said, this is a no-brainer ap (just a textfield>and nothing else). What's wrong? >>>What's the platform ? Version of wxPython, and ofPython ?Do the Pythoncard samples work OK ?How about the wxPython demos ?--Alex Tweedly http://www.tweedly.net--No virus found in this outgoing message.Checked by AVG Anti-Virus.Version: 7.0.322 / Virus Database: 267.5.2 - ReleaseDate: 03/06/2005--- This SF.Net email is sponsored by Yahoo.Introducing Yahoo! Search Developer Network - Createapps using Yahoo!Search APIs Find out how you can build Yahoo! directlyinto your own Applications - visithttp://developer.yahoo.net/?fr=offad-ysdn-ostg-q22005___Pythoncard-users mailing list [EMAIL PROTECTED]https://lists.sourceforge.net/lists/listinfo/pythoncard-users Ai, please post the whole error message, is _core.pypart of the Pythoncard package? I get the feeling it'sa part of wxPython.--'There is only one basic human right, and that is to do as you damn well please.And with it comes the only basic human duty, to takethe consequences.'---This SF.Net email is sponsored by: NEC IT Guy Games. How far can you shotputa projector? How fast can you ride your desk chair down the office luge track?If you want to score the big prize, get to know the little guy.Play to win an NEC 61" plasma display: http://www.necitguy.com/?r=20___Pythoncard-users mailing list[EMAIL PROTECTED] https://lists.sourceforge.net/lists/listinfo/pythoncard-users-- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about "hiding" a function/method in a class
> Maybe it's not a "schema" exactly. > > |Table Name|Fields |Type |Size|Primary Key|Not Null|Unique|Foreign Key| ... > > |'s represent each cell. It's just a way to organize your thoughts, and have > something a little more readable than an SQ script for a DB schema. There's been > less than 20 tables in a database for most of these applications that we write. > It's clear enough to see the relations(there's another column references). OK, so its just a tabular version of the SQL statements, I see. I guess that works for small schenas, I tend to think in terms of several hundred tables in a schema so I forget not everyone is doing those kinds of things! > > You do know that there are lots of ERD programs that allow you to draw > > the schema as an ERD and generate the SQL DDL directly? In fact even > > Visio > Can you point me to some Open Source/Free ERD programs that work with > Postgres? I've never used Postgres but I've used several commercial tools that generate Oracle, SQL Server, Sybase, Informix, DB2, etc. So I suspect they have postgres DDL drivers too. A couple of tools that spring to mind are Popkins System Architect and ERWin. Both are commercial but ERWin can be had for less than a single day of a contractor, and Popkins for less than a week. For any serious database development they pay back almost immediately. I've used Visio too for a smaller system - about 60-70 tables and it worked OK with Oracle. Again it cost less than a day of a staffer's time never mind a contractor! > (I'll google after I send this message.) I'd certainly would like to > look at ways to do this better. I don't know of any free tools but I'll be surprised if there aren't some at least - even if just demos with limited numbers of tables. The commercial tools are so cheap(relatively) that we've never even looked for freeware... Many of the UML tools (BOrland, iLogix, Rational Rose etc) have free trial versions which might be workable, at least to prove the concept before investing real money... Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building an SQL query
>data = {} >data['ids_to_process'] = ['1','2','3','5','7','11'] > >query = ''' >UPDATE my_table > SET state = 'processed' > WHERE id IN ARRAY%(ids_to_process)s >''' >db.execute(query, data) > Sorry. It should look like ... query = ''' UPDATE my_table SET state = 'processed' WHERE id = ANY(ARRAY%(ids_to_process)s) ''' _ Don't just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Postgresql+Python -tutorial?
>> > I've been using MySQL up this day, but would like to convert my >> > program to use Postgresql. >> >>I'm curious. Why? >>Is there some advantage to Postgres over MySql? > >Postgres behaves a lot like Python in that it'll die early rather than try >to guess at what the user means. Postgres handles bad data much more >responsibly, and usually doesn't quietly fail the way that MySQL does. > That describes it pretty well for me. That plus the fact that mysql devs kept saying things like "relational integrity? What do you need that for?" You mean in a relational database? Ah. Hmm _ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building an SQL query (Gabriel Farrell)
On Fri, Jun 03, 2005 at 03:50:09PM -0400, Lloyd Kvam wrote: > The code to update the database should look something like: > the_cursor.execute( sql_cmd, data) > In PyGreSQL/pgdb it's cursor.execute(query[, params]) but it means more or less the same thing because pgdb's paramstyle (I knew from the DB-API[1] to look in help(pgdb) for "paramstyle") is "pyformat". I googled that and found some explanation of pyformat in a message[2] on the DB-SIG mailing list. To quickly summarize that message, pyformat means the string fed to cursor.execute() should follow all the usual rules of Python string formatting. Knowing this, I can now execute my query thusly: >>> import pgdb >>> db = pgdb.connect(database='asdc') >>> cursor = db.cursor() >>> data = { ... 'noteType': None, ... 'note': "Lion's Mane", ... 'recordIdentifier': 'gsf136' ... } >>> cursor.execute("INSERT INTO notes (notetype, note, recordidentifier) \ ... VALUES (%(noteType)s, %(note)s, %(recordIdentifier)s)", data) >>> db.commit() Note that the re matching I had to do before is now taken care of by pgdb (in the _query() function Danny Yoo was kind enough to track down). Before the query gets to PostgreSQL, the None value turns into a NULL and "Lion's Mane" transforms into 'Lion''s Mane'. No re incantations necessary! gabe [1] http://www.python.org/peps/pep-0249.html [2] http://aspn.activestate.com/ASPN/Mail/Message/db-sig/1632007 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] interactif or not
On Fri, 2005-06-03 at 18:45 +0100, Alan G wrote: > > If I invoke it in a shell.. then it can be verbose > > > > If it is launched from a crontab.. then it is less verbose. > > You need to check who the process owner is. > > That can be done on *Nix by reading the USER environment > variable. Cron jobs are usually run under the 'cron' user > I believe. > > Hoever that won;t work if the python script is executed > in a shell script that is then executed by a user. Its usually > better to make verbosity controllable by a flag > - traditionally -v. Thus the default is non verbode and > verbosity can be switched on(or even given any one of > several levels) as desired. > > Alan G. > I think there's a better solution. Here's a quote from the “bash” manual: “An interactive shell is one started without non-option arguments and without the -c option whose standard input and error areboth connected to terminals (as determined by isatty(3)), or one started with the -i option. PS1 is set and $- includes i if bash is interactive, allowing a shell script or a startup file to test this state.” >From above you can examine the “$-” environment variable and check for “i” in it, if it exist you have an interactive “bash” shell, if not you have a non-interactive “bash” shell. However this only works if you're using “bash” (or, maybe, compatible shells like “ksh”, but I'm not sure). The other option would be to check for the environment variable “$PS1”. If it exist, then it's most likely an interactive shell (and I think it works with other shells like “csh”, again I'm not sure as I never worked with any other shell but “bash”). Hope this helpful to someone. Ziyad. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Class reference problem?
for item in function1(args): object = class() if (function2(item)): if (condition): object.variable = value object.function() print object # debug print object #debug The above pseudo code (not really, but close enough) is essentially what I'm playing with. I hope it gives a sense of what I'm trying to do. Any way, the debug lines both print "<__main__.CLASSNAME instance at ADDRESS>" like they should, but the addresses never match up. This leads me to believe that the original object isn't being referenced inside the second if block. This idea is reinforced slightly by the fact that outside of the two if blocks, the variable of the original object has not been modified. I've not encountered this problem before and I really have no idea what I should Google for. So, am I missing something or is there a way to get around this problem? This is being attempted with Python 2.4.1, by the way. I thank you in advance and apologize if I simply have not researched by problem thoroughly enough. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class reference problem?
On Fri, 3 Jun 2005, [EMAIL PROTECTED] wrote: > for item in function1(args): > object = class() > if (function2(item)): > if (condition): > object.variable = value > object.function() > print object # debug > print object #debug > > The above pseudo code (not really, but close enough) is essentially what > I'm playing with. I hope it gives a sense of what I'm trying to do. Hello! Hmmm... you may want to modify the print statements slightly to make it more clear which of the two print statements are being displayed. That is, I'd recommend you distinguish the debug statements by putting some kind of mark, like: ## for item in function1(args): object = class() if (function2(item)): if (condition): object.variable = value object.function() print "inner", object # debug print "outer", object #debug ## As the code stands, it's not clear that 'condition' is ever set to true. When you mention that: > Any way, the debug lines both print "<__main__.CLASSNAME instance at > ADDRESS>" like they should, but the addresses never match up. there is one alternative explanation for what you're seeing: it's possible that all of the print statements are coming off the outer print statement alone, and that neither the 'function2()' nor 'condition' branches are being taken. I just want to make sure you're testing what you think you're testing. *grin* Best of wishes to you! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class reference problem?
[EMAIL PROTECTED] wrote: > for item in function1(args): > object = class() > if (function2(item)): > if (condition): > object.variable = value > object.function() > print object # debug > print object #debug > > The above pseudo code (not really, but close enough) is essentially what > I'm playing with. I hope it gives a sense of what I'm trying to do. > > Any way, the debug lines both print "<__main__.CLASSNAME instance at > ADDRESS>" like they should, but the addresses never match up. Can you post some working code that shows the problem? Thanks, Ken ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class reference problem?
> Hmmm... you may want to modify the print statements slightly to make > it more clear which of the two print statements are being displayed. > As the code stands, it's not clear that 'condition' is ever set to true. /me slaps himself in the forehead. After modifying the print statements as suggested, it turns out that the memory addresses aren't changing. Only the second print statement was executing (as you said might be the case), which would explain why no two printed memory addresses were ever the same. > I just want to make sure you're testing what you think you're testing. I appreciate it. So, thank you! If you hadn't pointed that out, I would probably have continued pulling my hair out over something so minor as an if statement not being executed. Back to bug searching, I guess. Talk about embarrassing. :) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor