hello
Hello, I started learning python 2 days ago because the pgsql / plperl is buggy. I think I will love it and I will use it not only for stored sql procedures but also for fun. The only bad thing I found so far is that the tutorial is full of "while True... break". Of course I like John Cleese and Monty Python too. So hi everyone. Mage -- http://mail.python.org/mailman/listinfo/python-list
semicolons
Hello, I amafraid of I will stop using semicolons in other languages after one or two months of python. However I see that python simply ignores the semicolons atd the end of the lines. What's your advice? I don't want to write full-of-typo php scripts but I see the logic of the python syntax too. Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: database in python ?
Andy Dustman wrote: > >Transactions available since 3.23.17 (June 2000) > > Transactions only supported on slow database types like innodb. If you ever tried it you cannot say that mysql supports transactions. No. Last time when I tried mysql 4.x did explicit commit if you simply disconnected inside a transaction block. It was a year ago, but I will never forget it. >>foreign keys, >> >> > >Foreign keys available since 3.23.44 (Oct 2001) > > They are syntactically accepted but not forced. > >>procedures, >> >> > >Stored procedures available since 5.0 (5.0.3 is the current beta) > > It's a beta. > >Postgresql is also a fine database. But note that MySQLdb (the Python >adapter) also has an equivalent mechanism for returning rows as >dictionaries. As for speed: I don't do any benchmarking, but there >should be no substantial speed differences between the two interfaces. > > > I have seen real benchmarks. MySQL 5 is slower than postgresql and it's also slower than firebird if you do some real work. Mage -- http://mail.python.org/mailman/listinfo/python-list
packages
Hello, I read about modules and packages in the tutorial. I think I understand how to use packages and modules, even I know how to create a module (as far I understand it's a simple .py) file , but I don't know how can I create a package and when should I do it. Where should I look for more information? Mage -- http://mail.python.org/mailman/listinfo/python-list
modules and namespaces
Hello, I thought that this will work: #m1.py def f1(): return string.join('a','a') #m2.py def f2(): return string.join('b','b') #main.py import string import m1 import m2 print f1() print f2() - However it doesn't work until I import the string module into m1 and m2 modules. I found in the manual that imported modules will be searched in the container module first. Is it more efficient to import the string module into main and m1 and m2 than importing only into m1 and m2? Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: goto statement
praba kar wrote: >Dear All, > > In Python what is equivalent to goto statement > > > You shouldn't use goto in high-level languages. Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: goto statement
Maxim Kasimov wrote: > WOW, just greate! ... but i'd like to relax at some more interesting > way than to comment each of rows > There are editors that can comment and uncomment blocks. In worst case you can use """ to comment blocks (not elegant but works). Mage -- http://mail.python.org/mailman/listinfo/python-list
exception handling
Hello, def error_msg(msg): sys.exit(msg) try: do_something() if value != my_wish: error_msg('Invalid input') except: print "Fatal IO or Network error" This doesn't work because sys.exit raises an exception. I know that I can define exception types after except, but there might be many. Also I know I can write: except: if str(sys.exc_info()[0]) == 'exceptions.SystemExit': raise But honestly I would like simething like that: except (!SystemExit): Is this possible somehow? Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: goto statement
Michael Soulier wrote: >On 4/20/05, Maxim Kasimov <[EMAIL PROTECTED]> wrote: > > >>but what if i just can't to do this becouse i'm working thrue ssh, and have >>to use >>only installed editors (such as vi) >> >> > >Then learn to use vi. > >:.,+10s/^/# >" comment the next 10 lines > > Or if you don't like that you can use sftpfs with gui editor. Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: goto statement
Maxim Kasimov wrote: > > how do use this here: > > print "hello world" There are cases when you can't do it in any language. php: /* this is a debug comment function1(); function2(); /* this is a normal multiline comment block it ends here */ function3(); */ end of debug comment / if you don't really want to do it / Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: a=[ lambda t: t**n for n in range(4) ]
Scott David Daniels wrote: > > > See, the body of your anonymous function just looks for "the current > value of n" when it is _invoked_, not when it is _defined_. The "lambda functions" was an unclear part of the tutorial I read. Should I use them? Are they pythonic? As far I see they are good only for type less a bit. Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: Python or PHP?
Lad wrote: >Is anyone capable of providing Python advantages over PHP if there are >any? > > I am also new to python but I use php for 4 years. I can tell: - python is more *pythonic* than php - python has its own perfume http://www.1976.com.tw/image/trussardi_python_uomo.jpg and it's nice. php doesn't have any smell - writing python programs you feel much better check this: http://wiki.w4py.org/pythonvsphp.html Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: Python or PHP?
Tim Tyler wrote: >Mage <[EMAIL PROTECTED]> wrote or quoted: > > > >>check this: http://wiki.w4py.org/pythonvsphp.html >> >> > >Good - but it hardly mentions the issue of security - which seems >like a bit of a problem for PHP at the moment. > > I don't think so. Bad programmers are able to write bad programs in any language. Maybe there are more bad php programmers than python programmers and the 70% of the dynamic world wide web is copied from user comments in the php.net/manual. However one of the worst cases is the sql injection attack. And sql injections must be handled neither by php nor by python but by the programmer. I think a website or even a large portal is a well constructed database with triggers and stored procedures and some "echo", "if", "foreach" and "while" in the php code. To me the advantage of python seems to come out when you deal with xml, file handling or when you have to write a native server application for your website. But I am so new here, others may say other things. Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: Python or PHP?
Fredrik Lundh wrote: > >sql injection? what's your excuse for not using data binding? > > I am not sure I truly understand your question. So far my own servers didn't get successful sql injection attack. I just saw some on other sites and did one for demonstration. Avoid them is easy with set_type($value,"integer") for integer values and correct escaping for strings. However, php programmers usually don't initialize their variables because they don't have to do. They even turn off warnings and errors. Our php errorlog at my full time working company is so huge I could cry. We have php-copypasters. I don't know anyone IRL who uses python. So I started to learn it. Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: Handling lists
[EMAIL PROTECTED] wrote: >I have a question on python lists. >Suppose I have a 2D list >list = [[10,11,12,13,14,78,79,80,81,300,301,308]] >how do I convert it so that I arrange them into bins . >so If i hvae a set of consecutive numbers i would like to represent >them as a range in the list with max and min val of the range alone. >I shd get something like >list = [[10,14],[78,81],[300,308]] > > > Maybe: list = [10,11,12,13,14,78,79,80,81,300,301,308] new_list = [] start = 0 for i in range(1,len(list) + 1): if i == len(list) or list[i] - list[i-1] <> 1: new_list.append([list[start],list[i-1]]) start = i print new_list -- http://mail.python.org/mailman/listinfo/python-list
postgresql modules and performance
Hello, I started to write my PostgreSQL layer. I tried pyPgSQL and PyGreSQL. I made a *very minimal* performance test and comparsion with the same thing in php. Table "movie" has 129 record and many fields. I found PyGreSQL / DB-API / fetchall horrible slow (32 sec in my test). PHP did 13 secs and it gave the result in associative array. Maybe I did something bad. pyPgSQL / DB-API raised a futurewarning and didn't worked. pyPgSQL / libpg worked well. I can create php-like dictionary result in 14 secs. Here is the code. It's only a test... Mage -- test.py import mpypg import datetime print 'This is a python postgesql module' db = mpypg.mpypgdb('dbname=test host=localhost') def test(): res = db.query('select * from movie') #print res['fields'] #print res['rows'] #pass def test2(): res = db.query('select * from movie') #print res['fields'] #print len(res['rows']) #print res['rows'] print len(res) print res[1] start = datetime.datetime.now() for i in range(100): test() #pass end = datetime.datetime.now() print end - start test2() -- mpypg.py from pyPgSQL import libpq from pyPgSQL import PgSQL import sys import pgdb mpypg_connect_error_message = 'Could not connect to the database' mpypg_query_error_message = 'Could not run the query' class mpypgdb: 'my database class' def __init__(self,str): try: self.database = libpq.PQconnectdb(str) except: mpypg_error_msg(mpypg_connect_error_message) def query(self,query): try: res = self.database.query(query) fields = tuple([res.fname(i) for i in range(res.nfields)]) rows = [] ''' for name in fields: rows[name] = [] for i in range(res.ntuples): for j in range(len(fields)): rows[fields[j]].append(res.getvalue(i,j)) ''' ''' for j in range(len(fields)): rows[fields[j]] = tuple([res.getvalue(i,j) for i in range(res.ntuples)]) ''' for i in range(res.ntuples): rows.append(dict([(fields[j], res.getvalue(i,j)) for j in range(len(fields))])) res.clear() result = {'fields': fields, 'rows': rows} return result; except: mpypg_error_msg(mpypg_query_error_message) class mpgdb: 'my database class' def __init__(self,str): try: self.database = pgdb.connect(database='test') except: mpypg_error_msg(mpypg_connect_error_message) def query(self,query): try: cursor = self.database.cursor() res = cursor.execute(query) #result = {'fields': fields, 'rows': cursor.fetchall()} result = [cursor.fetchone() for i in range(cursor.rowcount)] #result = cursor.fetchall() return result; except: mpypg_error_msg(mpypg_query_error_message) def mpypg_error_msg(message): 'Database error handler' sys.exit(message) -- http://mail.python.org/mailman/listinfo/python-list
Re: postgresql modules and performance
Reinhold Birkenfeld wrote: > >Have you tried psycopg? > > Thank you. It did the fetchall() in 11 secs and 13 secs with dictionary creating. It's the fastest so far. Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting into Python, comming from Perl.
Miguel Manso wrote: > > > I've tryed to use python some times but I get frustrated very quick. I > get myself many times needing to figure out how to loop through a > list, declare an associative array, checking how to pass named > parameters to functions, and simple things like that. list = [3,5,9,11] list.append(17) for i in list: print i foo = dict() foo['bar'] = 7 foo['trooll'] = 'green' for k,v in foo.iteritems(): print k, v def test(**args): for key in args.keys(): print key, args[key] test(a='apple', c='orange') Mage -- http://mail.python.org/mailman/listinfo/python-list
when will the file be closed
Hello, The question is above: when will these file be closed? for s in file('/etc/passwd'): print s file('/home/mage/test.txt','w').write('foo') Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: How to start python interactively from python script?
[EMAIL PROTECTED] wrote: >Hi, > >I would like to have a python script which does some computations at >the beginning and then changes to interactive mode (by displaying the >prompt). How can I do this? > > popen() Mage -- http://mail.python.org/mailman/listinfo/python-list
popen2 psql
Hello, maybe my question is about linux and not about python. I tried to write a proxy script for "psql" command. I need some query log. I failed to read from the file object. I have tested: a,b = os.popen2('ls') for s in b.readlines(): print s, and: a,b = os.popen2('./pto.py') for s in b.readlines(): print s, popen2 works with 'ls' but it doesn't output anything with the './pto.py'. The 'pto.py' is an existing python script and contains some print. Likely I have the same problem with popening the python script and the psql binary. I can simple popen('psql').write(), but I would like to log everything, so I need stdin and stdout files. Please help. Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: popen2 psql
Klaus Alexander Seistrup wrote: >Mage wrote: > > > >>I tried to write a proxy script for "psql" command. I need some >>query log. I failed to read from the file object. >> >> > >The psql command is probably linked against readline; did you look >in the ~/.psql_history file? > > > Thank you. I will check but what about the python scripts? Why can't I read their *print* output with popen2? Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: So many things that need to be decided....
Heather Stovold wrote: > >I have programmed in the past with a plain text editor too did it for >years. - but I much prefer programming with tools that have syntax coloring, >code completion, and the ability to run from the editor. Debugging tools are >a bonus too. > > My opinion is that the GUI is for those who like the mouse. Since I play many games I am included. After tried some python editors I found Eclipse is mine. I have to tell that I really don't like it, even it's "you must create a project in every simple case" feature annoyes me. However I didn't find any other editor which is able to do all of these: - identing with tabs - showing tabs as 2 spaces - indicating if I use 2 spaces instead of a single tab (bad habit of mine from pascal-php times) - running the scripts - easy switching between source files - regular expression replacing - nice look and good design It should be able to show tabs with some different colors than spaces but it isn't. However other editors fail one or more of these above. Eclipse also supports subversion, but I use the command line svn client. Mage -- http://mail.python.org/mailman/listinfo/python-list
postgresql plpython bug
Hello! create or replace function trigger_keywords_maintain() returns trigger as $$ return 'MODIFY' $$ language plpythonu; update table set id = id where id = 7; ERROR: invalid input syntax for type timestamp: "2005-05-03 14:07:33,279213" I see that Python's timestamp format is not accepted by postgresql. Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: postgresql plpython bug
Jonathan Ellis wrote: > >First, you don't give enough context to see where your python code >generates a timestamp, but in any case it's more of a limitation than a >bug that plpython doesn't try to autoconvert certain datatypes. (Are >you even returning a datetime class, or a string?) > > I gave (almost) all the required information because my function doesn't generates any timestamp. I did not make any work with the timestamp field, it was only sent back with return 'MODIFY' Finally I found the source of the bug. It's not in plypython but it is in plperl. I call a plperl stored procedure in my plpython stored procedure. I won't do it anymore. Below is the sample script which produces the bug. I have to set the locale in plperl same to the server locales because buggy plperl doesn't see the database server locales (which plpsql and plpython does). I sent this issue to the general pgsql mailing list earlier. The funny thing that this plperl bug was one of the reasons of my first python adventures. create table test (id int, date timestamp); create or replace function trigger_test() returns trigger as $$ plpy.info(TD['new']) return 'MODIFY' $$ language plpythonu; create trigger test_update before update on test for each row execute procedure trigger_test(); insert into test values (1, now()); insert into test values (2, now()); update test set id = 3; create or replace function test_perl() returns boolean as $$ use locale; use POSIX qw(locale_h); setlocale(LC_COLLATE,'hu_HU'); setlocale(LC_CTYPE,'hu_HU'); setlocale(LC_NUMERIC,'hu_HU'); return True $$ language plperlu; create or replace function trigger_test() returns trigger as $$ plpy.info(TD['new']) plpy.execute('select * from test_perl()') return 'MODIFY' $$ language plpythonu; update test set id = 4; - CREATE TABLE CREATE FUNCTION CREATE TRIGGER INSERT 9138862 1 INSERT 9138863 1 INFO: ({'date': '2005-05-05 13:20:43.793551', 'id': 3},) INFO: ({'date': '2005-05-05 13:20:43.794401', 'id': 3},) UPDATE 2 CREATE FUNCTION CREATE FUNCTION INFO: ({'date': '2005-05-05 13:20:43.793551', 'id': 4},) ERROR: invalid input syntax for type timestamp: "2005-05-05 13:20:43.793551" --- Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime
Nader Emami wrote: >L.S., > >It is very simple question: Why doesn't work the next statments? > >import datetime > >today = datetime.date.today() > > > Works on python 2.3.5 Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: Strings for a newbie
Malcolm Wooden wrote: >In RB it would be simple: > >Dim s as string >Dim a(-1) as string >Dim i as integer > >s = "This is a sentence of words" >For i = 1 to CountFields(s," ") > a.append NthField(s," ",i) >next > >That's it an array a() containing the words of the sentence. > >Now can I see how this is done in Python? - nope! > > s = "This is a sentence of words" print s.split(' ') Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: without shell
Steven D'Aprano wrote: >On Sun, 12 Jun 2005 23:16:35 +0530, km wrote: > > > >>hi all, >> >>can any linux command be invoked/ executed without using shell (bash) ? >> >> > >py> import os >py> status = os.system("ls") > >Prints the output of ls and stores the exit code into status. > >py> file_list = os.popen("ls").read() > >Stores the output of ls into file_list. > > > These commands invoke shell indeed. Mage -- http://mail.python.org/mailman/listinfo/python-list
cursor positioning
Dear All, I am writing a database import script in python and I would like to print the percentage of the process to the last line. I would like to update the last line at every percent. You know what I mean. How can the cursor be positioned to the last line or somewhere else on the screen? Curses starts with clearing the whole screen and it is overkill. Many modules are on the net but I would like to resolve this simply task with native python. I tried: for something: print chr(8)*20+mystring, but it is nasty and didn't work well. Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: cursor positioning
Larry Bates wrote: >While not "curses" based this class will update screen as you >want. You could use it as a basis upon which to do a curses >version with your cursor positioning. > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/299207 > > > Thank you. This is good for displaying the percentage. However it fails to display this: 100 files read 200 files read 300 files read of course all in the same line and not under the last line. Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: cursor positioning
James Carroll wrote: >I haven't tried this myself, but I think the secret to displaying a >continuously updating %done on the command line is to >print "file 100, 1% done" > >then send exactly 7 backspaces to the terminal, then print 2% done... >so the backspaces will write over the previous text. > >Backspace is a \x08 (ascii character with the value 8.) > >It _could_ work... > > > I tried but printing backslashes won't work in a loop (i think the screen was not refreshed correctly). You can use stdout and flush. Actually I am using this: for (s,i) in [(list[i],i) for i in range(len(list))]: content = file(s).read() sys.stdout.write(chr(8)*35 + str(i + 1) + ' of ' + str(len(list)) + ' files read') sys.stdout.flush() Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: cursor positioning
Danny Milosavljevic wrote: >Hi, > > > >Examples > ESC[2JESC[H same as "clear", clear screen, go home > \rESC[Kprogress %dprobably what you want :) > > Well, like the good old Commodore times :) Thank you. Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: goto
Hayri ERDENER wrote: >hi, >what is the equivalent of C languages' goto statement in python? >best regards > > You really shouldn't use goto. Fortunately you can't. Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: goto
[EMAIL PROTECTED] wrote: >>>> what is the equivalent of C languages' goto statement in python? > >>> You really shouldn't use goto. >>> Fortunately you can't. > >Steven> Of course you can :-) > >Steven> You can write your own Python interpreter, in Python, and add a >Steven> goto to it. > >Maybe easier would be to write a Python assembler (there's probably already >one out there) and just write to Python's virtual machine... > > > Even easier to buy a book about programming. Note that python.org is second in google if you search "programming". So we need a little more work. Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: Python IDE
linuxfreak wrote: >Hi guys, > Got going with python...and i must say its a pretty cool language. >Been using Xemacs to write me programs. But I want an IDE that would >give me auto-completion, online help and the like... Tried SPE and >Dr.Pyhton but the former crashes regulary and the latter is quite >unweildy and does not have a great many features. I quite like the UML >feature found in SPE but the damn thing crashes way too often. What are >you guys using and what do you think is the best IDE...or should i >stick with Xemacs/emacs??? > > > I use Eclipse with the python plugin. It never crashed. I set it to display tabs as two spaces and Eclipse tells if I type spaces instead of tabs by accident. I like it. I had no luck with the code completion, but do you really need that for writing python programs? Mage -- http://mail.python.org/mailman/listinfo/python-list
is this pythonic?
Or is there better way? for (i, url) in [(i,links[i]) for i in range(len(links))]: ... "links" is a list. Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: question about deleting records from mysql
nephish wrote: >Simon Brunning wrote: > > > >>On 27 Jul 2005 04:29:33 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: >> >> >> >> >>>Hey there, >>>sorry , second question in as many days. >>>i am trying to do some stuff with MySQLdb and the thing is, i can >>>select records and such, but when i try to delete them, they dont >>>really go away. >>> >>> >>> >>> >>A fiver says you need to commit your changes. >> >> >> >> >> >ok, do i do that with cursor.commit() ? >thanks > > Yes, or maybe you should write a lightweight layer between the dbapi and your program which can turn on and off the autocommit by calling "commit" and "begin" as query. I did this in my pgsql layer. Using transactions every time is almost as bad as never using them. Mage -- http://mail.python.org/mailman/listinfo/python-list
pain
Hello, I started to learn python some months ago. Mostly for fun, but I replaced php to python in many tools at my company in the last weeks. Because of our boss decision now I have to learn java. I can tell java is one of the worst things including WW2. Even after seeing the light I may vomit when I write java code. Look at this tutorial from java.com: public class BasicsDemo { public static void main(String[] args) { int sum = 0; for (int current = 1; current <= 10; current++) { sum += current; } System.out.println("Sum = " + sum); } } It is "print sum(range(11))" in python. I just had to tell this, sorry for the bandwith. I suggest you to feel lucky if you may use python at your work. Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: pain
Mandus wrote: >Wed, 03 Aug 2005 17:45:34 +0200 skrev Mage: > > >> Hello, >> >>I started to learn python some months ago. Mostly for fun, but I >>replaced php to python in many tools at my company in the last weeks. >> >>Because of our boss decision now I have to learn java. I can tell java >> >> >[snip] > >maybe you can use jython, and tell your boss it's Java. A boss forcing >people to learn and use Java probably have no interest at all ever read >the code himself, so you will probably get away with it. I mean, a >clueless boss... > > Thank you, I will check this out. My company will switch to a jsp site. Isn't jython slower (I mean performance) than java? As well as I understand jython code will be interpreted twice. >or just find another place to work? > > Acceptable but I have some reasons to stay. >Don't code Java, be happy :-) > > I would be surprised if there were more than five python jobs in my country but have to look around. Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: pain
Michael Hoffman wrote: > >I would have used print sum(xrange(11)) myself. > This is why I love python and this list. I can't be as offtopic that you wouldn't be able to say something useful to me about python. Thank you. Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: pain
Terry Reedy wrote: >"Mage" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > > >>Thank you, I will check this out. My company will switch to a jsp site. >>Isn't jython slower (I mean performance) than java? As well as I >>understand jython code will be interpreted twice. >> >> > >I believe only in the sense that Java is interpreted twice: once to compile >to Java bytecode and again, as often as you want, to run the bytecode >(assuming that it is kept around, just as .pyc files are). > > Thank you, I will read it thoroughly instead of just fast-reading the mainpage as last time :) Mage -- http://mail.python.org/mailman/listinfo/python-list