From john at fouhy.net Fri Sep 1 00:52:43 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 1 Sep 2006 10:52:43 +1200 Subject: [Tutor] GUI Programing In-Reply-To: References: Message-ID: <5e58f2e40608311552x6591d6c7m4a10d80abb40f4f5@mail.gmail.com> On 01/09/06, Amadeo Bellotti wrote: > I'm going to try some GUI programming does anyone know where the start like > using tk or wx or what ever i want it to it will run on Windows UNIX and Mac > systems can you tell me whats best to use and give me a link to a good > tutorial? Tkinter is (IMO) easier to learn. In particular, check out "Thinking in Tkinter" (google for it); it's an excellent way to learn Tkinter. Tkinter is also very basic. wx has many more widgets and controls available. wx also looks a lot better. But the documentation for wx isn't very good. wxpython has been evolving -- it started out as a direct python port of some C++ libraries, and has been becoming more pythonic as time goes by. So if you go looking for example code, you could find something written in the modern, pythonic style, or you could get something written in the traditional, C++ style. Until you learn to recognise the latter and transform it to the former, you may find learning from the web difficult. Both Tkinter and wxpython should work across all platforms. -- John. From kent37 at tds.net Fri Sep 1 01:19:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 31 Aug 2006 19:19:46 -0400 Subject: [Tutor] logging module, how to print line numbers? In-Reply-To: References: Message-ID: <44F76E92.508@tds.net> Hans Fangohr wrote: > Hi, > > I have some trouble with the logging module. > > When I run this program with python2.3: > > #------------ > import logging,sys > formatter = logging.Formatter('%(name)s :%(asctime)s %(filename)s > %(lineno)s %(levelname)s %(message)s') > stdout_handler = logging.StreamHandler(sys.stdout) > stdout_handler.setFormatter(formatter) > logger=logging.getLogger('') > logger.addHandler(stdout_handler) > logger.setLevel(logging.DEBUG) > logging.debug('A debug message') > logging.info('Some information') > logging.warning('A shot across the bows') > #------------ > > I get the following output: > > root :2006-08-31 20:20:15,085 __init__.py 988 DEBUG A debug message > root :2006-08-31 20:20:15,085 __init__.py 988 INFO Some information > root :2006-08-31 20:20:15,085 __init__.py 988 WARNING A shot across thebows > > Note that the line number always appears as 988. I'd like it to be the > line number where the logging command has been executed. The documentation > says that %(lineno)d should work 'if available'. > When I run your program with Python 2.3.4 on WinXP I get the expected output: root :2006-08-31 18:51:27,046 logging.py 8 DEBUG A debug message root :2006-08-31 18:51:27,046 logging.py 9 INFO Some information root :2006-08-31 18:51:27,046 logging.py 10 WARNING A shot across the bows How are you running the program? What OS? What Python (2.3.??) Looking at the source (Python23\Lib\logging\__init__.py), the line number is pulled out of the stack by walking up the stack looking for a frame whose filename is different from _srcfile. What do you get if you print logging._srcfile and logging.__file__? Kent > Is this generally not available? Can I make it available? If so, how? > > Any advice welcome. > > Many thanks in advance, > > Hans > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From ralf.steckel at online.ms Fri Sep 1 03:24:12 2006 From: ralf.steckel at online.ms (ralf.steckel at online.ms) Date: Fri, 01 Sep 2006 03:24:12 +0200 Subject: [Tutor] logging module, how to print line numbers? Message-ID: <394286050@web.de> Dear Hans, i haven't worked with the logging module yet but as a guess from what you write in your message: according to the documentation the format statement for lineno should be %(lineno)d, but you use %(lineno)s. Best regards, Ralf > Hi, > > I have some trouble with the logging module. > > When I run this program with python2.3: > > #------------ > import logging,sys > formatter = logging.Formatter('%(name)s :%(asctime)s %(filename)s > %(lineno)s %(levelname)s %(message)s') > stdout_handler = logging.StreamHandler(sys.stdout) > stdout_handler.setFormatter(formatter) > logger=logging.getLogger('') > logger.addHandler(stdout_handler) > logger.setLevel(logging.DEBUG) > logging.debug('A debug message') > logging.info('Some information') > logging.warning('A shot across the bows') > #------------ > > I get the following output: > > root :2006-08-31 20:20:15,085 __init__.py 988 DEBUG A debug message > root :2006-08-31 20:20:15,085 __init__.py 988 INFO Some information > root :2006-08-31 20:20:15,085 __init__.py 988 WARNING A shot across thebows > > Note that the line number always appears as 988. I'd like it to be the > line number where the logging command has been executed. The documentation > says that %(lineno)d should work 'if available'. > > Is this generally not available? Can I make it available? If so, how? > > Any advice welcome. > > Many thanks in advance, > > Hans > From shaleh at speakeasy.net Fri Sep 1 05:52:34 2006 From: shaleh at speakeasy.net (Sean Perry) Date: Thu, 31 Aug 2006 20:52:34 -0700 Subject: [Tutor] Python decorator In-Reply-To: References: Message-ID: <44F7AE82.9010505@speakeasy.net> J?nos Juh?sz wrote: > Hi, > > I have just started to play with TurboGears - it is really nice - and I > couldn't understand the decorators used by it. > I have tried to interpret the http://wiki.python.org/moin/PythonDecorators > about decorators, but it is too difficult for me. > > May someone explain decorators in very sortly, what is it for and why ? > Do I need it anyway ? > A decorator is a function that takes a function and returns a new, modified function. In Django (a similar framework) there are a few places where decorators are used. @login_required def foo_view(args): # a view that must be authenticated # more code here This means that before foo_view() is ran the function login_required is run. Which in this case will redirect to a login screen if the user is not currently authenticated. here's the Django code: def user_passes_test(test_func, login_url=LOGIN_URL): """ Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. """ def _dec(view_func): def _checklogin(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) return HttpResponseRedirect('%s?%s=%s' % (login_url, REDIRECT_FIELD_ NAME, quote(request.get_full_path()))) _checklogin.__doc__ = view_func.__doc__ _checklogin.__dict__ = view_func.__dict__ return _checklogin return _dec login_required = user_passes_test(lambda u: u.is_authenticated()) From H.FANGOHR at soton.ac.uk Fri Sep 1 08:18:22 2006 From: H.FANGOHR at soton.ac.uk (Hans Fangohr) Date: Fri, 1 Sep 2006 07:18:22 +0100 (BST) Subject: [Tutor] logging module, how to print line numbers? In-Reply-To: <44F76E92.508@tds.net> References: <44F76E92.508@tds.net> Message-ID: Hi Kent, > > I have some trouble with the logging module. > > > > When I run this program with python2.3: > > > > #------------ > > import logging,sys > > formatter = logging.Formatter('%(name)s :%(asctime)s %(filename)s > > %(lineno)s %(levelname)s %(message)s') > > stdout_handler = logging.StreamHandler(sys.stdout) > > stdout_handler.setFormatter(formatter) > > logger=logging.getLogger('') > > logger.addHandler(stdout_handler) > > logger.setLevel(logging.DEBUG) > > logging.debug('A debug message') > > logging.info('Some information') > > logging.warning('A shot across the bows') > > #------------ > > > > I get the following output: > > > > root :2006-08-31 20:20:15,085 __init__.py 988 DEBUG A debug message > > root :2006-08-31 20:20:15,085 __init__.py 988 INFO Some information > > root :2006-08-31 20:20:15,085 __init__.py 988 WARNING A shot across thebows > > > > Note that the line number always appears as 988. I'd like it to be the > > line number where the logging command has been executed. The documentation > > says that %(lineno)d should work 'if available'. > > > When I run your program with Python 2.3.4 on WinXP I get the expected > output: > root :2006-08-31 18:51:27,046 logging.py 8 DEBUG A debug message > root :2006-08-31 18:51:27,046 logging.py 9 INFO Some information > root :2006-08-31 18:51:27,046 logging.py 10 WARNING A shot across the bows Interesting, thank you. > > How are you running the program? What OS? What Python (2.3.??) This was Debian Etch, python 2.3.4. I got the same problem with python 2.4.4 on the same system. I have just tried this on Mac OS X (with python from fink), and it works fine there. > Looking at the source (Python23\Lib\logging\__init__.py), the line > number is pulled out of the stack by walking up the stack looking for a > frame whose filename is different from _srcfile. What do you get if you > print logging._srcfile and logging.__file__? This was useful information. I played around with the __init__.py file and the relevant code in there (around line 970). It turns out that the problem disappears if I remove the As a result, python needs to read __init.py which appears to work correctly. So in summary, it seems that the precompiled /usr/lib/python2.3/logging/__init__.pyc file was somehow buggy. I have tried to reproduce the same problem on another machine with Debian Etch, and it doesn't exist there. To confuse matters further, (as stated above), I get the same error on that 'faulty' machine with python2.4. In summary, the code I emailed initially works fine but it seems that on the machine I used for testing something was broken with the precompiled __init__.py file of the logging module. This seems to be an issue with the debian package. Many thanks to all who replied, and in particular to Kent who put me on the right track of solving the problem. Cheers, Hans > > Kent > > Is this generally not available? Can I make it available? If so, how? > > > > Any advice welcome. > > > > Many thanks in advance, > > > > Hans > > > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- Hans Fangohr School of Engineering Sciences University of Southampton Phone: +44 (0) 238059 8345 Email: fangohr at soton.ac.uk http://www.soton.ac.uk/~fangohr From learner404 at gmail.com Fri Sep 1 11:58:27 2006 From: learner404 at gmail.com (learner404) Date: Fri, 1 Sep 2006 11:58:27 +0200 Subject: [Tutor] Tkinter: 'explanation text' when the mouse is over an image button ? Message-ID: <13a83ca10609010258x47031384w4911f407cd93dcea@mail.gmail.com> Hello, With a Tkinter app I have buttons with an image filling each button like this, bu10=Button(frame2, image=picPlay, bg="white", command=play) I want to give a small explanation of each button when the user puts the mouse over the picture (something like the title tag in a hyperlink). I thougth I saw this in Tkinter but can't find it here: http://effbot.org/tkinterbook/button.htm Thanks for any suggestions to achieve this. learner404 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060901/b44d4849/attachment.htm From kent37 at tds.net Fri Sep 1 13:49:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 01 Sep 2006 07:49:46 -0400 Subject: [Tutor] Tkinter: 'explanation text' when the mouse is over an image button ? In-Reply-To: <13a83ca10609010258x47031384w4911f407cd93dcea@mail.gmail.com> References: <13a83ca10609010258x47031384w4911f407cd93dcea@mail.gmail.com> Message-ID: <44F81E5A.2000800@tds.net> learner404 wrote: > Hello, > > With a Tkinter app I have buttons with an image filling each button like > this, > > bu10=Button(frame2, image=picPlay, bg="white", command=play) > > I want to give a small explanation of each button when the user puts the > mouse over the picture (something like the title tag in a hyperlink). > I thougth I saw this in Tkinter but can't find it here: > http://effbot.org/tkinterbook/button.htm You want a tooltip for the button. There is nothing built-in to Tkinter to do this. Here are a couple of possibilities: http://www.voidspace.org.uk/python/weblog/arch_d7_2006_07_01.shtml#e387 http://tkinter.unpythonic.net/wiki/ToolTip Kent From kent37 at tds.net Fri Sep 1 13:58:02 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 01 Sep 2006 07:58:02 -0400 Subject: [Tutor] logging module, how to print line numbers? In-Reply-To: <541413c60608311918vdf08857u83081df9104cc196@mail.gmail.com> References: <44F76E92.508@tds.net> <541413c60608311918vdf08857u83081df9104cc196@mail.gmail.com> Message-ID: <44F8204A.4050403@tds.net> Hans Fangohr wrote: > Hi Kent (and others), > > On 01/09/06, Kent Johnson wrote: > >> How are you running the program? What OS? What Python (2.3.??) >> > This is python 2.3.5 on Debian etch. Same results with python 2.4.4 on > Debian etch (although 'the linenumber' is 1072 instead of 988). > Running from the command line or in IDLE or ?? > >> Looking at the source (Python23\Lib\logging\__init__.py), the line >> number is pulled out of the stack by walking up the stack looking for a >> frame whose filename is different from _srcfile. What do you get if you >> print logging._srcfile and logging.__file__? >> > /usr/lib/python2.4/logging/__init__.py > /usr/lib/python2.4/logging/__init__.pyc > > I guess these files should rather be my source file(?). But they aren't. > No, they seem correct, they are the source file of the logging module. I'm perplexed, the values above seem correct. The way the logging module finds the line number is, it walks up through the stack looking for a stack frame that references a file different from the file containing the module itself. It uses the file and line number from that stack frame for the log. For some reason your stack frame has something different. One thing you could do is add a print to the logging module itself to see what it is seeing. In Python 2.3, there is a findCaller() method at lin 961 of logging/__init__.py. You could add print filename just after the line filename = os.path.normcase(co.co_filename) Then run your program again and see what it prints out. Kent From dyoo at hkn.eecs.berkeley.edu Fri Sep 1 16:33:20 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 1 Sep 2006 07:33:20 -0700 (PDT) Subject: [Tutor] Securing a Computer... In-Reply-To: References: <8C8990E64EFDD20-288-44F9@MBLK-M30.sysops.aol.com> Message-ID: >> I just got into high school, and the network and all the computers >> aren't secure at all...I'm trying to make a program that password >> protects the computer after an inactivity time, but there are some >> specific things I can't find how I'm supposed to do it. > > Windoze has this feature built in. It's called 'locking' the computer. > Look into it. Just as another non-Python comment: you should be using Control-Alt-Delete when logging into a Windows machine. It's the only key combination that's untrappable by other programs besdies the Windows kernel. See: http://en.wikipedia.org/wiki/Control-Alt-Delete#Windows_NT From lanky_nibs at yahoo.com Fri Sep 1 18:26:36 2006 From: lanky_nibs at yahoo.com (Lanky Nibs) Date: Fri, 1 Sep 2006 09:26:36 -0700 (PDT) Subject: [Tutor] SUPER NEWB: basic search and replace Message-ID: <20060901162636.65165.qmail@web33608.mail.mud.yahoo.com> I have a large volume of files to change so I need to automate the search and replace. I'll be replacing bits of text with other bits of text. This is working for now but I'd like to know how a real programmer would do it. The hard coded strings will eventually come from a list. All sugestions welcome and appreciated. #read all file lines into list and close allLines = fh.readlines() fh.close() #use split and join to replace a unique item chunk = allLines[0] splitChunk = chunk.split('xVAR1x') newChunk = 'my shoes fell off'.join(splitChunk) #write to a file file = open('test.html', 'w') for eachLine in newChunk: print 'writing line in text file' file.write(eachLine) file.close() __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent37 at tds.net Fri Sep 1 18:53:51 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 01 Sep 2006 12:53:51 -0400 Subject: [Tutor] SUPER NEWB: basic search and replace In-Reply-To: <20060901162636.65165.qmail@web33608.mail.mud.yahoo.com> References: <20060901162636.65165.qmail@web33608.mail.mud.yahoo.com> Message-ID: <44F8659F.1070507@tds.net> Lanky Nibs wrote: > I have a large volume of files to change so I need to > automate the search and replace. I'll be replacing > bits of text with other bits of text. This is working > for now but I'd like to know how a real programmer > would do it. The hard coded strings will eventually > come from a list. All sugestions welcome and > appreciated. > > #read all file lines into list and close > allLines = fh.readlines() > fh.close() > > #use split and join to replace a unique item > chunk = allLines[0] > Is the data to be replaced always in the first line? You only look at the first line. > splitChunk = chunk.split('xVAR1x') > newChunk = 'my shoes fell off'.join(splitChunk) > This is a very awkward way to replace part of a string. Try newChunk = chunk.replace('xVAR1x', 'my shoes fell off') > #write to a file > file = open('test.html', 'w') > for eachLine in newChunk: > print 'writing line in text file' > file.write(eachLine) > file.close() > Are you sure this is doing what you want? newChunk is just the first line of the file, iterating over it gives you each character from the file. If I wanted to replace every instance of 'xVAR1x' in a single file with 'my shoes fell off', I would do it like this: f = open(...) data = f.read() f.close() data = data.replace('xVAR1x', 'my shoes fell off') f = open(..., 'w') f.write(data) f.close() Variations are possible depending on exactly what you want to do, but this is the basic idea. No need to read a line at a time unless you actually need to process by lines, or if the file is too big to fit in memory (in which case your solution still needs a rewrite). Kent > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From dkuhlman at rexx.com Fri Sep 1 18:55:41 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 1 Sep 2006 09:55:41 -0700 Subject: [Tutor] SUPER NEWB: basic search and replace In-Reply-To: <20060901162636.65165.qmail@web33608.mail.mud.yahoo.com> References: <20060901162636.65165.qmail@web33608.mail.mud.yahoo.com> Message-ID: <20060901165541.GA24673@cutter.rexx.com> On Fri, Sep 01, 2006 at 09:26:36AM -0700, Lanky Nibs wrote: > I have a large volume of files to change so I need to > automate the search and replace. I'll be replacing > bits of text with other bits of text. This is working > for now but I'd like to know how a real programmer > would do it. The hard coded strings will eventually > come from a list. All sugestions welcome and > appreciated. > > #read all file lines into list and close > allLines = fh.readlines() > fh.close() > > #use split and join to replace a unique item > chunk = allLines[0] > splitChunk = chunk.split('xVAR1x') > newChunk = 'my shoes fell off'.join(splitChunk) Instead, consider the following: for line in allLines: line = line.replace('xVAR1x', 'my shoes fell off') outfile.write(line) Dave > > #write to a file > file = open('test.html', 'w') > for eachLine in newChunk: > print 'writing line in text file' > file.write(eachLine) > file.close() > -- Dave Kuhlman http://www.rexx.com/~dkuhlman From alan.gauld at freenet.co.uk Fri Sep 1 21:13:54 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 1 Sep 2006 20:13:54 +0100 Subject: [Tutor] GUI Programing References: Message-ID: <003a01c6cdfa$c46d3fd0$0201a8c0@XPpro> > I'm going to try some GUI programming does anyone know where the > start like > using tk or wx or what ever i want it to it will run on Windows UNIX > and Mac > systems can you tell me whats best to use and give me a link to a > good > tutorial? This is like asking which programming language is best, or which editor/IDE to use. Everyone has their own favourite. My personal view is: If you have used any GUI before then use wxPython - it looks better and has more widgets. But if you have never used a GUI toolkit before use Tkinter, its easier to learn (and use IMHO) and has much more documentation. Once you know Tkinter moving to wxPythobn is relatively straightforward because the underlying prionciples of all GUIs are the same. And of course Tkinter is based on Tk whicgh is also available for Perl and Tcl/Tk and Scheme. So its worth learning for its portability too. You can start with my GUI intro topic which teahches Tkinter but finishes with a wxPython example so you can quickly switch if you want to. BTW I strongly recommend startiung out with the raw toolkit and manual programming to understand how itall hangs together. Later you can pick up a GUI Builder like Glade/Blackadder/SpecTix etc. But its best to understand what these tools are doing first IMHO... Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Sep 1 21:16:26 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 1 Sep 2006 20:16:26 +0100 Subject: [Tutor] GUI Programing References: <5e58f2e40608311552x6591d6c7m4a10d80abb40f4f5@mail.gmail.com> Message-ID: <005901c6cdfb$1f4e2c20$0201a8c0@XPpro> > Tkinter is (IMO) easier to learn. In particular, check out > "Thinking > in Tkinter" (google for it); it's an excellent way to learn Tkinter. Last time I looked that was very out of date and still recommended the now obsolete parameters by dictionary stuyle of widget configuration. Fred Lundh's tutorial is much better nowadays - although longer. Alan G. From carroll at tjc.com Fri Sep 1 23:39:49 2006 From: carroll at tjc.com (Terry Carroll) Date: Fri, 1 Sep 2006 14:39:49 -0700 (PDT) Subject: [Tutor] GUI Programing In-Reply-To: <005901c6cdfb$1f4e2c20$0201a8c0@XPpro> Message-ID: On Fri, 1 Sep 2006, Alan Gauld wrote: > Fred Lundh's tutorial is much better nowadays - although longer. Tkinter docs are tough enough to come by that, in my view, longer is better. From amadeo.bellotti at gmail.com Sat Sep 2 00:24:55 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Fri, 1 Sep 2006 18:24:55 -0400 Subject: [Tutor] GUI Programing In-Reply-To: References: <005901c6cdfb$1f4e2c20$0201a8c0@XPpro> Message-ID: thank you all im reading up on it all its a diffreent mindset that i have tog et used to On 9/1/06, Terry Carroll wrote: > > On Fri, 1 Sep 2006, Alan Gauld wrote: > > > Fred Lundh's tutorial is much better nowadays - although longer. > > Tkinter docs are tough enough to come by that, in my view, longer is > better. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060901/e6d9e444/attachment.htm From alan.gauld at freenet.co.uk Sat Sep 2 01:04:38 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 2 Sep 2006 00:04:38 +0100 Subject: [Tutor] SUPER NEWB: basic search and replace References: <20060901162636.65165.qmail@web33608.mail.mud.yahoo.com> Message-ID: <007f01c6ce1b$003e2770$0201a8c0@XPpro> >I have a large volume of files to change so I need to > automate the search and replace. I'll be replacing > bits of text with other bits of text. This is working > for now but I'd like to know how a real programmer > would do it. A "real programmer" would use the right tool for the job, hence he/she would use sed! Not re-inventing the wheel is part of being a "real programmer" http://www.guidenet.net/resources/programmers.html :-) Alan G. From amitrane101 at yahoo.co.in Sat Sep 2 12:52:01 2006 From: amitrane101 at yahoo.co.in (Amit Rane) Date: Sat, 2 Sep 2006 03:52:01 -0700 (PDT) Subject: [Tutor] Hi All Message-ID: <20060902105204.72556.qmail@web8406.mail.in.yahoo.com> Hi , This is Amit from India ... i have just started working on Python ... please let me know the books to refer to start learning python ..as of now i am going thru online books ... please let me know if any additional books are there . Thanks & Regards , Amit Rane __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From tomdrak at gmail.com Sat Sep 2 13:39:05 2006 From: tomdrak at gmail.com (tomd) Date: Sat, 2 Sep 2006 13:39:05 +0200 Subject: [Tutor] Hi All In-Reply-To: <20060902105204.72556.qmail@web8406.mail.in.yahoo.com> References: <20060902105204.72556.qmail@web8406.mail.in.yahoo.com> Message-ID: > i have just started working on Python ... > please let me know the books to refer to start > learning I recommend Beginning Python from Magnus Lie Hetland, apart from being comprehensive and targetted at beginners, it will take you through the develoopment of 10 various projects, including game, file sharing application, or discussion forum. -- Tom, http://www.vscripts.net/ From jmpurser at gmail.com Sat Sep 2 16:23:29 2006 From: jmpurser at gmail.com (John Purser) Date: Sat, 2 Sep 2006 07:23:29 -0700 Subject: [Tutor] Hi All In-Reply-To: References: <20060902105204.72556.qmail@web8406.mail.in.yahoo.com> Message-ID: <20060902072329.d009b4ba.jmpurser@gmail.com> On Sat, 2 Sep 2006 13:39:05 +0200 tomd wrote: > > i have just started working on Python ... > > please let me know the books to refer to start > > learning > > I recommend Beginning Python from Magnus Lie Hetland, apart from being > comprehensive and targetted at beginners, it will take you through the > develoopment of 10 various projects, including game, file sharing > application, or discussion forum. > > -- > Tom, http://www.vscripts.net/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor What he said! John Purser -- Be careful! Is it classified? From gonzillaaa at gmail.com Sat Sep 2 18:03:03 2006 From: gonzillaaa at gmail.com (Gonzillaaa) Date: Sat, 2 Sep 2006 17:03:03 +0100 Subject: [Tutor] Handling hundreds of thousands of inserts with MySQLdb Message-ID: <370A80F3-C711-4245-A120-811A98D7D6CC@gmail.com> Hello all. I post this here since is my first attempt to solve a problem with python. I have fairly big log files that I'm doing some pre-processing to, to cleanup the data before they go into a MySQL database. After processing the files look something like this: 17, , 2006-8-21 12:04:29, 0, 3.0846, 25.105, 918, -0.12183, 0.20305, 25.389, 25.254, 180 18, , 2006-8-21 12:05:20, 17, 3.1705, 23.62, 949, 0.015228, 0.040609, 24.984, 110.2, 186 17, , 2006-8-21 12:07:30, 0, 3.0846, 25.353, 939, -0.1269, 0.20305, 25.254, 25.254, 293 18, , 2006-8-21 12:08:23, 17, 3.1705, 23.538, 958, 0.015228, 0.045685, 24.984, 110.2, 188 16, , 2006-8-21 12:09:21, 17, 3.0922, 24.691, 969, 0.26904, 0.10152, 25.389, 25.389, 175 then I have written another script to which I pass the filename as argument to insert that data into the db. The problem I'm getting is that some of the files contain 300000 records aprox. I have tried two approaches to inset the data but both have failed 1- use cursor.executemany which throws an error like this also if I understand it correctly executemany() does one insert at a time which seems hardly efficient. File "./xbow_MySQL_insert.py", line 39, in MySQLInsert cursor.executemany("INSERT INTO table \ File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/site-packages/MySQLdb/cursors.py", line 216, in executemany r = self._query(',\n'.join(q)) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/site-packages/MySQLdb/cursors.py", line 309, in _query rowcount = self._do_query(q) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/site-packages/MySQLdb/cursors.py", line 273, in _do_query db.query(q) _mysql_exceptions.OperationalError: (1153, "Got a packet bigger than 'max_allowed_packet' bytes") 2- use cursor.execute with a DELAYED INSERT but I think I'm just passing the wrong arguments to it: File "./xbow_MySQL_insert.py", line 43, in MySQLInsert cursor.execute("INSERT DELAYED INTO arup_03 \ File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/site-packages/MySQLdb/cursors.py", line 148, in execute query = query % db.literal(args) TypeError: not all arguments converted during string formatting Another solution I thought of but I'm not sure how to approach is to break the data into chunks and do delayed inserts with those chunks, although I'm not sure how to approach this (breaking the data up, and getting delayed inserts to work). Here is the code so far, any comments on general improvements are also welcome. Many thanks, Gonzalo. ####################################### import sys,string,MySQLdb #db config host, user, password, database = "localhost", "user", "pass", "xbow_data" def MySQLInsert(mysql_data): db = MySQLdb.connect(host, user, password, database) cursor = db.cursor() cursor.executemany("INSERT INTO table \ (id, sample, sample_time, parent, voltage, temp, light, accel_x, accel_y, mag_x, mag_y, mic) \ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", mysql_data) # cursor.execute("INSERT DELAYED INTO table \ # (id, sample, sample_time, parent, voltage, temp, light, accel_x, accel_y, mag_x, mag_y, mic) \ # VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", mysql_data) db.close() print "done inserting into db" def returnTuple(formatted_data): _data = [] for line in formatted_data: line = line.split(',') line = [item.strip() for item in line] _data.append(line) return [tuple(line) for line in _data] def Main(): #check if filename was passed when the program was called if (len(sys.argv) < 2): print "Usage:" + sys.argv[0] + " " sys.exit() #open file to work on filename = sys.argv[1] raw_data = open(filename,"r",1) # Get data on file converted into a series of tuples to be inserted into db mysql_data = returnTuple(raw_data) MySQLInsert(mysql_data) #close file raw_data.close() #print result print "done! " + str(len(mysql_data)) + " lines inserted" if __name__ == '__main__': Main() From kent37 at tds.net Sat Sep 2 18:37:57 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 02 Sep 2006 12:37:57 -0400 Subject: [Tutor] Handling hundreds of thousands of inserts with MySQLdb In-Reply-To: <370A80F3-C711-4245-A120-811A98D7D6CC@gmail.com> References: <370A80F3-C711-4245-A120-811A98D7D6CC@gmail.com> Message-ID: <44F9B365.8060104@tds.net> Gonzillaaa wrote: > Hello all. I post this here since is my first attempt to solve a > problem with python. > > I have fairly big log files that I'm doing some pre-processing to, to > cleanup the data before they go into a MySQL database. After > processing the files look something like this: > > 17, , 2006-8-21 12:04:29, 0, 3.0846, 25.105, 918, -0.12183, 0.20305, > 25.389, 25.254, 180 > 18, , 2006-8-21 12:05:20, 17, 3.1705, 23.62, 949, 0.015228, 0.040609, > 24.984, 110.2, 186 > 17, , 2006-8-21 12:07:30, 0, 3.0846, 25.353, 939, -0.1269, 0.20305, > 25.254, 25.254, 293 > 18, , 2006-8-21 12:08:23, 17, 3.1705, 23.538, 958, 0.015228, > 0.045685, 24.984, 110.2, 188 > 16, , 2006-8-21 12:09:21, 17, 3.0922, 24.691, 969, 0.26904, 0.10152, > 25.389, 25.389, 175 > > then I have written another script to which I pass the filename as > argument to insert that data into the db. The problem I'm getting is > that some of the files contain 300000 records aprox. I have tried two > approaches to inset the data but both have failed > > 1- use cursor.executemany which throws an error like this also if I > understand it correctly executemany() does one insert at a time which > seems hardly efficient. > > File "./xbow_MySQL_insert.py", line 39, in MySQLInsert > cursor.executemany("INSERT INTO table \ > File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ > python2.4/site-packages/MySQLdb/cursors.py", line 216, in executemany > r = self._query(',\n'.join(q)) > File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ > python2.4/site-packages/MySQLdb/cursors.py", line 309, in _query > rowcount = self._do_query(q) > File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ > python2.4/site-packages/MySQLdb/cursors.py", line 273, in _do_query > db.query(q) > _mysql_exceptions.OperationalError: (1153, "Got a packet bigger than > 'max_allowed_packet' bytes") > > From the error it looks like all the data is being sent at once, not in multple execute calls, so executemany() looks promising. It seems to be choking on the full data set. What if you try it with, e.g., 100 records at once instead of all 300,000? Something like this: def MySQLInsert(mysql_data): db = MySQLdb.connect(host, user, password, database) cursor = db.cursor() while mysql_data: small_data, mysql_data = mysql_data[:100], mysql_data[100:] cursor.executemany("INSERT INTO table \ (id, sample, sample_time, parent, voltage, temp, light, accel_x, accel_y, mag_x, mag_y, mic) \ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", small_data) db.close() You can tune this by picking the grouping size that gives the best performance. Kent > 2- use cursor.execute with a DELAYED INSERT but I think I'm just > passing the wrong arguments to it: > > File "./xbow_MySQL_insert.py", line 43, in MySQLInsert > cursor.execute("INSERT DELAYED INTO arup_03 \ > File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ > python2.4/site-packages/MySQLdb/cursors.py", line 148, in execute > query = query % db.literal(args) > TypeError: not all arguments converted during string formatting > > > Another solution I thought of but I'm not sure how to approach is to > break the data into chunks and do delayed inserts with those chunks, > although I'm not sure how to approach this (breaking the data up, and > getting delayed inserts to work). > > Here is the code so far, any comments on general improvements are > also welcome. > > Many thanks, > > Gonzalo. > > ####################################### > > import sys,string,MySQLdb > > #db config > host, user, password, database = "localhost", "user", "pass", > "xbow_data" > > def MySQLInsert(mysql_data): > db = MySQLdb.connect(host, user, password, database) > cursor = db.cursor() > > cursor.executemany("INSERT INTO table \ > (id, sample, sample_time, parent, voltage, temp, light, accel_x, > accel_y, mag_x, mag_y, mic) \ > VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", mysql_data) > > # cursor.execute("INSERT DELAYED INTO table \ > # (id, sample, sample_time, parent, voltage, temp, light, accel_x, > accel_y, mag_x, mag_y, mic) \ > # VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", > mysql_data) > > db.close() > print "done inserting into db" > > def returnTuple(formatted_data): > _data = [] > for line in formatted_data: > line = line.split(',') > line = [item.strip() for item in line] > _data.append(line) > > return [tuple(line) for line in _data] > > > def Main(): > #check if filename was passed when the program was called > if (len(sys.argv) < 2): > print "Usage:" + sys.argv[0] + " " > sys.exit() > > #open file to work on > filename = sys.argv[1] > raw_data = open(filename,"r",1) > > # Get data on file converted into a series of tuples to be inserted > into db > mysql_data = returnTuple(raw_data) > > MySQLInsert(mysql_data) > > #close file > raw_data.close() > > #print result > print "done! " + str(len(mysql_data)) + " lines inserted" > > if __name__ == '__main__': Main() > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From kent37 at tds.net Sat Sep 2 21:01:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 02 Sep 2006 15:01:56 -0400 Subject: [Tutor] [Fwd: Re: Handling hundreds of thousands of inserts with MySQLdb] Message-ID: <44F9D524.60607@tds.net> -------- Original Message -------- Subject: Re: [Tutor] Handling hundreds of thousands of inserts with MySQLdb Date: Sat, 2 Sep 2006 18:12:07 +0100 From: Gonzillaaa To: Kent Johnson References: <370A80F3-C711-4245-A120-811A98D7D6CC at gmail.com> <44F9B365.8060104 at tds.net> HI Kent, it works really well I was unsure how to take the slices of data. another issue is that some of the fields values are empty and I get the following : ./xbow_MySQL_insert.py:49: Warning: Out of range value adjusted for column 'sample' at row 64 cursor.executemany("INSERT INTO arup_04 \ is there a way to "silence" python so it doesn't output the errors? Many thanks. On 2 Sep 2006, at 17:37, Kent Johnson wrote: > small_data, mysql_data = mysql_data[:100], mysql_data[100:] From jgcox39 at highstream.net Sun Sep 3 00:15:52 2006 From: jgcox39 at highstream.net (Joe Cox) Date: Sat, 2 Sep 2006 15:15:52 -0700 Subject: [Tutor] Idle socket connection refused on w2k Message-ID: My Problem, Read the post about the Italian guy. I got the same problem off or on the net. I am a newbie and this has got my self study at a dead stop. This problem comes and goes. It says IDLE sub process error:connection refused,,,, Sometimes this shuts down all of Python, sometimes not. I have noticed that a small program will work fine, or intermittently. Or a big program launches the shell and just hangs up Restart >>>, no socket errors some time. The task manager shows shell running, and process has two pythonw.exe Turning off the firewall does nothing. I am scanning the registry now, found nothing. I have noticed it lakes longer to open IDLE up from scratch. Lately there is some improvement if I have only one GUI open at a time, faster opening and no sub process error message, sometimes. I have tried uninstalling, repairing, nothing helps. Please help. I don't want to give up on python. If I need to do a dual boot and add Linux so be it. Joe Cox 513-293-4830 From zslevi at sch.bme.hu Sat Sep 2 22:34:47 2006 From: zslevi at sch.bme.hu (=?ISO-8859-2?Q?Zs=EDros_Levente?=) Date: Sat, 02 Sep 2006 22:34:47 +0200 Subject: [Tutor] tkinter events: In-Reply-To: References: <44E9B6E0.3060305@sch.bme.hu> <44EE0A39.3070708@sch.bme.hu> Message-ID: <44F9EAE7.4050604@sch.bme.hu> Well, I considered encapsulation as syntactical sugar. And even prolog knows polymorphism, but I wouldn't call it OOP. (Yes, I know in a typless context polymorphism doesn't mean too much. And btw, if Python is a multi-paradigm language why doesn't support polygamy? :) ) Or maybe I'm wrong ... Alan Gauld wrote: >I just found this message (because Mike posted the tinyurl....) >and couldn't resist responding... > >"Zsiros Levente" wrote > > >>If we're talking about data hiding, let me ask: why Python doesn't >>implement data hiding (I mean 'private' and 'protected')? I consider >>it >>a very important OOP feature, because that makes OOP different from >>structural programming. >> >> > >This is a hot-button of mine... > >Why do you think data hiding is important for OOP? >And in particular why do you think it differentiates >OOP from structural techniques? > >Data Hiding was not part of the early OOP languages >(Simula, Lisp and the first Smalltalks) it was introduced >first by Smalltalk in (Smalltalk 74 I think) and it was only >when C++ came out that all the public/private nonsense >appeared, followed by protected in C++ v2.0 > >Many OOP languages do not support data hiding, it is >not necessary for OOP. Data hiding is supported in many >structual languages like the Modula family and ADA., >but they are not OOP. (The concept was introduced by >David Parnas in 1972 - long before OOP became popular) > >The point being that Data hiding is an orthogonal issue >to OOP which relies on encapsulation and polymorphism. >- Encapsulation(*) is the ability to treat the data and methods > as a single entity - an object. >- Polymorphism is the ability for different objects supporting > the same protocol to react in different ways to the same > message. > >Inheritance is an optional extra but is usually required to >implement polymorphism... > >(*)Some texts get data hiding and encapsulation confused. >Encapsulation as originally applied to OOP is about joining >the data and function together - so fundamental to OOP that >some folks forget its even there as a feature! > >Data hiding is about making data available through an API. >That API could be an object's protocol or it could be a >module interface. It's usually a good thing to do, but not >a requirement of OOP. > >Rant over, > >If anyone wants a more academic review oif the differences >between data hiding (or more correctly, information hiding), >encapsulation and abstraction see this white paper: > >http://www.itmweb.com/essay550.htm > >by Ed Berard. > > > From alan.gauld at freenet.co.uk Sat Sep 2 23:58:24 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 2 Sep 2006 22:58:24 +0100 Subject: [Tutor] tkinter events: References: <44E9B6E0.3060305@sch.bme.hu><44EE0A39.3070708@sch.bme.hu> <44F9EAE7.4050604@sch.bme.hu> Message-ID: <001b01c6ceda$ea0f6e30$0201a8c0@XPpro> > Well, I considered encapsulation as syntactical sugar. > And even prolog knows polymorphism, but I wouldn't call it OOP. Humor acknowledged, but... Encapsulation can be syntactic sugar - and often is. But the concept that it sugar coats is real enough. You can write OOP by convention using languages like C but its painful... But for OOP you need BOTH concepts - encapsulation and polymorphism. You can have either on its own and not have OOP. You can even have both and not have OOP, if they can't be combined.... But you can't have OOP without both - or if you can I've never seen it! > if Python is a multi-paradigm language why doesn't support polygamy? > :) ) :-) >>The point being that Data hiding is an orthogonal issue >>to OOP which relies on encapsulation and polymorphism. >>- Encapsulation(*) is the ability to treat the data and methods >> as a single entity - an object. >>- Polymorphism is the ability for different objects supporting >> the same protocol to react in different ways to the same >> message. >> >>Inheritance is an optional extra but is usually required to >>implement polymorphism... Alan G From alan.gauld at btinternet.com Sun Sep 3 01:15:03 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Sep 2006 00:15:03 +0100 Subject: [Tutor] Idle socket connection refused on w2k References: Message-ID: "Joe Cox" wrote in message > I am a newbie and this has got my self study at a dead stop. It shouldn't do, IDLE is a nice aid but hardly essential for learning poython. You can use the basic command prompt. If you are on Windows you can also use Pyhonwin If you are on Linux you can use emacs and python-mode So lots of opportunities to progress with Python without using IDLE. > Please help. I don't want to give up on python. If I need to do a > dual boot > and add Linux so be it. No need for Linux, use Pythonwin, its part of the winall package if you haven't already installed it, or standard with the ActiveState version of Python. On Windows it beats IDLE on every count. Alan G. From samrobertsmith at gmail.com Sun Sep 3 02:05:11 2006 From: samrobertsmith at gmail.com (linda.s) Date: Sat, 2 Sep 2006 17:05:11 -0700 Subject: [Tutor] about random seed Message-ID: <1d987df30609021705o3d2b9985x4f2066c526e0640a@mail.gmail.com> I read something about random.seed() but still confused. i can understand random.random() but it is very hard for me to understand random.seed(0... can anyone explain an example? Thanks a lot! Linda From bgailer at alum.rpi.edu Sun Sep 3 03:32:39 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 02 Sep 2006 18:32:39 -0700 Subject: [Tutor] about random seed In-Reply-To: <1d987df30609021705o3d2b9985x4f2066c526e0640a@mail.gmail.com> References: <1d987df30609021705o3d2b9985x4f2066c526e0640a@mail.gmail.com> Message-ID: <44FA30B7.9040300@alum.rpi.edu> linda.s wrote: > I read something about random.seed() but still confused. i can > understand random.random() but it is very hard for me to understand > random.seed(0... can anyone explain an example? > I suggest you read http://en.wikipedia.org/wiki/Pseudorandom_number_generator to get the gist of pseudorandom number generation. Section 4 Mersenne twister is the algorithm used by Python random. random.seed() sets the starting number for the generator. Setting the seed to a known value can be important if you want the same sequence of pseudorandom numbers to be generated each time you test/run your program. Note that in Python "the current system time is ... used to initialize the generator when the [random] module is first imported." This pretty well ensures that the sequence of numbers generated will be different each time. HTH. -- Bob Gailer 510-978-4454 From samrobertsmith at gmail.com Sun Sep 3 08:22:16 2006 From: samrobertsmith at gmail.com (linda.s) Date: Sat, 2 Sep 2006 23:22:16 -0700 Subject: [Tutor] about random seed In-Reply-To: <44FA30B7.9040300@alum.rpi.edu> References: <1d987df30609021705o3d2b9985x4f2066c526e0640a@mail.gmail.com> <44FA30B7.9040300@alum.rpi.edu> Message-ID: <1d987df30609022322s4bed842fr74d9099987ae6b72@mail.gmail.com> On 9/2/06, Bob Gailer wrote: > linda.s wrote: > > I read something about random.seed() but still confused. i can > > understand random.random() but it is very hard for me to understand > > random.seed(0... can anyone explain an example? > > > I suggest you read > http://en.wikipedia.org/wiki/Pseudorandom_number_generator to get the > gist of pseudorandom number generation. Section 4 Mersenne twister > > is the algorithm used by Python random. > > random.seed() sets the starting number for the generator. Setting the > seed to a known value can be important if you want the same sequence of > pseudorandom numbers to be generated each time you test/run your > program. Note that in Python "the current system time is ... used to > initialize the generator when the [random] module is first imported." > This pretty well ensures that the sequence of numbers generated will be > different each time. > I still can not understand. can you show me an example? Thanks! Linda From rdm at rcblue.com Sun Sep 3 09:08:18 2006 From: rdm at rcblue.com (Dick Moores) Date: Sun, 03 Sep 2006 00:08:18 -0700 Subject: [Tutor] What does "random" in shuffle( x[, random]) do? Message-ID: <7.0.1.0.2.20060902235901.03cec480@rcblue.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060903/5eac6266/attachment.html From rschroev_nospam_ml at fastmail.fm Sun Sep 3 10:02:30 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 03 Sep 2006 10:02:30 +0200 Subject: [Tutor] about random seed In-Reply-To: <1d987df30609022322s4bed842fr74d9099987ae6b72@mail.gmail.com> References: <1d987df30609021705o3d2b9985x4f2066c526e0640a@mail.gmail.com> <44FA30B7.9040300@alum.rpi.edu> <1d987df30609022322s4bed842fr74d9099987ae6b72@mail.gmail.com> Message-ID: linda.s schreef: > I still can not understand. can you show me an example? > Thanks! > Linda Example program: import random random.seed(42) for i in range(10): print random.random() At the start of the program, the random number generator is seeded with 42. This could be any number, but the point is that it doesn't change when you run the program again. As a result, the output is the same every time you run the program. If you choose a different seed, you get different results from random.random(). If you don't use random.seed(), the random module uses the current time as the seed. Since the current time always changes, the program will generate different output each time it runs. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From ajkadri at googlemail.com Sun Sep 3 11:34:43 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Sun, 3 Sep 2006 10:34:43 +0100 Subject: [Tutor] Problem with Pythonwin Message-ID: Hi folks, I am new to Python and have just taken a few steps in this long journey.. I am using a windows box and I have installed Activestate ActivePython 2.4 When I start Pythonwin IDE, it gives me the following error: * File "", line 1, in ? File "C:\python\Lib\site-packages\pythonwin\pywin\framework\startup.py", line 49, in ? exec "import %s\n" % moduleName File "", line 1, in ? File "C:\python\Lib\site-packages\pythonwin\pywin\framework\intpyapp.py", line 8, in ? import string File "C:\python\Lib\string.py", line 83, in ? import re as _re File "re.py", line 9, in ? i = input("Enter any positive integer\n") exceptions.EOFError: EOF when reading a line* ** *Can anyone help me with this??* ** *Regards,* *Asrar* -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060903/e6486217/attachment.html From khp at pflaesterer.de Sun Sep 3 12:47:15 2006 From: khp at pflaesterer.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Sun, 03 Sep 2006 12:47:15 +0200 Subject: [Tutor] Handling hundreds of thousands of inserts with MySQLdb In-Reply-To: <370A80F3-C711-4245-A120-811A98D7D6CC@gmail.com> (gonzillaaa@gmail.com's message of "Sat, 2 Sep 2006 17:03:03 +0100") References: <370A80F3-C711-4245-A120-811A98D7D6CC@gmail.com> Message-ID: On 2 Sep 2006, gonzillaaa at gmail.com wrote: > > Hello all. I post this here since is my first attempt to solve a > problem with python. > > I have fairly big log files that I'm doing some pre-processing to, to > cleanup the data before they go into a MySQL database. After > processing the files look something like this: > > 17, , 2006-8-21 12:04:29, 0, 3.0846, 25.105, 918, -0.12183, 0.20305, > 25.389, 25.254, 180 > 18, , 2006-8-21 12:05:20, 17, 3.1705, 23.62, 949, 0.015228, 0.040609, > 24.984, 110.2, 186 > 17, , 2006-8-21 12:07:30, 0, 3.0846, 25.353, 939, -0.1269, 0.20305, > 25.254, 25.254, 293 > 18, , 2006-8-21 12:08:23, 17, 3.1705, 23.538, 958, 0.015228, > 0.045685, 24.984, 110.2, 188 > 16, , 2006-8-21 12:09:21, 17, 3.0922, 24.691, 969, 0.26904, 0.10152, > 25.389, 25.389, 175 > > then I have written another script to which I pass the filename as > argument to insert that data into the db. The problem I'm getting is > that some of the files contain 300000 records aprox. I have tried two > approaches to inset the data but both have failed I would recommend a third approach: use "LOAD DATA INFILE" from MySql. You can find its syntax e.g here: http://dev.mysql.com/doc/refman/5.0/en/load-data.html That is very fast and you need only one statement. You could also use mysqlimport from the commandline to import the data. If you want to insert the data with INSERT statements I would read the data file line by line and insert that data. That is simple not as fast as LOAD DATA INFILE but for most situations fast enough. Then you shouldn't have the problem with max_allowed_packet (you can increase its value if you need to; for MySql 5.0 its maximum value is 1GB IIRC. If you need speed use mysqlimport from the commandline or LOAD DATA INFILE; insert statements even with multiple values will never be as fast as that. Karl -- Please do *not* send copies of replies to me. I read the list From fiveholiday55 at hotmail.com Sun Sep 3 13:36:38 2006 From: fiveholiday55 at hotmail.com (Henry Dominik) Date: Sun, 3 Sep 2006 12:36:38 +0100 Subject: [Tutor] Problem with Pythonwin References: Message-ID: It is very hard to know what caused that, but could you post the piece of code you were trying to execute?? Or did you get the error when you opened the Pythonwin without any code?? -- Dominik ----- Original Message ----- From: Asrarahmed Kadri To: tutor at python.org Sent: Sunday, September 03, 2006 10:34 AM Subject: [Tutor] Problem with Pythonwin Hi folks, I am new to Python and have just taken a few steps in this long journey.. I am using a windows box and I have installed Activestate ActivePython 2.4 When I start Pythonwin IDE, it gives me the following error: File "", line 1, in ? File "C:\python\Lib\site-packages\pythonwin\pywin\framework\startup.py", line 49, in ? exec "import %s\n" % moduleName File "", line 1, in ? File "C:\python\Lib\site-packages\pythonwin\pywin\framework\intpyapp.py", line 8, in ? import string File "C:\python\Lib\string.py", line 83, in ? import re as _re File "re.py", line 9, in ? i = input("Enter any positive integer\n") exceptions.EOFError: EOF when reading a line Can anyone help me with this?? Regards, Asrar ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060903/ee0ac77e/attachment.htm From kent37 at tds.net Sun Sep 3 13:43:41 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 03 Sep 2006 07:43:41 -0400 Subject: [Tutor] What does "random" in shuffle( x[, random]) do? In-Reply-To: <7.0.1.0.2.20060902235901.03cec480@rcblue.com> References: <7.0.1.0.2.20060902235901.03cec480@rcblue.com> Message-ID: <44FABFED.4080306@tds.net> Dick Moores wrote: > http://docs.python.org/lib/module-random.html says, > > "shuffle( x[, random]) > Shuffle the sequence x in place. The optional argument random is a 0-argument > function returning a random float in [0.0, 1.0); by default, this is the > function random()." > > >>> from random import shuffle, random > >>> lst = ["a", "b", "c", "d"] > >>> shuffle(lst) > >>> lst > ['c', 'b', 'd', 'a'] > >>> shuffle(lst, random) > >>> lst > ['d', 'c', 'b', 'a'] > >>> > > I can't see that shuffle(a) is any different from shuffle(a, random). Is it? And > how? > The docs say that shuffle(a) *is* the same as shuffle(a, random). If you don't supply a second argument, the function random() is used. So passing random as the second arg is the same as omitting the second arg. One reason to provide your own random function would be if you have one that is more random than the standard function, for example os.urandom() or a function based on an external random source such as http://www.fourmilab.ch/hotbits/. The random number generator in Python (Mersenne twister) is very high quality but that hasn't always been the case and it is still deterministic. You might be interested in the Wikipedia article: http://en.wikipedia.org/wiki/Random_number_generator http://en.wikipedia.org/wiki/Mersenne_twister Trying the two versions once each, getting different results and saying you can't see that they are different is...an interesting approach :-) But seriously, even with a poor random function you would have to call shuffle many times and analyze the entire body of results carefully to see any problem. Kent > Thanks, > > Dick Moores > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sun Sep 3 13:46:23 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 03 Sep 2006 07:46:23 -0400 Subject: [Tutor] Problem with Pythonwin In-Reply-To: References: Message-ID: <44FAC08F.4080209@tds.net> Asrarahmed Kadri wrote: > Hi folks, > > > I am new to Python and have just taken a few steps in this long journey.. > > I am using a windows box and I have installed Activestate ActivePython 2.4 > > When I start Pythonwin IDE, it gives me the following error: > > File "re.py", line 9, in ? > i = input("Enter any positive integer\n") > exceptions.EOFError: EOF when reading a line* > You have a file re.py in the python path that is shadowing the library module re. Rename your file to something else and try again. Kent From kent37 at tds.net Sun Sep 3 13:52:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 03 Sep 2006 07:52:15 -0400 Subject: [Tutor] Handling hundreds of thousands of inserts with MySQLdb In-Reply-To: <4B84C833-ADC0-4A0C-B1BD-71DE468A06C2@gmail.com> References: <370A80F3-C711-4245-A120-811A98D7D6CC@gmail.com> <44F9B365.8060104@tds.net> <4B84C833-ADC0-4A0C-B1BD-71DE468A06C2@gmail.com> Message-ID: <44FAC1EF.4080100@tds.net> Gonzillaaa wrote: > another issue is that some of the fields values are empty and I > get the following : > > ./xbow_MySQL_insert.py:49: Warning: Out of range value adjusted for > column 'sample' at row 64 > cursor.executemany("INSERT INTO arup_04 \ > > is there a way to "silence" python so it doesn't output the errors? Rather than silence the warnings I would fix the data. You could process each row in your returnTuple() function. Alternately you could perhaps change your database table to allow the data. Kent From alan.gauld at freenet.co.uk Sun Sep 3 17:51:05 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 3 Sep 2006 16:51:05 +0100 Subject: [Tutor] Problem with Pythonwin References: Message-ID: <002e01c6cf70$c440b6a0$0201a8c0@XPpro> > I am using a windows box and I have installed Activestate > ActivePython 2.4 > When I start Pythonwin IDE, it gives me the following error: > > * File "", line 1, in ? > File > "C:\python\Lib\site-packages\pythonwin\pywin\framework\startup.py", > line 49, in ? > exec "import %s\n" % moduleName > File "re.py", line 9, in ? > i = input("Enter any positive integer\n") > exceptions.EOFError: EOF when reading a line* Is this the first time you have started (or tried to start) Pythonwin? Or did it used to work and is now broken? How are you trying to start Pythonwin? Are you running it from the Start Menu? The error you are seeing should only occur if you are starting pythonwin with a commandline argument, and that's unusual! If you have just installed it and this is the first time you've tried running Pythonwin then I'd suggest uninstalling Python, and then reinstalling it. If that still gives the same error check the Pyhonwin shortcutr properties to see if any arguments are being passed to it. Best I can think of... Alan g From alan.gauld at freenet.co.uk Sun Sep 3 18:04:12 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 3 Sep 2006 17:04:12 +0100 Subject: [Tutor] What does "random" in shuffle( x[, random]) do? References: <7.0.1.0.2.20060902235901.03cec480@rcblue.com> Message-ID: <003401c6cf72$99634900$0201a8c0@XPpro> > "shuffle( x[, random]) > Shuffle the sequence x in place. The optional argument random is a > 0-argument function returning a random float in [0.0, 1.0); by > default, this is the function random()." > >>>> from random import shuffle, random >>>> lst = ["a", "b", "c", "d"] >>>> shuffle(lst) >>>> shuffle(lst, random) > > I can't see that shuffle(a) is any different from shuffle(a, > random). Is it? And how? It isn't any different in this case. The docs point out that if you don't provide a value then random is used. So by passing random you are simpoly doing what the default behaviour does. To see anything different try defining your own function that returns a value between 0 and 1: def r0(): return 0 def r1(): return 0.999999999) Try using those values and see if the amount of randomness in shuffles behaviour changes for f in [r0,r1,random]: print '-------------' for n in range(3): lst = ['a','b','c','d'] shuffle(lst,f) print lst Can you see how the function has a difference now? Alan G. From dyoo at hkn.eecs.berkeley.edu Sun Sep 3 19:50:34 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 3 Sep 2006 10:50:34 -0700 (PDT) Subject: [Tutor] about random seed In-Reply-To: <1d987df30609022322s4bed842fr74d9099987ae6b72@mail.gmail.com> References: <1d987df30609021705o3d2b9985x4f2066c526e0640a@mail.gmail.com> <44FA30B7.9040300@alum.rpi.edu> <1d987df30609022322s4bed842fr74d9099987ae6b72@mail.gmail.com> Message-ID: >> random.seed() sets the starting number for the generator. Setting the >> seed to a known value can be important if you want the same sequence of >> pseudorandom numbers to be generated each time you test/run your >> program. >> > I still can not understand. can you show me an example? Hi Linda, Ok, let's start from basics. Normally, functions give the same results if we pass in the same inputs. If we have a function like: ################ def square(x): return x * x ################ then we really expect 'square(42)' to return the same value as 'square(42)' because the input is the same. But this poses a dilemma: we'd like to have a function that gives us "random" numbers, but we also want to be able to call it using the same (empty) input. That is, we'd like: random.random() to give a different result than another call to: random.random() In the mathematical sense, random.random() isn't a "function", but that's ok, because we programmers play fast and loose with these things anyway. *grin* So how does this work? The idea is to have the random.random() function keep some memory of the last random number that it already returned. That way, when we call random.random() again, it'll have a chance to return something different. The idea looks like: ################################### _hidden_seed = 0 def my_random(): global _hidden_seed _hidden_seed = _hidden_seed + 1 return _hidden_seed ################################### I'm putting in the understored '_hidden_seed' global variable that's reused in our calls to my_random(). Now my_random() will give us varying results every time we call it: ###### >>> my_random() 1 >>> my_random() 2 >>> my_random() 3 ###### But the only problem here, now, is that the results aren't particularly "random" looking. So maybe we can do something a little crazier besides just adding 1 to it: maybe we can do some multiplication, take remainders, ... etc, to scramble the number up. That's the job of a good random number generator. Also notice that there's nothing truly "random" doing on here. The stream of numbers that come out of mutiple calls to my_random() is completely predictable if we know two things: * the initial seeding value * the algorithm used to generate the next value Out of these two, the only thing that's potentially different between Python runs is the seeding value, since the algorithm we use is fixed. When Python starts up, it's initially set to some value that relates to the current time, to further extend the illusion of randomness between program runs. random.seed(), the function you were trying to play with, resets the seed to something you want. So if you want to forcefully generate the same "random" values, set the seed to something hardcoded, and then start calling random.random(). Please feel free to ask more questions about this. From yegrix at free.fr Sun Sep 3 19:23:23 2006 From: yegrix at free.fr (yves) Date: Sun, 03 Sep 2006 19:23:23 +0200 Subject: [Tutor] tempfile and webbrowser Message-ID: <44FB0F8B.4000504@free.fr> Hello tutors, This programm works: ********** import webbrowser a = open('test.htm','wb') a.write("Test") webbrowser.open(a.name) a.close() *********** but I would like to avoid the risk of overwriting an already existing "test.htm" file, so I try to use the module tempfile: *********** import tempfile import webbrowser a = tempfile.NamedTemporaryFile('w+b',-1,'.html') a.write("Test") webbrowser.open(a.name) #a.close() ********** This does not work (no traceback error though): the browser displays a blank page. I am using Python2.3.3 on Windows XP, and Firefox. Have you got some suggestions to tackle this problem? -- Yves Egrix From kent37 at tds.net Sun Sep 3 21:35:58 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 03 Sep 2006 15:35:58 -0400 Subject: [Tutor] tempfile and webbrowser In-Reply-To: <44FB0F8B.4000504@free.fr> References: <44FB0F8B.4000504@free.fr> Message-ID: <44FB2E9E.7060600@tds.net> yves wrote: > Hello tutors, > > This programm works: > ********** > import webbrowser > a = open('test.htm','wb') > a.write("Test") > webbrowser.open(a.name) > a.close() > *********** > but I would like to avoid the risk of overwriting an already existing > "test.htm" file, so I try to use the module tempfile: > *********** > import tempfile > import webbrowser > a = tempfile.NamedTemporaryFile('w+b',-1,'.html') > a.write("Test") > webbrowser.open(a.name) > #a.close() > ********** > This does not work (no traceback error though): the browser displays a > blank page. The problem is that the file is never actually written because you omit the close. But when you do close the temp file, it is deleted. Try using a.flush() instead of a.close(), that will force the file to be written. Alternately use tempfile.mkstemp() which lets you close the file and delete it when you are done with it. Kent From chiselchip at earthlink.net Sun Sep 3 21:50:32 2006 From: chiselchip at earthlink.net (Lowell H. Tackett) Date: Sun, 3 Sep 2006 15:50:32 -0400 Subject: [Tutor] pretty_printing Message-ID: <200609031550.32866.chiselchip@earthlink.net> Hello, folks. These seems as good as another question to take a first plunge into your forum. I would like to---so far without luck--to print out my Python scripts with syntax highlighting (using Mandrake Linux as my OS/host.) Using enscript has not gotten me anywhere; nor has a package I found on the *net called 'pretty-print', or some such similar to that. It had occured to me that the root of my lack of success is simply that file XYZ.py sits on my HD as a simple string of X's and O's, not as a pretty, colorful text repository. Only thru the magic of say, Vim, is the display converted to meaningful hues. Therefor, Vim somehow knows how to detect each of the discrete syntax types: comments, quotes, reserved words, etc., and to apply an appropriate color into its' display. It occured to me that it ought to be very simple to gain access to those syntax discrimnators, write a code script that creates a 'dye' for each syntax type, and pipe a print request thru such a file. Just to put my experience in perspective, I'm about halfway thru Michael Dawson's [wonderful] book "Python Programming for the Absolute Beginner". This concept is jumping way out of my present 'box', and I'm kind of excited that the whole thing occured to me, and anxious to move ahead and experiement with it. Just don't know where to get started. (Yes, I know that there are probably many applications blowing about 'out there', but that's not the point, is it?) -- From Lowell's computer... From rdm at rcblue.com Sun Sep 3 21:55:25 2006 From: rdm at rcblue.com (Dick Moores) Date: Sun, 03 Sep 2006 12:55:25 -0700 Subject: [Tutor] What does "random" in shuffle( x[, random]) do? In-Reply-To: References: <7.0.1.0.2.20060902235901.03cec480@rcblue.com> Message-ID: <7.0.1.0.2.20060903123825.03ce5b08@rcblue.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060903/0fce8f2e/attachment.html From rdm at rcblue.com Sun Sep 3 22:16:16 2006 From: rdm at rcblue.com (Dick Moores) Date: Sun, 03 Sep 2006 13:16:16 -0700 Subject: [Tutor] What does "random" in shuffle( x[, random]) do? In-Reply-To: <44FABFED.4080306@tds.net> References: <7.0.1.0.2.20060902235901.03cec480@rcblue.com> <44FABFED.4080306@tds.net> Message-ID: <7.0.1.0.2.20060903130636.05d65be0@rcblue.com> At 04:43 AM 9/3/2006, Kent Johnson wrote: >Dick Moores wrote: > > http://docs.python.org/lib/module-random.html says, > > > > "shuffle( x[, random]) > > Shuffle the sequence x in place. The optional argument random is > a 0-argument > > function returning a random float in [0.0, 1.0); by default, this is the > > function random()." > > > > >>> from random import shuffle, random > > >>> lst = ["a", "b", "c", "d"] > > >>> shuffle(lst) > > >>> lst > > ['c', 'b', 'd', 'a'] > > >>> shuffle(lst, random) > > >>> lst > > ['d', 'c', 'b', 'a'] > > >>> > > > > I can't see that shuffle(a) is any different from shuffle(a, > random). Is it? And > > how? > > >The docs say that shuffle(a) *is* the same as shuffle(a, random). If you >don't supply a second argument, the function random() is used. So >passing random as the second arg is the same as omitting the second arg. > >One reason to provide your own random function would be if you have one >that is more random than the standard function, for example os.urandom() >or a function based on an external random source such as >http://www.fourmilab.ch/hotbits/. The random number generator in Python >(Mersenne twister) is very high quality but that hasn't always been the >case and it is still deterministic. > >You might be interested in the Wikipedia article: >http://en.wikipedia.org/wiki/Random_number_generator >http://en.wikipedia.org/wiki/Mersenne_twister > >Trying the two versions once each, getting different results and saying >you can't see that they are different is...an interesting approach :-) Well, sure it's stupid if you know what "supplying your own random function in place of random.random()" means. I do now, thanks to you and Alan Gauld. >But seriously, even with a poor random function you would have to call >shuffle many times and analyze the entire body of results carefully to >see any problem. Because I'm content with the pseudo-randomness supplied by the current random.random(), I won't pursue my questions about that 2nd argument of shuffle() any longer. Thanks to all, Dick Moores From yegrix at free.fr Sun Sep 3 22:54:05 2006 From: yegrix at free.fr (yves) Date: Sun, 03 Sep 2006 22:54:05 +0200 Subject: [Tutor] tempfile and webbrowser In-Reply-To: <44FB2E9E.7060600@tds.net> References: <44FB0F8B.4000504@free.fr> <44FB2E9E.7060600@tds.net> Message-ID: <44FB40ED.4050908@free.fr> Kent Johnson a ?crit : > The problem is that the file is never actually written because you omit > the close. But when you do close the temp file, it is deleted. Try using > a.flush() instead of a.close(), that will force the file to be written. > Alternately use tempfile.mkstemp() which lets you close the file and > delete it when you are done with it. Thank you, this works: ******** import tempfile import webbrowser a = tempfile.mkstemp('.html') f= open(a[1],'w') f.write("Test") f.close() webbrowser.open(f.name) ********* -- Yves Egrix From john at fouhy.net Sun Sep 3 23:41:26 2006 From: john at fouhy.net (John Fouhy) Date: Mon, 4 Sep 2006 09:41:26 +1200 Subject: [Tutor] pretty_printing In-Reply-To: <200609031550.32866.chiselchip@earthlink.net> References: <200609031550.32866.chiselchip@earthlink.net> Message-ID: <5e58f2e40609031441q36e05c50kea3a4076ae5ca5c2@mail.gmail.com> On 04/09/06, Lowell H. Tackett wrote: > I would like to---so far without luck--to print out my Python scripts with > syntax highlighting (using Mandrake Linux as my OS/host.) Using enscript has > not gotten me anywhere; nor has a package I found on the *net called > 'pretty-print', or some such similar to that. Well, you could open your code in vim or emacs and click "print"? :-) > It occured to me that it ought to be very simple to gain access to those > syntax discrimnators, write a code script that creates a 'dye' for each > syntax type, and pipe a print request thru such a file. Well, on this windows system, the vim python syntax file is in Vim\vim70\syntax\python.vim. It looks like you could make a reasonable stab at parsing it without knowing what everything means, especially if you're willing to accept the odd error. I'm not sure how you want to go about colourizing things, though. If you have a postscript printer, you could generate your own postscript, maybe.. -- John. From rabidpoobear at gmail.com Mon Sep 4 00:07:26 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 3 Sep 2006 17:07:26 -0500 Subject: [Tutor] What does "random" in shuffle( x[, random]) do? In-Reply-To: <7.0.1.0.2.20060903123825.03ce5b08@rcblue.com> References: <7.0.1.0.2.20060902235901.03cec480@rcblue.com> <7.0.1.0.2.20060903123825.03ce5b08@rcblue.com> Message-ID: [snip] Ah, I'd forgotten that in shuffle( x[, random], "random" would be the > default. But please bear with me. Using your function a, I wrote > testShuffle.py: > > # testShuffle.py > from random import * > > def a(): > return 0.5 > lst = ['1', '2', '3', '4'] > shuffle(lst,a) > print lst > > >>> > ['1', '4', '2', '3'] > >>> > > Again, this just the random reordering of lst in place. Could you show me > a little script where the 2nd argument of shuffle actually does something? > no, it's not a random reordering. As others have said already, you can't determine the randomness of a function just by running it once. Why do you think it's a random reordering? If you ran it many times, you'd see why we've been saying that it's important not to test it just once. #--- example script.py from random import shuffle def a(): return 0.5 def run_shuffle(lst): shuffle(lst,a) print lst import copy lst = [1,2,3,4] for x in range(20): tmp = copy.copy(lst) run_shuffle(tmp) #--- end output: [1, 4, 2, 3] [1, 4, 2, 3] [1, 4, 2, 3] [1, 4, 2, 3] [1, 4, 2, 3] [1, 4, 2, 3] [1, 4, 2, 3] [1, 4, 2, 3] [1, 4, 2, 3] [1, 4, 2, 3] [1, 4, 2, 3] [1, 4, 2, 3] [1, 4, 2, 3] [1, 4, 2, 3] [1, 4, 2, 3] [1, 4, 2, 3] [1, 4, 2, 3] [1, 4, 2, 3] [1, 4, 2, 3] [1, 4, 2, 3] >>> So yes, I have already given you an example where the second argument does something. Or do you still think that it's random? :) Thanks, > You're welcome. Dick Moores > -Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060903/b4f53c30/attachment.htm From dkuhlman at rexx.com Mon Sep 4 00:50:04 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sun, 3 Sep 2006 15:50:04 -0700 Subject: [Tutor] pretty_printing In-Reply-To: <5e58f2e40609031441q36e05c50kea3a4076ae5ca5c2@mail.gmail.com> References: <200609031550.32866.chiselchip@earthlink.net> <5e58f2e40609031441q36e05c50kea3a4076ae5ca5c2@mail.gmail.com> Message-ID: <20060903225004.GA57473@cutter.rexx.com> On Mon, Sep 04, 2006 at 09:41:26AM +1200, John Fouhy wrote: > On 04/09/06, Lowell H. Tackett wrote: > > I would like to---so far without luck--to print out my Python scripts with > > syntax highlighting (using Mandrake Linux as my OS/host.) Using enscript has > > not gotten me anywhere; nor has a package I found on the *net called > > 'pretty-print', or some such similar to that. > > Well, you could open your code in vim or emacs and click "print"? :-) > > > It occured to me that it ought to be very simple to gain access to those > > syntax discrimnators, write a code script that creates a 'dye' for each > > syntax type, and pipe a print request thru such a file. > > Well, on this windows system, the vim python syntax file is in > Vim\vim70\syntax\python.vim. > > It looks like you could make a reasonable stab at parsing it without > knowing what everything means, especially if you're willing to accept > the odd error. > > I'm not sure how you want to go about colourizing things, though. If > you have a postscript printer, you could generate your own postscript, > maybe.. > The SciTE text editor, which runs on both Linux and MS Windows, will export a Python source code file to HTML, PDF, RTF, LaTeX, and XML. See: http://www.scintilla.org/SciTE.html The export feature is under the File/Export menu item. SciTE also does syntax highlighting/colorizing of Python code. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From alan.gauld at btinternet.com Mon Sep 4 01:09:09 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 4 Sep 2006 00:09:09 +0100 Subject: [Tutor] tempfile and webbrowser References: <44FB0F8B.4000504@free.fr> Message-ID: > This program works: > ********** > import webbrowser > a = open('test.htm','wb') Any particular feason to open the file in binary mode? That can sometimes cause odd things to happen. > a.write("Test") > webbrowser.open(a.name) > a.close() The close should come before the browser reads the file, otherwise you are trying to read a file thats still open in write mode and the behaviouir there is "undefined" on most operating systems. > import tempfile > import webbrowser > a = tempfile.NamedTemporaryFile('w+b',-1,'.html') Now you are making it even more complex by using a read/write mode binary temporary file! > a.write("Test") > webbrowser.open(a.name) > #a.close() > ********** > Have you got some suggestions to tackle this problem? Simplify the file handling to use text files and close the file as soon as possible. These are good guidelines for any file handling you do. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Mon Sep 4 01:20:02 2006 From: rdm at rcblue.com (Dick Moores) Date: Sun, 03 Sep 2006 16:20:02 -0700 Subject: [Tutor] What does "random" in shuffle( x[, random]) do? In-Reply-To: References: <7.0.1.0.2.20060902235901.03cec480@rcblue.com> <7.0.1.0.2.20060903123825.03ce5b08@rcblue.com> Message-ID: <7.0.1.0.2.20060903161106.05d4f300@rcblue.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060903/5fdcb16d/attachment.html From srini_iyyer_bio at yahoo.com Mon Sep 4 06:41:37 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Sun, 3 Sep 2006 21:41:37 -0700 (PDT) Subject: [Tutor] Is this called a 'Hash table method for string mapping' Message-ID: <20060904044137.69152.qmail@web38108.mail.mud.yahoo.com> Dear group, for mapping a string of protein/nucleotides, BLAST is one tool that is highly sought. However, its performance is limited due to some factors and one such factor is length of the query string. IF the length of the query string is less than 30 characters, its output is questionable. So, what if one has to map a string of 15 character nucleotide to a jumbo string of characters of length in millions. The simplest solution to this could be string matching. A researcher from NCI (National Cancer Institute) said to map 500 thousand strings of nucleotides(length of string - 21), they used a hash-table method to map them on the a chromosome (say 15million length of string). I do not know what exactly could be a hash-table method. I tried a simplest way of mapping. Could tutors comment on this method of mapping. # Target string # a = 'GATGAAGACTTGCAGCGTGGACACTGGCCCAGCCCCGGGTCGCTAAGGAGCTCCGGCAGCTAGGCGCGGAGATGGGGGTGCCCGAACGTCCCACCCTGCTGCTTTTACTCTCCTTGCTACTGATTCCTCTGGGCCTCCCAGTCCTCTGTGCTCCCCCACGCCTCATCTGCGACAGTCGAGTTCTGGAGAGGTACATCTTAGAGGCCAAGGAGGCAGAAAATGTCACGATGGGTTGTGCAGAAGGTCCCAGACTGAGTGAAAATATTACAGTCCCAGATACCAAAGTCAACTTCTATGCTTGGAAAAGAATGGAGGTGGAAGAACAGGCCATAGAAGTTTGGCAAGGCCTGTCCCTGCTCTCAGAAGCCATCCTGCAGGCCCAGGCCCTGCTAGCCAATTCCTCCCAGCCACCAGAGACCCTTCAGCTTCATATAGACAAAGCCATCAGTGGTCTACGTAGCCTCACTTCACTGCTTCGGGTACTGGGAGCTCAGAAGGAATTGATGTCGCCTCCAGATACCACCCCACCTGCTCCACTCCGAACACTCACAGTGGATACTTTCTGCAAGCTCTTCCGGGTCTACGCCAACTTCCTCCGGGGGAAACTGAAGCTGTACACGGGAGAGGTCTGCAGGAGAGGGGACAGGTGACATGCTGCTGCCACCGTGGTGGACCGACGAACTTGCTCCCCGTCACTGTGTCATGCCAACCCTCC' # small query strings# q = ['GCAGGAGAGGGGACA', 'GAAGGTCCCAGACTG', 'CCCAGTCCTCTGTGC'] # In the following routine, I sliced the target string into characters of length 15. I created a dictionary of sliced target sequence and its coordinates# dk = [] dv = [] for m in range(len(a)): s = m e = m+15 u = m+1 nd = a[s:e] if len(nd)==15: x = ('%d:%d')%(u,e) dk.append(nd) dv.append(x) sdic = dict(zip(dk,dv)) for r in q: if sdic.has_key(r): print r+'\t'+sdic[r] # result Answer:# GCAGGAGAGGGGACA 631:645 GAAGGTCCCAGACTG 240:254 CCCAGTCCTCTGTGC 137:151 my question is : Is this a flavor of hash-table method. Do you think is there any flaw in this. Is there any better method that is possible. Thanks Sri __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From gonzillaaa at gmail.com Mon Sep 4 10:45:08 2006 From: gonzillaaa at gmail.com (Gonzillaaa) Date: Mon, 4 Sep 2006 09:45:08 +0100 Subject: [Tutor] Handling hundreds of thousands of inserts with MySQLdb In-Reply-To: <44FAC1EF.4080100@tds.net> References: <370A80F3-C711-4245-A120-811A98D7D6CC@gmail.com> <44F9B365.8060104@tds.net> <4B84C833-ADC0-4A0C-B1BD-71DE468A06C2@gmail.com> <44FAC1EF.4080100@tds.net> Message-ID: Kent I realised after I asked how silly it was to try to "silence" Python. Is just bad habits picked up from php, I fixed the schema and now is all fine. Karl you're absolutely right "LOAD DATA INFILE" works flawlessly and is a lot faster. it seems I was using the wrong tool for the job a quick shell script now does the same thing with a lot less effort, Python is still doing a great job at cleaning the file though ;) Thank you both for your help. Gonzalo. On 3 Sep 2006, at 12:52, Kent Johnson wrote: > Rather than silence the warnings I would fix the data. You could > process > each row in your returnTuple() function. Alternately you could perhaps > change your database table to allow the data. > > Kent > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From duncan at thermal.esa.int Mon Sep 4 11:46:49 2006 From: duncan at thermal.esa.int (Duncan Gibson) Date: Mon, 04 Sep 2006 11:46:49 +0200 Subject: [Tutor] Handling function parameters of mixed object and basic types Message-ID: <20060904094649.61AA522B6@zeeman.thermal.esa.int> I've taken over someone else's code (yes, honestly!) that has a complex class hierarchy on top of the main procedural code. This is unfortunate because it means that isinstance() is everywhere. Profiling recently highlighted one particular formatted output function that has a cascade of isinstance() tests where the order of the tests is significant, as in the example: def oldOutput(x): if x is None: pass elif isinstance(x, Z): pass elif isinstance(x, Y): pass elif isinstance(x, X): pass elif isinstance(x, int): pass elif isinstance(x, float): pass elif isinstance(x, str): pass else: pass # NOTE: # In the real code, there are various enumeration classes # derived from int, so we can't even test for the built in # types before we test for particular classes. I don't like this, because we are usurping Pythons class handling, and suggested that we create methods in the classes and let Python do the work, and replace the above with something like: def newOutput(x): if x is None: pass return try: x.output() except AttributeError: if isinstance(x, int): pass elif isinstance(x, float): pass elif isinstance(x, str): pass else: pass However, when I verified this example using timeit, the results were completely unexpected. The time to resolve the objects remains the same, but for the built-in types raising and catching the exception means that resolution of built-in types takes 3 or 4 times longer. The improved robustness of the code for objects is obviously good, but not at the expense of killing performance for the built-in types. Have I made a basic boo-boo in my test code? Is there a better way of speeding up the original function? I don't really want to spend hours (days?) implementing this in the real code if I'm barking up the wrong tree. I attach the full example code below. Cheers Duncan #--------------------------------------------------------------------- class X(object): def __init__(self): self.x = 0 def output(self): pass class Y(X): def __init__(self): X.__init__(self) self.y = 0 def output(self): pass class Z(Y): def __init__(self): Y.__init__(self) self.z = 0 def output(self): pass def oldOutput(x): if x is None: pass elif isinstance(x, Z): pass elif isinstance(x, Y): pass elif isinstance(x, X): pass elif isinstance(x, int): pass elif isinstance(x, float): pass elif isinstance(x, str): pass else: pass def newOutput(x): if x is None: pass return try: x.output() except AttributeError: if isinstance(x, int): pass elif isinstance(x, float): pass elif isinstance(x, str): pass else: pass if __name__ == '__main__': from timeit import Timer # first test that the functions 'work' before timing them # for i in (None, 1, 1.0, "one", X(), Y(), Z(), []): oldOutput(i) newOutput(i) # now time the functions # for i in ('None', '1', '1.0', '"one"', 'X()', 'Y()', 'Z()', '[]'): s = 'oldOutput(%s)' % i t = Timer(s, 'from __main__ import X, Y, Z, oldOutput, newOutput') print 'old', i, t.timeit() s = 'newOutput(%s)' % i t = Timer(s, 'from __main__ import X, Y, Z, oldOutput, newOutput') print 'new', i, t.timeit() print From alan.gauld at freenet.co.uk Mon Sep 4 12:40:20 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 4 Sep 2006 11:40:20 +0100 Subject: [Tutor] Handling function parameters of mixed object and basic types References: <20060904094649.61AA522B6@zeeman.thermal.esa.int> Message-ID: <001a01c6d00e$85753b50$0201a8c0@XPpro> > I've taken over someone else's code (yes, honestly!) that has a > complex class hierarchy on top of the main procedural code. This > is unfortunate because it means that isinstance() is everywhere. It shouldn't do. Multiple uses of isinstance is usually a sign of bad OO design, regardlerss of whether procedurak code is involved or not. As you go on to prove... :-) > def newOutput(x): > if x is None: > pass > return > try: > x.output() > except AttributeError: > if isinstance(x, int): > pass > elif isinstance(x, float): > pass > elif isinstance(x, str): > pass > else: > pass > > However, when I verified this example using timeit, the results were > completely unexpected. The time to resolve the objects remains the > same, but for the built-in types raising and catching the exception > means that resolution of built-in types takes 3 or 4 times longer. Yes, thats because whehn you call x.output when the method doesn't exist Python has to navigate the entire class heirarchy looking for the missing method before it can return the exception. The solution is to extend the logic you used for N0one - ie put all the non object cases first, then, only if it is an object, use isinstance. That should keep the speed up for the primitive types but keep the clean design for the OOP stuff. If you don't like that layout then you could do an isinstance call on a common superclass before invoking the method. > The improved robustness of the code for objects is obviously good, > but not at the expense of killing performance for the built-in > types. > > Have I made a basic boo-boo in my test code? Is there a better way > of speeding up the original function? I don't really want to spend > hours (days?) implementing this in the real code if I'm barking up > the wrong tree. Personally I'd just keep all the exception types together at the top. Alan G. From duncan at thermal.esa.int Mon Sep 4 14:07:14 2006 From: duncan at thermal.esa.int (Duncan Gibson) Date: Mon, 4 Sep 2006 14:07:14 +0200 Subject: [Tutor] Handling function parameters of mixed object and basic types In-Reply-To: <001a01c6d00e$85753b50$0201a8c0@XPpro> References: <20060904094649.61AA522B6@zeeman.thermal.esa.int> <001a01c6d00e$85753b50$0201a8c0@XPpro> Message-ID: <20060904140714.4966aa54.duncan@thermal.esa.int> I wrote: > > def newOutput(x): > > if x is None: > > pass > > return > > try: > > x.output() > > except AttributeError: > > if isinstance(x, int): > > pass > > elif isinstance(x, float): > > pass > > elif isinstance(x, str): > > pass > > else: > > pass > > > > However, when I verified this example using timeit, the results > > were completely unexpected. The time to resolve the objects > > remains the same, but for the built-in types raising and catching > > the exception means that resolution of built-in types takes 3 or > > 4 times longer. Alan replied: > Yes, thats because whehn you call x.output when the method doesn't > exist Python has to navigate the entire class heirarchy looking for > the missing method before it can return the exception. > > The solution is to extend the logic you used for None - ie put all > the non object cases first, then, only if it is an object, use > isinstance. That was my first thought when I looked at this last week, and just put all of the isinstance(built-in) tests at the top. However, as mentioned in the original post, but maybe not very clearly, there are some enumeration classes that derive from int, so I have to check for those before I check for int: class EnumerationType(int): pass if x is None: pass elif isinstance(x, EnumerationType): pass elif isinstance(x, int): pass ... And of course, there may be specific Enumeration type classes to be tested before testing for the generic, so we end up back at square one, having to know the class hierarchy so that we can test in the correct order. And that's why it was so disappointing to find that doing it the OO way to improve the code might give such poor performance. My colleague suggested using x.__class__ and below as an index into a jump table, but this just perpetuates the unmaintainable instead of letting Python's class mechanisms do all this for us. The EnumerationType class claims to have 'low memory usage and fast performance' but maybe we need to look at re-implementing it to derive from object and not int. Unfortunately it's one of the key abstractions in the code, and these enumerations are used just about everywhere. I'll need to see if other classes derive from built-in types too... Cheers Duncan From kent37 at tds.net Mon Sep 4 15:26:38 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 04 Sep 2006 09:26:38 -0400 Subject: [Tutor] Handling function parameters of mixed object and basic types In-Reply-To: <20060904094649.61AA522B6@zeeman.thermal.esa.int> References: <20060904094649.61AA522B6@zeeman.thermal.esa.int> Message-ID: <44FC298E.3070400@tds.net> Duncan Gibson wrote: > I've taken over someone else's code (yes, honestly!) that has a > complex class hierarchy on top of the main procedural code. This > is unfortunate because it means that isinstance() is everywhere. > > Profiling recently highlighted one particular formatted output > function that has a cascade of isinstance() tests where the order > of the tests is significant, as in the example: > > def oldOutput(x): > if x is None: > pass > elif isinstance(x, Z): > pass > elif isinstance(x, Y): > pass > elif isinstance(x, X): > pass > elif isinstance(x, int): > pass > elif isinstance(x, float): > pass > elif isinstance(x, str): > pass > else: > pass > > # NOTE: > # In the real code, there are various enumeration classes > # derived from int, so we can't even test for the built in > # types before we test for particular classes. Here are two more options. output3() checks for the specific builtin types, rather than instances, so your EnumerationType will not be found. They are both faster than oldOutput for builtins other than None. output3 is slower than newOutput for classes because the builtins are tested first, but it uses OO dispatch so it is more maintainable. output4 is almost as fast as newOutput for class types but it will require changes when a new type is added. def output3(x): if x is None: pass elif type(x) == int: pass elif type(x) == float: pass elif type(x) == str: pass elif type(x) == list: pass else: x.output() def passer(): pass dispatch = { type(None): passer, int: passer, float: passer, str: passer, list: passer, X: passer, Y: passer, Z: passer, } def output4(x): dispatch.get(type(x), passer)() PS on use of timeit - it's a good idea to time multiple runs and take the minimum. I used min(t.repeat(number=10000)). Kent From kayrivertree at yahoo.com Mon Sep 4 17:45:31 2006 From: kayrivertree at yahoo.com (Kay White) Date: Mon, 4 Sep 2006 08:45:31 -0700 (PDT) Subject: [Tutor] making independent program? In-Reply-To: <5e58f2e40608281432k19a81b7dl8c379afb0fd421c6@mail.gmail.com> Message-ID: <20060904154531.87483.qmail@web56106.mail.re3.yahoo.com> John Fouhy wrote: On 29/08/06, Alan Gauld wrote: > Thats probably because the most common methods for > producing an exe file are "non-trivial" to use, especially for > newbies. > > Look up py2exe on Google... py2exe is not too hard for simple tasks (unless something goes wrong), especially if you can find someone to throw a sample setup.py at you. There are people on this list who can help.. -- John. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor Hello again, :-) I'm now trying to use py2exe now to create an application out of my script, and. I have managed to create a simple setup.py that produces a working application, but the finished product is bloated with many things I don't want, such as Tkinter. I've tried to follow the py2exe wiki instructions on how to trim this out, http://www.py2exe.org/index.cgi/TkInter, but I seem to be doing something wrong. Here's my setup.py--- from distutils.core import setup import py2exe excludes = ["pywin", "pywin.debugger", "pywin.debugger.dbgcon", "pywin.dialogs", "pywin.dialogs.list", "Tkconstants","Tkinter","tcl", "_imagingtk", "PIL._imagingtk", "ImageTk", "PIL.ImageTk", "FixTk"] setup(windows=['ob_portrait.pyw']) Can somebody point out what I'm doing wrong? I think I have to put something in the setup() line, but everything I've tried has caused errors. This works, but it still creates a dist directory full of stuff I don't want. --------------------------------- Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great rates starting at 1?/min. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060904/6b11750f/attachment.htm From billburns at pennswoods.net Mon Sep 4 18:16:48 2006 From: billburns at pennswoods.net (Bill Burns) Date: Mon, 04 Sep 2006 12:16:48 -0400 Subject: [Tutor] making independent program? In-Reply-To: <20060904154531.87483.qmail@web56106.mail.re3.yahoo.com> References: <20060904154531.87483.qmail@web56106.mail.re3.yahoo.com> Message-ID: <44FC5170.4090201@pennswoods.net> > I've tried to follow the py2exe wiki instructions on how to trim this > out, http://www.py2exe.org/index.cgi/TkInter, but I seem to be doing > something wrong. Here's my setup.py--- > > from distutils.core import setup > import py2exe > > excludes = ["pywin", "pywin.debugger", "pywin.debugger.dbgcon", > "pywin.dialogs", "pywin.dialogs.list", > "Tkconstants","Tkinter","tcl", > "_imagingtk", "PIL._imagingtk", "ImageTk", "PIL.ImageTk", > "FixTk"] > > setup(windows=['ob_portrait.pyw']) Try changing your setup line to this: setup(windows=[{'script':'ob_portrait.pyw','excludes':excludes}]) HTH Bill From dyoo at hkn.eecs.berkeley.edu Mon Sep 4 19:37:28 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 4 Sep 2006 10:37:28 -0700 (PDT) Subject: [Tutor] Is this called a 'Hash table method for string mapping' In-Reply-To: <20060904044137.69152.qmail@web38108.mail.mud.yahoo.com> References: <20060904044137.69152.qmail@web38108.mail.mud.yahoo.com> Message-ID: > So, what if one has to map a string of 15 character nucleotide to a > jumbo string of characters of length in millions. Hi Srinivas, If you're doing research into this, I strongly recommend you take a look at Dan Gusfield's excellent textbook "Algorithms on Strings, Trees, and Sequences": http://www.cambridge.org/uk/catalogue/catalogue.asp?isbn=0521585198 Reinvention is fun, but there's already been a lot of work poured into this field; the textbook above provides more background, so you can stand on previous efforts. [code cut] > Do you think is there any flaw in this. It works, and I don't see anything immediately wrong with this. The only issue is that it'll be only exact matching on the oligos that have been stored in that hashtable. > Is there any better method that is possible. It depends on what you're looking for. Note that the approach you're using will only match properly if your oligo width matches the query string width. This may or may not be a problem for you. Gusfield's textbook above surveys several other methods of doing string matching that are particularly suitable for biologists. If you're planning to do a lot of small queries on a large string like that, then a data structure such as a "suffix tree" is worth knowing. http://en.wikipedia.org/wiki/Suffix_tree You may also want to look into specialized applications; arabidopsis.org hosts a program called 'patmatch' that may be helpful for you: http://nar.oxfordjournals.org/cgi/content/abstract/33/suppl_2/W262 (As a disclaimer: I did some work on patmatch.) Good luck. From kayrivertree at yahoo.com Mon Sep 4 21:48:19 2006 From: kayrivertree at yahoo.com (Kay White) Date: Mon, 4 Sep 2006 12:48:19 -0700 (PDT) Subject: [Tutor] making independent program? In-Reply-To: <44FC6334.4080306@gmail.com> Message-ID: <20060904194819.16390.qmail@web56113.mail.re3.yahoo.com> Andrew Robert wrote: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Rather than fight this, I recommend you try cx_freeze. Over all, it is much easier to use and does not require code modification of any kind. http://www.python.net/crew/atuining/cx_Freeze/ cx_freeze does make a much smaller dist directory, but the resulting exe has an error File "C:\Python24\lib\site-packages\PIL\Image.py", line 1745, in open raise IOError("cannot identify image file") IOError: cannot identify image file I looked in the archives of the cx_freeze mailing list and there is some discussion about this, but they don't seem to have a solution. --------------------------------- Do you Yahoo!? Get on board. You're invited to try the new Yahoo! Mail. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060904/cfbdacb1/attachment.html From kayrivertree at yahoo.com Mon Sep 4 21:53:30 2006 From: kayrivertree at yahoo.com (Kay White) Date: Mon, 4 Sep 2006 12:53:30 -0700 (PDT) Subject: [Tutor] making independent program? In-Reply-To: <44FC5170.4090201@pennswoods.net> Message-ID: <20060904195330.42287.qmail@web56115.mail.re3.yahoo.com> Bill Burns wrote: > I've tried to follow the py2exe wiki instructions on how to trim this > out, http://www.py2exe.org/index.cgi/TkInter, but I seem to be doing > something wrong. Here's my setup.py--- > > from distutils.core import setup > import py2exe > > excludes = ["pywin", "pywin.debugger", "pywin.debugger.dbgcon", > "pywin.dialogs", "pywin.dialogs.list", > "Tkconstants","Tkinter","tcl", > "_imagingtk", "PIL._imagingtk", "ImageTk", "PIL.ImageTk", > "FixTk"] > > setup(windows=['ob_portrait.pyw']) Try changing your setup line to this: setup(windows=[{'script':'ob_portrait.pyw','excludes':excludes}]) HTH Bill Thanks but that doesn't really change anything, still getting the unwanted files. I am deleting the old build and dist directories before running py2exe, so I'm sure they aren't being mixed in with the new. --------------------------------- Stay in the know. Pulse on the new Yahoo.com. Check it out. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060904/c44889f8/attachment-0001.htm From kayrivertree at yahoo.com Mon Sep 4 22:44:31 2006 From: kayrivertree at yahoo.com (Kay White) Date: Mon, 4 Sep 2006 13:44:31 -0700 (PDT) Subject: [Tutor] making independent program? Message-ID: <20060904204431.36729.qmail@web56113.mail.re3.yahoo.com> Kay White wrote: Andrew Robert wrote: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Rather than fight this, I recommend you try cx_freeze. Over all, it is much easier to use and does not require code modification of any kind. http://www.python.net/crew/atuining/cx_Freeze/ cx_freeze does make a much smaller dist directory, but the resulting exe has an error File "C:\Python24\lib\site-packages\PIL\Image.py", line 1745, in open raise IOError("cannot identify image file") IOError: cannot identify image file I looked in the archives of the cx_freeze mailing list and there is some discussion about this, but they don't seem to have a solution. --------------------------------- Replying to my own post here...I have found a solution in the mailing list after looking a bit more. My thanks for pointing me to cx_freeze. It's much easier to use and makes nice small files :-) --------------------------------- Do you Yahoo!? Everyone is raving about the all-new Yahoo! Mail. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060904/32c4627c/attachment.htm From asdlinux at yahoo.se Mon Sep 4 23:51:14 2006 From: asdlinux at yahoo.se (=?ISO-8859-1?Q?Magnus_Wirstr=F6m?=) Date: Mon, 04 Sep 2006 23:51:14 +0200 Subject: [Tutor] File open error Message-ID: <44FC9FD2.5070405@yahoo.se> Hi I'm trying to open a file with open() but i get this error i cant put my finger how to fix. Code looks like this. ... def OnStartaButton(self, event): print "Startade ", ctime(time()) self.startOP.SetLabel(ctime(time())) self.staticText7.SetLabel("L?ser konfiguration.") config = open("backup.conf", "r") config.readline() #discard line config.readline() #discard line filsource=config.readline() config.readline() #discard line fildest=config.readline() config.close() self.staticText7.SetLabel("L?ser katalogstruktur.") ... When i'm executing it i get this error (runtime) Traceback (most recent call last): File "C:\python\boa\backup\backupwin.py", line 135, in OnStartaButton config = open("backup.conf", "r") TypeError: an integer is required what does it want ? i can't figur it out ... the weird thing is that if i put the exactly same line (the open line) in the python shell it works. So why not in my program ?7 Thanks Magnus From john at fouhy.net Mon Sep 4 23:59:59 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 5 Sep 2006 09:59:59 +1200 Subject: [Tutor] File open error In-Reply-To: <44FC9FD2.5070405@yahoo.se> References: <44FC9FD2.5070405@yahoo.se> Message-ID: <5e58f2e40609041459u221e51e0n60399e7a1e48d7a4@mail.gmail.com> On 05/09/06, Magnus Wirstr?m wrote: > When i'm executing it i get this error (runtime) > > Traceback (most recent call last): > File "C:\python\boa\backup\backupwin.py", line 135, in OnStartaButton > config = open("backup.conf", "r") > TypeError: an integer is required Looks like you're redefining 'open' somewhere. Look through your code; do you have anything like: def open(...): or open = or from ... import open or from ... import * ? -- John. From dyoo at hkn.eecs.berkeley.edu Tue Sep 5 05:24:38 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 4 Sep 2006 20:24:38 -0700 (PDT) Subject: [Tutor] File open error In-Reply-To: <5e58f2e40609041459u221e51e0n60399e7a1e48d7a4@mail.gmail.com> References: <44FC9FD2.5070405@yahoo.se> <5e58f2e40609041459u221e51e0n60399e7a1e48d7a4@mail.gmail.com> Message-ID: On Tue, 5 Sep 2006, John Fouhy wrote: >> When i'm executing it i get this error (runtime) >> >> Traceback (most recent call last): >> File "C:\python\boa\backup\backupwin.py", line 135, in OnStartaButton >> config = open("backup.conf", "r") >> TypeError: an integer is required I agree with John: this is almost certainly os.open(), which takes integers, rather than the builtin open(). From emilia12 at mail.bg Tue Sep 5 08:32:49 2006 From: emilia12 at mail.bg (emilia12 at mail.bg) Date: Tue, 05 Sep 2006 09:32:49 +0300 Subject: [Tutor] [tutor] how to cast to stucture Message-ID: <1157437969.a0602dc9eaf36@mail.bg> Hi list, i have a complex data in binary file and i want to read its fields... the C way is to read file in buffer and then cast it to proper structure. Is there a way to do the same in Python or i have to read the data byte by byte ? Regards, E. ----------------------------- ??????? ?????????! bg.sportingbet.com From samrobertsmith at gmail.com Tue Sep 5 08:58:47 2006 From: samrobertsmith at gmail.com (linda.s) Date: Mon, 4 Sep 2006 23:58:47 -0700 Subject: [Tutor] about tkinter In-Reply-To: <001d01c6bbd1$ff361050$0201a8c0@XPpro> References: <1d987df30608090349o5643cf8do41a0ae6f8aa169e2@mail.gmail.com> <001d01c6bbd1$ff361050$0201a8c0@XPpro> Message-ID: <1d987df30609042358p250f173fif1f3b97928103835@mail.gmail.com> On 8/9/06, Alan Gauld wrote: > Linda, > > > Is that possible to open two Tkinter from one python shell? > > Tkinter is a python module. You can't really open a Tkinter, > you can only import the module. What you can do is write > a Tkinter application with multiple windows. > > You can have as many Tkinter applications running as > you like but they will all be separate processes. > > Can you be clearer about what exactly you want to do? > > Alan G. I want to open two windows with one having the blue triangle and the other one having the red triangle (the code is attached). I can not figure out how to use toplevel. Linda -------------- next part -------------- A non-text attachment was scrubbed... Name: two.py Type: text/x-python Size: 848 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060904/2939082a/attachment.py From Python at kraszewscy.net Tue Sep 5 09:34:39 2006 From: Python at kraszewscy.net (Pawel Kraszewski) Date: Tue, 5 Sep 2006 09:34:39 +0200 Subject: [Tutor] [tutor] how to cast to stucture In-Reply-To: <1157437969.a0602dc9eaf36@mail.bg> References: <1157437969.a0602dc9eaf36@mail.bg> Message-ID: <200609050934.39149.Python@kraszewscy.net> Dnia wtorek, 5 wrze?nia 2006 08:32, emilia12 at mail.bg napisa?: > i have a complex data in binary file and i want to read its > fields... the C way is to read file in buffer and then cast > it to proper structure. Is there a way to do the same in > Python or i have to read the data byte by byte ? cite: ----------------- struct -- Interpret strings as packed binary data This module performs conversions between Python values and C structs represented as Python strings. It uses format strings (explained below) as compact descriptions of the lay-out of the C structs and the intended conversion to/from Python values. This can be used in handling binary data stored in files or from network connections, among other sources. ----------------- see http://docs.python.org/lib/module-struct.html -- Pawel Kraszewski http://www.kraszewscy.net From alan.gauld at freenet.co.uk Tue Sep 5 09:55:41 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 5 Sep 2006 08:55:41 +0100 Subject: [Tutor] about tkinter References: <1d987df30608090349o5643cf8do41a0ae6f8aa169e2@mail.gmail.com> <001d01c6bbd1$ff361050$0201a8c0@XPpro> <1d987df30609042358p250f173fif1f3b97928103835@mail.gmail.com> Message-ID: <000501c6d0c0$c00f1530$0201a8c0@XPpro> Hi Linda, >> Can you be clearer about what exactly you want to do? >> > I want to open two windows with one having the blue triangle and the > other one having the red triangle (the code is attached). I can not > figure out how to use toplevel. Looking at your code it would help the readasbility if you put some of it into functions like draw_line(seg,color) draw_oval(x,y) Assuming you did this your code would then look a bit like: root = Tk() can = Canvas(root,....) can.pack() for x,y in points1: draw_oval(x,y) for seg in segs1: draw_line(seg,'blue') for x,y in points2: draw_oval(x,y) for seg in seg2: draw_line(seg, 'red') Now I assume that you want to split the code after the first pair of figures and create a second window there? You can use Toplevel just as you do root: top = Toplevel(root) can2 = Canvas(top,...) can2.pack() Note that because Toplevel inherits from root you only need the one mainloop() call, usually placed at the end of your code Here is a very short example of creating two windows: >>> from Tkinter import * >>> win = Tk() >>> win1 = Toplevel(win) >>> f = Frame(win) >>> f.pack() >>> g = Frame(win1) >>> g.pack() >>> Label(f,text="Main").pack() >>> Label(g,text="Sub").pack() >>> win.mainloop() BTW I personally find it best not to pack widgets directly into the toplevel/root window but to first insert a frame. Then pack the other widgets(like your canvas or my Labels) into the frame - it seems to make things behave a little more predictably.) HTH, Alan G. From michael22316497 at hotmail.com Tue Sep 5 09:54:36 2006 From: michael22316497 at hotmail.com (mike park) Date: Tue, 05 Sep 2006 07:54:36 +0000 Subject: [Tutor] Q Message-ID: my Q is how do you learn the languge of python ? and how do you program? From samrobertsmith at gmail.com Tue Sep 5 10:46:02 2006 From: samrobertsmith at gmail.com (linda.s) Date: Tue, 5 Sep 2006 01:46:02 -0700 Subject: [Tutor] about tkinter In-Reply-To: <000501c6d0c0$c00f1530$0201a8c0@XPpro> References: <1d987df30608090349o5643cf8do41a0ae6f8aa169e2@mail.gmail.com> <001d01c6bbd1$ff361050$0201a8c0@XPpro> <1d987df30609042358p250f173fif1f3b97928103835@mail.gmail.com> <000501c6d0c0$c00f1530$0201a8c0@XPpro> Message-ID: <1d987df30609050146p19271cfq90e5da8f07af1778@mail.gmail.com> On 9/5/06, Alan Gauld wrote: > Hi Linda, > > >> Can you be clearer about what exactly you want to do? > >> > > I want to open two windows with one having the blue triangle and the > > other one having the red triangle (the code is attached). I can not > > figure out how to use toplevel. > > Looking at your code it would help the readasbility if you put some > of it into functions like > draw_line(seg,color) > draw_oval(x,y) > > Assuming you did this your code would then look a bit like: > > root = Tk() > can = Canvas(root,....) > can.pack() > for x,y in points1: > draw_oval(x,y) > for seg in segs1: > draw_line(seg,'blue') > for x,y in points2: > draw_oval(x,y) > for seg in seg2: > draw_line(seg, 'red') > > Now I assume that you want to split the code after the first pair > of figures and create a second window there? > > You can use Toplevel just as you do root: > > top = Toplevel(root) > can2 = Canvas(top,...) > can2.pack() > > Note that because Toplevel inherits from root you only > need the one mainloop() call, usually placed at the end > of your code > > Here is a very short example of creating two windows: > > >>> from Tkinter import * > >>> win = Tk() > >>> win1 = Toplevel(win) > >>> f = Frame(win) > >>> f.pack() > >>> g = Frame(win1) > >>> g.pack() > >>> Label(f,text="Main").pack() > >>> Label(g,text="Sub").pack() > >>> win.mainloop() > > BTW I personally find it best not to pack widgets directly > into the toplevel/root window but to first insert a frame. Then > pack the other widgets(like your canvas or my Labels) into > the frame - it seems to make things behave a little > more predictably.) > > HTH, > > Alan G. > > If I close the 'main' window, 'sub' window will be closed too. How can I close just one window? Linda From klappnase at freenet.de Tue Sep 5 11:22:36 2006 From: klappnase at freenet.de (Michael Lange) Date: Tue, 5 Sep 2006 11:22:36 +0200 Subject: [Tutor] about tkinter In-Reply-To: <1d987df30609050146p19271cfq90e5da8f07af1778@mail.gmail.com> References: <1d987df30608090349o5643cf8do41a0ae6f8aa169e2@mail.gmail.com> <001d01c6bbd1$ff361050$0201a8c0@XPpro> <1d987df30609042358p250f173fif1f3b97928103835@mail.gmail.com> <000501c6d0c0$c00f1530$0201a8c0@XPpro> <1d987df30609050146p19271cfq90e5da8f07af1778@mail.gmail.com> Message-ID: <20060905112236.1a7516a8.klappnase@freenet.de> On Tue, 5 Sep 2006 01:46:02 -0700 "linda.s" wrote: > > > If I close the 'main' window, 'sub' window will be closed too. How can > I close just one window? > Linda Hi Linda, you can use a "hidden" root window, like this: root = Tk() root.withdraw()# hide the root window top1 = Toplevel(root) top2 = Toplevel(root) Don't forget to define a method that exits the application when the last Toplevel is being closed, because if you close both Toplevels the root window is still there and no way to close it from the gui. Here is a primitive to show how this might work: def close_top1(): global top1 top1.destroy() top1 = None if top2 is None: root.quit() top1.protocol("WM_DELETE_WINDOW", close_top1) ( and the same for top2 of course) This makes the close_top1() function be executed when the "X" in the window's upper right corner is clicked. I hope this helps. Michael From kent37 at tds.net Tue Sep 5 11:52:29 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 05 Sep 2006 05:52:29 -0400 Subject: [Tutor] Q In-Reply-To: References: Message-ID: <44FD48DD.2050105@tds.net> mike park wrote: > my Q is how do you learn the languge of python ? and how do you program? Read one of the tutorials here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Try things out. Experiment. Ask questions on this list when you get stuck or don't understand something. The book "Python Programming for the absolute beginner" by Michael Dawson is good for beginners with no programming background. Kent From tomdrak at gmail.com Tue Sep 5 11:40:31 2006 From: tomdrak at gmail.com (tomd) Date: Tue, 5 Sep 2006 11:40:31 +0200 Subject: [Tutor] Q In-Reply-To: Message-ID: <200695114031.028735@oem-up3sjowr2u8> > my Q is how do you learn the languge of python ? and how do you program? see http://www.freenetpages.co.uk/hp/alan.gauld/ -- Tom, http://www.vscripts.net/ From alan.gauld at freenet.co.uk Tue Sep 5 19:09:45 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 5 Sep 2006 18:09:45 +0100 Subject: [Tutor] about tkinter References: <1d987df30608090349o5643cf8do41a0ae6f8aa169e2@mail.gmail.com> <001d01c6bbd1$ff361050$0201a8c0@XPpro> <1d987df30609042358p250f173fif1f3b97928103835@mail.gmail.com> <000501c6d0c0$c00f1530$0201a8c0@XPpro> <1d987df30609050146p19271cfq90e5da8f07af1778@mail.gmail.com> Message-ID: <000301c6d10e$16994a90$0201a8c0@XPpro> >> Here is a very short example of creating two windows: >> >> >>> from Tkinter import * >> >>> win = Tk() >> >>> win1 = Toplevel(win) >> >>> f = Frame(win) >> >>> f.pack() >> >>> g = Frame(win1) >> >>> g.pack() >> >>> Label(f,text="Main").pack() >> >>> Label(g,text="Sub").pack() >> >>> win.mainloop() > If I close the 'main' window, 'sub' window will be closed too. How > can > I close just one window? You need to hide the main window (there must be one(*) but it can be very small!) and then make all your visible windows Toplevels. (*)That may not be true but I don't know of a way to avoid it... Alan g. From alan.gauld at freenet.co.uk Tue Sep 5 19:14:03 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 5 Sep 2006 18:14:03 +0100 Subject: [Tutor] [tutor] how to cast to stucture References: <1157437969.a0602dc9eaf36@mail.bg> Message-ID: <002301c6d10e$b06cde70$0201a8c0@XPpro> > i have a complex data in binary file and i want to read its > fields... the C way is to read file in buffer and then cast > it to proper structure. Is there a way to do the same in > Python or i have to read the data byte by byte ? You can use the struct module to unpack an arbitrary sequence of bytes. You can find a very basic intro to struct in the File Handliung topic of my tutorial. But its not as simple as in C where you can more or less map a memory area onto a structuure, you'll need to extract each field and inert it into the equivalent Python data structure - but if that is a class you can write a method (load say?) to do the heavy work and just call load(file) or whatever when needed. Alan G. From alan.gauld at freenet.co.uk Tue Sep 5 19:17:31 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 5 Sep 2006 18:17:31 +0100 Subject: [Tutor] Q References: Message-ID: <002e01c6d10f$2c4a76b0$0201a8c0@XPpro> > my Q is how do you learn the languge of python ? > and how do you program? Visit the Python website, download and install Python for your platform. Visit the beginners page and find a beginners tutorial that you like (maybe mine). http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Read it until you don't understand something, then ask a specific question here. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Sep 5 19:19:04 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 5 Sep 2006 18:19:04 +0100 Subject: [Tutor] about tkinter References: <1d987df30608090349o5643cf8do41a0ae6f8aa169e2@mail.gmail.com><001d01c6bbd1$ff361050$0201a8c0@XPpro><1d987df30609042358p250f173fif1f3b97928103835@mail.gmail.com><000501c6d0c0$c00f1530$0201a8c0@XPpro><1d987df30609050146p19271cfq90e5da8f07af1778@mail.gmail.com> <20060905112236.1a7516a8.klappnase@freenet.de> Message-ID: <003a01c6d10f$63c2c020$0201a8c0@XPpro> > you can use a "hidden" root window, like this: > > root = Tk() > root.withdraw()# hide the root window Aha! I thought there should be a better way than defining the size to be 1 pixel! :-) Thanks for that tip Michael, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Tue Sep 5 19:35:34 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 05 Sep 2006 13:35:34 -0400 Subject: [Tutor] [tutor] how to cast to stucture In-Reply-To: <1157437969.a0602dc9eaf36@mail.bg> References: <1157437969.a0602dc9eaf36@mail.bg> Message-ID: <44FDB566.7060804@tds.net> emilia12 at mail.bg wrote: > Hi list, > > i have a complex data in binary file and i want to read its > fields... the C way is to read file in buffer and then cast > it to proper structure. Is there a way to do the same in > Python or i have to read the data byte by byte ? As well as the struct module you might want to look at pyconstruct which is a bit higher-level. http://pyconstruct.wikispaces.com/ Kent From Barry.Carroll at psc.com Tue Sep 5 20:33:11 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 5 Sep 2006 11:33:11 -0700 Subject: [Tutor] Where to post a Python Program Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3735@eugsrv400.psc.pscnet.com> Greetings: I have written a console version of the dice game Yahtzee). I would like to post it for comment. It is too long to post here and I don't have a web site. Is there some place where I can post my code and get feedback about it? Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060905/8e32b741/attachment.html From simplebob at gmail.com Tue Sep 5 20:47:37 2006 From: simplebob at gmail.com (Daniel McQuay) Date: Tue, 5 Sep 2006 14:47:37 -0400 Subject: [Tutor] Where to post a Python Program In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C3735@eugsrv400.psc.pscnet.com> Message-ID: <44fdc64c.220e819c.7caf.ffff8b24@mx.gmail.com> > Greetings: > > I have written a console version of the dice game Yahtzee). I would like to post it for comment. It is too long to post here and I don't have a web site. > Is there some place where I can post my code and get feedback about it? Hey Barry, There are several websites that allow you to post your code for review. I think one of the best ones is [http://pastebin.com/]. You should also have a look at [http://pastebin.ca/] (not sure if they are affiliated) which happened to turn up during a google search. HTH, Daniel McQuay www.prowiseguys.com simplebob at gmail.com 814.825.0847 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060905/f0eac240/attachment.htm From Mike.Hansen at atmel.com Tue Sep 5 20:54:28 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Tue, 5 Sep 2006 12:54:28 -0600 Subject: [Tutor] Hi All Message-ID: <57B026980605A64F9B23484C5659E32E2E7B1D@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Amit Rane > Sent: Saturday, September 02, 2006 4:52 AM > To: tutor at python.org > Subject: [Tutor] Hi All > > Hi , > This is Amit from India ... > i have just started working on Python ... > please let me know the books to refer to start > learning > python ..as of now i am going thru online books ... > please let me know if any additional books are there . > > > > Thanks & Regards , > Amit Rane > > This question gets asked a lot, so here's a tinyurl link to the FAQ on this topic. http://tinyurl.com/kl9bu which is http://pyfaq.infogami.com/tutor-what-are-some-good-books-on-python ********************************************************************************************** IMPORTANT: The contents of this email and any attachments are confidential. They are intended for the named recipient(s) only. If you have received this email in error, please notify the system manager or the sender immediately and do not disclose the contents to anyone or make copies thereof. *** eSafe scanned this email for viruses, vandals, and malicious content. *** ********************************************************************************************** From hockeyc at umich.edu Tue Sep 5 20:55:12 2006 From: hockeyc at umich.edu (Collin Hockey) Date: Tue, 05 Sep 2006 14:55:12 -0400 Subject: [Tutor] Where to post a Python Program In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C3735@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A432C3735@eugsrv400.psc.pscnet.com> Message-ID: <44FDC810.9050700@umich.edu> I've posted things to http://www.uselesspython.com before. They don't have a specific comment form, but you can allow users to e-mail you with responses. Carroll, Barry wrote: > Greetings: > > > > I have written a console version of the dice game Yahtzee). I would > like to post it for comment. It is too long to post here and I don?t > have a web site. Is there some place where I can post my code and get > feedback about it? > > > > Regards, > > > > Barry > > barry.carroll at psc.com > > 541-302-1107 > > /*/________________________/*/ > > */We who cut mere stones must always be envisioning cathedrals./**//* > > */?Quarry worker's creed/**//* > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From tbrannon at utekcorp.com Tue Sep 5 21:43:51 2006 From: tbrannon at utekcorp.com (Terrence Brannon) Date: Tue, 05 Sep 2006 15:43:51 -0400 Subject: [Tutor] Bootstrapping PYTHONPATH In-Reply-To: <44FDC810.9050700@umich.edu> Message-ID: I'm writing a suite of data processing scripts with this layout Data/Vendor/A/proc.py Data/Vendor/B/proc.py Etc, etc Now, I started down the road of having a global config file in Data/Vendor/Global.ini and a per-vendor local config file in Data/Vendor/A/Local.ini But then I realized that I hate any and all mini-languages. I hate embedded templating languages for dynamic HTML generation (I prefer DOM). And I now hate mucking about with configuration systems. I prefer language and library over shortcut mini-languages in this case as well. Thus, instead of using a merge() operation between the global and local, I want to have a base class for configuration to replace Global.ini and I want to extend it in each vendor. To wit: class config: def ftpserver(): "generalftp.com" In vendor, extending base class class config(config): def ftpserver(): "specificftp.com" And in my code, I want to have: import config # imported from Data/Vendor/A/config.py # which extends Data/Vendor/config.py c = config() # merged config ftp = FTP(c.ftpserver()) # "specificftp.com" So my big problem is how to make each local config available to each local proc.py. I've thought of some approaches: * alias python to dataproc and make this a shell script with extends PYTHONPATH before calling proc.py * use a setup.py in each directory and install them in site-packages * Some deep magic line that parses __file__ and adds to PYTHONPATH Any feedback on how to do this is appreciated. From matthew.williams at cancer.org.uk Wed Sep 6 12:03:39 2006 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Wed, 06 Sep 2006 11:03:39 +0100 Subject: [Tutor] Sorting a list in an add order Message-ID: <44FE9CFB.4030002@cancer.org.uk> Dear List, I've written a small script to extract the definitions from my thesis, and output them as a .tex file, which works ok but I have a small problem. The input is done by specifying a directory, and using glob to find the ".tex" filenames. However, I want to process them so that they are arranged in the correct order, which means I need to sort the list of files. Of course, because they aren't named in any (obvious) order, I'm a bit stuck. I thought about using a dictionary to map names and order: so {"OAF":1, "Valuation":2...etc}, but I don't don't know how to take it on from here. I was thinking of looking up the filename in the dictionary (using .startswith() to get some basic rough-matching capacity) and then using that to return the order that the files should be handled in. Any comments/ better ideas? Thanks, Matt From nimrodx at slingshot.co.nz Wed Sep 6 12:38:36 2006 From: nimrodx at slingshot.co.nz (nimrodx) Date: Wed, 06 Sep 2006 22:38:36 +1200 Subject: [Tutor] content disposition header: email module In-Reply-To: <44FE9CFB.4030002@cancer.org.uk> References: <44FE9CFB.4030002@cancer.org.uk> Message-ID: <44FEA52C.9010107@slingshot.co.nz> Hi Python Gurus, I am trying to mail a txt file, then with another client I get the email and extract the text file. The email I send however, does not seem to turn out correctly. The content dispositon header is there, but it seems to be in the wrong place and my email client the text file just gets included in the message body, and the file name is not visible. This is the code: from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage def attch_send(self): msg = MIMEMultipart() #msg.add_header("From", sender) #msg.add_header("To", recv) msg.add_header('Content-Disposition', 'attachment', filename='web-list.txt') msg.attach(MIMEText(file(os.path.join(save_dir, "web-list.txt")).read())) server = smtplib.SMTP('localhost') #server.set_debuglevel(1) server.sendmail(sender, recv, msg.as_string()) server.quit() What is wrong with that? I'd really appreciate your suggestions. Thanks, Matt From mi.janssen at gmail.com Wed Sep 6 12:56:40 2006 From: mi.janssen at gmail.com (Michael Janssen) Date: Wed, 6 Sep 2006 12:56:40 +0200 Subject: [Tutor] Sorting a list in an add order In-Reply-To: <44FE9CFB.4030002@cancer.org.uk> References: <44FE9CFB.4030002@cancer.org.uk> Message-ID: <1ff2dfbf0609060356h43634fc7q98fce7fec777bbff@mail.gmail.com> On 9/6/06, Matt Williams wrote: > The input is done by specifying a directory, and using glob to find the > ".tex" filenames. > > However, I want to process them so that they are arranged in the correct > order, which means I need to sort the list of files. Of course, because > they aren't named in any (obvious) order, I'm a bit stuck. a clean way to do it would be to rename the files so that they can be sorted. OTOH this involves not much python and is entirely boring. OTOOH renaming the files might help you later on, when you need them ordered for other purposes. > I thought about using a dictionary to map names and order: so {"OAF":1, > "Valuation":2...etc}, but I don't don't know how to take it on from > here. I was thinking of looking up the filename in the dictionary (using > .startswith() to get some basic rough-matching capacity) and then using > that to return the order that the files should be handled in. you can specify your own comparing funtion for aList.sort(). Here's a comparing function, that does the same as the default: def mysort(a, b): return cmp(a, b) aList.sort(mysort) Now you can simply lookup other values for filenames a and b and compare that via python builtin cmp function. You can also use a list of filenames and sort by comparing the indecees. The bad thing is, that you have to specify all those filenames within the script - which defeats many of the advantages to read them in dynamically via glob ;-) Is there any chance to determine the sortorder from the files' content? rough-matching is another topic which might bring up some nice algorithms. regards Michael From info at pythonin.dk Wed Sep 6 13:15:44 2006 From: info at pythonin.dk (Morten Juhl Johansen) Date: Wed, 06 Sep 2006 13:15:44 +0200 Subject: [Tutor] Inverse range Message-ID: <44FEADE0.3070706@pythonin.dk> # Newbie warning I am playing with Python. Playing as in learning. Is it possible to reverse a range sequence? If, for instance, I call: for f in range( 1,5 ): print f - I get: 1 2 3 4 Is it possible to reverse it? As in: 4 3 2 1 Yours, Morten From kent37 at tds.net Wed Sep 6 13:51:27 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 06 Sep 2006 07:51:27 -0400 Subject: [Tutor] Sorting a list in an add order In-Reply-To: <44FE9CFB.4030002@cancer.org.uk> References: <44FE9CFB.4030002@cancer.org.uk> Message-ID: <44FEB63F.7050709@tds.net> Matt Williams wrote: > Dear List, > > I've written a small script to extract the definitions from my thesis, > and output them as a .tex file, which works ok but I have a small problem. > > The input is done by specifying a directory, and using glob to find the > ".tex" filenames. > > However, I want to process them so that they are arranged in the correct > order, which means I need to sort the list of files. Of course, because > they aren't named in any (obvious) order, I'm a bit stuck. > > I thought about using a dictionary to map names and order: so {"OAF":1, > "Valuation":2...etc}, but I don't don't know how to take it on from > here. I was thinking of looking up the filename in the dictionary (using > .startswith() to get some basic rough-matching capacity) and then using > that to return the order that the files should be handled in. I'm not entirely sure what you want to do - some example filenames would help. I guess that "OAF" and "Valuation" are prefixes to the filenames so you might have files named OAF2 and Valuation4, is that right? Then the sort would be by prefix, then by the number following? If this is correct, I think a list would be more helpful than a dictionary since dictionary lookup is always by exact key. I would make a helper function that makes a tuple of (index of prefix in key list, exact filename). Then use the "key=" parameter to sort on these tuples. For example: # The ordered list of prefixes In [1]: prefixes = ['OAF', 'ABC', 'Valuation'] # Some filenames In [2]: filenames = 'ABC3 ABC1 Valuation2 OAF3 Valuation5 OAF2'.split() # This is the key function, it finds the matching prefix for a name In [3]: def makekey(name): ...: for i, prefix in enumerate(prefixes): ...: if name.startswith(prefix): ...: return (i, name) ...: return (len(prefixes), name) ...: # Show what makekey does In [4]: [makekey(name) for name in filenames] Out[4]: [(1, 'ABC3'), (1, 'ABC1'), (2, 'Valuation2'), (0, 'OAF3'), (2, 'Valuation5'), (0, 'OAF2')] # Sort using makekey In [5]: filenames.sort(key=makekey) # It works! In [6]: filenames Out[6]: ['OAF2', 'OAF3', 'ABC1', 'ABC3', 'Valuation2', 'Valuation5'] There are several variations possible depending on what the data looks like. If the number part of the filename has varying numbers of digits you will have to convert it to an integer to get the correct sort order. If you have a *lot* of files and prefixes, the lookup of the prefix might be too costly (it is a linear search of a list). Then maybe you want to use a regular expression to pick off the prefix and look it up in a dictionary to get the index. I hope I haven't completely misunderstood what you want to do :-) Kent From kent37 at tds.net Wed Sep 6 13:53:27 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 06 Sep 2006 07:53:27 -0400 Subject: [Tutor] Sorting a list in an add order In-Reply-To: <1ff2dfbf0609060356h43634fc7q98fce7fec777bbff@mail.gmail.com> References: <44FE9CFB.4030002@cancer.org.uk> <1ff2dfbf0609060356h43634fc7q98fce7fec777bbff@mail.gmail.com> Message-ID: <44FEB6B7.80903@tds.net> Michael Janssen wrote: > you can specify your own comparing funtion for aList.sort(). Since Python 2.4, supplying a key function to list.sort() is generally preferable to a cmp function - the key function is easier to write and it is more efficient to use. See my reply to Matt for an example. Kent From kent37 at tds.net Wed Sep 6 13:55:04 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 06 Sep 2006 07:55:04 -0400 Subject: [Tutor] Inverse range In-Reply-To: <44FEADE0.3070706@pythonin.dk> References: <44FEADE0.3070706@pythonin.dk> Message-ID: <44FEB718.6010406@tds.net> Morten Juhl Johansen wrote: > # Newbie warning > > I am playing with Python. Playing as in learning. > Is it possible to reverse a range sequence? Take a look at the docs for the range() function: http://docs.python.org/lib/built-in-funcs.html#l2h-56 Kent From bastien.verbinnen at pandora.be Wed Sep 6 14:09:57 2006 From: bastien.verbinnen at pandora.be (Bastien Verbinnen) Date: Wed, 6 Sep 2006 14:09:57 +0200 Subject: [Tutor] Inverse range References: <44FEADE0.3070706@pythonin.dk> Message-ID: <006a01c6d1ad$5edbac40$01dea8c0@telenet.be> You could do the folowing with range: for f in range(4,0,-1) print f This should give you the wanted result. You start from 4 and range to 0 (not included), by sustracting 1 each time. Cheers, Bas. ----- Original Message ----- From: "Morten Juhl Johansen" To: Sent: Wednesday, September 06, 2006 1:15 PM Subject: [Tutor] Inverse range > # Newbie warning > > I am playing with Python. Playing as in learning. > Is it possible to reverse a range sequence? If, for instance, I call: > > for f in range( 1,5 ): > print f > > - I get: > 1 > 2 > 3 > 4 > > Is it possible to reverse it? As in: > 4 > 3 > 2 > 1 > > Yours, > Morten > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From devayani.barve at gmail.com Wed Sep 6 14:28:58 2006 From: devayani.barve at gmail.com (devayani barve) Date: Wed, 6 Sep 2006 17:58:58 +0530 Subject: [Tutor] xml dom Message-ID: <301929340609060528l7e695dcal7553e04ef91db50b@mail.gmail.com> hi I wanted to know if there was any other source of learning dom implementation apart from python library reference? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060906/f8c0d9f8/attachment.htm From jgcox39 at highstream.net Wed Sep 6 18:21:19 2006 From: jgcox39 at highstream.net (Joe Cox) Date: Wed, 06 Sep 2006 09:21:19 -0700 Subject: [Tutor] Idle socket connection refused on w2k Message-ID: <44FEF57F.5040008@highstream.net> Alan, I got Active State program, man what a difference. Thanks for the help. I having fun again. -- Joe Cox 513-293-4830 Mobile From info at pythonin.dk Wed Sep 6 16:34:17 2006 From: info at pythonin.dk (Morten Juhl Johansen) Date: Wed, 6 Sep 2006 16:34:17 +0200 (CEST) Subject: [Tutor] Inverse range In-Reply-To: <006a01c6d1ad$5edbac40$01dea8c0@telenet.be> References: <44FEADE0.3070706@pythonin.dk> <006a01c6d1ad$5edbac40$01dea8c0@telenet.be> Message-ID: <53276.131.165.154.10.1157553257.squirrel@webmail.vizion.dk> > You could do the folowing with range: > > for f in range(4,0,-1) > print f > > This should give you the wanted result. You start from 4 and range to 0 > (not > included), by sustracting 1 each time. > > Cheers, > Bas. Thank you, Bastien and Kent. Had tried: for f in range(4,0): print f - put obviously, something was missing. It is good to be a beginner around people who say "read the manual" and point to _where_ in the manual. Yours, Morten From kent37 at tds.net Wed Sep 6 17:28:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 06 Sep 2006 11:28:00 -0400 Subject: [Tutor] Inverse range In-Reply-To: <53276.131.165.154.10.1157553257.squirrel@webmail.vizion.dk> References: <44FEADE0.3070706@pythonin.dk> <006a01c6d1ad$5edbac40$01dea8c0@telenet.be> <53276.131.165.154.10.1157553257.squirrel@webmail.vizion.dk> Message-ID: <44FEE900.2090705@tds.net> Morten Juhl Johansen wrote: > Thank you, Bastien and Kent. You're welcome! > Had tried: > for f in range(4,0): > print f > > - put obviously, something was missing. > It is good to be a beginner around people who say "read the manual" and > point to _where_ in the manual. Trying to teach you to fish :-) I highly recommend becoming familiar with chapter 2 of the Library Reference, it has a wealth of detail about built-in functions and types (string, list, dict...). I actually have four browser bookmarks that point into that chapter (built-in functions, built-in types, string methods and built-in exceptions). Kent From dkuhlman at rexx.com Wed Sep 6 17:34:22 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 6 Sep 2006 08:34:22 -0700 Subject: [Tutor] xml dom In-Reply-To: <301929340609060528l7e695dcal7553e04ef91db50b@mail.gmail.com> References: <301929340609060528l7e695dcal7553e04ef91db50b@mail.gmail.com> Message-ID: <20060906153422.GA3028@cutter.rexx.com> On Wed, Sep 06, 2006 at 05:58:58PM +0530, devayani barve wrote: > hi > I wanted to know if there was any other source of learning dom > implementation apart from python library reference? More than you wanted to know is here: http://xml.coverpages.org/dom.html You may also want to ask your question on the Python XML special interest group (SIG): http://www.python.org/community/sigs/current/xml-sig/ And, as has been suggested previously on this list I believe, ElementTree is considered to be an improved DOM for Python. See: http://effbot.org/zone/element-index.htm And, lxml is an alternative implementation of the ElementTree API, but requires installation of libxml. From the lxml Web page: "lxml also extends this API to expose libxml2 and libxslt specific functionality, such as XPath, Relax NG, XML Schema, XSLT, and c14n. Python code can be called from XPath expressions and XSLT stylesheets through the use of extension functions. "In addition to the ElementTree API, lxml also features a sophisticated API for custom element classes. This is a simple way to write arbitrary XML driven APIs on top of lxml. "lxml also offers a SAX compliant API, that works with the SAX support in the standard library." Lxml is at: http://codespeak.net/lxml/ Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From kent37 at tds.net Wed Sep 6 17:47:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 06 Sep 2006 11:47:53 -0400 Subject: [Tutor] xml dom In-Reply-To: <301929340609060528l7e695dcal7553e04ef91db50b@mail.gmail.com> References: <301929340609060528l7e695dcal7553e04ef91db50b@mail.gmail.com> Message-ID: <44FEEDA9.7030102@tds.net> devayani barve wrote: > hi > I wanted to know if there was any other source of learning dom > implementation apart from python library reference? There is the XML topic guide at http://pyxml.sourceforge.net/topics/ If you like books, Python in a Nutshell has a chapter on XML processing and O'Reilly also has a complete book on "Python & XML". However, I personally think there are better ways to work with XML than the standard DOM libraries, which I find kind of clunky. I prefer ElementTree (now standard in Python 2.5). Unless you have a specific requirement for DOM I would look into the alternatives. http://effbot.org/zone/element.htm Kent From alan.gauld at freenet.co.uk Wed Sep 6 19:36:15 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 6 Sep 2006 18:36:15 +0100 Subject: [Tutor] Sorting a list in an add order References: <44FE9CFB.4030002@cancer.org.uk> Message-ID: <002701c6d1da$f4db0d30$0201a8c0@XPpro> Matt, > However, I want to process them so that they are arranged in the > correct order, which means I need to sort the list of files. Of > course, because they aren't named in any (obvious) order, I'm a bit > stuck. > > I thought about using a dictionary to map names and order: so > {"OAF":1, "Valuation":2...etc}, but I don't don't know how to take > it on from here. If you are going to have to put the names in a dictionary you don't need glob. Just oput them in a list and iterate over that list! But I'd probably go back to the source and rename the files with a sequence number in front: 01OAF 02Valuation etc Its a manual one time process but allows simple mechanised processing thereafter. You could maybe even write a script to autonumber any new files added... > .startswith() to get some basic rough-matching capacity) and then > using that to return the order that the files should be handled in. If you know the order and are going to have to manually type that into Python then its pointless using glob. Just use the list you create. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Sep 6 19:39:44 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 6 Sep 2006 18:39:44 +0100 Subject: [Tutor] Inverse range References: <44FEADE0.3070706@pythonin.dk> Message-ID: <002f01c6d1db$711f5680$0201a8c0@XPpro> > I am playing with Python. Playing as in learning. > Is it possible to reverse a range sequence? If, for instance, I > call: > > for f in range( 1,5 ): > print f > > Is it possible to reverse it? As in: > 4 > 3 > 2 > 1 Yes, there is a normally unused third parameter to range used to control the step size. It can bew negative so: range(4,0,-1) does what you want... Alan G. From Senthil_OR at Dell.com Wed Sep 6 19:51:59 2006 From: Senthil_OR at Dell.com (Senthil_OR at Dell.com) Date: Wed, 6 Sep 2006 23:21:59 +0530 Subject: [Tutor] Inverse range In-Reply-To: <002f01c6d1db$711f5680$0201a8c0@XPpro> Message-ID: >> I am playing with Python. Playing as in learning. >> Is it possible to reverse a range sequence? If, for instance, I >> call: >> >> for f in range( 1,5 ): >> print f >> >> Is it possible to reverse it? As in: >> 4 >> 3 >> 2 >> 1 >Yes, there is a normally unused third parameter to range used to control the step size. It can bew negative so: >range(4,0,-1) And then there is also this reversed() call: >>> for f in reversed(range(1,5)): print f 4 3 2 1 >>> Thanks, Senthil From pyro9219 at gmail.com Wed Sep 6 22:51:54 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 6 Sep 2006 13:51:54 -0700 Subject: [Tutor] Looking for a few commands Message-ID: Woohoo for my first post! Simple command to clear console? (C++ was something like system.clr()) Some sort of cursor positioning? (C++ was something like gotoxy) Thanks alot! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060906/572ee1e8/attachment.html From bgailer at alum.rpi.edu Thu Sep 7 01:30:12 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 06 Sep 2006 16:30:12 -0700 Subject: [Tutor] Looking for a few commands In-Reply-To: References: Message-ID: <44FF5A04.6070500@alum.rpi.edu> Chris Hengge wrote: > Woohoo for my first post! > > Simple command to clear console? (C++ was something like system.clr()) > Some sort of cursor positioning? (C++ was something like gotoxy) This is operating system dependent. Which OS you use? -- Bob Gailer 510-978-4454 From jeffpeery at yahoo.com Thu Sep 7 01:56:03 2006 From: jeffpeery at yahoo.com (Jeff Peery) Date: Wed, 6 Sep 2006 16:56:03 -0700 (PDT) Subject: [Tutor] how do I find where my program is installed? Message-ID: <20060906235603.51663.qmail@web30501.mail.mud.yahoo.com> hello, I created an executable using py2exe and innosetup for windows. I need to figure out where the user has installed my program so that I can direct the program to the installation files that it needs to run. I ran into this problem because I have a file type that my program reads and I have registered this type in the windows registry so that when this file type is double clicked my application is launched. when this happens my program thinks the working directory is the directory where that registered file was located... not the installation directory where it should be working in.... needless to say that lots of things go wrong when my program is launched this way. so I need to tell my program to set the working directory back to the installation directory... but where is this? thanks! Jeff --------------------------------- Stay in the know. Pulse on the new Yahoo.com. Check it out. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060906/e5416562/attachment.htm From pyro9219 at gmail.com Thu Sep 7 02:30:16 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 6 Sep 2006 17:30:16 -0700 Subject: [Tutor] Simple SQL server access... Message-ID: I've been doing some searching for ways to access existing SQL server databases, but I'm finding so many different ways to do it, is there one that anyone recommends for a "new to python" programmer? I've used VB and C# for accessing SQL, so maybe something that would feel similiar to that to get me started? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060906/77158303/attachment.html From andrew.arobert at gmail.com Thu Sep 7 03:11:29 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Wed, 06 Sep 2006 21:11:29 -0400 Subject: [Tutor] Simple SQL server access... In-Reply-To: References: Message-ID: <44FF71C1.6040105@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Chris Hengge wrote: > I've been doing some searching for ways to access existing SQL server > databases, but I'm finding so many different ways to do it, is there one > that anyone recommends for a "new to python" programmer? I've used VB > and C# for accessing SQL, so maybe something that would feel similiar to > that to get me started? > > Thanks. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor How about something like this? I use it for connecting to Oracle databases. Information on cx_Oracle and similar can be found at http://www.python.net/crew/atuining/cx_Oracle/ import cx_Oracle class db: def __init__(self, db, uname, passwd): self.connection = cx_Oracle.connect(dsn=db,user=uname,password=passwd) def execute(self, sql): cursor = self.connection.cursor() cursor.execute(sql) return cursor def close(self): self.connection.close() self.connection = None # Prevent reusing a closed connection -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (MingW32) Comment: GnuPT 2.7.2 iD8DBQFE/3HBDvn/4H0LjDwRAqPlAKCPFY6uzHHHWQ4ZKrq3BfqQy9QufgCfZs0a Zj69XcmwAlW4L+HbH56Wxf8= =yMOb -----END PGP SIGNATURE----- From justin.mailinglists at gmail.com Thu Sep 7 03:15:17 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Thu, 7 Sep 2006 09:15:17 +0800 Subject: [Tutor] content disposition header: email module Message-ID: <3c6718980609061815i8ce239esfcf5e9f21997caac@mail.gmail.com> try something like the following (UNTESTED) code: from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.Message import Message def attch_send(self): msg = MIMEMultipart() #msg.add_header("From", sender) #msg.add_header("To", recv) msg.attach(MIMEText('file(s) attached')) # the body text attachment = Message() attachment.add_header('Content-type', 'text/plain', name="web-list.txt") attachment.add_header('Content-Disposition', 'attachment', filename="web-list.txt") attachment.set_payload(file(os.path.join(save_dir,"web-list.txt")).read()) msg.attach(attachment) server = smtplib.SMTP('localhost') #server.set_debuglevel(1) server.sendmail(sender, recv, msg.as_string()) server.quit() From andrew.arobert at gmail.com Thu Sep 7 03:16:20 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Wed, 06 Sep 2006 21:16:20 -0400 Subject: [Tutor] Simple SQL server access... In-Reply-To: References: Message-ID: <44FF72E4.4000801@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Chris Hengge wrote: > I've been doing some searching for ways to access existing SQL server > databases, but I'm finding so many different ways to do it, is there one > that anyone recommends for a "new to python" programmer? I've used VB > and C# for accessing SQL, so maybe something that would feel similiar to > that to get me started? > > Thanks. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor For a list of modules that can help, I recommend you look at http://www.python.org/doc/topics/database/modules/ There are specific modules for DB2, Oracle, Sybase, Postgress, MySQL, etc. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (MingW32) Comment: GnuPT 2.7.2 iD8DBQFE/3LkDvn/4H0LjDwRAoJ/AKCQ2HIpfduCorgJmlQsfACWbKKLCQCglYcm kE5KDOfwu29boHiRiODqEIc= =TGXp -----END PGP SIGNATURE----- From kent37 at tds.net Thu Sep 7 03:45:16 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 06 Sep 2006 21:45:16 -0400 Subject: [Tutor] how do I find where my program is installed? In-Reply-To: <20060906235603.51663.qmail@web30501.mail.mud.yahoo.com> References: <20060906235603.51663.qmail@web30501.mail.mud.yahoo.com> Message-ID: <44FF79AC.4040906@tds.net> Jeff Peery wrote: > hello, I created an executable using py2exe and innosetup for windows. I > need to figure out where the user has installed my program so that I can > direct the program to the installation files that it needs to run. I ran > into this problem because I have a file type that my program reads and I > have registered this type in the windows registry so that when this file > type is double clicked my application is launched. when this happens my > program thinks the working directory is the directory where that > registered file was located... not the installation directory where it > should be working in.... needless to say that lots of things go wrong > when my program is launched this way. so I need to tell my program to > set the working directory back to the installation directory... but > where is this? Try the __file__ variable in your main module; it should have the path to the .py file. os.path.dirname(__file__) will give you the directory. Then use os.chdir() to change the working dir. Kent From kent37 at tds.net Thu Sep 7 03:51:23 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 06 Sep 2006 21:51:23 -0400 Subject: [Tutor] Simple SQL server access... In-Reply-To: References: Message-ID: <44FF7B1B.8060608@tds.net> Chris Hengge wrote: > I've been doing some searching for ways to access existing SQL server > databases, but I'm finding so many different ways to do it, is there one > that anyone recommends for a "new to python" programmer? I've used VB > and C# for accessing SQL, so maybe something that would feel similiar to > that to get me started? Take a look at http://adodbapi.sourceforge.net/ or http://pymssql.sourceforge.net/, they both support MS SQL Server using the standard DB-API interface. adodbapi is Windows-only and LGPL licensed. pymssql runs on Windows and *nix, it is GPL licensed. Documentation for DB-API is here: http://www.python.org/dev/peps/pep-0249/ Kent From patriciap.gu at gmail.com Thu Sep 7 04:42:35 2006 From: patriciap.gu at gmail.com (Patricia) Date: Thu, 7 Sep 2006 02:42:35 +0000 (UTC) Subject: [Tutor] python & mysql question Message-ID: Hi, I have to store and retrieve text files from a database table and the size of each file is about 500k. Can someone give me an idea on how to do this? Thanks, Patricia From issakarambal at yahoo.com Wed Sep 6 11:47:51 2006 From: issakarambal at yahoo.com (issa karambal) Date: Wed, 6 Sep 2006 02:47:51 -0700 (PDT) Subject: [Tutor] information Message-ID: <20060906094752.44488.qmail@web58408.mail.re3.yahoo.com> hi my name is ISSA, from Chad, I am learning python, I want to have on tutor to help me to understand this good language of programmation please, I am looking for the good answer from you regards and thanks --------------------------------- Yahoo! Messenger with Voice. Make PC-to-Phone Calls to the US (and 30+ countries) for 2?/min or less. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060906/445033f4/attachment.htm From pyro9219 at gmail.com Thu Sep 7 05:48:36 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 06 Sep 2006 20:48:36 -0700 Subject: [Tutor] Looking for a few commands In-Reply-To: <44FF5A04.6070500@alum.rpi.edu> References: <44FF5A04.6070500@alum.rpi.edu> Message-ID: <1157600916.5005.9.camel@localhost> On Wed, 2006-09-06 at 16:30 -0700, Bob Gailer wrote: > Chris Hengge wrote: > > Woohoo for my first post! > > > > Simple command to clear console? (C++ was something like system.clr()) > > Some sort of cursor positioning? (C++ was something like gotoxy) > This is operating system dependent. Which OS you use? > I hope I'm replying to this correctly. But I'm currently learning the language on XP, but I will eventually be writing applications for both linux and windows at home and at work. Thanks. From fiveholiday55 at hotmail.com Thu Sep 7 09:27:15 2006 From: fiveholiday55 at hotmail.com (Henry Dominik) Date: Thu, 7 Sep 2006 08:27:15 +0100 Subject: [Tutor] information References: <20060906094752.44488.qmail@web58408.mail.re3.yahoo.com> Message-ID: Nice to have you around! This list is to help with any problem you may be having with the language and how to solve certain problems. So, if you have specific questions, please do post them. And be warned, no one here would like to do any homework for you. Enjoy you stay Dom ----- Original Message ----- From: issa karambal To: tutor at python.org Sent: Wednesday, September 06, 2006 10:47 AM Subject: [Tutor] information hi my name is ISSA, from Chad, I am learning python, I want to have on tutor to help me to understand this good language of programmation please, I am looking for the good answer from you regards and thanks ------------------------------------------------------------------------------ Yahoo! Messenger with Voice. Make PC-to-Phone Calls to the US (and 30+ countries) for 2?/min or less. ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060907/234a20df/attachment.htm From alan.gauld at freenet.co.uk Thu Sep 7 09:36:14 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 7 Sep 2006 08:36:14 +0100 Subject: [Tutor] how do I find where my program is installed? References: <20060906235603.51663.qmail@web30501.mail.mud.yahoo.com> Message-ID: <003801c6d250$4ce5e7f0$0201a8c0@XPpro> > hello, I created an executable using py2exe and innosetup for > windows. > I need to figure out where the user has installed my program > so that I can direct the program to the installation files that it > needs to run. The location of the installation files - I assume you mean some kind of config file? - should not be hard coded in that way, much better to store the files in a flexible location and use an environment variable or registry setting to point to it. > when this file type is double clicked my application is launched. > when this happens my program thinks the working directory > is the directory where that registered file was located... Interesting, I didn't know Windows would do that. > the working directory back to the installation directory... > but where is this? If the current working directory is not set to the home location of your program but rather to the target file then I don't know! Another good reason for setting an environment variable or registry entry. However the sys module contains two functions that might help: exec_prefix() and executable() Not sure how they play with py2exe however. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Sep 7 09:44:52 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 7 Sep 2006 08:44:52 +0100 Subject: [Tutor] Looking for a few commands References: <002601c6d206$73bada60$0201a8c0@XPpro> <1157603107.5005.11.camel@localhost> Message-ID: <004801c6d251$812f4320$0201a8c0@XPpro> Replying to the List.... The trick is to know either that Fred works at Pythonware, or that his nickname is the effbot... :-) http://effbot.org/downloads/ Sorry, neither are intuitively obvious... but he has lots of goodies on his site, worth perusing the list. And Fred's code is usually of a very high standard - ie it just works! Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ----- Original Message ----- From: "Chris Hengge" To: "Alan Gauld" Sent: Thursday, September 07, 2006 5:25 AM Subject: Re: Looking for a few commands > Where is Fred's site? lol... I've been looking for it and not > finding > anything like this. > >> Finally Fred Lundh has a console library that tries to pull all >> this >> together into a single platform independant module, but its not a >> standard library module(yet) and you have to download it from >> Fred's >> site. >> >> Frankly if I need to do detailed screen manipulation in Python I >> usually >> just bite the bullet and build a GUI - its easier. >> >> HTH, >> >> Alan Gauld >> Author of the Learn to Program web site >> http://www.freenetpages.co.uk/hp/alan.gauld >> > From etrade.griffiths at dsl.pipex.com Thu Sep 7 09:34:04 2006 From: etrade.griffiths at dsl.pipex.com (Etrade Griffiths) Date: Thu, 07 Sep 2006 08:34:04 +0100 Subject: [Tutor] Running DOS jobs in batch Message-ID: <6.1.2.0.2.20060907083117.04098540@pop.dsl.pipex.com> Hi I am trying to write a PYTHON script that automates the running of an application program MX200510.EXE under XP Pro via a DOS window. This file is in directory C:\Program Files\CMG\IMEX\2005.10\EXE The command line arguments are MX200510.EXE -f "temp.dat" -wd "C:\Projects\Vitol\New business\Octon\simulation\full field model\0608" My Python script is as follows: # # Test Python script to submit IMEX jobs # import os # # Start of MAIN program # # Initialisation work_dir=r'C:\Projects\Vitol\New business\Octon\simulation\full field model\0608' imex_dir=r'C:\Program Files\CMG\IMEX\2005.10\EXE' imex_fil='"temp.dat"' imex_args=('mx200510.exe','-f',imex_fil,'-wd','"'+work_dir+'"') nscen=2 # Check IMEX directory and files exist os.chdir(imex_dir) L=os.listdir(imex_dir) for item in L: print item # Change directory to working directory os.chdir(work_dir) # Loop over N scenarios for n in range(1,nscen): # Spawn IMEX job and wait for completion os.spawnv(os.P_WAIT, imex_dir, imex_args) The output from this script is ck9700.dll libguide40.dll mx200510.exe mx200510en.chm mx200510sp.chm Traceback (most recent call last): File "C:/Projects/Vitol/New business/Octon/simulation/full field model/0608/test_imex.py", line 39, in -toplevel- os.spawnv(os.P_WAIT, imex_dir, imex_args) OSError: [Errno 2] No such file or directory I tried following the ARGS into the os module using the debugger but this did not help much, presumably because OS is precompiled. Not sure which file or directory Python is unhappy about - LISTDIR shows that the EXE file and path exist so presumably it's something in the way I set up the argument list. All suggestions gratefully received! Thanks Alun Griffiths From janos.juhasz at VELUX.com Thu Sep 7 10:09:12 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Thu, 7 Sep 2006 10:09:12 +0200 Subject: [Tutor] Thread forever ? Message-ID: Dear Tutors, ################################### from threading import Thread import sys import time # This thread would read lines from a # barcode scanner class ComThread(Thread): def __init__(self): Thread.__init__(self) def run(self): while 1: time.sleep(2) print time.ctime() com = ComThread() com.start() # Main loop for handling the keyboard while 1: s = raw_input() if s == '': continue elif s in 'qQ': # may I com.Terminate() here sys.exit() # when I goes out here # the comthread is just running. else: try: num = int(s) print 'mod qty=%d' % num except: pass ################################# When this program leaves from the while loop, it doesn't terminate the comreader thread. It can be terminated with the 'X' at the topright corner, but it seems to be not the best way. Yours sincerely, ______________________________ Janos Juhasz -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060907/e2a483f0/attachment.htm From rdm at rcblue.com Thu Sep 7 10:33:37 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 07 Sep 2006 01:33:37 -0700 Subject: [Tutor] Some questions about my yen-USD.py Message-ID: <7.0.1.0.2.20060905215943.061a2828@rcblue.com> I've just finished a script for converting Yen to USD, and vice-versa. A simple, even silly thing to do (a friend asked me to write it for him--probably just to humor me), but I have tried to build in some bells and whistles. In doing so, some questions arose. If some of you Tutors could take look at my script, yen-USD.py, I'd greatly appreciate it. My questions: (1) Have I handled possible user-errors OK? (2) Is my roundingN() function OK? Is there a better way to write it? Will the line n = round(float(n)*(10**rounding))/(10**rounding) get me into trouble with the flakiness of float(n)? In testing I didn't find any problems, but .. (3) Is there a better name for roundingN()? I don't like it, but can't think of a better one. (4) I wanted to call closingMessage() in main(), but in some cases, if it's in main() it gets 2 successive calls. I can't figure out why. Would IDLE's debugger be of use here? (I've never used it before.) I haven't been able to find up-to-date IDLE help. Thanks, Dick Moores From pyro9219 at gmail.com Thu Sep 7 11:05:12 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 07 Sep 2006 02:05:12 -0700 Subject: [Tutor] Looking for a few commands In-Reply-To: <004801c6d251$812f4320$0201a8c0@XPpro> References: <002601c6d206$73bada60$0201a8c0@XPpro> <1157603107.5005.11.camel@localhost> <004801c6d251$812f4320$0201a8c0@XPpro> Message-ID: <1157619912.5005.19.camel@localhost> Thanks for the details, I see several code bits I'll have to play with. I got the screen clearing bit no problem, thanks for that one. I'm still not used to being able to just use c libraries. I don't actually have a need to draw the cursor all over the screen for any practical application either personal or work, but I've got a bit of a fascination with linux terminals being able to draw progress bars or "busy" animations and figured I'd have a little fun. :] I came across "curses" which looks to be included in activepython so that might be of some use for my linux programming. Thanks again. On Thu, 2006-09-07 at 08:44 +0100, Alan Gauld wrote: > Replying to the List.... > > The trick is to know either that Fred works at Pythonware, > or that his nickname is the effbot... :-) > > http://effbot.org/downloads/ > > Sorry, neither are intuitively obvious... but he has lots of goodies > on his site, worth perusing the list. And Fred's code is usually > of a very high standard - ie it just works! > > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > ----- Original Message ----- > From: "Chris Hengge" > To: "Alan Gauld" > Sent: Thursday, September 07, 2006 5:25 AM > Subject: Re: Looking for a few commands > > > > Where is Fred's site? lol... I've been looking for it and not > > finding > > anything like this. > > > >> Finally Fred Lundh has a console library that tries to pull all > >> this > >> together into a single platform independant module, but its not a > >> standard library module(yet) and you have to download it from > >> Fred's > >> site. > >> > >> Frankly if I need to do detailed screen manipulation in Python I > >> usually > >> just bite the bullet and build a GUI - its easier. > >> > >> HTH, > >> > >> Alan Gauld > >> Author of the Learn to Program web site > >> http://www.freenetpages.co.uk/hp/alan.gauld > >> > > > From rabidpoobear at gmail.com Thu Sep 7 11:27:43 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 7 Sep 2006 04:27:43 -0500 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: <7.0.1.0.2.20060905215943.061a2828@rcblue.com> References: <7.0.1.0.2.20060905215943.061a2828@rcblue.com> Message-ID: On 9/7/06, Dick Moores wrote: > > I've just finished a script for converting Yen to USD, and > vice-versa. A simple, even silly thing to do (a friend asked me to > write it for him--probably just to humor me), but I have tried to > build in some bells and whistles. In doing so, some questions arose. > If some of you Tutors could take look at my script, yen-USD.py, I'd > greatly appreciate it. > > My questions: > > (1) Have I handled possible user-errors OK? seems like it (2) Is my roundingN() function OK? Is there a better way to write it? > Will the line I think that you could just use string formatting to do this... say f is a float. (Note I don't have access to a python interpreter right now so if this code is incorrect it should at least give you an idea of what I mean.) so f is a float. f = 0.023 s = str(f) print f should output '0.023' and y = s.split('.') so then you do... f = int(y[0]) now f is the whole-number part of your number. Now for the decimal part :D f += float('.'+y[1][:roundingprecision-1]) if y[1][roundingprecision] >= 5: f += float('.'.zfill(roundingprecision-1)+'1') I hope that makes sense. I'd be amazed if the code actually worked, but anyway, I think you see what trickery I used to get this. Someone else like Danny Yoo or Alan could probably awesome it more than I can, though. Hope that helps n = round(float(n)*(10**rounding))/(10**rounding) > > get me into trouble with the flakiness of float(n)? In testing I > didn't find any problems, but .. the 'flakiness' of float is not going to get you into trouble. Your friend won't get mad because he had to spend 1 more yen than he thought. In some cases maybe it's a problem, but I don't think it will be here. (3) Is there a better name for roundingN()? I don't like it, but > can't think of a better one. maybe round()? or setprecision()? ;) (4) I wanted to call closingMessage() in main(), but in some cases, > if it's in main() it gets 2 successive calls. I can't figure out why. > Would IDLE's debugger be of use here? (I've never used it before.) I > haven't been able to find up-to-date IDLE help. Didn't look at the code closely enough to tell, and I only have 5 hours to sleep before my Music History class, so sorry. I'll look at it again in the morning if no one else answers. Thanks, > > Dick Moores -Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060907/53cda58d/attachment.html From alan.gauld at freenet.co.uk Thu Sep 7 11:29:42 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 7 Sep 2006 10:29:42 +0100 Subject: [Tutor] Looking for a few commands References: <002601c6d206$73bada60$0201a8c0@XPpro> <1157603107.5005.11.camel@localhost> <004801c6d251$812f4320$0201a8c0@XPpro> <1157619912.5005.19.camel@localhost> Message-ID: <000301c6d260$266b56e0$0201a8c0@XPpro> > I got the screen clearing bit no problem, thanks for that one. I'm > still > not used to being able to just use c libraries. Even the C libraries are non standard - they aren't part of the ANSI C definition. Its just that C libraries for the PC know what the hardware will look like so they can provide screen manipulation routines. But that code will be completely non-portable to any other computing platform. And even between C vendors the screen calls can be completely different. For example my MIX compiler uses cls() to clear the screen, My Borland one uses ClrScr() and I think that Microsoft Visual C uses something else again. Similarly for positioning the cursor, MIX uses curscol(), cursrow() whereas the Borland one uses gotoXY() - I think, its been a while! > a fascination with linux terminals being able to draw progress bars > or > "busy" animations and figured I'd have a little fun. :] I came > across > "curses" which looks to be included in activepython so that might be > of > some use for my linux programming. There is an old curses module for DOS somewhere but I never got it working and it didn't implement all the functions.. Alan G. From kent37 at tds.net Thu Sep 7 11:56:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 07 Sep 2006 05:56:15 -0400 Subject: [Tutor] Running DOS jobs in batch In-Reply-To: <6.1.2.0.2.20060907083117.04098540@pop.dsl.pipex.com> References: <6.1.2.0.2.20060907083117.04098540@pop.dsl.pipex.com> Message-ID: <44FFECBF.6000308@tds.net> Etrade Griffiths wrote: > Hi > > I am trying to write a PYTHON script that automates the running of an > application program MX200510.EXE under XP Pro via a DOS window. This file > is in directory > > C:\Program Files\CMG\IMEX\2005.10\EXE > > The command line arguments are > > MX200510.EXE -f "temp.dat" -wd "C:\Projects\Vitol\New > business\Octon\simulation\full field model\0608" > > My Python script is as follows: > > # > # Test Python script to submit IMEX jobs > # > > import os > > # > # Start of MAIN program > # > > # Initialisation > > work_dir=r'C:\Projects\Vitol\New business\Octon\simulation\full field > model\0608' > imex_dir=r'C:\Program Files\CMG\IMEX\2005.10\EXE' > imex_fil='"temp.dat"' > > imex_args=('mx200510.exe','-f',imex_fil,'-wd','"'+work_dir+'"') > > nscen=2 > > # Check IMEX directory and files exist > > os.chdir(imex_dir) > L=os.listdir(imex_dir) > > for item in L: > print item > > # Change directory to working directory > > os.chdir(work_dir) > > # Loop over N scenarios > > for n in range(1,nscen): > > # Spawn IMEX job and wait for completion > > os.spawnv(os.P_WAIT, imex_dir, imex_args) I think the second arg to spawnv() should be the name of the program to run (MX200510.EXE), not the path to the dir containing MX200510.EXE. The parameter is named path but if you look at the examples in the doc it is just the name. Kent > > The output from this script is > > ck9700.dll > libguide40.dll > mx200510.exe > mx200510en.chm > mx200510sp.chm > > Traceback (most recent call last): > File "C:/Projects/Vitol/New business/Octon/simulation/full field > model/0608/test_imex.py", line 39, in -toplevel- > os.spawnv(os.P_WAIT, imex_dir, imex_args) > OSError: [Errno 2] No such file or directory From kent37 at tds.net Thu Sep 7 12:01:07 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 07 Sep 2006 06:01:07 -0400 Subject: [Tutor] Thread forever ? In-Reply-To: References: Message-ID: <44FFEDE3.3000607@tds.net> J?nos Juh?sz wrote: > > Dear Tutors, > > ################################### > from threading import Thread > import sys > import time > > # This thread would read lines from a > # barcode scanner > class ComThread(Thread): > def __init__(self): > Thread.__init__(self) If you call self.setDaemon() here you will mark the thread as a daemon thread and it will not block the exit of the program. > > def run(self): > while 1: > time.sleep(2) > print time.ctime() > > com = ComThread() > com.start() > > # Main loop for handling the keyboard > while 1: > s = raw_input() > if s == '': continue > elif s in 'qQ': > # may I com.Terminate() here > sys.exit() > # when I goes out here > # the comthread is just running. > else: > try: > num = int(s) > print 'mod qty=%d' % num > except: > pass > ################################# > > When this program leaves from the while loop, it doesn't terminate the > comreader thread. setDaemon() is the simplest way, as noted above. You could also have the main loop set a flag that the thread loop checks; if the flag is set the thread loop exits. Kent From x.yang3 at ugrad.unimelb.edu.au Thu Sep 7 09:21:28 2006 From: x.yang3 at ugrad.unimelb.edu.au (Xiao Yu Michael Yang) Date: Thu, 07 Sep 2006 17:21:28 +1000 (EST) Subject: [Tutor] ABout distinquishing elements in a string/regular expr Message-ID: <50750.61.69.246.25.1157613688.squirrel@webmail.student.unimelb.edu.au> Hi tutors, I am currently working on a project that identifies languages of html documents, using Python, of course. Just wondering, given a string: str = " title this is french 77 992 / " what is the python expression for: 1. r = return_anything_that's_within<> (str), i.e. it should give "html, aaabbbccc, html" 2. r = remove_all_numbers(str), (what is the python expression for 'is_int') i.e. it removes "77" and "992" 3. dif = listA_minus_listB(str, r), i.e. should return ['77', '992'], using the above 'r' value. thank you for your time! From kent37 at tds.net Thu Sep 7 13:47:55 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 07 Sep 2006 07:47:55 -0400 Subject: [Tutor] ABout distinquishing elements in a string/regular expr In-Reply-To: <50750.61.69.246.25.1157613688.squirrel@webmail.student.unimelb.edu.au> References: <50750.61.69.246.25.1157613688.squirrel@webmail.student.unimelb.edu.au> Message-ID: <450006EB.2080001@tds.net> Xiao Yu Michael Yang wrote: > Hi tutors, > > I am currently working on a project that identifies languages of html > documents, using Python, of course. You might be interested in http://chardet.feedparser.org/ which seems to work directly on HTML. > Just wondering, given a string: > > str = " title this is french 77 992 / " Note that str is the name of the built-in string type and not a good choice for a variable name. > what is the python expression for: > > 1. r = return_anything_that's_within<> (str), i.e. it should give "html, > aaabbbccc, html" You can do this with a regular expression: In [1]: s = " title this is french 77 992 / " In [2]: import re In [3]: re.findall('<.*?>', s) Out[3]: ['', '', ''] If you are trying to strip the tags from the HTML, try one of these: http://www.oluyede.org/blog/2006/02/13/html-stripper/ http://www.aminus.org/rbre/python/cleanhtml.py > > 2. r = remove_all_numbers(str), (what is the python expression for > 'is_int') i.e. it removes "77" and "992" What should r look like here? Is it the string s with digits removed, or some kind of list? s.isdigit() will test if s is a string containing all digits. > > 3. dif = listA_minus_listB(str, r), i.e. should return ['77', '992'], > using the above 'r' value. You seem to be confused about strings vs lists. s is a string, not a list. If you have two lists a and b and you want a new list containing everything in a not in b, use a list comprehension: [ aa for aa in a if aa not in b ] If what you are looking for is all the number strings from s, you can use a regular expression again: In [4]: re.findall(r'\d+', s) Out[4]: ['77', '992'] Kent From kent37 at tds.net Thu Sep 7 13:59:32 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 07 Sep 2006 07:59:32 -0400 Subject: [Tutor] Looking for a few commands In-Reply-To: <1157619912.5005.19.camel@localhost> References: <002601c6d206$73bada60$0201a8c0@XPpro> <1157603107.5005.11.camel@localhost> <004801c6d251$812f4320$0201a8c0@XPpro> <1157619912.5005.19.camel@localhost> Message-ID: <450009A4.8030309@tds.net> Chris Hengge wrote: > Thanks for the details, I see several code bits I'll have to play with. > > I got the screen clearing bit no problem, thanks for that one. I'm still > not used to being able to just use c libraries. The ctypes module lets you call functions in shared libraries. It is standard in Python 2.5 or available from http://starship.python.net/crew/theller/ctypes/ > > I don't actually have a need to draw the cursor all over the screen for > any practical application either personal or work, but I've got a bit of > a fascination with linux terminals being able to draw progress bars or > "busy" animations and figured I'd have a little fun. :] I came across > "curses" which looks to be included in activepython so that might be of > some use for my linux programming. Here is a progress bar: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/299207 You also might look at urwid though it doesn't seem to run on Windows: http://excess.org/urwid/ Unfortunately I don't think there is a console library that works on both Windows and Linux. For portable (and more functional) UIs you are better off learning Tkinter or wxPython. Kent > > Thanks again. > > On Thu, 2006-09-07 at 08:44 +0100, Alan Gauld wrote: >> Replying to the List.... >> >> The trick is to know either that Fred works at Pythonware, >> or that his nickname is the effbot... :-) >> >> http://effbot.org/downloads/ >> >> Sorry, neither are intuitively obvious... but he has lots of goodies >> on his site, worth perusing the list. And Fred's code is usually >> of a very high standard - ie it just works! >> >> Alan Gauld >> Author of the Learn to Program web site >> http://www.freenetpages.co.uk/hp/alan.gauld >> >> ----- Original Message ----- >> From: "Chris Hengge" >> To: "Alan Gauld" >> Sent: Thursday, September 07, 2006 5:25 AM >> Subject: Re: Looking for a few commands >> >> >>> Where is Fred's site? lol... I've been looking for it and not >>> finding >>> anything like this. >>> >>>> Finally Fred Lundh has a console library that tries to pull all >>>> this >>>> together into a single platform independant module, but its not a >>>> standard library module(yet) and you have to download it from >>>> Fred's >>>> site. >>>> >>>> Frankly if I need to do detailed screen manipulation in Python I >>>> usually >>>> just bite the bullet and build a GUI - its easier. >>>> >>>> HTH, >>>> >>>> Alan Gauld >>>> Author of the Learn to Program web site >>>> http://www.freenetpages.co.uk/hp/alan.gauld >>>> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From etrade.griffiths at dsl.pipex.com Thu Sep 7 14:29:40 2006 From: etrade.griffiths at dsl.pipex.com (Etrade Griffiths) Date: Thu, 07 Sep 2006 13:29:40 +0100 Subject: [Tutor] Running DOS jobs in batch In-Reply-To: References: Message-ID: <6.1.2.0.2.20060907122851.02c0baf0@pop.dsl.pipex.com> Thanks for that Kent. I did imex_exe=r'C:\Program Files\CMG\IMEX\2005.10\EXE\mx200510.exe' imex_args=('mx200510.exe','-f',imex_fil,'-wd','"'+work_dir+'"') for n in range(1,nscen): os.spawnv(os.P_WAIT, imex_exe, imex_args) and it seems to work. Not sure why I need to provide the name of the application twice though: the lib pages for spawn* say "In either case, the arguments to the child process must start with the name of the command being run" but hey, it works! Thanks again Alun -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060907/8254d3fd/attachment.html From project5 at redrival.net Thu Sep 7 14:37:31 2006 From: project5 at redrival.net (Andrei) Date: Thu, 7 Sep 2006 12:37:31 +0000 (UTC) Subject: [Tutor] Some questions about my yen-USD.py References: <7.0.1.0.2.20060905215943.061a2828@rcblue.com> Message-ID: Dick Moores rcblue.com> writes: > (1) Have I handled possible user-errors OK? I've tested it a bit and it seems to be quite robust. > (2) Is my roundingN() function OK? Is there a better way to write it? > Will the line > > n = round(float(n)*(10**rounding))/(10**rounding) Using format strings is easier I think. "%.2f" % 2.34234 will give '2.34'. > get me into trouble with the flakiness of float(n)? In testing I > didn't find any problems, but .. Nah. Float accuracy is only a problem if you need around lots of significant digits (16 or so). > (4) I wanted to call closingMessage() in main(), but in some cases, > if it's in main() it gets 2 successive calls. I can't figure out why. > Would IDLE's debugger be of use here? (I've never used it before.) I > haven't been able to find up-to-date IDLE help. I think the main loop could be improved. 1) Python idiom is to *not* always call main(), because that makes it impossible to use functions from your module in a different program: importing the module would start running the converter, while you might only be interested in reusing getRate(). It's better to put the following code at the bottom instead: if __name__ == "__main__": # if module is running standalone (not imported) main() 2) If the application is used extensively, you'll exceed the maximum recursion depth, because what the application does is essentially this (if the user chooses to continue): main calls again calls main calls again calls... ad infinitum This is called recursion - main essentially calls itself. You can test what happens by disabling the entire main loop up to "again()" as well as the raw_input line in again(). Python will quickly give up with: File "yen.py", line 164, in again main() File "yen.py", line 184, in main again() RuntimeError: maximum recursion depth exceeded It's better to have a main() which does something like this: - get the conversion rate and store it in some (global?) variable (instead of asking for it every time) - start a while True loop: -- get the rate , currency and amount -- calculate and print result -- ask the user whether to do it again and stop loop if answer is No 3) The function again() uses an internal variable called 'again'. This is not good coding practice (confusing). 3b) Note that this is a variable local to the again() function, so you cannot use it in the main() anyway: again() if again: break "if again" actually checks if there is something called 'again' with a non-zero/non-empty/non-None/True value. Your function is such a thing, so the if condition always evaluates as True. (Tip: try "print again" before the "if again", you'll see something like ""). This is of course related to recursion problem above. Improved version would be: def again(): answer = raw_input('Another?') return answer in 'yY' # evaluates to True if the user pressed 'y' or 'Y' def main(): # stuff while True: # stuff if not again(): closingMessage() return None Notice that this code is also easier to read than the original, because it's a literal translation of you intention: if the user doesn't want to run it again, say goodbye and stop. 4) Function names are important and should be chosen in such a way that they are not confusing. Most of them are OK, but commas() is non-descripting and printResult() is confusing - it doesn't just print, it actually calculates. A third party interested in reusing your calculation routine wouldn't expect the printResult to be the culprit. 5) Checks like "if currency in 'USD'" work, but are a bit unstable. It works in this case because Yen and USD have no letters in common, so input of 'y', 'e' or 'n' all lead to 'Yen', while 'u', 's' and 'd' go to 'USD'. Imagine you'd extend your program to also handle 'AUD', 'EUR', 'CAD' and 'SEK'. The 'e' would now lead to Yen instead of EUR. 6) I would trim down the the checks in checkAmount: - there is no need to use "continue" in that loop, because the loop will continue anyway. 'continue' is only useful if there is some code later in the loop that you want to skip. - separate checks for negative and zero values seem pointless. Either handle 0 as any other number (gives result 0), or put a single check on "amount <= 0" and inform the user that a number larger than 0 is required. Here's a modified version: def getAmount(currency): while True: useramount = raw_input('Amount: ').lower().strip() if useramount in 'qx': return useramount try: amount = float(useramount) except ValueError: continue # we want to skip the code below if amount <= 0: print "Amount must be more than 0." else: return amount Using multiple returns in a single function is sometimes frowned upon; but then again, so are break and continue :). Yours, Andrei From project5 at redrival.net Thu Sep 7 14:42:52 2006 From: project5 at redrival.net (Andrei) Date: Thu, 7 Sep 2006 12:42:52 +0000 (UTC) Subject: [Tutor] python & mysql question References: Message-ID: Patricia gmail.com> writes: > I have to store and retrieve text files from a database table and > the size of each file is about 500k. Can someone give me an idea > on how to do this? You might want to have a look at this: http://sourceforge.net/projects/mysql-python Yours, Andrei From python at venix.com Thu Sep 7 14:11:58 2006 From: python at venix.com (Python) Date: Thu, 07 Sep 2006 08:11:58 -0400 Subject: [Tutor] python & mysql question In-Reply-To: References: Message-ID: <1157631118.4242.138.camel@www.venix.com> On Thu, 2006-09-07 at 02:42 +0000, Patricia wrote: > Hi, > > I have to store and retrieve text files from a database table and > the size of each file is about 500k. Can someone give me an idea > on how to do this? > > Thanks, > Patricia http://dustman.net/andy/python/python-and-mysql Provides some background for the MySQLdb module. This should get you started. The next reference provides more background, but may not be needed. http://www.python.org/dev/peps/pep-0249/ This describes how the Python DB modules behave. Hopefully, that gets you started. We can help with more specific questions as they arise. > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From janos.juhasz at VELUX.com Thu Sep 7 15:10:50 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Thu, 7 Sep 2006 15:10:50 +0200 Subject: [Tutor] Thread forever Message-ID: Dear Kent, thanks your comment. >> > When this program leaves from the while loop, it doesn't terminate the >> > comreader thread. >>If you call self.setDaemon() here you will mark the thread as a daemon >>thread and it will not block the exit of the program. It works well. Yours sincerely, ______________________________ Janos Juhasz -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060907/1c333ce6/attachment.htm From dyoo at hkn.eecs.berkeley.edu Thu Sep 7 16:05:34 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 7 Sep 2006 07:05:34 -0700 (PDT) Subject: [Tutor] python & mysql question In-Reply-To: <1157631118.4242.138.camel@www.venix.com> References: <1157631118.4242.138.camel@www.venix.com> Message-ID: >> I have to store and retrieve text files from a database table and the >> size of each file is about 500k. Can someone give me an idea on how to >> do this? >> >> Thanks, >> Patricia > http://dustman.net/andy/python/python-and-mysql > Provides some background for the MySQLdb module. This should get you > started. The next reference provides more background, but may not be > needed. And just as a heads up: you'll probably need to configure your database tables to use TEXT or LONGTEXT columns, since 500k texts are definitely larger than the 255-char limit imposed by varchars. From dyoo at hkn.eecs.berkeley.edu Thu Sep 7 16:16:46 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 7 Sep 2006 07:16:46 -0700 (PDT) Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: References: <7.0.1.0.2.20060905215943.061a2828@rcblue.com> Message-ID: Hi Dick, I'm looking at the last part of the main() function: ################# def main(): while True: ... again() if again: break ################# This looks a little suspicious. What does the again() function do, and is it supposed to return a value? From Python at kraszewscy.net Thu Sep 7 19:08:30 2006 From: Python at kraszewscy.net (Pawel Kraszewski) Date: Thu, 7 Sep 2006 19:08:30 +0200 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: References: <7.0.1.0.2.20060905215943.061a2828@rcblue.com> Message-ID: <200609071908.30531.Python@kraszewscy.net> Dnia czwartek, 7 wrze?nia 2006 14:37, Andrei napisa?: > > get me into trouble with the flakiness of float(n)? In testing I > > didn't find any problems, but .. > > Nah. Float accuracy is only a problem if you need around lots of > significant digits (16 or so). I wouldn't bet. Such a simple thing as 0.1 can't be represented correctly on Float... That's what 'decimal' is for. See that: >>> 0.1 + 0.1 + 0.1 - 0.3 5.5511151231257827e-17 >>> >>> from decimal import Decimal >>> Decimal("0.1")+ Decimal("0.1")+ Decimal("0.1")-Decimal("0.3") Decimal("0.0") >>> For more see: http://docs.python.org/lib/module-decimal.html -- Pawel Kraszewski http://www.kraszewscy.net From alan.gauld at freenet.co.uk Thu Sep 7 19:10:11 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 7 Sep 2006 18:10:11 +0100 Subject: [Tutor] Running DOS jobs in batch References: <6.1.2.0.2.20060907122851.02c0baf0@pop.dsl.pipex.com> Message-ID: <004201c6d2a0$7af31870$0201a8c0@XPpro> > imex_exe=r'C:\Program Files\CMG\IMEX\2005.10\EXE\mx200510.exe' > imex_args=('mx200510.exe','-f',imex_fil,'-wd','"'+work_dir+'"') > > for n in range(1,nscen): > os.spawnv(os.P_WAIT, imex_exe, imex_args) > > and it seems to work. Not sure why I need to provide the name of > the > application twice though: the lib pages for spawn* say "In either > case, the > arguments to the child process must start with the name of the > command > being run" but hey, it works! Glad it works. But you probably should be using the new Subprocess module for this kind of thing... It is supposed to supercede popen/spawn etc Alan G. From yegrix at free.fr Thu Sep 7 22:16:44 2006 From: yegrix at free.fr (yves) Date: Thu, 07 Sep 2006 22:16:44 +0200 Subject: [Tutor] tempfile and webbrowser In-Reply-To: <44FB40ED.4050908@free.fr> References: <44FB0F8B.4000504@free.fr> <44FB2E9E.7060600@tds.net> <44FB40ED.4050908@free.fr> Message-ID: <45007E2C.1080706@free.fr> Hello, Here is another problem: Considering this programm: ######## import os, tempfile a = tempfile.mkstemp() f= open(a[1],'w') f.write("foo") f.close() print f.name # here some code to do some things with f os.unlink(f.name) #################### The output is: Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ## working on region in file c:/DOCUME~1/Yves/LOCALS~1/Temp/python-1408y8u... c:\docume~1\yves\locals~1\temp\tmp8fr4-9 Traceback (most recent call last): File "", line 1, in ? File "c:/DOCUME~1/Yves/LOCALS~1/Temp/python-1408y8u", line 8, in ? os.unlink(f.name) OSError: [Errno 13] Permission denied: 'c:\\docume~1\\yves\\locals~1\\temp\\tmp8fr4-9' >>> The file deletion (os.unlink(f.name)) does not work on Windows (it works on Ubuntu with Python 2.4, though). So, is there a way to get this os.unlink(f.name) to work on Windows? -- Yves Egrix From billburns at pennswoods.net Thu Sep 7 22:51:00 2006 From: billburns at pennswoods.net (billburns at pennswoods.net) Date: Thu, 07 Sep 2006 16:51:00 -0400 Subject: [Tutor] how do I find where my program is installed? In-Reply-To: <20060906235603.51663.qmail@web30501.mail.mud.yahoo.com> References: <20060906235603.51663.qmail@web30501.mail.mud.yahoo.com> Message-ID: <1157662260.4500863483cc7@webmail.pennswoods.net> > way. so I need to tell my program to set the working directory back to the > installation directory... but where is this? > Here's what I do in my py2exe app: installDir = os.path.dirname(os.path.abspath(sys.argv[0])) and take a look at this link: http://www.py2exe.org/index.cgi/WhereAmI HTH, Bill From jeffpeery at yahoo.com Thu Sep 7 23:28:25 2006 From: jeffpeery at yahoo.com (Jeff Peery) Date: Thu, 7 Sep 2006 14:28:25 -0700 (PDT) Subject: [Tutor] how do I find where my program is installed? In-Reply-To: <1157662260.4500863483cc7@webmail.pennswoods.net> Message-ID: <20060907212825.97106.qmail@web30512.mail.mud.yahoo.com> Thanks Bill, I read the link you sent, and I am not sure what they mean by "You cannot rely on __file__, because __file__ is not there in the py2exed main-script." can't I use _file_ in my application though? This is what I just added to my application and it seems to do the trick... is there an exception that I am not aware of? using your method, what do you do with 'installDir' in py2exe? thanks for the help. billburns at pennswoods.net wrote: > way. so I need to tell my program to set the working directory back to the > installation directory... but where is this? > Here's what I do in my py2exe app: installDir = os.path.dirname(os.path.abspath(sys.argv[0])) and take a look at this link: http://www.py2exe.org/index.cgi/WhereAmI HTH, Bill --------------------------------- Do you Yahoo!? Get on board. You're invited to try the new Yahoo! Mail. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060907/1ce4c6ee/attachment.htm From rdm at rcblue.com Fri Sep 8 00:10:41 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 07 Sep 2006 15:10:41 -0700 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: References: <7.0.1.0.2.20060905215943.061a2828@rcblue.com> Message-ID: <7.0.1.0.2.20060907145403.02099740@rcblue.com> At 07:16 AM 9/7/2006, Danny Yoo wrote: >Hi Dick, > >I'm looking at the last part of the main() function: > >################# >def main(): > while True: > ... > again() > if again: > break >################# > >This looks a little suspicious. What does the again() function do, and is >it supposed to return a value? I've just seen all the answers to my original post. Thank you all. For now, just to answer Danny's question: Danny, Yes. It will return anything other than "y", "Y", etc., in answer to the prompt, "\n\nDo you want to do another calculation? Y/N: ". This will cause a break out of the while loop and call closingMesssage(). Too convoluted, I'm sure, but it does work. Dick From billburns at pennswoods.net Fri Sep 8 00:27:27 2006 From: billburns at pennswoods.net (Bill Burns) Date: Thu, 07 Sep 2006 18:27:27 -0400 Subject: [Tutor] how do I find where my program is installed? In-Reply-To: <20060907212825.97106.qmail@web30512.mail.mud.yahoo.com> References: <20060907212825.97106.qmail@web30512.mail.mud.yahoo.com> Message-ID: <45009CCF.4020805@pennswoods.net> [Jeff] > I read the link you sent, and I am not sure what they mean by "You > cannot rely on __file__, because __file__ is not there in the py2exed > main-script." can't I use _file_ in my application though? This is what > I just added to my application and it seems to do the trick... is there > an exception that I am not aware of? [Bill] Apparently, py2exe does something (when it freezes the script), which makes __file__ break or at least makes it unreliable. What that something is, I have know idea. Someone else on the list may know... [Jeff] > using your method, what do you do with 'installDir' in py2exe? > [Bill] The documentation for my program lives in a sub-directory of the program directory. Example: C:\Program Files\FilePrinter\documentation But the 'program directory' could be anywhere the user felt like installing it, so... when a user wants to open the docs, they click on a menu item in the GUI and this code gets fired: def on_openDocs_command(self, event): """Opens the documention.""" installDir = os.path.dirname(os.path.abspath(sys.argv[0])) docs = r'documentation\FilePrinter.html' webbrowser.open(os.path.join(installDir, docs)) and no matter where they installed my program, it's possible for me to find the file 'FilePrinter.html' and open it. HTH Bill From rfquerin at gmail.com Fri Sep 8 04:49:53 2006 From: rfquerin at gmail.com (Richard Querin) Date: Thu, 7 Sep 2006 22:49:53 -0400 Subject: [Tutor] A simple list question... Message-ID: <7d81675b0609071949u33849b5t5f972a502f102137@mail.gmail.com> I've got a list of strings. There are some duplicates. I want a list of only the unique entries in that list. So I do the following: mylist = ['project1' , 'project2', 'project3', 'project4', 'project1'] d = {} for item in mylist: d[item] = None cleanedlist = d.keys() But d.keys() seems to add '\n' to each entry in cleanedlist. 1. How can I easily strip out the newline characters from the elements of cleanedlist? 2. Is there a better way to achieve my objective (ie. a list method for generating the cleaned list?) From rdm at rcblue.com Fri Sep 8 05:06:08 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 07 Sep 2006 20:06:08 -0700 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: References: <7.0.1.0.2.20060905215943.061a2828@rcblue.com> Message-ID: <7.0.1.0.2.20060907195058.06172128@rcblue.com> At 05:37 AM 9/7/2006, Andrei wrote: >Dick Moores rcblue.com> writes: > > > (2) Is my roundingN() function OK? Is there a better way to write it? > > Will the line > > > > n = round(float(n)*(10**rounding))/(10**rounding) > >Using format strings is easier I think. "%.2f" % 2.34234 will give '2.34'. I had mistakenly believed that format strings could be used only in print expressions! So now that I know better, I'm trying to write the beginnings of a general setPrecision() function using format strings. However, it appears that a variable cannot be used instead of the ".2" in "%.2f" % 2.234234 def setPrecision(n, precision): n = str(n) p = precision if "." in n: n = "%.pf" % float(n) n = str(n) return n n = 2.234234 precision = 2 print setPrecision(n, precision) This get the error: ValueError: unsupported format character 'p' (0x70) at index 2 How to do this? Dick From kent37 at tds.net Fri Sep 8 05:07:30 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 07 Sep 2006 23:07:30 -0400 Subject: [Tutor] A simple list question... In-Reply-To: <7d81675b0609071949u33849b5t5f972a502f102137@mail.gmail.com> References: <7d81675b0609071949u33849b5t5f972a502f102137@mail.gmail.com> Message-ID: <4500DE72.4080406@tds.net> Richard Querin wrote: > I've got a list of strings. There are some duplicates. I want a list > of only the unique entries in that list. So I do the following: > > mylist = ['project1' , 'project2', 'project3', 'project4', 'project1'] > > d = {} > > for item in mylist: > d[item] = None > > cleanedlist = d.keys() > > > But d.keys() seems to add '\n' to each entry in cleanedlist. No, it doesn't. You are confused somewhere; my guess is your original data has newlines. Using your code above exactly: In [1]: mylist = ['project1' , 'project2', 'project3', 'project4', 'project1'] In [2]: d = {} In [3]: for item in mylist: ...: d[item] = None ...: In [4]: cleanedlist = d.keys() In [5]: cleanedlist Out[5]: ['project4', 'project1', 'project3', 'project2'] No newlines here. > 2. Is there a better way to achieve my objective (ie. a list method > for generating the cleaned list?) If you don't care about the order of items in the new list, just convert to a set and back (essentially a more concise version of what you did with a dict): In [6]: list(set(mylist)) Out[6]: ['project4', 'project1', 'project3', 'project2'] Kent From john at fouhy.net Fri Sep 8 05:10:28 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 8 Sep 2006 15:10:28 +1200 Subject: [Tutor] A simple list question... In-Reply-To: <7d81675b0609071949u33849b5t5f972a502f102137@mail.gmail.com> References: <7d81675b0609071949u33849b5t5f972a502f102137@mail.gmail.com> Message-ID: <5e58f2e40609072010o1f90005bx67229ba38278ba39@mail.gmail.com> On 08/09/06, Richard Querin wrote: > I've got a list of strings. There are some duplicates. I want a list > of only the unique entries in that list. So I do the following: > > mylist = ['project1' , 'project2', 'project3', 'project4', 'project1'] > > d = {} > > for item in mylist: > d[item] = None > > cleanedlist = d.keys() > > But d.keys() seems to add '\n' to each entry in cleanedlist. Um. I'm not in a position to test your code right now, but I can't think of any reason why it would do that.. > 1. How can I easily strip out the newline characters from the elements > of cleanedlist? You could do [s.strip() for s in cleanedlist] -- the .strip() string method will strip whitespace from both ends of the string. > 2. Is there a better way to achieve my objective (ie. a list method > for generating the cleaned list?) cleanedlist = list(set(mylist)) If you don't have python 2.4+, you will need to import the sets module. Also, depending on what you are doing with cleanedlist, you could just leave it as a set. Or even construct mylist as a set. -- John. From rfquerin at gmail.com Fri Sep 8 05:28:11 2006 From: rfquerin at gmail.com (Richard Querin) Date: Thu, 7 Sep 2006 23:28:11 -0400 Subject: [Tutor] A simple list question... In-Reply-To: <4500DE72.4080406@tds.net> References: <7d81675b0609071949u33849b5t5f972a502f102137@mail.gmail.com> <4500DE72.4080406@tds.net> Message-ID: <7d81675b0609072028j5b8b92deiade3ee36a8fd11f0@mail.gmail.com> On 9/7/06, Kent Johnson wrote: > No, it doesn't. You are confused somewhere; my guess is your original > data has newlines. Sorry, my bad. When I created the original list I was splitting a string in two pieces. The latter portion of the string had a newline at the end. I had taken the slice with [index:] instead of [index:-1]. Thanks for the help and the tips regarding other ways to do it. From dyoo at hkn.eecs.berkeley.edu Fri Sep 8 06:39:09 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 7 Sep 2006 21:39:09 -0700 (PDT) Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: <7.0.1.0.2.20060907145403.02099740@rcblue.com> References: <7.0.1.0.2.20060905215943.061a2828@rcblue.com> <7.0.1.0.2.20060907145403.02099740@rcblue.com> Message-ID: >> I'm looking at the last part of the main() function: >> >> ################# >> def main(): >> while True: >> ... >> again() >> if again: >> break >> ################# >> >> This looks a little suspicious. What does the again() function do, and >> is it supposed to return a value? > > Yes. It will return anything other than "y", "Y", etc., in answer to the > prompt, "\n\nDo you want to do another calculation? Y/N: ". Hi Dick, Are you sure? When you say "it will return anything other than 'y', 'Y', what do you mean? What's the return value of again()? Just from a pure pattern matching perspective, compare what you had in the previous statements in terms of shape: rate = getRate() if str(rate) in "QqXx": break or: currency = getYenOrUSD() if currency in "QqXx": break versus the shape of the again block: again() if again: break Do you see something about the "shape" of the third block that's different from the first two blocks? That's what I'm trying to get at: there's something very different here. Read Andrei's point 3 on again() again, and see if what he says makes sense to you. http://mail.python.org/pipermail/tutor/2006-September/049105.html This is a point that you'll want to look at with scrutiny: even though the program looks like it's working, suspend your belief for the moment. *grin* There's something funky happening in the control flow of the code around this area. If you don't understand, ask for more clarification, and one of us here will be more explicit. Just to be fair: what you have does work, from a purely technical perspective. The thing is that it is not following the human intentions that you've written into the code, and other readers will get confused unless they stare at the code for a while. Best of wishes! From project5 at redrival.net Fri Sep 8 08:46:59 2006 From: project5 at redrival.net (Andrei) Date: Fri, 8 Sep 2006 06:46:59 +0000 (UTC) Subject: [Tutor] Some questions about my yen-USD.py References: <7.0.1.0.2.20060905215943.061a2828@rcblue.com> <200609071908.30531.Python@kraszewscy.net> Message-ID: Pawel Kraszewski kraszewscy.net> writes: > > > get me into trouble with the flakiness of float(n)? In testing I > > > didn't find any problems, but .. > > > > Nah. Float accuracy is only a problem if you need around lots of > > significant digits (16 or so). > > I wouldn't bet. Such a simple thing as 0.1 can't be represented correctly on > Float... That's what 'decimal' is for. > > See that: > > >>> 0.1 + 0.1 + 0.1 - 0.3 > 5.5511151231257827e-17 For the intents and purposes of this script, this difference is of no consequence (that value is close enough to zero): >>> "%.2f" % (.1+.1+.1-.3) '0.00' Andrei From project5 at redrival.net Fri Sep 8 08:57:01 2006 From: project5 at redrival.net (Andrei) Date: Fri, 8 Sep 2006 06:57:01 +0000 (UTC) Subject: [Tutor] Some questions about my yen-USD.py References: <7.0.1.0.2.20060905215943.061a2828@rcblue.com> <7.0.1.0.2.20060907195058.06172128@rcblue.com> Message-ID: Dick Moores rcblue.com> writes: > So now that I know better, I'm trying to write the beginnings of a > general setPrecision() function using format strings. However, it > appears that a variable cannot be used instead of the ".2" in > > "%.2f" % 2.234234 > How to do this? You could use simple string concatenation: >>> "%." + str(2) + 'f' '%.2f' >>> "%." + str(4) + 'f' '%.4f' Or use format strings to create other format strings, by escaping the '%' with '%%'. E.g.: >>> "%%.%df" % 2 # the '%%' will be changed to '%' in the result '%.2f' >>> "%%.%df" % 4 '%.4f' >>> s1 = "%%.%df" % 2 >>> print s1, s1 % 3.41234 '%.2f', '3.41' >>> s2 = "%%.%df" % 4 >>> print s2, s2 % 3.41234 '%.4f', '3.4123' >>> ("%%.%df" % 2) % 3.23423 '3.23' Yours, Andrei From rdm at rcblue.com Fri Sep 8 09:18:13 2006 From: rdm at rcblue.com (Dick Moores) Date: Fri, 08 Sep 2006 00:18:13 -0700 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: References: <7.0.1.0.2.20060905215943.061a2828@rcblue.com> <7.0.1.0.2.20060907145403.02099740@rcblue.com> Message-ID: <7.0.1.0.2.20060907232524.063df9d8@rcblue.com> At 09:39 PM 9/7/2006, Danny Yoo wrote: > >> I'm looking at the last part of the main() function: > >> > >> ################# > >> def main(): > >> while True: > >> ... > >> again() > >> if again: > >> break > >> ################# > >> > >> This looks a little suspicious. What does the again() function do, and > >> is it supposed to return a value? > > > > Yes. It will return anything other than "y", "Y", etc., in answer to the > > prompt, "\n\nDo you want to do another calculation? Y/N: ". > > >Hi Dick, > >Are you sure? When you say "it will return anything other than 'y', 'Y', >what do you mean? What's the return value of again()? > > >Just from a pure pattern matching perspective, compare what you had in the >previous statements in terms of shape: > > rate = getRate() > if str(rate) in "QqXx": break > >or: > > currency = getYenOrUSD() > if currency in "QqXx": break > >versus the shape of the again block: > > again() > if again: > break > >Do you see something about the "shape" of the third block that's different >from the first two blocks? That's what I'm trying to get at: there's >something very different here. > > >Read Andrei's point 3 on again() again, and see if what he says makes >sense to you. > > http://mail.python.org/pipermail/tutor/2006-September/049105.html > >This is a point that you'll want to look at with scrutiny: even though the >program looks like it's working, suspend your belief for the moment. >*grin* > > >There's something funky happening in the control flow of the code around >this area. If you don't understand, ask for more clarification, and one >of us here will be more explicit. > >Just to be fair: what you have does work, from a purely technical >perspective. The thing is that it is not following the human intentions >that you've written into the code, and other readers will get confused >unless they stare at the code for a while. Yes, Danny, I've taken yours and Andrei's comment about again() to heart; I see my confusion. I've revised again() and main(). See my version 2: http://www.rcblue.com/Python/yen-USD-v2.txt Is this better? I've still got to consider Andrei's instructions on the use of string formatting, the inappropriate names of some of my functions (including splitting up of printResult() into 2 functions, and probably some other points. So there will be at least a v3 to come. Dick From alan.gauld at freenet.co.uk Fri Sep 8 10:36:14 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 8 Sep 2006 09:36:14 +0100 Subject: [Tutor] tempfile and webbrowser References: <44FB0F8B.4000504@free.fr> <44FB2E9E.7060600@tds.net><44FB40ED.4050908@free.fr> <45007E2C.1080706@free.fr> Message-ID: <002001c6d321$d8c309c0$0201a8c0@XPpro> > The file deletion (os.unlink(f.name)) does not work on Windows (it > works on Ubuntu with Python 2.4, though). > > So, is there a way to get this os.unlink(f.name) to work on Windows? Use os.remove() instead. Alan G. From alan.gauld at freenet.co.uk Fri Sep 8 10:41:00 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 8 Sep 2006 09:41:00 +0100 Subject: [Tutor] A simple list question... References: <7d81675b0609071949u33849b5t5f972a502f102137@mail.gmail.com> Message-ID: <002a01c6d322$83a427c0$0201a8c0@XPpro> > 1. How can I easily strip out the newline characters from the > elements > of cleanedlist? You can use the string strip() method. > 2. Is there a better way to achieve my objective (ie. a list method > for generating the cleaned list?) You can convert the list to a Set. >>> L = [1,2,1,3,4,2] >>> s = set(L) >>> s set([1, 2, 3, 4]) >>> HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From justin.mailinglists at gmail.com Fri Sep 8 11:02:38 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Fri, 8 Sep 2006 17:02:38 +0800 Subject: [Tutor] Some questions about my yen-USD.py Message-ID: <3c6718980609080202mb07e256u9b950aa7dfd23f24@mail.gmail.com> Dick Moores rcblue.com> writes: > So now that I know better, I'm trying to write the beginnings of a > general setPrecision() function using format strings. However, it > appears that a variable cannot be used instead of the ".2" in > > "%.2f" % 2.234234 > How to do this? http://www.python.org/doc/current/lib/typesseq-strings.html >>> "%.*f" % (2, 2.234234) '2.23' >>> "%.*f" % (3, 2.234234) '2.234' >>> "%.*f" % (1, 2.234234) '2.2' >>> "%.*f" % (0, 2.234234) '2' From alan.gauld at freenet.co.uk Fri Sep 8 11:24:55 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 8 Sep 2006 10:24:55 +0100 Subject: [Tutor] Some questions about my yen-USD.py References: <7.0.1.0.2.20060905215943.061a2828@rcblue.com> <7.0.1.0.2.20060907195058.06172128@rcblue.com> Message-ID: <001101c6d328$a5d04440$0201a8c0@XPpro> > So now that I know better, I'm trying to write the beginnings of a > general setPrecision() function using format strings. However, it > appears that a variable cannot be used instead of the ".2" in > > "%.2f" % 2.234234 The trick is to create the format string using the variable then use the format string for your final result: value = 11234.23456789345 width = 12 precision = 3 fmt = "%%s.%sf" % (width,precision) result = fmt % value HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Fri Sep 8 12:11:04 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 08 Sep 2006 06:11:04 -0400 Subject: [Tutor] tempfile and webbrowser In-Reply-To: <002001c6d321$d8c309c0$0201a8c0@XPpro> References: <44FB0F8B.4000504@free.fr> <44FB2E9E.7060600@tds.net><44FB40ED.4050908@free.fr> <45007E2C.1080706@free.fr> <002001c6d321$d8c309c0$0201a8c0@XPpro> Message-ID: <450141B8.5090105@tds.net> Alan Gauld wrote: >> The file deletion (os.unlink(f.name)) does not work on Windows (it >> works on Ubuntu with Python 2.4, though). >> >> So, is there a way to get this os.unlink(f.name) to work on Windows? > > Use os.remove() instead. os.remove() and os.unlink() are identical according to the docs; if you look at posix_module.c you can see this is true - they both map to posix_unlink(). Kent From rdm at rcblue.com Fri Sep 8 13:01:52 2006 From: rdm at rcblue.com (Dick Moores) Date: Fri, 08 Sep 2006 04:01:52 -0700 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: References: <7.0.1.0.2.20060905215943.061a2828@rcblue.com> Message-ID: <7.0.1.0.2.20060908022704.061e6100@rcblue.com> Version 3 is now at http://www.rcblue.com/Python/yen-USD-v3.txt . Am I done? Or will a v4 be necessary/advisable? At 05:37 AM 9/7/2006, Andrei wrote: >Dick Moores rcblue.com> writes: > > (1) Have I handled possible user-errors OK? > >I've tested it a bit and it seems to be quite robust. Thanks. > > (2) Is my roundingN() function OK? Is there a better way to write it? > > Will the line > > > > n = round(float(n)*(10**rounding))/(10**rounding) > >Using format strings is easier I think. "%.2f" % 2.34234 will give '2.34'. Yes, I finally got that implemented, thanks to your further assistance. > > get me into trouble with the flakiness of float(n)? In testing I > > didn't find any problems, but .. > >Nah. Float accuracy is only a problem if you need around lots of significant >digits (16 or so). > > > (4) I wanted to call closingMessage() in main(), but in some cases, > > if it's in main() it gets 2 successive calls. I can't figure out why. > > Would IDLE's debugger be of use here? (I've never used it before.) I > > haven't been able to find up-to-date IDLE help. > >I think the main loop could be improved. > >1) Python idiom is to *not* always call main(), because that makes >it impossible >to use functions from your module in a different program: importing the module >would start running the converter, while you might only be >interested in reusing >getRate(). It's better to put the following code at the bottom instead: > >if __name__ == "__main__": # if module is running standalone (not imported) > main() Done. >2) If the application is used extensively, you'll exceed the maximum recursion >depth, because what the application does is essentially this (if the user >chooses to continue): > > main calls again calls main calls again calls... ad infinitum > >This is called recursion - main essentially calls itself. You can test what >happens by disabling the entire main loop up to "again()" as well as the >raw_input line in again(). Python will quickly give up with: > > File "yen.py", line 164, in again > main() > File "yen.py", line 184, in main > again() > RuntimeError: maximum recursion depth exceeded > >It's better to have a main() which does something like this: > - get the conversion rate and store it in some (global?) variable > (instead of asking for it every time) > - start a while True loop: > -- get the rate , currency and amount > -- calculate and print result > -- ask the user whether to do it again and stop loop if answer is No Your point about recursion is well-taken, but I doubt that the user I have in mind will run into it. And he would be as likely to want to vary the exchange rate as the amount. >3) The function again() uses an internal variable called 'again'. This is not >good coding practice (confusing). >3b) Note that this is a variable local to the again() function, so you cannot >use it in the main() anyway: > > again() > if again: > break > >"if again" actually checks if there is something called 'again' with a >non-zero/non-empty/non-None/True value. Your function is such a >thing, so the if >condition always evaluates as True. (Tip: try "print again" before the "if >again", you'll see something like ""). >This is of >course related to recursion problem above. > >Improved version would be: > >def again(): > answer = raw_input('Another?') > return answer in 'yY' # evaluates to True if the user pressed 'y' or 'Y' > >def main(): > # stuff > while True: > # stuff > if not again(): > closingMessage() > return None > >Notice that this code is also easier to read than the original, because it's a >literal translation of you intention: if the user doesn't want to >run it again, >say goodbye and stop. Thanks. Between yours and Danny's help, I finally understand the problem. I haven't heard back from Danny yet, but I think I've corrected the problem. >4) Function names are important and should be chosen in such a way >that they are >not confusing. Most of them are OK, but commas() is non-descripting I've renamed commas() to numberCommas(). Is that descriptive enough? I'm reluctant to go with even a longer name. I'll be using it a lot elsewhere. > and >printResult() is confusing - it doesn't just print, it actually calculates. A >third party interested in reusing your calculation routine wouldn't expect the >printResult to be the culprit. I've separated printResult() into calculateAnswer() and printAnswer(). >5) Checks like "if currency in 'USD'" work, but are a bit unstable. >It works in >this case because Yen and USD have no letters in common, so input of >'y', 'e' or >'n' all lead to 'Yen', while 'u', 's' and 'd' go to 'USD'. Imagine >you'd extend >your program to also handle 'AUD', 'EUR', 'CAD' and 'SEK'. The 'e' would now >lead to Yen instead of EUR. Thanks for that general point, but I'll revise the function when necessary. >6) I would trim down the the checks in checkAmount: >- there is no need to use "continue" in that loop, because the loop will >continue anyway. 'continue' is only useful if there is some code later in the >loop that you want to skip. >- separate checks for negative and zero values seem pointless. Either handle 0 >as any other number (gives result 0), or put a single check on >"amount <= 0" and >inform the user that a number larger than 0 is required. >Here's a modified version: > > def getAmount(currency): > while True: > useramount = raw_input('Amount: ').lower().strip() > if useramount in 'qx': > return useramount > try: > amount = float(useramount) > except ValueError: > continue # we want to skip the code below > if amount <= 0: > print "Amount must be more than 0." > else: > return amount > >Using multiple returns in a single function is sometimes frowned >upon; but then >again, so are break and continue :). I didn't know till now that a return statement could be used inside a while loop, to close the function. I had thought that with a "while True:" I always had to break out of it with a "break". Using your example, I revised getRate(), getAmount(), and getYenOrUSD(). Cut down the number of continue's and cut out all break's. Thanks very much, Andrei. Dick From kent37 at tds.net Fri Sep 8 13:52:35 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 08 Sep 2006 07:52:35 -0400 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: <7.0.1.0.2.20060907195058.06172128@rcblue.com> References: <7.0.1.0.2.20060905215943.061a2828@rcblue.com> <7.0.1.0.2.20060907195058.06172128@rcblue.com> Message-ID: <45015983.6030102@tds.net> Dick Moores wrote: > At 05:37 AM 9/7/2006, Andrei wrote: >> Dick Moores rcblue.com> writes: >> >>> (2) Is my roundingN() function OK? Is there a better way to write it? >>> Will the line >>> >>> n = round(float(n)*(10**rounding))/(10**rounding) >> Using format strings is easier I think. "%.2f" % 2.34234 will give '2.34'. > > I had mistakenly believed that format strings could be used only in > print expressions! > > So now that I know better, I'm trying to write the beginnings of a > general setPrecision() function using format strings. However, it > appears that a variable cannot be used instead of the ".2" in > > "%.2f" % 2.234234 Yes, it can, just not the way you think - if you use a * for the precision, the value will be read from the provided parameters: In [1]: '%.*f' % (2, 2.234234) Out[1]: '2.23' In [2]: '%.*f' % (4, 2.234234) Out[2]: '2.2342' You can do this with the width parameter also which can be very useful when you have computed a field width: In [3]: '%*s' % (4, 'foo') Out[3]: ' foo' In [4]: '%*s' % (10, 'foo') Out[4]: ' foo' Kent From kent37 at tds.net Fri Sep 8 14:04:14 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 08 Sep 2006 08:04:14 -0400 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: <7.0.1.0.2.20060907232524.063df9d8@rcblue.com> References: <7.0.1.0.2.20060905215943.061a2828@rcblue.com> <7.0.1.0.2.20060907145403.02099740@rcblue.com> <7.0.1.0.2.20060907232524.063df9d8@rcblue.com> Message-ID: <45015C3E.3050608@tds.net> Dick Moores wrote: > Yes, Danny, I've taken yours and Andrei's comment about again() to > heart; I see my confusion. I've revised again() and main(). See my > version 2: http://www.rcblue.com/Python/yen-USD-v2.txt Is this better? Have you noticed the similarity between getRate() and getAmount()? Maybe you could make a single getPositiveNumber() function that replaces both? A better name for comma() might be commify() ? confirmCurrency() doesn't just confirm, it also puts the currency into a standard form. I would make that a responsibility of getYenOrUSD(). Others have commented on potential problems with 'if currency not in "YENUSD":'. I would combine the test with the normalization. Here are two ways to do it: by testing each one: currency = currency.upper() # string.upper() is deprecated if currency in ['Y', 'YEN']: return 'Yen' if currency in ['U', 'USD']: return 'USD' with a dictionary: currencies = { 'U' : 'USD', 'USD' : 'USD', 'Y' : 'Yen', 'YEN' : 'Yen' } try: return currencies[currency] except KeyError: continue The dict method is more extensible, you could even create the dict automatically from a list of the return codes you want. Kent From project5 at redrival.net Fri Sep 8 14:46:15 2006 From: project5 at redrival.net (Andrei) Date: Fri, 8 Sep 2006 12:46:15 +0000 (UTC) Subject: [Tutor] Some questions about my yen-USD.py References: <7.0.1.0.2.20060905215943.061a2828@rcblue.com> <7.0.1.0.2.20060908022704.061e6100@rcblue.com> Message-ID: Dick Moores rcblue.com> writes: > Version 3 is now at http://www.rcblue.com/Python/yen-USD-v3.txt . Am > I done? Or will a v4 be necessary/advisable? The original program worked fine from the user's POV and the code had lots of good features (functions instead of monolithic code, docstrings). IMO the most important problem of the code was the "if again" thing in the loop, which, as you point out, is not a problem for the user (who won't hit the recursion limit), but it is a very big conceptual issue that's prone to bite you every time you write a function. Beyond that, any program above 10 lines (and even many smaller ones) offers infinite opportunities at fiddling - at some point opinions will start to differ about the 'perfect' approach and further micro-optimizations. It's best to let programs that are "good enough" alone and focus on new things that will give new learning opportunities: you could write something different, or choose to extend the program in radical new ways (e.g. automatic downloading of conversion rates, a GUI/web interface). > >4) Function names are important and should be chosen in such a way > >that they are > >not confusing. Most of them are OK, but commas() is non-descripting > > I've renamed commas() to numberCommas(). Is that descriptive enough? > I'm reluctant to go with even a longer name. I'll be using it a lot elsewhere. A guideline for function names is that they should contain a (well chosen) verb and an object. As always it ends up being a matter of personal taste. I for example might call that function insertSeparators or formatNumber, but other people might prefer longer names like insertSeparatorsInNumber or prettyPrintNumber or something completely different. Yours, Andrei From jfabiani at yolo.com Fri Sep 8 16:32:37 2006 From: jfabiani at yolo.com (johnf) Date: Fri, 8 Sep 2006 07:32:37 -0700 Subject: [Tutor] is there a tutorial on ez_install.py Message-ID: <200609080732.37591.jfabiani@yolo.com> Hi, Is there a location (web link) that explains the inner workings of setuptools, etc.... John From kent37 at tds.net Fri Sep 8 19:17:03 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 08 Sep 2006 13:17:03 -0400 Subject: [Tutor] is there a tutorial on ez_install.py In-Reply-To: <200609080732.37591.jfabiani@yolo.com> References: <200609080732.37591.jfabiani@yolo.com> Message-ID: <4501A58F.5040507@tds.net> johnf wrote: > Hi, > > Is there a location (web link) that explains the inner workings of setuptools, > etc.... http://peak.telecommunity.com/DevCenter/EasyInstall Kent From alan.gauld at freenet.co.uk Fri Sep 8 19:30:39 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 8 Sep 2006 18:30:39 +0100 Subject: [Tutor] Some questions about my yen-USD.py References: <3c6718980609080202mb07e256u9b950aa7dfd23f24@mail.gmail.com> Message-ID: <000b01c6d36c$8117ff00$0201a8c0@XPpro> > http://www.python.org/doc/current/lib/typesseq-strings.html > >>>> "%.*f" % (2, 2.234234) > '2.23' Cool! I'd never noticed this, or maybe just difdn't understand the significance. And it works for multiple values too: >>> "%*.*" % (12,3,123.456789) unfortunately 3 values won't work, it only works for numbers... >>> "%**.*" % ('-', 12,3,123.456789) Error... Alan G From kent37 at tds.net Fri Sep 8 19:47:49 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 08 Sep 2006 13:47:49 -0400 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: <000b01c6d36c$8117ff00$0201a8c0@XPpro> References: <3c6718980609080202mb07e256u9b950aa7dfd23f24@mail.gmail.com> <000b01c6d36c$8117ff00$0201a8c0@XPpro> Message-ID: <4501ACC5.5010402@tds.net> Alan Gauld wrote: > unfortunately 3 values won't work, it only works for numbers... > >>>> "%**.*" % ('-', 12,3,123.456789) > > Error... How about this: In [4]: "%*.*f" % (-12,3,123.456789) Out[4]: '123.457 ' Kent From bill at celestial.net Fri Sep 8 19:47:15 2006 From: bill at celestial.net (Bill Campbell) Date: Fri, 8 Sep 2006 10:47:15 -0700 Subject: [Tutor] is there a tutorial on ez_install.py In-Reply-To: <4501A58F.5040507@tds.net> References: <200609080732.37591.jfabiani@yolo.com> <4501A58F.5040507@tds.net> Message-ID: <20060908174715.GA18131@alexis.mi.celestial.com> On Fri, Sep 08, 2006, Kent Johnson wrote: >johnf wrote: >> Hi, >> >> Is there a location (web link) that explains the inner workings of setuptools, >> etc.... > >http://peak.telecommunity.com/DevCenter/EasyInstall Is it possible to use EasyInstall to install relative to a directory other than the site-packages directory in the manner that the standard distutils does with the ``--root'' option? I build a lot of packages under the OpenPKG portable packaging system which is an RPM based system, and find EasyInstall fits Doug Gwynn's description of GUIs ``GUIs make simple things simple and complex things impossible''. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 ``People who relieve others of their money with guns are called robbers. It does not alter the immorality of the act when the income transfer is carried out by government.'' From kent37 at tds.net Fri Sep 8 20:15:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 08 Sep 2006 14:15:50 -0400 Subject: [Tutor] is there a tutorial on ez_install.py In-Reply-To: <20060908174715.GA18131@alexis.mi.celestial.com> References: <200609080732.37591.jfabiani@yolo.com> <4501A58F.5040507@tds.net> <20060908174715.GA18131@alexis.mi.celestial.com> Message-ID: <4501B356.80309@tds.net> Bill Campbell wrote: > On Fri, Sep 08, 2006, Kent Johnson wrote: >> http://peak.telecommunity.com/DevCenter/EasyInstall > > Is it possible to use EasyInstall to install relative to a > directory other than the site-packages directory in the manner > that the standard distutils does with the ``--root'' option? Did you see the section "Custom Installation Locations" in the above-referenced guide? Does that do what you want? http://peak.telecommunity.com/DevCenter/EasyInstall#custom-installation-locations Kent From alan.gauld at freenet.co.uk Fri Sep 8 21:37:07 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 8 Sep 2006 20:37:07 +0100 Subject: [Tutor] tempfile and webbrowser References: <44FB0F8B.4000504@free.fr> <44FB2E9E.7060600@tds.net><44FB40ED.4050908@free.fr> <45007E2C.1080706@free.fr><002001c6d321$d8c309c0$0201a8c0@XPpro> <450141B8.5090105@tds.net> Message-ID: <001001c6d37e$2c03e2b0$0201a8c0@XPpro> >> Use os.remove() instead. > > os.remove() and os.unlink() are identical according to the docs; if > you look at posix_module.c you can see this is true - they both map > to posix_unlink(). > > Kent Maybe so, but os.remove() works on my XP box... :-) I didn't try unlink since the OP said it didn't work. And maybe significantly MS Visual C doesn't (or didn't up to v6) include the unlink system call. So I figured maybe remove was implemented to be system specific. But it was not a scientific test. Alan G. From alan.gauld at freenet.co.uk Fri Sep 8 21:40:53 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 8 Sep 2006 20:40:53 +0100 Subject: [Tutor] Some questions about my yen-USD.py References: <3c6718980609080202mb07e256u9b950aa7dfd23f24@mail.gmail.com><000b01c6d36c$8117ff00$0201a8c0@XPpro> <4501ACC5.5010402@tds.net> Message-ID: <001e01c6d37e$b2d2fe70$0201a8c0@XPpro> > Alan Gauld wrote: >> unfortunately 3 values won't work, it only works for numbers... >> >>>>> "%**.*" % ('-', 12,3,123.456789) >> >> Error... > > How about this: > In [4]: "%*.*f" % (-12,3,123.456789) > Out[4]: '123.457 ' Silly me! Obvious when you see it :-) Alan G. From kent37 at tds.net Fri Sep 8 22:08:51 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 08 Sep 2006 16:08:51 -0400 Subject: [Tutor] tempfile and webbrowser In-Reply-To: <001001c6d37e$2c03e2b0$0201a8c0@XPpro> References: <44FB0F8B.4000504@free.fr> <44FB2E9E.7060600@tds.net><44FB40ED.4050908@free.fr> <45007E2C.1080706@free.fr><002001c6d321$d8c309c0$0201a8c0@XPpro> <450141B8.5090105@tds.net> <001001c6d37e$2c03e2b0$0201a8c0@XPpro> Message-ID: <4501CDD3.5090104@tds.net> Alan Gauld wrote: >>> Use os.remove() instead. >> os.remove() and os.unlink() are identical according to the docs; if >> you look at posix_module.c you can see this is true - they both map >> to posix_unlink(). >> >> Kent > > Maybe so, but os.remove() works on my XP box... :-) > > I didn't try unlink since the OP said it didn't work. Did you try the OP's code with os.remove()? I doubt it works for you, here is what I got: In [9]: import os, tempfile In [10]: a = tempfile.mkstemp() In [11]: f= open(a[1],'w') In [12]: f.write("foo") In [13]: f.close() In [14]: print f.name c:\docume~1\ktjohn~1\locals~1\temp\tmpy_3mmh In [15]: # here some code to do some things with f In [16]: os.unlink(f.name) --------------------------------------------------------------------------- exceptions.OSError Traceback (most recent call last) D:\Projects\e3po\ OSError: [Errno 13] Permission denied: 'c:\\docume~1\\ktjohn~1\\locals~1\\temp\\tmpy_3mmh' os.remove() doesn't work either: In [17]: os.remove(f.name) --------------------------------------------------------------------------- exceptions.OSError Traceback (most recent call last) D:\Projects\e3po\ OSError: [Errno 13] Permission denied: 'c:\\docume~1\\ktjohn~1\\locals~1\\temp\\tmpy_3mmh' Maybe time for another trip to the docs: mkstemp() returns a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order. Aha, mkstemp() is already opening the file, so the explicit open() creates a *second* handle to the open file; when it is closed, the original handle is still open. Try it like this, using os.fdopen() to convert the low-level file handle from mkstemp() to a Python file object: In [21]: fd, fname = tempfile.mkstemp() In [22]: f = os.fdopen(fd, 'w') In [23]: f.write('foo') In [24]: f.close() In [25]: os.unlink(fname) Seems to work... Kent From bill at celestial.net Fri Sep 8 23:19:52 2006 From: bill at celestial.net (Bill Campbell) Date: Fri, 8 Sep 2006 14:19:52 -0700 Subject: [Tutor] is there a tutorial on ez_install.py In-Reply-To: <4501B356.80309@tds.net> References: <200609080732.37591.jfabiani@yolo.com> <4501A58F.5040507@tds.net> <20060908174715.GA18131@alexis.mi.celestial.com> <4501B356.80309@tds.net> Message-ID: <20060908211951.GB45178@alexis.mi.celestial.com> On Fri, Sep 08, 2006, Kent Johnson wrote: >Bill Campbell wrote: >> On Fri, Sep 08, 2006, Kent Johnson wrote: >>> http://peak.telecommunity.com/DevCenter/EasyInstall >> >> Is it possible to use EasyInstall to install relative to a >> directory other than the site-packages directory in the manner >> that the standard distutils does with the ``--root'' option? > >Did you see the section "Custom Installation Locations" in the >above-referenced guide? Does that do what you want? >http://peak.telecommunity.com/DevCenter/EasyInstall#custom-installation-locations No. That would have the installation looking for it in some location like /opkg/RPM/TMP/package-name-root/lib/python... instead of the proper location under the site-packages on the installed system. It seems to me that EasyInstall is aimed at people installing on individual systems, not ones building packages that will be installed on multiple machines using a package manager. We build many packages under the OpenPKG.org portable package manager which allows us to use standard source packages on a wide variety of Linux and UNIX systems. The main package we build that uses EasyInstall is sqlobject, and I'm currently kludging this by doing the build under the control of EasyInstall (being careful that all the supporting packages are current so it doesn't go grabbing things across the network that aren't in the package). Once the build is done, my SPEC file then copies from the build directory to the temporary destination directory, skipping the EasyInstall install routine. Personally I haven't found any good reasons not to use the standard distutils, particularly since all the dependencies are handled already by the OpenPKG package manager. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software, LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 ``there is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things. Because the innovator has for enemies all those who have done well under the old conditions, and lukewarm defenders in those who may do well under the new.'' -- Machiavelli From carroll at tjc.com Sat Sep 9 00:15:10 2006 From: carroll at tjc.com (Terry Carroll) Date: Fri, 8 Sep 2006 15:15:10 -0700 (PDT) Subject: [Tutor] [OT] some jobs are just too big for Python Message-ID: http://www.news.com.au/dailytelegraph/story/0,22049,20372915-5006003,00.html Summary: A python (the actual snake) ate an entire pregnant sheep in Malaysia; and was unable to even move afterwards. The story above includes an impressive if somewhat disturbing photo. From amadeo.bellotti at gmail.com Sat Sep 9 00:28:31 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Fri, 8 Sep 2006 18:28:31 -0400 Subject: [Tutor] [OT] some jobs are just too big for Python In-Reply-To: References: Message-ID: Thats acutally a pretty good analogy but i think python isnt yet at its fullest potential or even close On 9/8/06, Terry Carroll wrote: > > > > > http://www.news.com.au/dailytelegraph/story/0,22049,20372915-5006003,00.html > > Summary: A python (the actual snake) ate an entire pregnant sheep in > Malaysia; and was unable to even move afterwards. > > The story above includes an impressive if somewhat disturbing photo. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060908/55870780/attachment.htm From klaus.ramelow at GMX.de Sat Sep 9 21:06:36 2006 From: klaus.ramelow at GMX.de (Klaus Ramelow) Date: Sat, 09 Sep 2006 21:06:36 +0200 Subject: [Tutor] Tutor Digest, Vol 31, Issue 23 - some jobs are just too big for Python In-Reply-To: References: Message-ID: <450310BC.8030001@GMX.de> Sometimes I have also some - or more - problems trying digesting python and feeling totally blocked. My programming experience (beginning at the card-reader aera) main-frame, mini and micro : Bit / Byte / Word system-programming via switch-console followed by Assembler and commercial software using Basic, Cobol, Pascal and SQL. Mnemonic programming-language - in my understanding - can only be consisting of expressions near the human language. The best example for writing non-system-programms are Basic and SQL. Why should I waste time in learning a "language" like Java (or more positive: python) ? Nevertheless this Tutor Digest is most helpful, the number of questions / problems show some more people are looking for a mnemonic-language which should cross-compile to something with multiplatform-capability like Java. Please let me know, if I am entirely wrong. Klaus Ramelow > > ------------------------------------------------------------------------ > > Betreff: > [Tutor] [OT] some jobs are just too big for Python > Von: > Terry Carroll > Datum: > Fri, 8 Sep 2006 15:15:10 -0700 (PDT) > An: > tutor at python.org > > An: > tutor at python.org > > > http://www.news.com.au/dailytelegraph/story/0,22049,20372915-5006003,00.html > > Summary: A python (the actual snake) ate an entire pregnant sheep in > Malaysia; and was unable to even move afterwards. > > The story above includes an impressive if somewhat disturbing photo. > > > From john.corry at ntlworld.com Sun Sep 10 00:14:27 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sat, 9 Sep 2006 23:14:27 +0100 Subject: [Tutor] Dates Message-ID: <000001c6d45d$554f8680$513ea8c0@JOHNC> Hi All, I am using the code below to select items from a visual foxpro database where the dates are between the 31/01/2006 and 31/12/2006. The good news is that the code below works. However, I want to make the from and to dates variable. I want to change the range depending on user input. I can't get this to work. I have tried the code below marked "Tried" but I get the error: Traceback (most recent call last): File "C:\test\timemanager.py", line 16, in ? c.execute('SELECT * FROM times where rt_weekst >= ? and rt_weekst <= ? and rt_type == ?', (a,b,"R",)) DataError: ('22005', 301, '[Microsoft][ODBC Visual FoxPro Driver]Operator/operand type mismatch.', 4579) Code that works is below: import mx.ODBC import mx.ODBC.Windows import mx.DateTime db = mx.ODBC.Windows.DriverConnect('DSN=tnt') c = db.cursor() c.execute('SELECT * FROM times where rt_weekst >= date(2006,01,31) and rt_weekst <= date(2006,12,31) and rt_type == ?', ("R",)) for row in c.fetchall(): print row row = str(row) c.close() Tried but get errors: import mx.ODBC import mx.ODBC.Windows import mx.DateTime import datetime a = datetime.date(2006,01,31) b = datetime.date(2006,12,31) db = mx.ODBC.Windows.DriverConnect('DSN=tnt') c = db.cursor() c.execute('SELECT * FROM times where rt_weekst >= ? and rt_weekst <= ? and rt_type == ?', (a,b,"R",)) for row in c.fetchall(): print row row = str(row) c.close() Is there a way to format the date so that the Select statement works? Thanks, John. From alan.gauld at btinternet.com Sun Sep 10 01:13:30 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 10 Sep 2006 00:13:30 +0100 Subject: [Tutor] Tutor Digest, Vol 31, Issue 23 - some jobs are just too big for Python References: <450310BC.8030001@GMX.de> Message-ID: "Klaus Ramelow" wrote > My programming experience (beginning at the card-reader aera) > main-frame, mini and micro : > Bit / Byte / Word system-programming via switch-console followed by > Assembler and commercial > software using Basic, Cobol, Pascal and SQL. I go back to a similar era but not on mainframes, I cut my teath on DEC PDP10 and Data General Midi computers > Mnemonic programming-language - in my understanding - can only be > consisting of expressions near the human language. Yes, but the human language can be mathematics :-) Thus Fortran and PL/1 are not much like English but are mnemonic in form to their users. > The best example for writing non-system-programms are > Basic and SQL. Interesting choice, I'd have probably included COBOL there too. > Why should I waste time in learning a "language" like Java (or more > positive: python) ? Two different questions. Java is a replacement for C++ and tries to be a portable systems language. It has libraries to tackle a lot of fairly low level tasks and is often used where C++B would have been. It offers few advantages over C++ (garbage collection mainly) and has several disadvantages, (speed, no operator overloading etc) but delivers(nearly) the promise of portability. Python is a different kind of language, much close to languages like Perl and Tcl. It is a higher level language in that it requires far fewer lines of code to achieve the same functional;itry - 3-10 times compared to C++ or Java and 3-5 times compared to BASIC in my experience, even compared to modern BASICs like Visual Basic. Pythpon excels in building applications quickly, even if you might have to rewrite some parts in a loewr level language like C++/Java later. Python, is also much easier to learn so plays an important role as a training language - compare it to Logo rather than Pascal in that regard! SQL stands alone as a data access language. It is in no way a general purpose language but it is the de-facto data access mechanism, even in Python.. > Nevertheless this Tutor Digest is most helpful, the number of > questions > / problem show some more people are looking for a mnemonic-language > which should cross-compile to something with > multiplatform-capability > like Java. I don't know how many people consider Pythons cross platform capability to be that high on their list. I certainly don;t. And although Python does compile under the covers I never really think of it as compiled. I just like it as a language which lets me build stuff quickly with minimum thought about the language itself and maximum thought about the problem and solution. > Please let me know, if I am entirely wrong. you are not completely wrong but you may be focused on only one aspect of a multi faceted picture. IMHO of course :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Sep 10 01:15:44 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 10 Sep 2006 00:15:44 +0100 Subject: [Tutor] Dates References: <000001c6d45d$554f8680$513ea8c0@JOHNC> Message-ID: John, > c.execute('SELECT * FROM times where rt_weekst >= date(2006,01,31) > and > rt_weekst <= date(2006,12,31) and rt_type == ?', ("R",)) > a = datetime.date(2006,01,31) > b = datetime.date(2006,12,31) > c.execute('SELECT * FROM times where rt_weekst >= ? and rt_weekst <= > ? > and rt_type == ?', (a,b,"R",)) In the first case the dates are strings passed to the SQL date function. In the second they are Python datetime objects. I suspect you need to convert the datetime objects to strings before passing them as arguments to execute() Alan G From Lbrannma at yahoo.com Sun Sep 10 06:51:59 2006 From: Lbrannma at yahoo.com (LL) Date: Sun, 10 Sep 2006 06:51:59 +0200 Subject: [Tutor] error in writelines Message-ID: <01ab01c6d494$da56ae80$6500a8c0@mynewbox> Hi All, I have a list containing 108 filenames. I want to open each file and write it to an output file, appending it to the previous write. I use the code below. Everything appears to work fine until I reach file 107. Only part of the file is written, and file 108 is not written at all. The program runs to completion (I get exit code 0). I debugged the problem and found that readlines() is reading all of file 107's contents but that writelines() is not writing all of file 107's contents. There are no strange characters where the write stops. Any advice would be greatly appreciated. Thanks, Lance ----------------------------------------------------------------- fileobjectw = open(COMPILETRACEDIR + '\\IncludeCode.prg', 'w') for line in listext: line = string.strip(line) fileobjectr = open(line, 'r') sa = fileobjectr.readlines() fileobjectr.close() fileobjectw.writelines(sa) fileobjectw.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060910/9f0faca2/attachment.html From Lbrannma at yahoo.com Sun Sep 10 07:12:13 2006 From: Lbrannma at yahoo.com (LL) Date: Sun, 10 Sep 2006 07:12:13 +0200 Subject: [Tutor] please do not post question about writelines Message-ID: <01b401c6d497$ae037450$6500a8c0@mynewbox> Hi... I sent a question about an apparent error with writelines. I discovered my error (not closing the file correctly). Please don't post my question. Thanks, Lance -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060910/e30f8865/attachment.htm From alan.gauld at btinternet.com Sun Sep 10 09:50:03 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 10 Sep 2006 08:50:03 +0100 Subject: [Tutor] Looking for a few commands References: Message-ID: "Chris Hengge" wrote > Simple command to clear console? (C++ was something like > system.clr()) > Some sort of cursor positioning? (C++ was something like gotoxy) While looking for something else I stumbled across this module in the Vaults of Parnassus: WConio http://newcenturycomputers.net/projects/wconio.html Its a port of the old Borland turboC conio library to Python and there is a version for Python versions up to 2.4. Only works for DOS windows so far as I can tell, but thats what we wanted... It includes amongst many others the functions: WConio.clrscr() clears the screen and homes the cursor. WConio.cputs(string) prints a string starting at the current cursor position. WConio.getch() retrieves a keystroke from the console WConio.gettext(left, top, right, bottom) copies characters and attributes from the screen coordinates given and returns them in a string buffer. Usually used with puttext() below. WConio.gotoxy(x, y) positions the cursor at the given coordinates. etc... HTH -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rabidpoobear at gmail.com Sun Sep 10 00:08:58 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 09 Sep 2006 17:08:58 -0500 Subject: [Tutor] error in writelines In-Reply-To: <01ab01c6d494$da56ae80$6500a8c0@mynewbox> References: <01ab01c6d494$da56ae80$6500a8c0@mynewbox> Message-ID: <45033B7A.1030401@gmail.com> LL wrote: > Hi All, > > I have a list containing 108 filenames. I want to open each file and > write it to an output file, appending it to the previous write. I use > the code below. Everything appears to work fine until I reach file > 107. Only part of the file is written, and file 108 is not written at > all. The program runs to completion (I get exit code 0). I debugged > the problem and found that readlines() is reading all of file 107's > contents but that writelines() is not writing all of file 107's > contents. There are no strange characters where the write stops. > > Any advice would be greatly appreciated. > Thanks, > Lance > ----------------------------------------------------------------- > fileobjectw = open(COMPILETRACEDIR + '\\IncludeCode.prg', 'w') > for line in listext: > line = string.strip(line) > fileobjectr = open(line, 'r') > sa = fileobjectr.readlines() > fileobjectr.close() > fileobjectw.writelines(sa) > fileobjectw.close() Sounds like maybe you should just do a binary read -> write. like, outputfile = file(os.path.join(COMPILETRACEDIR,'IncludeCode.prg'),'wb') tmp = file('filenames.txt','r') filenames = [a.strip() for a in tmp.readlines()] tmp.close() for filename in filenames: inputfile = file(filename,'rb') outputfile.write(inputfile.read()) inputfile.close() outputfile.close() I think that should work. I don't have the files you're running this all on, though. It might help if you gave us the text of a successful file and of 107. HTH, -Luke From rabidpoobear at gmail.com Sun Sep 10 00:11:28 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 09 Sep 2006 17:11:28 -0500 Subject: [Tutor] please do not post question about writelines In-Reply-To: <01b401c6d497$ae037450$6500a8c0@mynewbox> References: <01b401c6d497$ae037450$6500a8c0@mynewbox> Message-ID: <45033C10.5020603@gmail.com> LL wrote: > Hi... I sent a question about an apparent error with writelines. I > discovered my error (not closing the file correctly). Please don't > post my question. > Oops, I didn't read this e-mail before I sent my reply to your other e-mail. :). hope that it helps you anyway. Also, whenever you e-mail tutor at python.org it automatically sends to us all, there's not some middleman who reads over the e-mails. It seemed to me like you thought this was happening from your 'please don't post my question' comment. HTH, -Luke > Thanks, > Lance > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From john.corry at ntlworld.com Sun Sep 10 13:02:16 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sun, 10 Sep 2006 12:02:16 +0100 Subject: [Tutor] Dates Message-ID: <000001c6d4c8$989f4400$513ea8c0@JOHNC> Alan, Thanks for the help. I have converted the dates to strings but I get the same error. Please see the updated code below, is this what you meant by converting the dates to strings? import mx.ODBC import mx.ODBC.Windows import mx.DateTime import datetime a = datetime.date(2006,01,31) b = datetime.date(2006,12,31) c = str(a) d = str(b) print a,b,c,d db = mx.ODBC.Windows.DriverConnect('DSN=tnt') c = db.cursor() c.execute('SELECT * FROM times where rt_weekst >= ? and rt_weekst <= ? and rt_type == ?', (c,d,"R",)) for row in c.fetchall(): print row row = str(row) c.close() The output is below: 2006-01-31 2006-12-31 2006-01-31 2006-12-31 Traceback (most recent call last): File "C:\test\timemanager.py", line 18, in ? c.execute('SELECT * FROM times where rt_weekst >= ? and rt_weekst <= ? and rt_type == ?', (c,d,"R",)) DataError: ('22005', 301, '[Microsoft][ODBC Visual FoxPro Driver]Operator/operand type mismatch.', 4579) Is there another way I can approach this problem? Say if I use something like: c.execute('SELECT * FROM times where rt_weekst >= date(?) and rt_weekst <= date(?) and rt_type == ?', (c,d,"R",)) I get the following error: 2006-01-31 2006-12-31 2006-01-31 2006-12-31 Traceback (most recent call last): File "C:\test\timemanager.py", line 18, in ? c.execute('SELECT * FROM times where rt_weekst >= date(?) and rt_weekst <= date(?) and rt_type == ?', (c,d,"R",)) ProgrammingError: ('37000', 229, '[Microsoft][ODBC Visual FoxPro Driver]Too few arguments.', 4579) Thanks for any suggestions. John. From yegrix at free.fr Sun Sep 10 18:01:08 2006 From: yegrix at free.fr (yves) Date: Sun, 10 Sep 2006 18:01:08 +0200 Subject: [Tutor] tempfile and webbrowser In-Reply-To: <4501CDD3.5090104@tds.net> References: <44FB0F8B.4000504@free.fr> <44FB2E9E.7060600@tds.net> <44FB40ED.4050908@free.fr> <45007E2C.1080706@free.fr> <002001c6d321$d8c309c0$0201a8c0@XPpro> <450141B8.5090105@tds.net> <001001c6d37e$2c03e2b0$0201a8c0@XPpro> <4501CDD3.5090104@tds.net> Message-ID: <450436C4.6010803@free.fr> Kent Johnson a ?crit : Hello, > Try it like this, using os.fdopen() to convert the low-level file handle > from mkstemp() to a Python file object: > > In [21]: fd, fname = tempfile.mkstemp() > > In [22]: f = os.fdopen(fd, 'w') > > In [23]: f.write('foo') > > In [24]: f.close() > > In [25]: os.unlink(fname) > > Seems to work... Yes, indeed, it works. Not so easy for me to understand, though. I think I get it, more or less, with the help of the Python tempfile module documentation and the help of the Wikipedia article on file descriptors: http://en.wikipedia.org/wiki/File_descriptor Thank you. -- Yves Egrix From alan.gauld at btinternet.com Sun Sep 10 18:55:07 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 10 Sep 2006 17:55:07 +0100 Subject: [Tutor] Dates References: <000001c6d4c8$989f4400$513ea8c0@JOHNC> Message-ID: > a = datetime.date(2006,01,31) > b = datetime.date(2006,12,31) > c = str(a) > d = str(b) I'm not sure what format your data base expects for dates but given you used the SQL date function before I'd go for that again. Just pass the string equivalent of your dates into the SQL date function. You probavly don;t need the datetime stuff above at all. > Is there another way I can approach this problem? Say if I use > something like: > > c.execute('SELECT * FROM times where rt_weekst >= date(?) and > rt_weekst > <= date(?) and rt_type == ?', (c,d,"R",)) Yes this is what I mean but to male it work c and d need to be in the same format you had before, something like c = "2006,01,31" That will then be inserted into the query string. I'm not sure if it will work like that, you may need to split it into 3 separate parameters. > Driver]Too few arguments.', 4579) I think thats because it sees the x-y-z format as an arithmetic sum or as a single non standard string. ButIi'm guessing a bit here as I've never used the ODBC driver nor Foxbase. HTH, Alan G. From kent37 at tds.net Sun Sep 10 18:58:38 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Sep 2006 12:58:38 -0400 Subject: [Tutor] tempfile and webbrowser In-Reply-To: <450436C4.6010803@free.fr> References: <44FB0F8B.4000504@free.fr> <44FB2E9E.7060600@tds.net> <44FB40ED.4050908@free.fr> <45007E2C.1080706@free.fr> <002001c6d321$d8c309c0$0201a8c0@XPpro> <450141B8.5090105@tds.net> <001001c6d37e$2c03e2b0$0201a8c0@XPpro> <4501CDD3.5090104@tds.net> <450436C4.6010803@free.fr> Message-ID: <4504443E.9030002@tds.net> yves wrote: > Kent Johnson a ?crit : > > Hello, > >> Try it like this, using os.fdopen() to convert the low-level file handle >> from mkstemp() to a Python file object: >> >> In [21]: fd, fname = tempfile.mkstemp() >> >> In [22]: f = os.fdopen(fd, 'w') >> >> In [23]: f.write('foo') >> >> In [24]: f.close() >> >> In [25]: os.unlink(fname) >> >> Seems to work... > > Yes, indeed, it works. > Not so easy for me to understand, though. I think I get it, more or > less, with the help of the Python tempfile module documentation and the > help of the Wikipedia article on file descriptors: > http://en.wikipedia.org/wiki/File_descriptor OK...the problem was that mkstemp() was opening the file and returning a low-level object that references the open file. You were opening the file a second time, so it would have to be closed twice before it could be deleted. The object returned by mkstemp is actually just an integer called a file handle. This is the way C refers to open files. The call to os.fdopen() wraps the low-level file handle with a Python file object which you can then use just as if you opened it yourself. Kent From bgailer at alum.rpi.edu Sun Sep 10 19:17:28 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 10 Sep 2006 10:17:28 -0700 Subject: [Tutor] Dates In-Reply-To: <000001c6d45d$554f8680$513ea8c0@JOHNC> References: <000001c6d45d$554f8680$513ea8c0@JOHNC> Message-ID: <450448A8.8010003@alum.rpi.edu> John CORRY wrote: > Hi All, > > I am using the code below to select items from a visual foxpro database > where the dates are between the 31/01/2006 and 31/12/2006. The good > news is that the code below works. > > However, I want to make the from and to dates variable. I want to > change the range depending on user input. I can't get this to work. I > have tried the code below marked "Tried" but I get the error: > > Traceback (most recent call last): > File "C:\test\timemanager.py", line 16, in ? > c.execute('SELECT * FROM times where rt_weekst >= ? and rt_weekst <= > ? and rt_type == ?', (a,b,"R",)) > DataError: ('22005', 301, '[Microsoft][ODBC Visual FoxPro > Driver]Operator/operand type mismatch.', 4579) > > Code that works is below: > > > import mx.ODBC > import mx.ODBC.Windows > import mx.DateTime > > > > db = mx.ODBC.Windows.DriverConnect('DSN=tnt') > c = db.cursor() > c.execute('SELECT * FROM times where rt_weekst >= date(2006,01,31) and > rt_weekst <= date(2006,12,31) and rt_type == ?', ("R",)) > for row in c.fetchall(): > print row > row = str(row) > > c.close() > > > Tried but get errors: > > import mx.ODBC > import mx.ODBC.Windows > import mx.DateTime > > import datetime > a = datetime.date(2006,01,31) > b = datetime.date(2006,12,31) > db = mx.ODBC.Windows.DriverConnect('DSN=tnt') > c = db.cursor() > c.execute('SELECT * FROM times where rt_weekst >= ? and rt_weekst <= ? > and rt_type == ?', (a,b,"R",)) > for row in c.fetchall(): > print row > row = str(row) > > c.close() > > Is there a way to format the date so that the Select statement works? > a = "date(%i,%i,%i)" % (2006,01,31) b = "date(%i,%i,%i)" % (2006,12,31) sql = 'SELECT * FROM times where rt_weekst >= %s and rt_weekst <= %s and rt_type = ' % (a,b,"R") c.execute(sql) OR you could shorten it a bit: sql = 'SELECT * FROM times where rt_weekst between %s and %s and rt_type = "%s"' % (a,b,"R") I like to assign sql first, then execute it, as I can inspect sql if there is a problem. FoxPro also recognizes date constants like {12/31/2006} (note braces not parentheses). -- Bob Gailer 510-978-4454 From john.corry at ntlworld.com Sun Sep 10 23:08:07 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sun, 10 Sep 2006 22:08:07 +0100 Subject: [Tutor] Dates Message-ID: <000001c6d51d$3c223340$513ea8c0@JOHNC> Bob and Alan, Thanks for the help. I have gone with the following code and it works! a = "date(%i,%i,%i)" % (2006,01,31) b = "date(%i,%i,%i)" % (2006,12,31) sql = 'SELECT * FROM times where rt_weekst >= %s and rt_weekst <= %s and rt_type = "%s" ' % (a,b,"R",) db = mx.ODBC.Windows.DriverConnect('DSN=tnt') c = db.cursor() c.execute(sql) As you rightly pointed out, I needed to get my sql string formatted and working before putting it anywhere near the c.execute command. Many thanks, John. From pyro9219 at gmail.com Mon Sep 11 08:04:00 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sun, 10 Sep 2006 23:04:00 -0700 Subject: [Tutor] Looking for a few commands In-Reply-To: References: Message-ID: <1157954640.5005.21.camel@localhost> Nice Find! On Sun, 2006-09-10 at 08:50 +0100, Alan Gauld wrote: > "Chris Hengge" wrote > > Simple command to clear console? (C++ was something like > > system.clr()) > > Some sort of cursor positioning? (C++ was something like gotoxy) > > While looking for something else I stumbled across this module in > the Vaults of Parnassus: WConio > > http://newcenturycomputers.net/projects/wconio.html > > Its a port of the old Borland turboC conio library to Python and there > is a > version for Python versions up to 2.4. Only works for DOS windows > so far as I can tell, but thats what we wanted... > > It includes amongst many others the functions: > > WConio.clrscr() clears the screen and homes the cursor. > WConio.cputs(string) prints a string starting at the current cursor > position. > > WConio.getch() retrieves a keystroke from the console > > WConio.gettext(left, top, right, bottom) copies characters and > attributes from the screen coordinates given and returns them in a > string buffer. Usually used with puttext() below. > > WConio.gotoxy(x, y) positions the cursor at the given coordinates. > > etc... > > HTH From willshattuck at gmail.com Mon Sep 11 09:54:34 2006 From: willshattuck at gmail.com (Will Shattuck) Date: Mon, 11 Sep 2006 00:54:34 -0700 Subject: [Tutor] Getting Started with Python Message-ID: Hi all, I started going through the [Tutor] archives looking for resources on where to start. I have wanted to program for many years, but only just recently have made the time. I thought through different languages to start with: C, C# (My work uses .NET), Java, Python, Ruby, and others. I think I will still learn Java, but I have settled on putting most of my effort into Python first. So, where do I start? I have very little money for books, but I expect there are good resources on the web. My eventual goal is to write either a sci-fi rogue-like game or a rogue-like game engine that allows "anyone" to create their own. I have glanced at PyGame, and like what it can do, but I don't even really know many basics of programming. Anyway, Thanks for taking the time to read this. Oh, some background... I graduated College with a music degree and a music teaching credential. That led into, believe it or not, a night job doing internet tech support, then a full time customer service manager at the same company, then help desk support at a non-profit, then help desk at a for profit.... Anyway, I'm a teacher by schooling, a computer tech by learning, and a programmer by yearning. :) Ok enough... Thanks for your time. Will -- Will Shattuck ( willshattuck.at.gmail.com ) Home Page: http://www.thewholeclan.com/will When you get to your wit's end, you'll find God lives there. From tomdrak at gmail.com Mon Sep 11 11:10:49 2006 From: tomdrak at gmail.com (tomd) Date: Mon, 11 Sep 2006 11:10:49 +0200 Subject: [Tutor] Getting Started with Python In-Reply-To: Message-ID: <2006911111049.268647@oem-up3sjowr2u8> Hi Will, do a search in the archives, plenty of similar discussions, even just few days ago. Try http://wiki.python.org/moin/BeginnersGuide/NonProgrammers (Admins: consider sending a welcome message on the subscription to each newcomer specifying usually recommended sources.) > just recently have made the time. I thought through different > languages to start with: C, C# (My work uses .NET), Java, Python, Once you learn the basics, look for Python for .NET, IronPython, http://www.codeplex.com/Release/ProjectReleases.aspx?ProjectName=IronPython&ReleaseId=423. I'm not sure how it measures up to C# nor whether it would be usable in your work, but seems you could kill two flies in one hit that way. -- Tom, http://www.vscripts.net/ From robvog at gmail.com Mon Sep 11 11:24:26 2006 From: robvog at gmail.com (Rob Vogel) Date: Mon, 11 Sep 2006 11:24:26 +0200 Subject: [Tutor] howto keep a program organised? Message-ID: Hello All, I have been programming with Python for a few weeks now. By now I have problems keeping my program organised. (program runs from a Linux Busybox environment). For example, I may need to mount the usb storage device at some point in the program. For this end I made the following functions: - usbMount() -> main function. - usbUmount() -> main function. - usbMounted() -> help function. Checks if usb already mounted. - usbConnected() -> help function. Checks id usb connected to computer. - usbValid() -> help function. Checks if usb contains certain info (only these may be mounted). The help functions are called from the main functions. So I have multiple help functions, while only two are actively called. What is a good way to keep this organised? - Just put it in a usb.py module? - Should I make a class? I haven't worked with OOP before, because I didn't think it would be useful so far. Are there any advantages if I put this in a class, instead of in a module? This is only a small example, but I run into the same problem with other parts of my program, that are larger, and where the functions also depend on each other, while only a few are called (and the rest just clutter my view in the IDE). Any advice about how you organise this kind of things, is very much appreciated. Thanks, Rob From kent37 at tds.net Mon Sep 11 12:05:30 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Sep 2006 06:05:30 -0400 Subject: [Tutor] Getting Started with Python In-Reply-To: <2006911111049.268647@oem-up3sjowr2u8> References: <2006911111049.268647@oem-up3sjowr2u8> Message-ID: <450534EA.60804@tds.net> tomd wrote: > Hi Will, > > do a search in the archives, plenty of similar discussions, even just > few days ago. Try http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > (Admins: consider sending a welcome message on the subscription to > each newcomer specifying usually recommended sources.) Good idea! I just added this text to the welcome message: There are many on-line resources that can help you get started with Python. See the Beginners Guide for a list of some good ones. Kent From alan.gauld at freenet.co.uk Mon Sep 11 12:35:04 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 11 Sep 2006 11:35:04 +0100 Subject: [Tutor] howto keep a program organised? References: Message-ID: <000b01c6d58d$f1e41700$0201a8c0@XPpro> Hi Rob, > For example, I may need to mount the usb storage device at some > point > in the program. > For this end I made the following functions: > - usbMount() -> main function. > - usbUmount() -> main function. > - usbMounted() -> help function. Checks if usb already mounted. > - usbConnected() -> help function. Checks id usb connected to > computer. > - usbValid() -> help function. Checks if usb contains certain info > (only these may be mounted). > The help functions are called from the main functions. > So I have multiple help functions, while only two are actively > called. > > What is a good way to keep this organised? > - Just put it in a usb.py module? Thats a very good place to start. > - Should I make a class? I think, without seeing the internals of the code, that this is likely to be a good idea in this case. If you have a number of shared global variables between functions then I'd certainly say yes. > Are there any advantages if I put this in a class, instead of in a > module? The advantage of a class is that if you ever need more than one USB device mounted then the instances of the class can each hold their own state information, whereas with global variables you would be limited to one mounted instance - unless you stuck very rigorously to functional programming principles... > This is only a small example, but I run into the same problem with > other parts of my program, that are larger, and where the functions > also depend on each other, while only a few are called (and the rest > just clutter my view in the IDE). Where things depend on each other a module is the minimum organising device. Where functions share data a class is usually a good idea on top of that. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bugracakir at gmail.com Mon Sep 11 12:46:56 2006 From: bugracakir at gmail.com (Bugra Cakir) Date: Mon, 11 Sep 2006 13:46:56 +0300 Subject: [Tutor] Tutor Digest, Vol 31, Issue 26 In-Reply-To: References: Message-ID: <5a00f6240609110346j2290f635na7611ff1608a72d4@mail.gmail.com> Hi, My thought is seperate main and utility functions to different files. For example there will be a Main.py and UsbUtil.py and from Main.py you can import usb functions. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060911/873f4450/attachment.html From robvog at gmail.com Mon Sep 11 13:19:21 2006 From: robvog at gmail.com (Rob Vogel) Date: Mon, 11 Sep 2006 13:19:21 +0200 Subject: [Tutor] howto keep a program organised? In-Reply-To: <000b01c6d58d$f1e41700$0201a8c0@XPpro> References: <000b01c6d58d$f1e41700$0201a8c0@XPpro> Message-ID: Thanks Alan, The functions do not share variables, I don't use global vars, and I don't need a new instance. So in my case the only use of a class would be that all related usb code will be grouped together, even though I do not need any of the Class special abilities, as far as I understand. I think I will make a usb class to keep it better organised. I have attached the module that contains the usb and related code, to give a better view of what I'm talking, and I would appreciate any feedback on it. Thanks, Rob On 9/11/06, Alan Gauld wrote: > Hi Rob, > > > For example, I may need to mount the usb storage device at some > > point > > in the program. > > For this end I made the following functions: > > - usbMount() -> main function. > > - usbUmount() -> main function. > > - usbMounted() -> help function. Checks if usb already mounted. > > - usbConnected() -> help function. Checks id usb connected to > > computer. > > - usbValid() -> help function. Checks if usb contains certain info > > (only these may be mounted). > > The help functions are called from the main functions. > > So I have multiple help functions, while only two are actively > > called. > > > > What is a good way to keep this organised? > > - Just put it in a usb.py module? > > Thats a very good place to start. > > > - Should I make a class? > > I think, without seeing the internals of the code, that this is > likely to be a good idea in this case. If you have a number of > shared global variables between functions then I'd certainly > say yes. > > > Are there any advantages if I put this in a class, instead of in a > > module? > > The advantage of a class is that if you ever need more than > one USB device mounted then the instances of the class can > each hold their own state information, whereas with global > variables you would be limited to one mounted instance > - unless you stuck very rigorously to functional programming > principles... > > > This is only a small example, but I run into the same problem with > > other parts of my program, that are larger, and where the functions > > also depend on each other, while only a few are called (and the rest > > just clutter my view in the IDE). > > Where things depend on each other a module is the minimum > organising device. Where functions share data a class is usually > a good idea on top of that. > > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > From kent37 at tds.net Mon Sep 11 13:34:10 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Sep 2006 07:34:10 -0400 Subject: [Tutor] howto keep a program organised? In-Reply-To: References: <000b01c6d58d$f1e41700$0201a8c0@XPpro> Message-ID: <450549B2.80701@tds.net> Rob Vogel wrote: > Thanks Alan, > > The functions do not share variables, I don't use global vars, and I > don't need a new instance. > So in my case the only use of a class would be that all related usb > code will be grouped together, even though I do not need any of the > Class special abilities, as far as I understand. All good reasons *not* to make a class. A module is a fine way to group related code together. > > I think I will make a usb class to keep it better organised. Grouping the usb code in a module accomplishes all the organization you need, from what you have said. It sounds like putting it in a class just adds needless complexity. > > I have attached the module that contains the usb and related code, to > give a better view of what I'm talking, and I would appreciate any > feedback on it. The attachment didn't make it to the list... Kent From alan.gauld at btinternet.com Mon Sep 11 15:04:52 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Sep 2006 14:04:52 +0100 Subject: [Tutor] howto keep a program organised? References: <000b01c6d58d$f1e41700$0201a8c0@XPpro> <450549B2.80701@tds.net> Message-ID: > The functions do not share variables, I don't use global vars, and I > don't need a new instance. In that case you don't need a class. A module should do all you need by providing a common namespace for your functions. > So in my case the only use of a class would be that all related usb > code will be grouped together, even though I do not need any of the > Class special abilities, as far as I understand. A module groups code together nicely, if the code doesn't share data and you don't create multiple instances there is no need for a class. Alan G. From robvog at gmail.com Mon Sep 11 15:27:56 2006 From: robvog at gmail.com (Rob Vogel) Date: Mon, 11 Sep 2006 15:27:56 +0200 Subject: [Tutor] howto keep a program organised? In-Reply-To: References: <000b01c6d58d$f1e41700$0201a8c0@XPpro> <450549B2.80701@tds.net> Message-ID: Thanks for the info. I will use a module. Regards, Rob On 9/11/06, Alan Gauld wrote: > > The functions do not share variables, I don't use global vars, and I > > don't need a new instance. > > In that case you don't need a class. > A module should do all you need by providing a common namespace > for your functions. > > > So in my case the only use of a class would be that all related usb > > code will be grouped together, even though I do not need any of the > > Class special abilities, as far as I understand. > > A module groups code together nicely, if the code doesn't share data > and you don't create multiple instances there is no need for a class. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From tiagosaboga at terra.com.br Mon Sep 11 15:55:00 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Mon, 11 Sep 2006 10:55:00 -0300 Subject: [Tutor] man pages parsing (still) Message-ID: <200609111055.00530.tiagosaboga@terra.com.br> I'm still there, trying to parse man pages (I want to gather a list of all options with their help strings). I've tried to use regex on both the formatted output of man and the source troff files and I discovered what is already said in the doclifter man page: you have to do a number of hints, and it's really not simple. So I'm know using doclifter, and it's working, but is terribly slow. Doclifter itself take around a second to parse the troff file, but my few lines of code take 25 seconds to parse the resultant xml. I've pasted the code at http://pastebin.ca/166941 and I'd like to hear from you how I could possibly optimize it. Thanks, Tiago. From kent37 at tds.net Mon Sep 11 16:15:20 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Sep 2006 10:15:20 -0400 Subject: [Tutor] man pages parsing (still) In-Reply-To: <200609111055.00530.tiagosaboga@terra.com.br> References: <200609111055.00530.tiagosaboga@terra.com.br> Message-ID: <45056F78.8040701@tds.net> Tiago Saboga wrote: > I'm still there, trying to parse man pages (I want to gather a list of all > options with their help strings). I've tried to use regex on both the > formatted output of man and the source troff files and I discovered what is > already said in the doclifter man page: you have to do a number of hints, and > it's really not simple. So I'm know using doclifter, and it's working, but is > terribly slow. Doclifter itself take around a second to parse the troff file, > but my few lines of code take 25 seconds to parse the resultant xml. I've > pasted the code at http://pastebin.ca/166941 > and I'd like to hear from you how I could possibly optimize it. How big is the XML? 25 seconds is a long time...I would look at cElementTree (implementation of ElementTree in C), it is pretty fast. http://effbot.org/zone/celementtree.htm In particular iterparse() might be helpful: http://effbot.org/zone/element-iterparse.htm I would also try specifying a buffer size in the call to os.popen2(), if the I/O is unbuffered or the buffer is small that might be the bottleneck. Kent From tiagosaboga at terra.com.br Mon Sep 11 17:05:01 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Mon, 11 Sep 2006 12:05:01 -0300 Subject: [Tutor] man pages parsing (still) In-Reply-To: <45056F78.8040701@tds.net> References: <200609111055.00530.tiagosaboga@terra.com.br> <45056F78.8040701@tds.net> Message-ID: <200609111205.02057.tiagosaboga@terra.com.br> Em Segunda 11 Setembro 2006 11:15, Kent Johnson escreveu: > Tiago Saboga wrote: > > I'm still there, trying to parse man pages (I want to gather a list of > > all options with their help strings). I've tried to use regex on both the > > formatted output of man and the source troff files and I discovered what > > is already said in the doclifter man page: you have to do a number of > > hints, and it's really not simple. So I'm know using doclifter, and it's > > working, but is terribly slow. Doclifter itself take around a second to > > parse the troff file, but my few lines of code take 25 seconds to parse > > the resultant xml. I've pasted the code at http://pastebin.ca/166941 > > and I'd like to hear from you how I could possibly optimize it. > > How big is the XML? 25 seconds is a long time...I would look at > cElementTree (implementation of ElementTree in C), it is pretty fast. > http://effbot.org/zone/celementtree.htm It's about 10k. Hey, it seems easy, but I'd like not to start over again. Of course, if it's the only solution... 25 (28, in fact, for the cp man page) isn't really acceptable. > In particular iterparse() might be helpful: > http://effbot.org/zone/element-iterparse.htm Ok, I'll look that. > I would also try specifying a buffer size in the call to os.popen2(), if > the I/O is unbuffered or the buffer is small that might be the bottleneck. What's appropriate in that case? I really don't understand how I should determine a buffer size. Any pointers? Thanks, Tiago. From kent37 at tds.net Mon Sep 11 17:24:04 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Sep 2006 11:24:04 -0400 Subject: [Tutor] man pages parsing (still) In-Reply-To: <200609111205.02057.tiagosaboga@terra.com.br> References: <200609111055.00530.tiagosaboga@terra.com.br> <45056F78.8040701@tds.net> <200609111205.02057.tiagosaboga@terra.com.br> Message-ID: <45057F94.8020102@tds.net> Tiago Saboga wrote: > Em Segunda 11 Setembro 2006 11:15, Kent Johnson escreveu: >> Tiago Saboga wrote: >> How big is the XML? 25 seconds is a long time...I would look at >> cElementTree (implementation of ElementTree in C), it is pretty fast. >> http://effbot.org/zone/celementtree.htm > > It's about 10k. Hey, it seems easy, but I'd like not to start over again. Of > course, if it's the only solution... 25 (28, in fact, for the cp man page) > isn't really acceptable. That's tiny! No way it should take 25 seconds to parse a 10k file. Have you tried saving the file separately and parsing from disk? That would help determine if the interprocess pipe is the problem. > >> I would also try specifying a buffer size in the call to os.popen2(), if >> the I/O is unbuffered or the buffer is small that might be the bottleneck. > > What's appropriate in that case? I really don't understand how I should > determine a buffer size. Any pointers? To tell the truth I don't use popen myself so if anyone else wants to chime in that would be fine...but I would try maybe 1024 or 10240 (10k). Kent From tiagosaboga at terra.com.br Mon Sep 11 17:44:49 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Mon, 11 Sep 2006 12:44:49 -0300 Subject: [Tutor] man pages parsing (still) In-Reply-To: <45057F94.8020102@tds.net> References: <200609111055.00530.tiagosaboga@terra.com.br> <200609111205.02057.tiagosaboga@terra.com.br> <45057F94.8020102@tds.net> Message-ID: <200609111244.51473.tiagosaboga@terra.com.br> Em Segunda 11 Setembro 2006 12:24, Kent Johnson escreveu: > Tiago Saboga wrote: > > Em Segunda 11 Setembro 2006 11:15, Kent Johnson escreveu: > >> Tiago Saboga wrote: > >> How big is the XML? 25 seconds is a long time...I would look at > >> cElementTree (implementation of ElementTree in C), it is pretty fast. > >> http://effbot.org/zone/celementtree.htm > > > > It's about 10k. Hey, it seems easy, but I'd like not to start over again. > > Of course, if it's the only solution... 25 (28, in fact, for the cp man > > page) isn't really acceptable. > > That's tiny! No way it should take 25 seconds to parse a 10k file. > > Have you tried saving the file separately and parsing from disk? That > would help determine if the interprocess pipe is the problem. Just tried, and - incredible - it took even longer: 46s. But in the second run it came back to 25s. I really don't understand what's going on. I did some other tests, and I found that all the code before "parser.parse(stout)" runs almost instantly; it then takes all the running somewhere between this call and the first event; and the rest is almost instantly again. Any ideas? By the way, I've read the pages you indicated at effbot, but I don't see where to begin. Do you know of a gentler introduction to this module (cElementTree)? Thanks, Tiago. From kent37 at tds.net Mon Sep 11 17:59:03 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Sep 2006 11:59:03 -0400 Subject: [Tutor] man pages parsing (still) In-Reply-To: <200609111244.51473.tiagosaboga@terra.com.br> References: <200609111055.00530.tiagosaboga@terra.com.br> <200609111205.02057.tiagosaboga@terra.com.br> <45057F94.8020102@tds.net> <200609111244.51473.tiagosaboga@terra.com.br> Message-ID: <450587C7.9090306@tds.net> Tiago Saboga wrote: > Em Segunda 11 Setembro 2006 12:24, Kent Johnson escreveu: >> Tiago Saboga wrote: >>> Em Segunda 11 Setembro 2006 11:15, Kent Johnson escreveu: >>>> Tiago Saboga wrote: >>>> How big is the XML? 25 seconds is a long time...I would look at >>>> cElementTree (implementation of ElementTree in C), it is pretty fast. >>>> http://effbot.org/zone/celementtree.htm >>> It's about 10k. Hey, it seems easy, but I'd like not to start over again. >>> Of course, if it's the only solution... 25 (28, in fact, for the cp man >>> page) isn't really acceptable. >> That's tiny! No way it should take 25 seconds to parse a 10k file. >> >> Have you tried saving the file separately and parsing from disk? That >> would help determine if the interprocess pipe is the problem. > > Just tried, and - incredible - it took even longer: 46s. But in the second run > it came back to 25s. I really don't understand what's going on. I did some > other tests, and I found that all the code before "parser.parse(stout)" runs > almost instantly; it then takes all the running somewhere between this call > and the first event; and the rest is almost instantly again. Any ideas? What did you try, buffering or reading from a file? If parsing from a file takes 25 secs, I am amazed... > > By the way, I've read the pages you indicated at effbot, but I don't see where > to begin. Do you know of a gentler introduction to this module > (cElementTree)? The main ElementTree page is here, but try parsing from a file first, your file is so small... http://effbot.org/zone/element.htm Kent From hmm at woolgathering.cx Mon Sep 11 18:11:37 2006 From: hmm at woolgathering.cx (William O'Higgins Witteman) Date: Mon, 11 Sep 2006 12:11:37 -0400 Subject: [Tutor] Injecting Data into XML Files Message-ID: <20060911161137.GA23503@sillyrabbi.dyndns.org> I am wrestling with the incredibly vast array of XML parsing and writing documentation, and I'm not seeing (or perhaps not understanding) what I'm looking for. Here's the situation: I have a large number of XML documents to add data to. They are currently skeletal documents, looking like this: ... What I want is to open each document and inject some data between specific sets of tags. I've been able to parse these documents, but I am not seeing how to inject data between tags so I can write it back to the file. Any pointers are appreciated. Thanks. -- yours, William From dkuhlman at rexx.com Mon Sep 11 18:57:28 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Mon, 11 Sep 2006 09:57:28 -0700 Subject: [Tutor] Injecting Data into XML Files In-Reply-To: <20060911161137.GA23503@sillyrabbi.dyndns.org> References: <20060911161137.GA23503@sillyrabbi.dyndns.org> Message-ID: <20060911165728.GA85646@cutter.rexx.com> On Mon, Sep 11, 2006 at 12:11:37PM -0400, William O'Higgins Witteman wrote: > I am wrestling with the incredibly vast array of XML parsing and writing > documentation, and I'm not seeing (or perhaps not understanding) what > I'm looking for. Here's the situation: > > I have a large number of XML documents to add data to. They are > currently skeletal documents, looking like this: > > > > > > > > ... > > What I want is to open each document and inject some data between > specific sets of tags. I've been able to parse these documents, but I am > not seeing how to inject data between tags so I can write it back to the > file. Any pointers are appreciated. Thanks. *How* did you parse your XML document? If you parsed it and produced a minidom tree or, better yet, an ElementTree tree, you can modify the DOM tree, and then you can write that tree out to disk. Here is a bit of code to give you the idea with ElementTree (or lxml, which uses the same API as ElementTree): from elementtree import ElementTree as etree doc = etree.parse('content.xml') root = doc.getroot()) # Do something with the DOM tree here. o o o # Now write the tree back to disk. f = open('tmp.xml', 'w') doc.write(f) f.close() Here is info on ElementTree -- Scroll down and look at the example in the section titled "Usage", which seems to do something very similar to what you ask about: http://effbot.org/zone/element-index.htm And, lxml -- same API as ElementTree plus additional capabilities, but requires installation of libxml: http://codespeak.net/lxml/ Also, minidom: http://docs.python.org/lib/module-xml.dom.minidom.html Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From hmm at woolgathering.cx Mon Sep 11 20:18:17 2006 From: hmm at woolgathering.cx (William O'Higgins Witteman) Date: Mon, 11 Sep 2006 14:18:17 -0400 Subject: [Tutor] Injecting Data into XML Files In-Reply-To: <20060911165728.GA85646@cutter.rexx.com> References: <20060911161137.GA23503@sillyrabbi.dyndns.org> <20060911165728.GA85646@cutter.rexx.com> Message-ID: <20060911181817.GA23683@sillyrabbi.dyndns.org> On Mon, Sep 11, 2006 at 09:57:28AM -0700, Dave Kuhlman wrote: >On Mon, Sep 11, 2006 at 12:11:37PM -0400, William O'Higgins Witteman wrote: >> I have a large number of XML documents to add data to. They are >> currently skeletal documents, looking like this: >> >> >> >> >> >> >> >> ... >> >> What I want is to open each document and inject some data between >> specific sets of tags. I've been able to parse these documents, but I am >> not seeing how to inject data between tags so I can write it back to the >> file. Any pointers are appreciated. Thanks. >*How* did you parse your XML document? If you parsed it and >produced a minidom tree or, better yet, an ElementTree tree, >you can modify the DOM tree, and then you can write that tree out >to disk. I have tried the common XML modules - minidom, sax and ElementTree. There are clear, easy-to-follow examples of parsing for each one. >Here is a bit of code to give you the idea with ElementTree (or >lxml, which uses the same API as ElementTree): > > from elementtree import ElementTree as etree > doc = etree.parse('content.xml') > root = doc.getroot() > # Do something with the DOM tree here. > o This is the bit I'm missing - I can't seem to find an existing element and change it's value. When I do so I just get an additional element. Here's the code I'm using: main = etree.SubElement(root,"rdf:Description") title = etree.SubElement(main,"title") title.text = "Example Title" > o > # Now write the tree back to disk. > f = open('tmp.xml', 'w') > doc.write(f) > f.close() > >Here is info on ElementTree -- Scroll down and look at the example >in the section titled "Usage", which seems to do something very >similar to what you ask about: > > http://effbot.org/zone/element-index.htm This is, I suspect, a fine module, but the documentation you mention is not helpful to me. Specifically, in the above-mentioned section, it reads like this: # if you need the root element, use getroot root = tree.getroot() # ...manipulate tree... What I need is an example or a clear description of what they mean when they write "manipulate tree". My problem is not "which tool to use?" but "how does it work?". Thanks for the help thusfar - one last push would be greatly appreciated. Thanks again. -- yours, William From kent37 at tds.net Mon Sep 11 20:38:46 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Sep 2006 14:38:46 -0400 Subject: [Tutor] Injecting Data into XML Files In-Reply-To: <20060911181817.GA23683@sillyrabbi.dyndns.org> References: <20060911161137.GA23503@sillyrabbi.dyndns.org> <20060911165728.GA85646@cutter.rexx.com> <20060911181817.GA23683@sillyrabbi.dyndns.org> Message-ID: <4505AD36.2040109@tds.net> William O'Higgins Witteman wrote: > On Mon, Sep 11, 2006 at 09:57:28AM -0700, Dave Kuhlman wrote: >> On Mon, Sep 11, 2006 at 12:11:37PM -0400, William O'Higgins Witteman wrote: >>> I have a large number of XML documents to add data to. They are >>> currently skeletal documents, looking like this: >>> >>> >>> >>> >>> >>> >>> >>> ... >>> >>> What I want is to open each document and inject some data between >>> specific sets of tags. I've been able to parse these documents, but I am >>> not seeing how to inject data between tags so I can write it back to the >>> file. Any pointers are appreciated. Thanks. > >> Here is a bit of code to give you the idea with ElementTree (or >> lxml, which uses the same API as ElementTree): >> >> from elementtree import ElementTree as etree >> doc = etree.parse('content.xml') >> root = doc.getroot() >> # Do something with the DOM tree here. >> o > > This is the bit I'm missing - I can't seem to find an existing element > and change it's value. When I do so I just get an additional element. > Here's the code I'm using: > > main = etree.SubElement(root,"rdf:Description") > title = etree.SubElement(main,"title") > title.text = "Example Title" That's what SubElement does - it creates a new element. You need to find the existing element. The section on Searching should point you in the right direction: http://effbot.org/zone/element.htm#searching-for-subelements Try something like title = root.find('{http://www.w3.org/1999/02/22-rdf-syntax-ns#}Description/title') Note that ET uses the URI of the namespace, not the short name. You can explore a bit from the interactive interpreter to help get your bearings, for example print root for sub in root: print sub will give you a good idea what the correct name of the Description element. Kent From hmm at woolgathering.cx Mon Sep 11 20:56:46 2006 From: hmm at woolgathering.cx (William O'Higgins Witteman) Date: Mon, 11 Sep 2006 14:56:46 -0400 Subject: [Tutor] Injecting Data into XML Files In-Reply-To: <4505AD36.2040109@tds.net> References: <20060911161137.GA23503@sillyrabbi.dyndns.org> <20060911165728.GA85646@cutter.rexx.com> <20060911181817.GA23683@sillyrabbi.dyndns.org> <4505AD36.2040109@tds.net> Message-ID: <20060911185646.GA23754@sillyrabbi.dyndns.org> On Mon, Sep 11, 2006 at 02:38:46PM -0400, Kent Johnson wrote: >>>On Mon, Sep 11, 2006 at 12:11:37PM -0400, William O'Higgins Witteman >>>wrote: >>>>What I want is to open each document and inject some data between >>>>specific sets of tags. I've been able to parse these documents, but I am >>>>not seeing how to inject data between tags so I can write it back to the >>>>file. Any pointers are appreciated. Thanks. >> >>>Here is a bit of code to give you the idea with ElementTree (or >>>lxml, which uses the same API as ElementTree): >>> >>> from elementtree import ElementTree as etree >>> doc = etree.parse('content.xml') >>> root = doc.getroot() >>> # Do something with the DOM tree here. >>> o >> >>This is the bit I'm missing - I can't seem to find an existing element >>and change it's value. >That's what SubElement does - it creates a new element. You need to find >the existing element. The section on Searching should point you in the >right direction: >http://effbot.org/zone/element.htm#searching-for-subelements > >Try something like >title = >root.find('{http://www.w3.org/1999/02/22-rdf-syntax-ns#}Description/title') > >Note that ET uses the URI of the namespace, not the short name. That's a huge help, thank you. What would I do if there is no namespace for the given documents? I find that a great deal of "XML" content is just well-formed ad-hoc-ery, lacking formal definitions and namespaces, and so there is no URI to put in the find argument. Do I have to find a new module? Thanks again. -- yours, William From kent37 at tds.net Mon Sep 11 21:23:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Sep 2006 15:23:53 -0400 Subject: [Tutor] Injecting Data into XML Files In-Reply-To: <20060911185646.GA23754@sillyrabbi.dyndns.org> References: <20060911161137.GA23503@sillyrabbi.dyndns.org> <20060911165728.GA85646@cutter.rexx.com> <20060911181817.GA23683@sillyrabbi.dyndns.org> <4505AD36.2040109@tds.net> <20060911185646.GA23754@sillyrabbi.dyndns.org> Message-ID: <4505B7C9.9080706@tds.net> William O'Higgins Witteman wrote: > On Mon, Sep 11, 2006 at 02:38:46PM -0400, Kent Johnson wrote: >> Note that ET uses the URI of the namespace, not the short name. > > That's a huge help, thank you. What would I do if there is no namespace > for the given documents? I find that a great deal of "XML" content is > just well-formed ad-hoc-ery, lacking formal definitions and namespaces, > and so there is no URI to put in the find argument. Do I have to find a > new module? Thanks again. I think it will just parse as the tag name in that case; try it and see! If you have truly bad XML - that is not well-formed so it won't parse with a correct parser - then you need BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/documentation.html Kent From tiagosaboga at terra.com.br Mon Sep 11 22:00:18 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Mon, 11 Sep 2006 17:00:18 -0300 Subject: [Tutor] man pages parsing (still) In-Reply-To: <450587C7.9090306@tds.net> References: <200609111055.00530.tiagosaboga@terra.com.br> <200609111244.51473.tiagosaboga@terra.com.br> <450587C7.9090306@tds.net> Message-ID: <200609111700.19432.tiagosaboga@terra.com.br> Em Segunda 11 Setembro 2006 12:59, Kent Johnson escreveu: > Tiago Saboga wrote: > > Em Segunda 11 Setembro 2006 12:24, Kent Johnson escreveu: > >> Tiago Saboga wrote: > >>> Em Segunda 11 Setembro 2006 11:15, Kent Johnson escreveu: > >>>> Tiago Saboga wrote: > >>>> How big is the XML? 25 seconds is a long time...I would look at > >>>> cElementTree (implementation of ElementTree in C), it is pretty fast. > >>>> http://effbot.org/zone/celementtree.htm > >>> > >>> It's about 10k. Hey, it seems easy, but I'd like not to start over > >>> again. Of course, if it's the only solution... 25 (28, in fact, for the > >>> cp man page) isn't really acceptable. > >> > >> That's tiny! No way it should take 25 seconds to parse a 10k file. > >> > >> Have you tried saving the file separately and parsing from disk? That > >> would help determine if the interprocess pipe is the problem. > > > > Just tried, and - incredible - it took even longer: 46s. But in the > > second run it came back to 25s. I really don't understand what's going > > on. I did some other tests, and I found that all the code before > > "parser.parse(stout)" runs almost instantly; it then takes all the > > running somewhere between this call and the first event; and the rest is > > almost instantly again. Any ideas? > > What did you try, buffering or reading from a file? If parsing from a > file takes 25 secs, I am amazed... I read from a file, and before you ask, no, I'm not working in a 286 and compiling my kernel at the same time... ;-) In fact, I decided to strip down both my code and the xml file. I've stripped the code to almost nothing, having yet a 23s time. And the same with the xml file... until I cut out the second line, with the dtd [1]. And surprise: I've a nice time. So I put it all together again, but have the following caveat: there's an error that did not raise previously:] Traceback (most recent call last): File "./liftopy.py", line 130, in ? parser.parse(stout) File "/usr/lib/python2.3/site-packages/_xmlplus/sax/expatreader.py", line 109, in parse xmlreader.IncrementalParser.parse(self, source) File "/usr/lib/python2.3/site-packages/_xmlplus/sax/xmlreader.py", line 123, in parse self.feed(buffer) File "/usr/lib/python2.3/site-packages/_xmlplus/sax/expatreader.py", line 220, in feed self._err_handler.fatalError(exc) File "/usr/lib/python2.3/site-packages/_xmlplus/sax/handler.py", line 38, in fatalError raise exception xml.sax._exceptions.SAXParseException: /home/tiago/Computador/python/opy/manraw/doclift/cp.1.xml.stripped:279:16: undefined entity Ok, the guilty line (279) has a "©" that was probably defined in the dtd, but as it doesn't know what is the right dtd... But wait... How does python read the dtd? It fetches it from the net? I tried it (disconnected) and the answer is yes, it fetches it from the net. So that's the problem! But how do I avoid it? I'll search. But if you can spare me some time, you'll make me a little happier. [1] - The line is as follows: Thanks! Tiago. From klaus.ramelow at GMX.de Mon Sep 11 22:43:52 2006 From: klaus.ramelow at GMX.de (Klaus Ramelow) Date: Mon, 11 Sep 2006 22:43:52 +0200 Subject: [Tutor] Java: (and python ?) nearer measles than coffee In-Reply-To: References: Message-ID: <4505CA88.9020507@GMX.de> Sometimes I have also some - or more - problems trying digesting python and feeling totally blocked. My programming experience (beginning at the card-reader era) main-frame, mini and micro : Bit / Byte / Word system-programming via switch-console followed by Assembler and commercial software using Basic, Cobol, Pascal and SQL. Mnemonic programming-language - in my understanding - can only be consisting of expressions near the human language. The best example for writing non-system-programms are Basic, Cobol (thanks to Alan) and SQL(especially Informix-SQL as full language - not only for DB). Why should I waste time in learning a "language" like Java (or more positive: python) ? Nevertheless this Tutor Digest is most helpful, the number of questions / problems show: some more people are looking for a mnemonic-language which should optimized cross-compile to something with multiplatform-capability like Java. Please let me know, if I am entirely wrong. Klaus Ramelow From kent37 at tds.net Mon Sep 11 23:20:47 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Sep 2006 17:20:47 -0400 Subject: [Tutor] Java: (and python ?) nearer measles than coffee In-Reply-To: <4505CA88.9020507@GMX.de> References: <4505CA88.9020507@GMX.de> Message-ID: <4505D32F.80809@tds.net> Klaus Ramelow wrote: > Sometimes I have also some - or more - problems trying digesting python > and feeling totally blocked. > > My programming experience (beginning at the card-reader era) > main-frame, mini and micro : > Bit / Byte / Word system-programming via switch-console followed by > Assembler and commercial software using Basic, Cobol, Pascal and SQL. > > Mnemonic programming-language - in my understanding - can only be > consisting of expressions near the human language. > The best example for writing non-system-programms are > Basic, Cobol (thanks to Alan) and SQL(especially Informix-SQL as full > language - not only for DB). > Why should I waste time in learning a "language" like Java (or more > positive: python) ? > Nevertheless this Tutor Digest is most helpful, the number of questions > / problems show: > some more people are looking for a mnemonic-language which should > optimized cross-compile to something with multiplatform-capability > like Java. > Please let me know, if I am entirely wrong. I'm not really sure what you are asking. Many people find Python to be useful and enjoyable for a wide variety of personal and professional programming. But if you are happy with Basic and Cobol and they meet your needs then there is no need to "waste your time" learning anything else, I suppose. I am not really interested in trying to convince you to learn python; if you decide you want to learn this list is a great place to get help. Kent From sisson.j at gmail.com Mon Sep 11 17:40:34 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Mon, 11 Sep 2006 10:40:34 -0500 Subject: [Tutor] Java: (and python ?) nearer measles than coffee In-Reply-To: <4505CA88.9020507@GMX.de> References: <4505CA88.9020507@GMX.de> Message-ID: <45058372.90703@gmail.com> Hrmmm...my opinion is that you shouldn't waste your time with Java (sorry to any Java coders on this list). It's entirely too automated for my tastes (automatic garbage collection, transparent pointers, etc...). To quote an unknown author who was quite the anti-OOP programmer, "it made me want to throw a java.f***ThisException". So why, might you ask, am I bothering learning Python? Well, at first I was looking for a powerful scripting language to prototype with. You know the routine...whip up a quick and dirty "version 0.1" and let the customer see what's in store, test layouts, algorithms, design ideas, etc... Reason I use Python #1: But then I noticed something. Python runs on my wife's Windows machine...and my Linux machine...and my OpenBSD machine...and ...etc... The real catch for me was OpenBSD support. Find a thorough java runtime for OpenBSD (I last looked probably a year or two ago, so correct me if I'm wrong on this), and perhaps I'll try it out, but until then, Python is my choice when I need code that will run on multiple OS's. Reason I use Python #2: I'm not trying to flatter anyone, seriously, I'm not...but this list is another reason Python has been a favorite of mine. Reason I use Python #3: I am a strong advocate of Open Source Software and the GPL. If Sun truly supported Open Source, then the OpenBSD team would have the specs for Java. Reason I use Python #4: If I want to code something in Java, give me a week. For Python, give me one night, perhaps two. I prefer getting done so I can move on, ya know? Anyways, those are the first few reasons I use Python. Jonathon Klaus Ramelow wrote: > Sometimes I have also some - or more - problems trying digesting python > and feeling totally blocked. > > My programming experience (beginning at the card-reader era) > main-frame, mini and micro : > Bit / Byte / Word system-programming via switch-console followed by > Assembler and commercial software using Basic, Cobol, Pascal and SQL. > > Mnemonic programming-language - in my understanding - can only be > consisting of expressions near the human language. > The best example for writing non-system-programms are > Basic, Cobol (thanks to Alan) and SQL(especially Informix-SQL as full > language - not only for DB). > Why should I waste time in learning a "language" like Java (or more > positive: python) ? > Nevertheless this Tutor Digest is most helpful, the number of questions > / problems show: > some more people are looking for a mnemonic-language which should > optimized cross-compile to something with multiplatform-capability > like Java. > Please let me know, if I am entirely wrong. > > Klaus Ramelow > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From pyro9219 at gmail.com Mon Sep 11 23:53:33 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Mon, 11 Sep 2006 14:53:33 -0700 Subject: [Tutor] Traversing Excel Columns Message-ID: This is what I have, but it requires me to know the end of the column I'm working with, which changes. try:#Loop through the rows from 6 -> 25 for row in range(6, 25): #Write each row, increment 1+row in column 5 print >> file, "(%d) => %s" % (row, xlSht.Cells (1+row, 5).Value) I'm looking for something more like try:#Loop until rows are null while row in xlwksht != null #Write each row, incriment 1+row in column 5 print >> file, "'" + %s + "',", % (xlSht.Cells(1+row,5).Value) Maybe someone already tackled this? Or am I over thinking this problem? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060911/c7d06be0/attachment.html From kent37 at tds.net Tue Sep 12 00:28:58 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Sep 2006 18:28:58 -0400 Subject: [Tutor] Traversing Excel Columns In-Reply-To: References: Message-ID: <4505E32A.10309@tds.net> Chris Hengge wrote: > This is what I have, but it requires me to know the end of the column > I'm working with, which changes. > > try:#Loop through the rows from 6 -> 25 > for row in range(6, 25): > #Write each row, increment 1+row in column 5 > print >> file, "(%d) => %s" % (row, xlSht.Cells (1+row, 5).Value) > > I'm looking for something more like > try:#Loop until rows are null > while row in xlwksht != null > #Write each row, incriment 1+row in column 5 > print >> file, "'" + %s + "',", % (xlSht.Cells(1+row,5).Value) What is xlSht? Are you using COM, or xlrd, or pycelerator, or?? to read the spreadsheet? It probably has a way to find out the last row, or if the cell has data... Kent From alan.gauld at btinternet.com Tue Sep 12 00:31:51 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Sep 2006 23:31:51 +0100 Subject: [Tutor] Traversing Excel Columns References: Message-ID: I'm no expert in Excel programming but I assum,e you tried the obvious: > I'm looking for something more like > try:#Loop until rows are null > while row in xlwksht != null > #Write each row, incriment 1+row in column 5 > print >> file, "'" + %s + "',", % > (xlSht.Cells(1+row,5).Value) for row in xlSht.Cells: print >> file, row.Value I know you can do something similar in VBScript, I'm not sure if the Python bindinghs to the COM objects are gtthat clever however. But might be worth some experimenting at the >>> prompt. Alan G. From pyro9219 at gmail.com Tue Sep 12 00:36:53 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Mon, 11 Sep 2006 15:36:53 -0700 Subject: [Tutor] Traversing Excel Columns In-Reply-To: <4505E32A.10309@tds.net> References: <4505E32A.10309@tds.net> Message-ID: from win32com.client import Dispatch soo... that would be com.. sorry about that.. xlSht is the worksheet I'm currently reading from. On 9/11/06, Kent Johnson wrote: > > Chris Hengge wrote: > > This is what I have, but it requires me to know the end of the column > > I'm working with, which changes. > > > > try:#Loop through the rows from 6 -> 25 > > for row in range(6, 25): > > #Write each row, increment 1+row in column 5 > > print >> file, "(%d) => %s" % (row, xlSht.Cells (1+row, > 5).Value) > > > > I'm looking for something more like > > try:#Loop until rows are null > > while row in xlwksht != null > > #Write each row, incriment 1+row in column 5 > > print >> file, "'" + %s + "',", % (xlSht.Cells(1+row,5).Value) > > What is xlSht? Are you using COM, or xlrd, or pycelerator, or?? to read > the spreadsheet? It probably has a way to find out the last row, or if > the cell has data... > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060911/2d4915f3/attachment.htm From pyro9219 at gmail.com Tue Sep 12 00:41:27 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Mon, 11 Sep 2006 15:41:27 -0700 Subject: [Tutor] Traversing Excel Columns In-Reply-To: References: Message-ID: Just tried that (pretty sure I already did, but hey... I could have goofed it) No go On 9/11/06, Alan Gauld wrote: > > I'm no expert in Excel programming but I assum,e you tried > the obvious: > > > I'm looking for something more like > > try:#Loop until rows are null > > while row in xlwksht != null > > #Write each row, incriment 1+row in column 5 > > print >> file, "'" + %s + "',", % > > (xlSht.Cells(1+row,5).Value) > > for row in xlSht.Cells: > print >> file, row.Value > > I know you can do something similar in VBScript, I'm not sure > if the Python bindinghs to the COM objects are gtthat clever however. > > But might be worth some experimenting at the >>> prompt. > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060911/c8d55391/attachment.html From kent37 at tds.net Tue Sep 12 00:45:25 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Sep 2006 18:45:25 -0400 Subject: [Tutor] man pages parsing (still) In-Reply-To: <200609111700.19432.tiagosaboga@terra.com.br> References: <200609111055.00530.tiagosaboga@terra.com.br> <200609111244.51473.tiagosaboga@terra.com.br> <450587C7.9090306@tds.net> <200609111700.19432.tiagosaboga@terra.com.br> Message-ID: <4505E705.9000801@tds.net> Tiago Saboga wrote: > Ok, the guilty line (279) has a "©" that was probably defined in the dtd, > but as it doesn't know what is the right dtd... But wait... How does python > read the dtd? It fetches it from the net? I tried it (disconnected) and the > answer is yes, it fetches it from the net. So that's the problem! > > But how do I avoid it? I'll search. But if you can spare me some time, you'll > make me a little happier. > > [1] - The line is as follows: > "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd"> I'm just guessing, but I think if you find the right combination of handlers and feature settings you can at least make it just pass through the external entities without looking up the DTDs. Take a look at these pages for some hints: http://www.cafeconleche.org/books/xmljava/chapters/ch07s02.html#d0e10350 http://www.cafeconleche.org/books/xmljava/chapters/ch06s11.html They are talking about Java but the SAX interface is a cross-language standard so the names and semantics should be the same. Kent From dyoo at hkn.eecs.berkeley.edu Tue Sep 12 00:49:04 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 11 Sep 2006 15:49:04 -0700 (PDT) Subject: [Tutor] Java: (and python ?) nearer measles than coffee In-Reply-To: <4505D32F.80809@tds.net> References: <4505CA88.9020507@GMX.de> <4505D32F.80809@tds.net> Message-ID: >> some more people are looking for a mnemonic-language which should >> optimized cross-compile to something with multiplatform-capability like >> Java. Please let me know, if I am entirely wrong. > > I'm not really sure what you are asking. Many people find Python to be > useful and enjoyable for a wide variety of personal and professional > programming. But if you are happy with Basic and Cobol and they meet > your needs then there is no need to "waste your time" learning anything > else, I suppose. I want to support Kent in this. We're not language bigots. (In fact, I'm not really much of a Python programmer at the moment. *grin*) I have no idea what a mnemonic language should be: perhaps you're talking about domain-specific languages in the sense discussed in: http://www.ddj.com/184405575 In which case, one argument for learning Python or any other general purpose language is to know the necessary tools to write the domain-specific language you want. That is, the point of a general purpose language is to "bootstrap": to give us enough tools to build our way up to the domain. If someone's already done that work, then yes, of course, use the domain-specific language. If I'm doing some kind of simple text processing, then Perl's probably a good choice, because that language has a lot of built-in support for text munging. If I need to do something with database management, I'd be silly if I didn't take a close look at an SQL implementation first. But if I'm writing a simulator for elevator systems, I might be in for some work. It's unlikely that someone has written a domain-specific language for ascending platforms, and I'm probably going to have to bootstrap my way up from a general purpose language (like Python or Perl or Ruby or Java or Scheme or ...) so that I can eventually talk about the problem in the natural terms of my domain. And if a language helps me claw up that much more quickly, then that's a very good reason for me to learn that new language. That's the claim of high-level, general purpose languages: we don't learn them just for their own sake, but because they help us build the tools we need to get to the real interesting problems. From dyoo at hkn.eecs.berkeley.edu Tue Sep 12 01:01:29 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 11 Sep 2006 16:01:29 -0700 (PDT) Subject: [Tutor] man pages parsing (still) In-Reply-To: <200609111055.00530.tiagosaboga@terra.com.br> References: <200609111055.00530.tiagosaboga@terra.com.br> Message-ID: > terribly slow. Doclifter itself take around a second to parse the troff > file, but my few lines of code take 25 seconds to parse the resultant > xml. I've pasted the code at http://pastebin.ca/166941 and I'd like to > hear from you how I could possibly optimize it. Hi Tiago, Before we go any further: have you run your program through the Python profiler yet? Take a look at: http://docs.python.org/lib/profile.html and see if that can help isolate the slow sections in your program. If I really had to guess, without profiling information, I'd take a very close look at the characters() method: it's doing some string concatentation there that may have very bad performance, depending on the input. See: http://mail.python.org/pipermail/tutor/2004-August/031568.html and the thread around that time for details on why string concatentation should be treated carefully. From kent37 at tds.net Tue Sep 12 01:23:01 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Sep 2006 19:23:01 -0400 Subject: [Tutor] man pages parsing (still) In-Reply-To: References: <200609111055.00530.tiagosaboga@terra.com.br> Message-ID: <4505EFD5.1090205@tds.net> Danny Yoo wrote: > If I really had to guess, without profiling information, I'd take a very > close look at the characters() method: it's doing some string > concatentation there that may have very bad performance, depending on the > input. See: > > http://mail.python.org/pipermail/tutor/2004-August/031568.html > > and the thread around that time for details on why string concatentation > should be treated carefully. Gee, Danny, it's hard to disagree with you when you quote me in support of your argument, but...the characters() method is probably called only once or twice per tag, and the string is reinitialized for each tag. So this seems unlikely to be the culprit. Course it helps that I have read to the end of the thread - the problem seems to be accessing the external DTD ;-) By the way that article of mine is obsoleted by Python 2.4, which optimizes string concatenation in a loop... http://www.python.org/doc/2.4.3/whatsnew/node12.html#SECTION0001210000000000000000 Kent From pyro9219 at gmail.com Tue Sep 12 02:48:22 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Mon, 11 Sep 2006 17:48:22 -0700 Subject: [Tutor] Traversing Excel Columns In-Reply-To: References: Message-ID: Hmm... ok... after some thought... this is what I'm looking for #some great line that gives me an int for the number of not null cells intLastUsedRow = xlSht.Cells.LastValue #Made this up, but basically what I need. I need to iterate through a range() because I dont know another good way to tell it not to use the column headings and other junk over the data I want to collect. try: #Loop through rows for row in range(5,intLastUsedRow): #Write each row, incriment 1+row in column 5 file.write(xlSht.Cells(1+row,5).Value) On 9/11/06, Alan Gauld wrote: > > I'm no expert in Excel programming but I assum,e you tried > the obvious: > > > I'm looking for something more like > > try:#Loop until rows are null > > while row in xlwksht != null > > #Write each row, incriment 1+row in column 5 > > print >> file, "'" + %s + "',", % > > ( xlSht.Cells(1+row,5).Value) > > for row in xlSht.Cells: > print >> file, row.Value > > I know you can do something similar in VBScript, I'm not sure > if the Python bindinghs to the COM objects are gtthat clever however. > > But might be worth some experimenting at the >>> prompt. > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060911/06c3e6e5/attachment.htm From maradix at sapo.pt Tue Sep 12 02:49:06 2006 From: maradix at sapo.pt (Jose P) Date: Tue, 12 Sep 2006 01:49:06 +0100 Subject: [Tutor] encoding Message-ID: <1158022146.5919.14.camel@pa-desktop> watch this example: >>> a=['lula', 'ca??o'] >>> print a ['lula', 'ca\xc3\xa7\xc3\xa3o'] >>> print a[1] ca??o when i print the list the special characters are not printed correctly! But if i print only the list item that has the special charaters it runs OK. How do i get list print correctly? From kent37 at tds.net Tue Sep 12 03:29:07 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Sep 2006 21:29:07 -0400 Subject: [Tutor] encoding In-Reply-To: <1158022146.5919.14.camel@pa-desktop> References: <1158022146.5919.14.camel@pa-desktop> Message-ID: <45060D63.203@tds.net> Jose P wrote: > watch this example: > >>>> a=['lula', 'ca??o'] >>>> print a > ['lula', 'ca\xc3\xa7\xc3\xa3o'] >>>> print a[1] > ca??o > > > when i print the list the special characters are not printed correctly! When you print a list, it uses repr() to format the contents of the list; when you print an item directly, str() is used. For a string containing non-ascii characters, the results are different. > > But if i print only the list item that has the special charaters it runs > OK. > > How do i get list print correctly? You will have to do the formatting your self. A simple solution might be for x in a: print x If you want exactly the list formatting you have to work harder. Try something like "['" + "', '".join([str(x) for x in a]) + "']" Kent From patriciap.gu at gmail.com Tue Sep 12 04:16:19 2006 From: patriciap.gu at gmail.com (Patricia) Date: Tue, 12 Sep 2006 02:16:19 +0000 (UTC) Subject: [Tutor] urllib Message-ID: Hi, I have used urllib and urllib2 to post data like the following: dict = {} dict['data'] = info dict['system'] = aname data = urllib.urlencode(dict) req = urllib2.Request(url) And to get the data, I emulated a web page with a submit button: s = "" s += "
" s += "" s += "" s += "" s += "
" I would like to know how to send a file. It's a text file that will be gzipped before being posted. I'm using python version 2.2.3. Thanks, Patricia From cspears2002 at yahoo.com Tue Sep 12 04:45:57 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon, 11 Sep 2006 19:45:57 -0700 (PDT) Subject: [Tutor] foreach loops Message-ID: <20060912024557.91349.qmail@web51606.mail.yahoo.com> Does python have foreach loops? I don't see any mention of them in the docs. Am I going to have to use Perl (gasp!) if I want my beloved foreach loop? -Chris From dyoo at hkn.eecs.berkeley.edu Tue Sep 12 04:51:16 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 11 Sep 2006 19:51:16 -0700 (PDT) Subject: [Tutor] man pages parsing (still) In-Reply-To: <4505EFD5.1090205@tds.net> References: <200609111055.00530.tiagosaboga@terra.com.br> <4505EFD5.1090205@tds.net> Message-ID: > Gee, Danny, it's hard to disagree with you when you quote me in support > of your argument, but...the characters() method is probably called only > once or twice per tag, and the string is reinitialized for each tag. So > this seems unlikely to be the culprit. Ah, didn't see those; that'll teach me not to guess. From dyoo at hkn.eecs.berkeley.edu Tue Sep 12 04:52:07 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 11 Sep 2006 19:52:07 -0700 (PDT) Subject: [Tutor] foreach loops In-Reply-To: <20060912024557.91349.qmail@web51606.mail.yahoo.com> References: <20060912024557.91349.qmail@web51606.mail.yahoo.com> Message-ID: > Does python have foreach loops? I don't see any mention of them in the > docs. Am I going to have to use Perl (gasp!) if I want my beloved > foreach loop? Can you show an example of a Perl foreach loop? Perhaps someone can help translate it into idiomatic Python. Good luck! From rabidpoobear at gmail.com Mon Sep 11 17:04:17 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 11 Sep 2006 10:04:17 -0500 Subject: [Tutor] foreach loops In-Reply-To: References: <20060912024557.91349.qmail@web51606.mail.yahoo.com> Message-ID: <45057AF1.4060907@gmail.com> Danny Yoo wrote: > >> Does python have foreach loops? I don't see any mention of them in the >> docs. Am I going to have to use Perl (gasp!) if I want my beloved >> foreach loop? >> > > Can you show an example of a Perl foreach loop? Perhaps someone can help > translate it into idiomatic Python. > It seems to me that foreach is the same as the python 'for' loop.... #-- perl code @myNames = ('Larry', 'Curly', 'Moe'); print "Who's on the list:\n"; foreach (@myNames) { print $_ . "\n"; } #--- python code: names = ['Larry','Curly','Moe'] print "Who's on the list?\n" for x in mynames: print x+'\n' #---- Am I missing the point here? -Luke > Good luck! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From cspears2002 at yahoo.com Tue Sep 12 05:32:34 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon, 11 Sep 2006 20:32:34 -0700 (PDT) Subject: [Tutor] foreach loops In-Reply-To: <45057AF1.4060907@gmail.com> Message-ID: <20060912033234.29202.qmail@web51608.mail.yahoo.com> Hmmm...Perl is probably a bad example. My apologies. I was thinking more along the lines of this: A C++ for loop: #include using std::cout; int main() { for (int i = 0; i < 10; i++) { cout << i << "\n"; } return 0; } From rabidpoobear at gmail.com Mon Sep 11 17:39:05 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 11 Sep 2006 10:39:05 -0500 Subject: [Tutor] foreach loops In-Reply-To: <20060912033234.29202.qmail@web51608.mail.yahoo.com> References: <20060912033234.29202.qmail@web51608.mail.yahoo.com> Message-ID: <45058319.7060300@gmail.com> Christopher Spears wrote: > Hmmm...Perl is probably a bad example. My apologies. > I was thinking more along the lines of this: > > A C++ for loop: > > #include > > using std::cout; > > int main() { > > for (int i = 0; i < 10; i++) { > cout << i << "\n"; > } > > return 0; > } > > for i in range(10): print i+'\n' that does the same thing as a = [0,1,2,3,4,5,6,7,8,9] for i in a: print i+'\n' or a = range(10) for i in a: print i+'\n' Python's 'for' loop is not really meant as an iterator over a list of numbers so this feature isn't built into the loop itself, you have to use the range function, which just generates a list of numbers to iterate over. Perhaps you should read an introductory Python tutorial. Any one of them should cover the types of questions that people from other languages have about Python. It sounds like you know how to program already, so the 'python for non-programmers' type of tutorial may not be best-suited to you, but just look around. If you have any more questions I'd be happy to answer them, as would the rest of the list, I'm sure. HTH, -Luke > > From jordangreenberg at gmail.com Tue Sep 12 07:44:33 2006 From: jordangreenberg at gmail.com (Jordan Greenberg) Date: Tue, 12 Sep 2006 01:44:33 -0400 Subject: [Tutor] foreach loops In-Reply-To: <20060912033234.29202.qmail@web51608.mail.yahoo.com> References: <20060912033234.29202.qmail@web51608.mail.yahoo.com> Message-ID: <45064941.4000105@gmail.com> Christopher Spears wrote: > Hmmm...Perl is probably a bad example. My apologies. > I was thinking more along the lines of this: > > A C++ for loop: > > #include > > using std::cout; > > int main() { > > for (int i = 0; i < 10; i++) { > cout << i << "\n"; > } > > return 0; > } > The same functionality can be provided using python for and the range() function, like: for i in range(0, 10): print i Though because of the way python works you don't need to use this type of loop anywhere near as often as in other languages. For example in java (and c++, but my c++ is so rusty I'm not going embarrass myself trying to write an example) you're constantly doing things like looping over an array: public void main(String[] args) { int[] foo; /* then later after foo has been initialized to whatever: */ for (int i=0; i References: Message-ID: <1158040019.5127.1.camel@localhost> I don't suppose that anyone has a fix for me eh? I've tried about all I can think of and I'd like to be able to give this program a trial tomorrow when I get back to work.. sure would save me some time :] On Mon, 2006-09-11 at 17:48 -0700, Chris Hengge wrote: > Hmm... ok... after some thought... this is what I'm looking for > > #some great line that gives me an int for the number of not null cells > intLastUsedRow = xlSht.Cells.LastValue #Made this up, but basically > what I need. > > I need to iterate through a range() because I dont know another good > way to tell it not to use the column headings and other junk over the > data I want to collect. > > try: #Loop through rows > for row in range(5,intLastUsedRow): > #Write each row, incriment 1+row in column 5 > file.write(xlSht.Cells(1+row,5).Value) > > > On 9/11/06, Alan Gauld wrote: > I'm no expert in Excel programming but I assum,e you tried > the obvious: > > > I'm looking for something more like > > try:#Loop until rows are null > > while row in xlwksht != null > > #Write each row, incriment 1+row in column 5 > > print >> file, "'" + %s + "',", % > > ( xlSht.Cells(1+row,5).Value) > > for row in xlSht.Cells: > print >> file, row.Value > > I know you can do something similar in VBScript, I'm not sure > if the Python bindinghs to the COM objects are gtthat clever > however. > > But might be worth some experimenting at the >>> prompt. > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From john at fouhy.net Tue Sep 12 08:03:06 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 12 Sep 2006 18:03:06 +1200 Subject: [Tutor] Traversing Excel Columns In-Reply-To: <1158040019.5127.1.camel@localhost> References: <1158040019.5127.1.camel@localhost> Message-ID: <5e58f2e40609112303j63074a84qe435d44911172848@mail.gmail.com> On 12/09/06, Chris Hengge wrote: > I don't suppose that anyone has a fix for me eh? I've tried about all I > can think of and I'd like to be able to give this program a trial > tomorrow when I get back to work.. sure would save me some time :] Will there be internal blanks? You could just scan for Cells(row, col).Value in (None, ''). Otherwise, run makepy.py (if you haven't already) on Excel, and then look through the code it generates. It will show you all the methods you can call, and what arguments they expect. Something may leap out at you. -- John. From pyro9219 at gmail.com Tue Sep 12 09:33:53 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Tue, 12 Sep 2006 00:33:53 -0700 Subject: [Tutor] Traversing Excel Columns In-Reply-To: <5e58f2e40609112303j63074a84qe435d44911172848@mail.gmail.com> References: <1158040019.5127.1.camel@localhost> <5e58f2e40609112303j63074a84qe435d44911172848@mail.gmail.com> Message-ID: <1158046433.5127.5.camel@localhost> I'm not sure what internal blanks means.. but I'll take a stab and say "no", there are going to be NO blanks once I start reading the column unless there are no more values to read... null or "" would be fine for a stopping point. also, what is makepy.py? I'm still working through a couple books on python, so I haven't got all the tricks yet :] Thanks On Tue, 2006-09-12 at 18:03 +1200, John Fouhy wrote: > On 12/09/06, Chris Hengge wrote: > > I don't suppose that anyone has a fix for me eh? I've tried about all I > > can think of and I'd like to be able to give this program a trial > > tomorrow when I get back to work.. sure would save me some time :] > > Will there be internal blanks? You could just scan for Cells(row, > col).Value in (None, ''). > > Otherwise, run makepy.py (if you haven't already) on Excel, and then > look through the code it generates. It will show you all the methods > you can call, and what arguments they expect. Something may leap out > at you. > From kent37 at tds.net Tue Sep 12 12:11:39 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 12 Sep 2006 06:11:39 -0400 Subject: [Tutor] urllib In-Reply-To: References: Message-ID: <450687DB.5050707@tds.net> Patricia wrote: > Hi, > > I have used urllib and urllib2 to post data like the following: > > dict = {} > dict['data'] = info > dict['system'] = aname > > data = urllib.urlencode(dict) > req = urllib2.Request(url) > > And to get the data, I emulated a web page with a submit button: > s = "" > s += "
" > s += "" > s += "" > s += "" > s += "
" > > > I would like to know how to send a file. It's a text file that will be > gzipped before being posted. I'm using python version 2.2.3. There are some old examples hereA http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 I think the modern way uses email.MIMEMultipart but I don't have an example handy. Kent From sky.asia at yahoo.com Tue Sep 12 12:43:20 2006 From: sky.asia at yahoo.com (Náv) Date: Tue, 12 Sep 2006 03:43:20 -0700 (PDT) Subject: [Tutor] urllib In-Reply-To: <450687DB.5050707@tds.net> Message-ID: <20060912104320.705.qmail@web51704.mail.yahoo.com> Hi, You can try this: import httplib, urllib params = urllib.urlencode({'ID':'1','Name':'name', 'Eid':'we[at]you.com'}) #Assumed URL: test.com/cgi-bin/myform h = httplib.HTTP("test.com") h.putrequest("POST", "/cgi-bin/myform") h.putheader("Content-length", "%d" % len(params)) h.putheader('Accept', 'text/plain') h.putheader('Host', 'test.com') h.endheaders() h.send(params) reply, msg, hdrs = h.getreply() print reply # should be 200 in case of reply data = h.getfile().read() # get the raw HTML f = open('test.html','w') # put response in the html form f.write(data) f.close() Hope it will solve your problem. Regards, Nav --- We on Orkut.com!!! The Revolutions (Comp Sci RnD) www.orkut.com/Community.aspx?cmm=13263692- Jobs by Employee Reference www.orkut.com/Community.aspx?cmm=19517702 Kent Johnson wrote: Patricia wrote: > Hi, > > I have used urllib and urllib2 to post data like the following: > > dict = {} > dict['data'] = info > dict['system'] = aname > > data = urllib.urlencode(dict) > req = urllib2.Request(url) > > And to get the data, I emulated a web page with a submit button: > s = "" > s += " " > s += "" > s += " [input] " > s += " [input] " > s += "" > > > I would like to know how to send a file. It's a text file that will be > gzipped before being posted. I'm using python version 2.2.3. There are some old examples hereA http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 I think the modern way uses email.MIMEMultipart but I don't have an example handy. Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great rates starting at 1¢/min. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060912/731ee0a0/attachment.html From govilakanksha at yahoo.com Tue Sep 12 13:23:20 2006 From: govilakanksha at yahoo.com (Akanksha Govil) Date: Tue, 12 Sep 2006 04:23:20 -0700 (PDT) Subject: [Tutor] Help needed for etherealXML parsing Message-ID: <20060912112320.20912.qmail@web36502.mail.mud.yahoo.com> Hi, I have downloaded an add on python script "etherealXML.py" for parsing the ethereal captured packets. This script runs fine on python 2.3 but on python 2.4 it gives error. Has any one tried porting this script? Also I found the SAX parser earlier used to return a call back function which is no longer the case, so how do we modify the script according to the new SAX parser? Any help would be highly appreciated Thanks Akanksha --------------------------------- Stay in the know. Pulse on the new Yahoo.com. Check it out. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060912/fde0b9ba/attachment.htm From etrade.griffiths at dsl.pipex.com Tue Sep 12 13:25:50 2006 From: etrade.griffiths at dsl.pipex.com (Etrade Griffiths) Date: Tue, 12 Sep 2006 12:25:50 +0100 Subject: [Tutor] Traversing Excel Columns In-Reply-To: References: Message-ID: <6.1.2.0.2.20060912122142.02c34610@pop.dsl.pipex.com> Chris are you looking for something like this? xlSht=xlApp.Worksheets("Sheet1") irow=1 XL_row_has_data=1 while XL_row_has_data: xlRng=xlSht.Range(xlSht.Cells(irow,1),xlSht.Cells(irow,256)) ncell=xlApp.WorksheetFunction.CountA(xlRng) if ncell ==0: # Cells in current row are all empty XL_row_has_data=0 else: # Look in next row irow=irow+1 print "first row with empty cells is row "+str(irow) HTH Alun Griffiths From kent37 at tds.net Tue Sep 12 13:47:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 12 Sep 2006 07:47:05 -0400 Subject: [Tutor] Help needed for etherealXML parsing In-Reply-To: <20060912112320.20912.qmail@web36502.mail.mud.yahoo.com> References: <20060912112320.20912.qmail@web36502.mail.mud.yahoo.com> Message-ID: <45069E39.7060600@tds.net> Akanksha Govil wrote: > Hi, > > I have downloaded an add on python script "etherealXML.py" for parsing > the ethereal captured packets. > > This script runs fine on python 2.3 but on python 2.4 it gives error.\ What is the error? > > Has any one tried porting this script? This might give a clue: http://www.python.org/doc/2.4.3/whatsnew/node15.html > > Also I found the SAX parser earlier used to return a call back function > which is no longer the case, so how do we modify the script according to > the new SAX parser? Which parser? Which callback was returned? From what call? Kent From johan at accesstel.co.za Tue Sep 12 18:00:15 2006 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Tue, 12 Sep 2006 18:00:15 +0200 Subject: [Tutor] HTML page status Message-ID: <4506D98F.5060008@accesstel.co.za> Hi all, I looked a little bit at the urllib and it all looks fairly easy. What I didn't see, if it is there, was how to know or identify if a page was successfully downloaded. I want to do tests to see if a connection to a webpage was successful by parsing whatever came back. Will this be the easiest way of doing this or is there a different way of testing the availability of webpages? Let's say I can connect to a webpage, but it failed to upload 100%, how will I know that the connection was not 100% successful? I'm not very familiar with url parsing and HTML to know if there are other indicators to notify me if a page or any web access is possible. Once this was done, can I add features to say how fast the page was downloaded? Thanks Johan From johan at accesstel.co.za Mon Sep 11 14:07:06 2006 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Mon, 11 Sep 2006 14:07:06 +0200 Subject: [Tutor] HTML page status Message-ID: <4505516A.2020807@accesstel.co.za> Hi all, I looked a little bit at the urllib and it all looks fairly easy. What I didn't see, if it is there, was how to know or identify if a page was successfully downloaded. I want to do tests to see if a connection to a webpage was successful by parsing whatever came back. Will this be the easiest way of doing this or is there a different way of testing the availability of webpages? Let's say I can connect to a webpage, but it failed to upload 100%, how will I know that the connection was not 100% successful? I'm not very familiar with url parsing and HTML to know if there are other indicators to notify me if a page or any web access is possible. Once this was done, can I add features to say how fast the page was downloaded? Thanks Johan From rabidpoobear at gmail.com Tue Sep 12 07:32:19 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 12 Sep 2006 00:32:19 -0500 Subject: [Tutor] HTML page status In-Reply-To: <4506D98F.5060008@accesstel.co.za> References: <4506D98F.5060008@accesstel.co.za> Message-ID: <45064663.7000806@gmail.com> Johan Geldenhuys wrote: > Hi all, > > I looked a little bit at the urllib and it all looks fairly easy. > What I didn't see, if it is there, was how to know or identify if a page > was successfully downloaded. I want to do tests to see if a connection > to a webpage was successful by parsing whatever came back. > > Will this be the easiest way of doing this or is there a different way > of testing the availability of webpages? Let's say I can connect to a > webpage, but it failed to upload 100%, how will I know that the > connection was not 100% successful? I'm not very familiar with url > parsing and HTML to know if there are other indicators to notify me if a > page or any web access is possible. > > Once this was done, can I add features to say how fast the page was > downloaded? > > if you use httplib you can capture the returned headers and look at the error code. 404 if the page wasn't found,etc etc. I'm really bad at using it so I won't attempt to give you an example. GIYF I guess :) -Luke > Thanks > > Johan > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at freenet.co.uk Tue Sep 12 20:07:43 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 12 Sep 2006 19:07:43 +0100 Subject: [Tutor] foreach loops References: <20060912024557.91349.qmail@web51606.mail.yahoo.com> Message-ID: <001b01c6d696$58657380$0201a8c0@XPpro> > Does python have foreach loops? I don't see any > mention of them in the docs. Am I going to have to > use Perl (gasp!) if I want my beloved foreach loop? Its called a for loop in Python... Or is there some extra magic in the Perl version that I'm missing? Alan G. From alan.gauld at freenet.co.uk Tue Sep 12 20:09:41 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 12 Sep 2006 19:09:41 +0100 Subject: [Tutor] foreach loops References: <20060912033234.29202.qmail@web51608.mail.yahoo.com> Message-ID: <002501c6d696$9eea9510$0201a8c0@XPpro> > I was thinking more along the lines of this: > > A C++ for loop: This is exactly NOT a foreach loop, its a vanilla for loop. > > #include > > using std::cout; > > int main() { > > for (int i = 0; i < 10; i++) { > cout << i << "\n"; > } for i in range(10): print i Alan G. From arcege at gmail.com Tue Sep 12 20:47:34 2006 From: arcege at gmail.com (Michael P. Reilly) Date: Tue, 12 Sep 2006 14:47:34 -0400 Subject: [Tutor] HTML page status In-Reply-To: <4506D98F.5060008@accesstel.co.za> References: <4506D98F.5060008@accesstel.co.za> Message-ID: <7e5ba9220609121147v5c644ce2o6194e77af798618c@mail.gmail.com> On 9/12/06, Johan Geldenhuys wrote: > > > Hi all, > > I looked a little bit at the urllib and it all looks fairly easy. > What I didn't see, if it is there, was how to know or identify if a page > was successfully downloaded. I want to do tests to see if a connection > to a webpage was successful by parsing whatever came back. > > Will this be the easiest way of doing this or is there a different way > of testing the availability of webpages? Let's say I can connect to a > webpage, but it failed to upload 100%, how will I know that the > connection was not 100% successful? I'm not very familiar with url > parsing and HTML to know if there are other indicators to notify me if a > page or any web access is possible. > > Once this was done, can I add features to say how fast the page was > downloaded? > > Thanks > > Johan > I've just finished writing a smoke test engine after releasing new webpages. I use httplib.HTTPConnection classes. Here is an example: import urlparse, httplib class SiteCheck: reqtype = 'POST' def __init__(self, url): self.url = url pieces = urlparse.urlparse(url) self.hostname = pieces[1] self.conn = httplib.HTTPConnection(self.hostname) def run(self): self.conn.request(self.reqtype, self.url) response = self.conn.getresponse() method_name = 'response_%d' % response.status try: method = getattr(self, method_name) except AttributeError: self.response_default(response) else: method(response) def response_default(self, response): self.result = '%d %s' % (response.status, response.reason) def response_200(self, response): self.result = response.reason # "OK" def response_302(self, response): self.result = response.msg['Location'] # 302 redirect Hopefully this will give you some ideas. -Arcege -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060912/c606d256/attachment.htm From johan at accesstel.co.za Tue Sep 12 22:31:25 2006 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Tue, 12 Sep 2006 22:31:25 +0200 Subject: [Tutor] HTML page status In-Reply-To: <7e5ba9220609121147v5c644ce2o6194e77af798618c@mail.gmail.com> References: <4506D98F.5060008@accesstel.co.za> <7e5ba9220609121147v5c644ce2o6194e77af798618c@mail.gmail.com> Message-ID: <4507191D.4010704@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060912/b353f799/attachment.htm From tiagosaboga at terra.com.br Tue Sep 12 22:59:52 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Tue, 12 Sep 2006 17:59:52 -0300 Subject: [Tutor] man pages parsing (still) In-Reply-To: <4505E705.9000801@tds.net> References: <200609111055.00530.tiagosaboga@terra.com.br> <200609111700.19432.tiagosaboga@terra.com.br> <4505E705.9000801@tds.net> Message-ID: <200609121759.52787.tiagosaboga@terra.com.br> Em Segunda 11 Setembro 2006 19:45, Kent Johnson escreveu: > Tiago Saboga wrote: > > Ok, the guilty line (279) has a "©" that was probably defined in the > > dtd, but as it doesn't know what is the right dtd... But wait... How does > > python read the dtd? It fetches it from the net? I tried it > > (disconnected) and the answer is yes, it fetches it from the net. So > > that's the problem! > > > > But how do I avoid it? I'll search. But if you can spare me some time, > > you'll make me a little happier. > > > > [1] - The line is as follows: > > > > > "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd"> > > I'm just guessing, but I think if you find the right combination of > handlers and feature settings you can at least make it just pass through > the external entities without looking up the DTDs. I got it! I just set the feature_external_ges to false and it doesn't fetch the dtd any more. Thanks!!! ;-) > > Take a look at these pages for some hints: > http://www.cafeconleche.org/books/xmljava/chapters/ch07s02.html#d0e10350 > http://www.cafeconleche.org/books/xmljava/chapters/ch06s11.html It looks very interesting, and it was exactly what I needed. But I couldn't grab it at first, I need some more time to understand it all. Thanks again!!! Tiago. From john at fouhy.net Tue Sep 12 23:27:27 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 13 Sep 2006 09:27:27 +1200 Subject: [Tutor] Traversing Excel Columns In-Reply-To: <1158046433.5127.5.camel@localhost> References: <1158040019.5127.1.camel@localhost> <5e58f2e40609112303j63074a84qe435d44911172848@mail.gmail.com> <1158046433.5127.5.camel@localhost> Message-ID: <5e58f2e40609121427v71d2e1f5wff278096d00d080@mail.gmail.com> On 12/09/06, Chris Hengge wrote: > I'm not sure what internal blanks means.. but I'll take a stab and say > "no", there are going to be NO blanks once I start reading the column > unless there are no more values to read... null or "" would be fine for > a stopping point. Well, basically, I'm thinking you could say something like: for i in itertools.count(1): if xlSht.Cells(1, i).Value in (None, ''): maxCol = i break This should start at (1,1) (the top-left cell), and move right, until it hits a blank cell, at which point it aborts. You could do the same thing, but changing row instead of column, to find the maximum column. So, by "internal blanks", I meant blank cells with non-blank cells to the right, or below. Also, if the first row is not necessarily the longest, you would need a bit more trickery. > also, what is makepy.py? I'm still working through a couple books on > python, so I haven't got all the tricks yet :] makepy.py is a utility that comes with pythonwin. Basically it builds python libraries corresponding to COM objects. If you do this (one-time only), your code should run faster. Also, you will get meaningful help(), and you can look at the code it produces to get a quick list of all the available methods, and what arguments they expect. You can run it from the command line, or you can run it from the menu of the pythonwin IDE. -- John. From kent37 at tds.net Wed Sep 13 00:28:28 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 12 Sep 2006 18:28:28 -0400 Subject: [Tutor] HTML page status In-Reply-To: <4507191D.4010704@accesstel.co.za> References: <4506D98F.5060008@accesstel.co.za> <7e5ba9220609121147v5c644ce2o6194e77af798618c@mail.gmail.com> <4507191D.4010704@accesstel.co.za> Message-ID: <4507348C.8070301@tds.net> Johan Geldenhuys wrote: > I don't know if this will work in all cases. I tried it with a > internet connection and could get a 'OK' response. Then I tried it > withoput a internet connection and received a Traceback error, which is > not what I want. > > It gave me some idea what is possible. The traceback is because the connection attempt raised an exception when it failed to connect. If you look at the kind of exception (printed in the traceback) you can catch it in your code and handle it a different way. For example, if the exception is urllib.error (just a guess!) then you would write try: # code to try the connection here except urllib.error: # code to handle the error goes here. Kent From pyro9219 at gmail.com Wed Sep 13 00:50:23 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Tue, 12 Sep 2006 15:50:23 -0700 Subject: [Tutor] Traversing Excel Columns In-Reply-To: <5e58f2e40609121427v71d2e1f5wff278096d00d080@mail.gmail.com> References: <1158040019.5127.1.camel@localhost> <5e58f2e40609112303j63074a84qe435d44911172848@mail.gmail.com> <1158046433.5127.5.camel@localhost> <5e58f2e40609121427v71d2e1f5wff278096d00d080@mail.gmail.com> Message-ID: I got it working! try:#Attempt to record the fields from the excel file. row = 10 #Set the row in excel. #While the cell isn't 'None', keep looping. #Excel (row,col) for navigation while xlSht.Cells(row,1).Value != None: print >> file, "'%s'," % xlSht.Cells(row,1).Value, row = 1 + row This does exactly what I want. Now perhaps, is there a prettier way to write it? I can get file.write("'%s',") % xlSht.Cells(row,1).Value to work.. I'm just taking all the values from the cells and dumping them into a text file with single quotes and a comma (sorta like comma seperated values) that need to be on long line(like I've got it above in my working code). Also, why doesn't 'xlSht.Cells(row + 1, 1).Value' work for this loop, but it did for the previous loop I posted to tutor? On 9/12/06, John Fouhy wrote: > > On 12/09/06, Chris Hengge wrote: > > I'm not sure what internal blanks means.. but I'll take a stab and say > > "no", there are going to be NO blanks once I start reading the column > > unless there are no more values to read... null or "" would be fine for > > a stopping point. > > Well, basically, I'm thinking you could say something like: > > for i in itertools.count(1): > if xlSht.Cells(1, i).Value in (None, ''): > maxCol = i > break > > This should start at (1,1) (the top-left cell), and move right, until > it hits a blank cell, at which point it aborts. > > You could do the same thing, but changing row instead of column, to > find the maximum column. > > So, by "internal blanks", I meant blank cells with non-blank cells to > the right, or below. > > Also, if the first row is not necessarily the longest, you would need > a bit more trickery. > > > also, what is makepy.py? I'm still working through a couple books on > > python, so I haven't got all the tricks yet :] > > makepy.py is a utility that comes with pythonwin. Basically it builds > python libraries corresponding to COM objects. If you do this > (one-time only), your code should run faster. Also, you will get > meaningful help(), and you can look at the code it produces to get a > quick list of all the available methods, and what arguments they > expect. > > You can run it from the command line, or you can run it from the menu > of the pythonwin IDE. > > -- > John. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060912/ffd39805/attachment.html From alan.gauld at freenet.co.uk Wed Sep 13 05:12:21 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 13 Sep 2006 04:12:21 +0100 Subject: [Tutor] Traversing Excel Columns References: <1158040019.5127.1.camel@localhost><5e58f2e40609112303j63074a84qe435d44911172848@mail.gmail.com><1158046433.5127.5.camel@localhost><5e58f2e40609121427v71d2e1f5wff278096d00d080@mail.gmail.com> Message-ID: <008101c6d6e2$6da5e760$0201a8c0@XPpro> > I can get file.write("'%s',") % xlSht.Cells(row,1).Value > to work.. file.write("'%s'," % xlSht.Cells(row,1).Value) Try that.... The string formatting must happen inside the parens. BTW using 'file' as a variab;e is not good since file is a built-in function name (albeit an alias for open) and could confuse a reader.. Alan G. From anilmrn at yahoo.com Wed Sep 13 09:14:10 2006 From: anilmrn at yahoo.com (anil maran) Date: Wed, 13 Sep 2006 00:14:10 -0700 (PDT) Subject: [Tutor] encoding text in html Message-ID: <20060913071410.95149.qmail@web55910.mail.re3.yahoo.com> i was trying to display some text it is in utf-8 in postgres and when it is displayed in firefox and ie, it gets displayed as some symols with 4numbers in a box or so even for ' apostrophe please tell me how to display this properly i try title.__str__ or title.__repr__ both dont work -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060913/c1d0b7e7/attachment.html From pyro9219 at gmail.com Wed Sep 13 10:06:35 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 13 Sep 2006 01:06:35 -0700 Subject: [Tutor] Traversing Excel Columns In-Reply-To: <008101c6d6e2$6da5e760$0201a8c0@XPpro> References: <1158040019.5127.1.camel@localhost> <5e58f2e40609112303j63074a84qe435d44911172848@mail.gmail.com> <1158046433.5127.5.camel@localhost> <5e58f2e40609121427v71d2e1f5wff278096d00d080@mail.gmail.com> <008101c6d6e2$6da5e760$0201a8c0@XPpro> Message-ID: <1158134795.5127.12.camel@localhost> I'll give that a shot tomorrow when I work on the script some more. Thanks for the note on 'file'... none of the IDE's I've used have colored or yelled at me, so I just assumed it was free for the taking.. (used to VS where it yells at you for more then I'd care) I've just started using SPE though... I'm very impressed with it compared to some of the others of tried which either just weren't quite ready for retail or to much like a plain text editor for my liking. Unless something comes up that I can't get working right, I'll be pitching the author a few bucks for his work :] Thanks again for all the help. Hopefully one day I'll be able to contribute some back! On Wed, 2006-09-13 at 04:12 +0100, Alan Gauld wrote: > > I can get file.write("'%s',") % xlSht.Cells(row,1).Value > > to work.. > > file.write("'%s'," % xlSht.Cells(row,1).Value) > > Try that.... > > The string formatting must happen inside the parens. > > > BTW using 'file' as a variab;e is not good since file is a > built-in function name (albeit an alias for open) and could > confuse a reader.. > > > Alan G. > From anilmrn at yahoo.com Wed Sep 13 11:08:45 2006 From: anilmrn at yahoo.com (anil maran) Date: Wed, 13 Sep 2006 02:08:45 -0700 (PDT) Subject: [Tutor] encoding text in html Message-ID: <20060913090845.63689.qmail@web55915.mail.re3.yahoo.com> submits: We\xe2\x80\x99re pretty sur this is how it is stored in postgres please help me out thanks ----- Original Message ---- From: anil maran To: tutor at python.org Sent: Wednesday, September 13, 2006 12:14:10 AM Subject: encoding text in html i was trying to display some text it is in utf-8 in postgres and when it is displayed in firefox and ie, it gets displayed as some symols with 4numbers in a box or so even for ' apostrophe please tell me how to display this properly i try title.__str__ or title.__repr__ both dont work -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060913/f58c9b8b/attachment.html From anilmrn at yahoo.com Wed Sep 13 11:11:44 2006 From: anilmrn at yahoo.com (anil maran) Date: Wed, 13 Sep 2006 02:11:44 -0700 (PDT) Subject: [Tutor] encoding text in html In-Reply-To: <20060913090755.18876.qmail@web55912.mail.re3.yahoo.com> Message-ID: <20060913091144.56930.qmail@web55904.mail.re3.yahoo.com> ???????????30?TVCF?ver.0.1 this is how it is getting displayed in browser ----- Original Message ---- From: anil maran To: anil maran Sent: Wednesday, September 13, 2006 2:07:55 AM Subject: Re: [Tutor] encoding text in html i was trying to display some text it is in utf-8 in postgres and when it is displayed in firefox and ie, it gets displayed as some symols with 4numbers in a box or so even for ' apostrophe please tell me how to display this properly i try title.__str__ or title.__repr__ both dont work _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060913/a8b4985a/attachment.htm From kent37 at tds.net Wed Sep 13 11:59:02 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Sep 2006 05:59:02 -0400 Subject: [Tutor] encoding text in html In-Reply-To: <20060913091144.56930.qmail@web55904.mail.re3.yahoo.com> References: <20060913091144.56930.qmail@web55904.mail.re3.yahoo.com> Message-ID: <4507D666.2070600@tds.net> anil maran wrote: > > ???????????30?TVCF?ver.0.1 > > this is how it is getting displayed in browser I'm pretty sure that is not how We\xe2\x80\x99re displays; can you show an example of the same text as it is stored and as it displays? Kent > > ----- Original Message ---- > From: anil maran > To: anil maran > Sent: Wednesday, September 13, 2006 2:07:55 AM > Subject: Re: [Tutor] encoding text in html > > > > submits: We\xe2\x80\x99re pretty sur > this is how it is stored in postgres > please help me out > thanks > > > > ----- Original Message ---- > From: anil maran > To: tutor at python.org > Sent: Wednesday, September 13, 2006 12:14:10 AM > Subject: [Tutor] encoding text in html > > > i was trying to display some text > it is in utf-8 in postgres and when it is displayed in firefox and ie, > it gets displayed as some symols with 4numbers in a box or so > even for ' apostrophe > please tell me how to display this properly > i try > title.__str__ > > or title.__repr__ > both dont work > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Wed Sep 13 11:59:24 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Sep 2006 05:59:24 -0400 Subject: [Tutor] encoding text in html In-Reply-To: <20060913071410.95149.qmail@web55910.mail.re3.yahoo.com> References: <20060913071410.95149.qmail@web55910.mail.re3.yahoo.com> Message-ID: <4507D67C.2090102@tds.net> anil maran wrote: > > > i was trying to display some text > it is in utf-8 in postgres and when it is displayed in firefox and ie, > it gets displayed as some symols with 4numbers in a box or so > even for ' apostrophe > please tell me how to display this properly > i try > title.__str__ > > or title.__repr__ > both dont work Do you have the page encoding set to utf-8 in Firefox? You can do this with View / Character Encoding as a test. If it displays correctly when you set the encoding then you should include a meta tag in the HTML that sets the charset. Put this in the of the HTML: Kent From samrobertsmith at gmail.com Wed Sep 13 14:33:27 2006 From: samrobertsmith at gmail.com (linda.s) Date: Wed, 13 Sep 2006 05:33:27 -0700 Subject: [Tutor] about assert Message-ID: <1d987df30609130533v6f7c0538n785915ac28fa2555@mail.gmail.com> Python manual has a very brief introduction of "assert" statements. It is very difficult for me to understand it. Can anyone give me an example? Thanks, Linda From rabidpoobear at gmail.com Wed Sep 13 15:44:34 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 13 Sep 2006 08:44:34 -0500 Subject: [Tutor] about assert In-Reply-To: <1d987df30609130533v6f7c0538n785915ac28fa2555@mail.gmail.com> References: <1d987df30609130533v6f7c0538n785915ac28fa2555@mail.gmail.com> Message-ID: <45080B42.6050103@gmail.com> linda.s wrote: > Python manual has a very brief introduction of "assert" statements. It > is very difficult for me to understand it. Can anyone give me an > example? > #example of assert.py def test(a): if 25 / 4 == a: return True else: return False def assert_it(a): try: assert a print "Success!" except AssertionError: print "something went wrong!" f = test(4) assert_it(f) f = test(6) assert_it(f) #--- end code It seems to me that you don't really need to know what assert is, because the value of __debug__ will probably be true, and so you might as well write if not a: raise AssertionError instead, except I guess assert is shorter. But then if you use assert assuming __debug__ will be true, then if it's not bad things will happen. I'm sure someone can give you a better explanation of this, but I have to get to class. HTH, -Luke > Thanks, > Linda > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From marc_a_poulin at yahoo.com Wed Sep 13 15:47:25 2006 From: marc_a_poulin at yahoo.com (Marc Poulin) Date: Wed, 13 Sep 2006 06:47:25 -0700 (PDT) Subject: [Tutor] about assert In-Reply-To: <1d987df30609130533v6f7c0538n785915ac28fa2555@mail.gmail.com> Message-ID: <20060913134725.48309.qmail@web34102.mail.mud.yahoo.com> --- "linda.s" wrote: > Python manual has a very brief introduction of > "assert" statements. It > is very difficult for me to understand it. Every program has some fundamental assumptions that must remain true in order for the program to continue giving correct results. The assert statement is used to verify those assumptions. (The optional 2nd parameter can be used to give additional information about what went wrong.) For example, in my world no one is allowed to have a negative age. A negative age means my program is hopelessly confused and should halt immediately. >>> myAge=42 >>> assert myAge>=0 ## this is OK >>> myAge= -1 ## logically impossible >>> assert myAge >= 0 Traceback (most recent call last): File "", line 1, in ? AssertionError ## here I print the condition that failed >>> assert myAge >=0, 'myAge >= 0' Traceback (most recent call last): File "", line 1, in ? AssertionError: myAge >= 0 __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From dpotter at nc.rr.com Wed Sep 13 16:01:31 2006 From: dpotter at nc.rr.com (dpotter at nc.rr.com) Date: Wed, 13 Sep 2006 10:01:31 -0400 Subject: [Tutor] quick ? Message-ID: I am new to Python (and programming). In teaching myself I wrote a small program that will pick random lottery numbers, I want to check for duplicates and rerun the random function. But I am hitting a wall. This is what I think should work, but I still get duplicates. TIA. print "\n" count = input("How many quick picks do you need? ") print "\n" num = 0 while count > 0: num1 = randint(1,55) num2 = randint(1,55) while num2 == num1: # looking for duplicates num2 = randint(1,55) num3 = randint(1,55) while num3 == (num1 or num2): # looking for duplicates num3 = randint(1,55) num4 = randint(1,55) while num4 == (num1 or num2 or num3): # looking for duplicates num4 = randint(1,55) num5 = randint(1,55) while num5 == (num1 or num2 or num3 or num4): # looking for duplicates num5 = randint(1,55) pb = randint(1,42) count = count - 1 answer = [num1, num2, num3, num4, num5] answer.sort() num = num + 1 print "#",num, answer, "and for the powerball:", pb print "\n" From kent37 at tds.net Wed Sep 13 16:30:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Sep 2006 10:30:56 -0400 Subject: [Tutor] quick ? In-Reply-To: References: Message-ID: <45081620.90005@tds.net> dpotter at nc.rr.com wrote: > I am new to Python (and programming). In teaching myself I wrote a > small program that will pick random lottery numbers, I want to check for > duplicates and rerun the random function. But I am hitting a wall. > This is what I think should work, but I still get duplicates. TIA. > > > > print "\n" > count = input("How many quick picks do you need? ") > print "\n" > num = 0 > while count > 0: > num1 = randint(1,55) > num2 = randint(1,55) > while num2 == num1: > # looking for duplicates > num2 = randint(1,55) > num3 = randint(1,55) > while num3 == (num1 or num2): This doesn't do what you want; (num1 or num2) is evaluated first; the value of this expression will be num1, since num1 is not 0. Then you compare num3 to the result. You need while num3 == num1 or num3 == num2: or, a version that scales better: while num3 in [ num1, num2 ] or even better, take a look at random.sample() Kent > # looking for duplicates > num3 = randint(1,55) > num4 = randint(1,55) > while num4 == (num1 or num2 or num3): > # looking for duplicates > num4 = randint(1,55) > num5 = randint(1,55) > while num5 == (num1 or num2 or num3 or num4): > # looking for duplicates > num5 = randint(1,55) > pb = randint(1,42) > count = count - 1 > answer = [num1, num2, num3, num4, num5] > answer.sort() > num = num + 1 > print "#",num, answer, "and for the powerball:", pb > print "\n" > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kyrath at cox.net Wed Sep 13 15:51:51 2006 From: kyrath at cox.net (Rob) Date: Wed, 13 Sep 2006 09:51:51 -0400 Subject: [Tutor] CGI / HTTP Message-ID: <00c201c6d73b$c3ee8970$0701a8c0@kasil> I created a CGI form mailer script that would keep individual email addresses private. The emailer works fine and I have created similar scripts that work. However, I wanted to forward the info from a form without having the script return any content. So if there are no errors, the visitor would only get a javascript alert thanking them for contacting us, no page change is made. I've tried a couple of things and either get a 500 error or the browser tries to download the CGI script. I have a feeling that it has to do with HTTP headers. Except for content-type:, I don't know how to properly use HTTP headers from within a python CGI script. Is there a way to submit form data to a CGI script and not have anything returned? Thanks, -- Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060913/9e501f14/attachment.html From dyoo at hkn.eecs.berkeley.edu Wed Sep 13 16:37:51 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 13 Sep 2006 07:37:51 -0700 (PDT) Subject: [Tutor] encoding text in html In-Reply-To: <20060913071410.95149.qmail@web55910.mail.re3.yahoo.com> References: <20060913071410.95149.qmail@web55910.mail.re3.yahoo.com> Message-ID: On Wed, 13 Sep 2006, anil maran wrote: > > i was trying to display some text it is in utf-8 in postgres and when it > is displayed in firefox and ie, it gets displayed as some symols with > 4numbers in a box or so even for ' apostrophe please tell me how to > display this properly i try title.__str__ I'm assuming that you're dynamically generating some HTML document. If so, have you declared the "document encoding" in the HTML file to be utf-8? See: http://www.joelonsoftware.com/articles/Unicode.html Do you have a small sample of the HTML file that's being generated? One of us here may want to inspect it to make sure you really are generating UTF-8 output. You may also want to show the Python code you've written to generate the output. Try to give us enough information so we can attempt to reproduce what you're seeing. Good luck! From hmm at woolgathering.cx Wed Sep 13 17:15:44 2006 From: hmm at woolgathering.cx (William O'Higgins Witteman) Date: Wed, 13 Sep 2006 11:15:44 -0400 Subject: [Tutor] Excluding branches while walking directory tree Message-ID: <20060913151544.GA6574@sillyrabbi.dyndns.org> Hello all, I am looking for an approach for the following problem: I have to walk a directory tree and examine files within it. I have a set of directory names and filename patterns that I must skip while doing this walk. How do I create a set of rules to skip files or directory branches? I'm looking for something reasonably scalable, 'cause I'm sure to need to update these rules in the future. Thanks. -- yours, William From bgailer at alum.rpi.edu Wed Sep 13 17:18:57 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 13 Sep 2006 08:18:57 -0700 Subject: [Tutor] quick ? In-Reply-To: References: Message-ID: <45082161.2010207@alum.rpi.edu> dpotter at nc.rr.com wrote: > I am new to Python (and programming). In teaching myself I wrote a > small program that will pick random lottery numbers, I want to check for > duplicates and rerun the random function. But I am hitting a wall. > This is what I think should work, but I still get duplicates. TIA. random.shuffle() is the predefined way to do this. But for more general things like this it is better to use a list to hold multiple values. Example: import random picks = [] # collect unique picks count = input("How many quick picks do you need? ") while len(picks) < count: pick = random.randint(1,55) if not pick in picks: picks.append(pick) print picks OR import random picks = [0]*55 count = input("How many quick picks do you need? ") got = 0 while got < count: pick = random.randint(1,55) if not picks[pick]: picks[pick] = 1 got += 1 for i in range(len(picks)+1): if picks[i]: print i, -- Bob Gailer 510-978-4454 From kent37 at tds.net Wed Sep 13 17:34:25 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Sep 2006 11:34:25 -0400 Subject: [Tutor] Excluding branches while walking directory tree In-Reply-To: <20060913151544.GA6574@sillyrabbi.dyndns.org> References: <20060913151544.GA6574@sillyrabbi.dyndns.org> Message-ID: <45082501.1070006@tds.net> William O'Higgins Witteman wrote: > Hello all, > > I am looking for an approach for the following problem: > > I have to walk a directory tree and examine files within it. I have a > set of directory names and filename patterns that I must skip while > doing this walk. How do I create a set of rules to skip files or > directory branches? I'm looking for something reasonably scalable, > 'cause I'm sure to need to update these rules in the future. os.walk() lets you prune the directory list to avoid processing specific directories. fnmatch.fnmatch() does simple wildcard pattern matching. So maybe something like this (*not* tested): import os, fnmatch def matchesAny(name, tests): for test in tests: if fnmatch.fnmatch(name, test): return True return False dirsToSkip = [ ... ] # list of directory patterns to skip filesToSkip = [ ... ] # list of file patterns to skip for dirpath, dirnames, filenames in os.walk(baseDir): # Note use of slice assignment - you have to modify the caller's list dirnames[:] = [ name for name in dirnames if not matchesAny(name, dirsToSkip) ] filenames = [name for name in filenames if not matchesAny(name, filesToSkip) ] for name in filenames: # whatever file processing you want to do goes here You could get the list of patterns from another file that you import, or a config file, or command line args, depending on how you want to store them and change them. For more flexibility in the patterns you could use a regular expression match instead of fnmatch(). You also might want to match on full paths rather than just the file or dir name. HTH, Kent From ziad.rahhal at gmail.com Wed Sep 13 17:39:13 2006 From: ziad.rahhal at gmail.com (Ziad Rahhal) Date: Wed, 13 Sep 2006 17:39:13 +0200 Subject: [Tutor] Using my own installed python version in my directory tree. Message-ID: Hi, I installed pythin on Linux operating system but on my own tree directory. Now I want to get rid (not deleting) the default python installation, which means I want my own python version to be recognized when I use "python" command. PYTHONPATH has nothing to do with that since it just points to modules. I tried to set the PATH to $HOME/python/bin but this didn't work. So in bried I want to use my own installed python version in my directory without the need to type $HOME/python/bin... and I want to use my own installed python libraries and modules, ignoring the default installation. How that could be done? Thank you in advance, Ziad -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060913/7fe8168f/attachment.htm From dkuhlman at rexx.com Wed Sep 13 17:53:51 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 13 Sep 2006 08:53:51 -0700 Subject: [Tutor] Excluding branches while walking directory tree In-Reply-To: <20060913151544.GA6574@sillyrabbi.dyndns.org> References: <20060913151544.GA6574@sillyrabbi.dyndns.org> Message-ID: <20060913155351.GA18012@cutter.rexx.com> On Wed, Sep 13, 2006 at 11:15:44AM -0400, William O'Higgins Witteman wrote: > Hello all, > > I am looking for an approach for the following problem: > > I have to walk a directory tree and examine files within it. I have a > set of directory names and filename patterns that I must skip while > doing this walk. How do I create a set of rules to skip files or > directory branches? I'm looking for something reasonably scalable, > 'cause I'm sure to need to update these rules in the future. > For the first part of your problem, take a look at os.walk(): http://docs.python.org/lib/os-file-dir.html And also glob.glob(): http://docs.python.org/lib/module-glob.html The "in" operator is likely to be helpful in determining which files to skip. Suppose that you have a list of file names to be ignored: skips = ['ignore1.txt', 'ignore2.txt'] then check a filename against the names to be skipped: if filename not in skips: # process the files not to be ignored here. And, for more complex cases, you may want to write a test function that returns True or False depending on whether the file is to be ignored. A trivial example: def good_file(filename, skips): if filename in skips: return False else: return True skips = ['ignore1.txt', 'ignore2.txt'] if good_file(filename, skips): # process good files here o o o Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From dkuhlman at rexx.com Wed Sep 13 18:28:03 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 13 Sep 2006 09:28:03 -0700 Subject: [Tutor] Using my own installed python version in my directory tree. In-Reply-To: References: Message-ID: <20060913162803.GB18012@cutter.rexx.com> On Wed, Sep 13, 2006 at 05:39:13PM +0200, Ziad Rahhal wrote: > Hi, > > I installed pythin on Linux operating system but on my own tree directory. > Now I want to get rid (not deleting) > the default python installation, which means I want my own python version to > be recognized when I use "python" command. > > PYTHONPATH has nothing to do with that since it just points to modules. I > tried to set the PATH to $HOME/python/bin but this > didn't work. > > So in bried I want to use my own installed python version in my directory > without the need to type $HOME/python/bin... and I want > to use my own installed python libraries and modules, ignoring the default > installation. > > How that could be done? 1. The first part of your problem (not typing $HOME/python/bin... each time could be solved in either of two ways: - Create an alias: alias python='$HOME/python/bin/...' - Create a symbolic link in a directory that is on your PATH *before* the directories containing other pythons: ln -s $HOME/python/bin... python 2. With respect to importing up modules from the correct location, if you have installed Python correctly, using your python executable will also tell python where to look for modules. I also have two Pythons installed on my Linux machine (maybe more, I'm not sure). One is under /usr and the other under /usr/local. When I run /usr/bin/python, it uses the modules installed under /usr/lib/python2.4/site-packages/. And, when I run /usr/local/bin/python, it uses modules installed under /usr/local/lib/python2.4/site-packages/. You can check this by doing something like: ~ [5] /usr/bin/python Python 2.4.3 (#2, Apr 27 2006, 14:43:58) [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> import sys >>> sys.path which tells you where python looks for modules to be imported. And, by the way, when you install a python package/module by using: $ python setup.py install python will install the package in the correct location depending on which python executable you use to do the install. So, the following two lines install a module in two different places: $ /usr/bin/python setup.py install $ /usr/local/bin/python setup.py install Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From fedekiller at gmail.com Wed Sep 13 19:29:07 2006 From: fedekiller at gmail.com (federico ramirez) Date: Wed, 13 Sep 2006 14:29:07 -0300 Subject: [Tutor] python for web developing Message-ID: <26a78a3c0609131029i49da17e4m1fd6355c8cd91326@mail.gmail.com> Hello! I have heard that python is very good for web development, but you need frameworks, like django or turbogears. I know that you dont really need them, you can just write cgi scripts with python...but Im a php programmer, and i want to make another dinamic site with sql, in python, but i need sql object or other sql... And i cant get a host with it, a free host just to test it. Any recomendations? -- Best Regards. fedekiller -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060913/d030efd6/attachment.htm From kent37 at tds.net Wed Sep 13 19:46:14 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Sep 2006 13:46:14 -0400 Subject: [Tutor] CGI / HTTP In-Reply-To: <00c201c6d73b$c3ee8970$0701a8c0@kasil> References: <00c201c6d73b$c3ee8970$0701a8c0@kasil> Message-ID: <450843E6.5010309@tds.net> Rob wrote: > > I created a CGI form mailer script that would keep individual email > addresses private. > > The emailer works fine and I have created similar scripts that work. > However, I wanted to forward the info from a form without having the > script return any content. So if there are no errors, the visitor would > only get a javascript alert thanking them for contacting us, no page > change is made. > > I've tried a couple of things and either get a 500 error or the browser > tries to download the CGI script. I have a feeling that it has to do > with HTTP headers. Except for content-type:, I don't know how to > properly use HTTP headers from within a python CGI script. > > Is there a way to submit form data to a CGI script and not have anything > returned? This is not really a Python question...when you submit a form in the normal way, the browser expects the server to respond with a new page which the browser displays. So I don't think you can submit a form with a normal POST and keep the same page display. You need to look at alternate methods to send the data to the server such as XmlHttpRequest (AJAX). Google "ajax form submit" for lots of suggestions. Kent From josipl2000 at yahoo.com Wed Sep 13 19:54:36 2006 From: josipl2000 at yahoo.com (josip) Date: Wed, 13 Sep 2006 10:54:36 -0700 (PDT) Subject: [Tutor] what happens when... Message-ID: <20060913175436.83265.qmail@web60815.mail.yahoo.com> Hi all! Can You explain me what happens when in this function I remove board arg: def human_move(board, human)? What is doing that argument? Thanks! # global constants X = "X" O = "O" EMPTY = " " TIE = "TIE" NUM_SQUARES = 9 def display_instruct(): """Display game instructions.""" print \ """ Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe. This will be a showdown between your human brain and my silicon processor. You will make your move known by entering a number, 0 - 8. The number will correspond to the board position as illustrated: 0 | 1 | 2 --------- 3 | 4 | 5 --------- 6 | 7 | 8 Prepare yourself, human. The ultimate battle is about to begin. \n """ def ask_yes_no(question): """Ask a yes or no question.""" response = None while response not in ("y", "n"): response = raw_input(question).lower() return response def ask_number(question, low, high, step=1): """Ask for a number within a range.""" response = None while response not in range(low, high, step): response = int(raw_input(question)) return response def pieces(): """Determine if player or computer goes first.""" go_first = ask_yes_no("Do you require the first move? (y/n): ") if go_first == "y": print "\nThen take the first move. You will need it." human = X computer = O else: print "\nYour bravery will be your undoing... I will go first." computer = X human = O return computer, human def new_board(): """Create new game board.""" board = [] for square in range(NUM_SQUARES): board.append(EMPTY) return board def display_board(board): """Display game board on screen.""" print "\n\t", board[0], "|", board[1], "|", board[2] print "\t", "---------" print "\t", board[3], "|", board[4], "|", board[5] print "\t", "---------" print "\t", board[6], "|", board[7], "|", board[8], "\n" def legal_moves(board): """Create list of legal moves.""" moves = [] for square in range(NUM_SQUARES): if board[square] == EMPTY: moves.append(square) return moves def winner(board): """Determine the game winner.""" WAYS_TO_WIN = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)) for row in WAYS_TO_WIN: if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY: winner = board[row[0]] return winner if EMPTY not in board: return TIE return None def human_move(human): # <= here is board removed """Get human move.""" legal = legal_moves(board) move = None while move not in legal: move = ask_number("Where will you move? (0 - 8):", 0, NUM_SQUARES) if move not in legal: print "\nThat square is already occupied, foolish human. Choose another.\n" print "Fine.." return move def computer_move(board, computer, human): """Make computer move.""" # make a copy to work with since function will be changing list board = board[:] # the best positions to have, in order BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7) print "I shall take square number", # if computer can win, take that move for move in legal_moves(board): board[move] = computer if winner(board) == computer: print move return move # done checking this move, undo it board[move] = EMPTY # if human can win, block that move for move in legal_moves(board): board[move] = human if winner(board) == human: print move return move # done checkin this move, undo it board[move] = EMPTY # since no one can win on next move, pick best open square for move in BEST_MOVES: if move in legal_moves(board): print move return move def next_turn(turn): """Switch turns.""" if turn == X: return O else: return X def congrat_winner(the_winner, computer, human): """Congratulate the winner.""" if the_winner != TIE: print the_winner, "won!\n" else: print "It's a tie!\n" if the_winner == computer: print "As I predicted, human, I am triumphant once more. \n" \ "Proof that computers are superior to humans in all regards." elif the_winner == human: print "No, no! It cannot be! Somehow you tricked me, human. \n" \ "But never again! I, the computer, so swears it!" elif the_winner == TIE: print "You were most lucky, human, and somehow managed to tie me. \n" \ "Celebrate today... for this is the best you will ever achieve." def main(): display_instruct() computer, human = pieces() turn = X board = new_board() display_board(board) while not winner(board): if turn == human: move = human_move(human) #and here is board removed board[move] = human else: move = computer_move(board, computer, human) board[move] = computer display_board(board) turn = next_turn(turn) the_winner = winner(board) congrat_winner(the_winner, computer, human) # start the program main() raw_input("\n\nPress the enter key to quit.") --------------------------------- Yahoo! Messenger with Voice. Make PC-to-Phone Calls to the US (and 30+ countries) for 2?/min or less. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060913/53ef95b9/attachment.htm From alan.gauld at freenet.co.uk Wed Sep 13 20:11:10 2006 From: alan.gauld at freenet.co.uk (alan.gauld at freenet.co.uk) Date: Wed, 13 Sep 2006 19:11:10 +0100 Subject: [Tutor] about assert Message-ID: <380-220069313181110264@freenet.co.uk> >>Python manual has a very brief introduction >>of "assert" statements. It is very difficult First you probably don't need to use asserts very often, they are useful if you are building production strength code but for most users of Python the exception mechanism is good enough. Basically we use asserts to check pre and post conditions as well as\ invariants in functions. Anything other than that should be done using explicit if/else or exceptions. The reason for that is that asserts only operate when the code is in debug mode... so they should not be used for normal run time error detection. Typical things to check are that input values are within expected ranges and of desired types. Also that the final retrurn value of a function is within expected limits. Once we finish testing the overhead of those checks might not be required in the final version if we are sure they will never deviate from the test results. The syntax can be demonstrated quite easily and Luke has done that, the intent is a little less obvious and IMHO really needs a larger example to make the value obvious. Since I'm at a cyber-cafe net terminal I dont feel like trying that just now! :-) HTH, Alan G. From srini_iyyer_bio at yahoo.com Wed Sep 13 21:17:38 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 13 Sep 2006 12:17:38 -0700 (PDT) Subject: [Tutor] List manipulation Message-ID: <20060913191738.32612.qmail@web38115.mail.mud.yahoo.com> Dear group: I have a data like this: 10 15 16 20 25 35 45 50 55 60 61 65 75 80 Since 15 precedes 16, I want to consider 10:20 as one unit. If I repeat completely for data I would get: 10 20 25 35 45 50 55 65 75 80 test = ['10\t15', '16\t20', '25\t35', '45\t50', '55\t60', '61\t65', '75\t80'] I cannot think a way to do this in simple. Could members suggest some way to solve this please. thanks __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From singh01 at gmail.com Wed Sep 13 21:25:21 2006 From: singh01 at gmail.com (Nagendra Singh) Date: Wed, 13 Sep 2006 15:25:21 -0400 Subject: [Tutor] GDAL- Help Message-ID: Hi, I am just starting to learn Python and I want to perform some GIS tasks which requires the gdal module (http://www.gdal.org/). I have installed FWTools which also comes with a built in Python interface but I also have a stand alone version of Python which I use. I am trying to use the gdal module but I keep getting an error message that gdal module is not found,even after appending the module using the sys.path.append command. Can you anyone please let me know how do I use the gdal module in the python I have (I dowlloaded it from activestate) or I have to use the Python which comes with gdal but it does not offer me the IDE. thanks in advance Nagendra From marc_a_poulin at yahoo.com Wed Sep 13 21:34:30 2006 From: marc_a_poulin at yahoo.com (Marc Poulin) Date: Wed, 13 Sep 2006 12:34:30 -0700 (PDT) Subject: [Tutor] about assert In-Reply-To: <380-220069313181110264@freenet.co.uk> Message-ID: <20060913193430.43057.qmail@web34105.mail.mud.yahoo.com> --- alan.gauld at freenet.co.uk wrote: > >>Python manual has a very brief introduction > >>of "assert" statements. It is very difficult > > First you probably don't need to use asserts > very often, they are useful if you are building > production strength code but for most users > of Python the exception mechanism is good enough. > This link makes some good points about how and when to use assertions: http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From bgailer at alum.rpi.edu Wed Sep 13 21:49:33 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 13 Sep 2006 12:49:33 -0700 Subject: [Tutor] List manipulation In-Reply-To: <20060913191738.32612.qmail@web38115.mail.mud.yahoo.com> References: <20060913191738.32612.qmail@web38115.mail.mud.yahoo.com> Message-ID: <450860CD.7050608@alum.rpi.edu> Srinivas Iyyer wrote: > Dear group: > > I have a data like this: > 10 15 > 16 20 > 25 35 > 45 50 > 55 60 > 61 65 > 75 80 > > Since 15 precedes 16, I want to consider 10:20 as one > unit. If I repeat completely for data > > I would get: > 10 20 > 25 35 > 45 50 > 55 65 > 75 80 > > test = ['10\t15', '16\t20', '25\t35', '45\t50', > '55\t60', '61\t65', '75\t80'] > > > I cannot think a way to do this in simple. Could > members suggest some way to solve this please. > I assume by "precedes" you mean is one-less-than. To test this you should convert the strings into integers. Since the numbers come in pairs each pair must be split at the \t (using split), then convert each number to integer (using int). Hope that's enough to get you started. -- Bob Gailer 510-978-4454 From pyro9219 at gmail.com Wed Sep 13 22:40:26 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 13 Sep 2006 13:40:26 -0700 Subject: [Tutor] Methods and classes Message-ID: <1158180026.25247.4.camel@localhost> Can anyone explain what I've been reading? I'm trying to understand why many documents show: def myMethod(vars): or class myClass(var): and others show: def myMetheod(self, vars) or class myClass(self, vars) Either way seems to work fine, so I'm not sure what it happening. Also, what is with the double underscores? (__init__ for example) is this required? or a Pythonic naming convention? When and how to use? I'm 'trying' to write clear pythonic code since in all reality it gives a nice polish to the code when compared to writing c style. Thanks. From srini_iyyer_bio at yahoo.com Wed Sep 13 22:47:47 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 13 Sep 2006 13:47:47 -0700 (PDT) Subject: [Tutor] List manipulation In-Reply-To: <450860CD.7050608@alum.rpi.edu> Message-ID: <20060913204747.85059.qmail@web38113.mail.mud.yahoo.com> Thank you Bob for your email. Sorry for the confusion. here is what I ment: test = ['10\t15', '16\t20', '25\t35', '45\t50', '55\t60', '61\t65', '75\t80'] >>> x = [] >>> y = [] >>> for m in test: ... cols = m.split('\t') ... x.append(cols[0]) ... y.append(cols[1]) ... >>> x ['10', '16', '25', '45', '55', '61', '75'] >>> y ['15', '20', '35', '50', '60', '65', '80'] >>> for m in range(0,6): ... k = m+1 ... if int(x[k])-int(y[m])==1: ... print x[m]+'\t'+y[k] ... else: ... print x[m]+'\t'+y[m] ... 10 20 16 20 # This is unwanted ##### 25 35 45 50 55 65 61 65# This is unwanted ##### 75 80 # IS MISSING from result### 16-20 and 61-65 is unwanted, to get rid of these I am doing these. My desired result: 10 20 25 35 45 50 55 65 75 80 If I consider the length of the list: >>> for m in range(0,7): ... k = m+1 ... if int(x[k])-int(y[m])==1: ... print x[m]+'\t'+y[k] ... else: ... print x[m]+'\t'+y[m] ... 10 20 16 20 25 35 45 50 55 65 61 65 Traceback (most recent call last): File "", line 3, in ? IndexError: list index out of range How can I avoid 16-20 and 61-65 and get 75-80 in the result. Also, is there any easy way to do this. Thanks --- Bob Gailer wrote: > Srinivas Iyyer wrote: > > Dear group: > > > > I have a data like this: > > 10 15 > > 16 20 > > 25 35 > > 45 50 > > 55 60 > > 61 65 > > 75 80 > > > > Since 15 precedes 16, I want to consider 10:20 as > one > > unit. If I repeat completely for data > > > > I would get: > > 10 20 > > 25 35 > > 45 50 > > 55 65 > > 75 80 > > > > test = ['10\t15', '16\t20', '25\t35', '45\t50', > > '55\t60', '61\t65', '75\t80'] > > > > > > I cannot think a way to do this in simple. Could > > members suggest some way to solve this please. > > > I assume by "precedes" you mean is one-less-than. To > test this you > should convert the strings into integers. Since the > numbers come in > pairs each pair must be split at the \t (using > split), then convert each > number to integer (using int). > > Hope that's enough to get you started. > > -- > Bob Gailer > 510-978-4454 > > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From john at fouhy.net Wed Sep 13 23:18:47 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 14 Sep 2006 09:18:47 +1200 Subject: [Tutor] Methods and classes In-Reply-To: <1158180026.25247.4.camel@localhost> References: <1158180026.25247.4.camel@localhost> Message-ID: <5e58f2e40609131418n4bcf7adfwc8ea85d967c49d85@mail.gmail.com> On 14/09/06, Chris Hengge wrote: > Can anyone explain what I've been reading? I'm trying to understand why > many documents show: > def myMethod(vars): > or > class myClass(var): > and others show: > def myMetheod(self, vars) > or > class myClass(self, vars) Um. Can you give an example of something saying "class myClass(self, vars)" ? The "arguments" to a class are other classes that you want to inherit from, and are different from function arguments! As to your other question, though --- Suppose I have a class: class MyClass(object): # etc And suppose I create an instance of that class: mc = MyClass() And then I call a method on that instance: mc.someFunc(3, 'foo') Although I have given the function someFunc two arguments, it will actually be passed _three_ arguments. The first argument will be mc itself. So, in the definition of MyClass, you would have: def someFunc(self, x, s): # etc "self" is the name traditionally given to the first parameter, which receives the class instance. If you wanted to make things explicit, you could instead do: MyClass.someFunc(mc, 3, 'foo') I think this is exactly equivalent to mc.someFunc(3, 'foo'). (someone confirm?) On the other hand, if you're writing a utility function that's not part of a class, you won't give it a "self" parameter. Hope this helps :-) > Also, what is with the double underscores? (__init__ for example) is > this required? or a Pythonic naming convention? When and how to use? Various special methods have the form "__xxx__". For example, the builtin function str converts things into strings. str is associated with the special method __str__. If you write: s = str(o) this is equivalent to: s = o.__str__() and you can define / override the __str__ function in your own classes to control how they are converted to strings. Also, there is a convention that variable names starting with a single underscore are private (since there's no "true" concept of private/public in python). Variable names starting with two underscores are "more private", and python mangles the name a bit. eg, try the following: class Foo(object): def __init__(self): self.x = 1 self._y = 2 self.__z = 3 f = Foo() print f.x print f._y print f.__z > I'm 'trying' to write clear pythonic code since in all reality it gives > a nice polish to the code when compared to writing c style. I don't think you'll find many here who disagree with that :-) -- John. From john at fouhy.net Wed Sep 13 23:21:25 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 14 Sep 2006 09:21:25 +1200 Subject: [Tutor] what happens when... In-Reply-To: <20060913175436.83265.qmail@web60815.mail.yahoo.com> References: <20060913175436.83265.qmail@web60815.mail.yahoo.com> Message-ID: <5e58f2e40609131421n2ce21fc1v9c9aad60ce506517@mail.gmail.com> On 14/09/06, josip wrote: > > Hi all! > Can You explain me what happens when in this function I remove board arg: > def human_move(board, human)? > What is doing that argument? Have you tried removing the argument and running the code? What error message do you get? What do you think it means? -- John. From pyro9219 at gmail.com Wed Sep 13 23:57:12 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 13 Sep 2006 14:57:12 -0700 Subject: [Tutor] Methods and classes In-Reply-To: <5e58f2e40609131418n4bcf7adfwc8ea85d967c49d85@mail.gmail.com> References: <1158180026.25247.4.camel@localhost> <5e58f2e40609131418n4bcf7adfwc8ea85d967c49d85@mail.gmail.com> Message-ID: <1158184632.25247.14.camel@localhost> OK, now that you asked for an example of a class using 'self', I can't find it..so either the thing I was reading was wrong... or I dreamed it up.. or it was something specific that I was looking at that decided I wasn't interested in and now I don't remember. As for a quick example of the methods using (self, variables).. the first example I've found of my list of resources is the deitel book "Python - How to Program" Every method I've seen in this particular book places 'self' as a parameter for each method. I am sure I've seen this in at least one other book, as well as a few websites I've hit. The deitel book has a note on page 229: Failure to specify an object reference (usually called self) as the first parameter in a method definition causes fatal logic errors when the method is invoked at runt-ime. Now I've got methods all over the place among several scripts that don't use self, and each other works fine as I'd expect. Thanks for the other information! On Thu, 2006-09-14 at 09:18 +1200, John Fouhy wrote: > On 14/09/06, Chris Hengge wrote: > > Can anyone explain what I've been reading? I'm trying to understand why > > many documents show: > > def myMethod(vars): > > or > > class myClass(var): > > and others show: > > def myMetheod(self, vars) > > or > > class myClass(self, vars) > > Um. Can you give an example of something saying "class myClass(self, > vars)" ? The "arguments" to a class are other classes that you want > to inherit from, and are different from function arguments! > > As to your other question, though --- > > Suppose I have a class: > > class MyClass(object): > # etc > > And suppose I create an instance of that class: > > mc = MyClass() > > And then I call a method on that instance: > > mc.someFunc(3, 'foo') > > Although I have given the function someFunc two arguments, it will > actually be passed _three_ arguments. The first argument will be mc > itself. So, in the definition of MyClass, you would have: > > def someFunc(self, x, s): > # etc > > "self" is the name traditionally given to the first parameter, which > receives the class instance. If you wanted to make things explicit, > you could instead do: > > MyClass.someFunc(mc, 3, 'foo') > > I think this is exactly equivalent to mc.someFunc(3, 'foo'). (someone confirm?) > > On the other hand, if you're writing a utility function that's not > part of a class, you won't give it a "self" parameter. > > Hope this helps :-) > > > Also, what is with the double underscores? (__init__ for example) is > > this required? or a Pythonic naming convention? When and how to use? > > Various special methods have the form "__xxx__". For example, the > builtin function str converts things into strings. str is associated > with the special method __str__. If you write: > > s = str(o) > > this is equivalent to: > > s = o.__str__() > > and you can define / override the __str__ function in your own classes > to control how they are converted to strings. > > Also, there is a convention that variable names starting with a single > underscore are private (since there's no "true" concept of > private/public in python). Variable names starting with two > underscores are "more private", and python mangles the name a bit. > > eg, try the following: > > class Foo(object): > def __init__(self): > self.x = 1 > self._y = 2 > self.__z = 3 > > f = Foo() > print f.x > print f._y > print f.__z > > > I'm 'trying' to write clear pythonic code since in all reality it gives > > a nice polish to the code when compared to writing c style. > > I don't think you'll find many here who disagree with that :-) > From john at fouhy.net Thu Sep 14 00:15:23 2006 From: john at fouhy.net (John Fouhy) Date: Thu, 14 Sep 2006 10:15:23 +1200 Subject: [Tutor] Methods and classes In-Reply-To: <1158184632.25247.14.camel@localhost> References: <1158180026.25247.4.camel@localhost> <5e58f2e40609131418n4bcf7adfwc8ea85d967c49d85@mail.gmail.com> <1158184632.25247.14.camel@localhost> Message-ID: <5e58f2e40609131515p49c494efp7ac6f8f7f995c976@mail.gmail.com> On 14/09/06, Chris Hengge wrote: > The deitel book has a note on page 229: > Failure to specify an object reference (usually called self) as the > first parameter in a method definition causes fatal logic errors when > the method is invoked at runt-ime. > > Now I've got methods all over the place among several scripts that don't > use self, and each other works fine as I'd expect. It depends whether you're writing class methods or not. I could do this, for example: def increment(x): return x+1 and that would be fine, with no self parameter. It's just a standalone function. OTOH, I might decide I want to write my own integer wrapper. class MyInt(object): def __init__(self, i): self.value = i I would create an instance of MyInt like so: i = MyInt(3) The parameter 3 gets passed to __init__ as 'i'. If I left out 'self', python would complain that __init__ only takes one argument and I've given it two. I could define a MyInt method like this: def increment(self): self.value = self.value + 1 thus: >>> i.increment() >>> i.increment() >>> print i.value 5 How would you write increment() without a self parameter? You need some way of referring to the "value" attribute of the instance. If you just write "value = value + 1", python will think you are talking about a local variable, and complain because it can't find one with that name. If you write: def increment(): self.value = self.value + 1 then you're referring to this variable called "self", but where is it coming from? There's no global variable "self", it's not one of the parameters to the method, and you're not defining it in the method. Does that help at all? -- John. From kent37 at tds.net Thu Sep 14 00:26:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Sep 2006 18:26:53 -0400 Subject: [Tutor] Methods and classes In-Reply-To: <1158184632.25247.14.camel@localhost> References: <1158180026.25247.4.camel@localhost> <5e58f2e40609131418n4bcf7adfwc8ea85d967c49d85@mail.gmail.com> <1158184632.25247.14.camel@localhost> Message-ID: <450885AD.2020506@tds.net> Chris Hengge wrote: > The deitel book has a note on page 229: > Failure to specify an object reference (usually called self) as the > first parameter in a method definition causes fatal logic errors when > the method is invoked at runt-ime. > > Now I've got methods all over the place among several scripts that don't > use self, and each other works fine as I'd expect. You have to distinguish between a method (a function that is part of a class definition) and a standalone function (not part of any class). Python allows both. Standalone functions don't have a 'self' parameter; class methods always do (you can give it a different name but if you omit it you will get a runtime error when you call the method). Kent From pyro9219 at gmail.com Thu Sep 14 00:30:08 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 13 Sep 2006 15:30:08 -0700 Subject: [Tutor] Methods and classes In-Reply-To: <450885AD.2020506@tds.net> References: <1158180026.25247.4.camel@localhost> <5e58f2e40609131418n4bcf7adfwc8ea85d967c49d85@mail.gmail.com> <1158184632.25247.14.camel@localhost> <450885AD.2020506@tds.net> Message-ID: <1158186609.25247.19.camel@localhost> On Wed, 2006-09-13 at 18:26 -0400, Kent Johnson wrote: > Chris Hengge wrote: > > The deitel book has a note on page 229: > > Failure to specify an object reference (usually called self) as the > > first parameter in a method definition causes fatal logic errors when > > the method is invoked at runt-ime. > > > > Now I've got methods all over the place among several scripts that don't > > use self, and each other works fine as I'd expect. > > You have to distinguish between a method (a function that is part of a > class definition) and a standalone function (not part of any class). > Python allows both. Standalone functions don't have a 'self' parameter; > class methods always do (you can give it a different name but if you > omit it you will get a runtime error when you call the method). > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor So just make sure I always declare self for methods (functions in classes)? Is this unique to python? or do some other languages already include self, and just hide it from the programmer? From kent37 at tds.net Thu Sep 14 01:00:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Sep 2006 19:00:50 -0400 Subject: [Tutor] Methods and classes In-Reply-To: <1158186609.25247.19.camel@localhost> References: <1158180026.25247.4.camel@localhost> <5e58f2e40609131418n4bcf7adfwc8ea85d967c49d85@mail.gmail.com> <1158184632.25247.14.camel@localhost> <450885AD.2020506@tds.net> <1158186609.25247.19.camel@localhost> Message-ID: <45088DA2.5040901@tds.net> Chris Hengge wrote: > On Wed, 2006-09-13 at 18:26 -0400, Kent Johnson wrote: >> You have to distinguish between a method (a function that is part of a >> class definition) and a standalone function (not part of any class). >> Python allows both. Standalone functions don't have a 'self' parameter; >> class methods always do (you can give it a different name but if you >> omit it you will get a runtime error when you call the method). >> >> Kent >> > So just make sure I always declare self for methods (functions in > classes)? Is this unique to python? or do some other languages already > include self, and just hide it from the programmer? All the OO languages I know have a similar concept. Python is more explicit than most. Java has a 'this' variable that is magically defined in the scope of any method. For most accesses to member variables and methods you don't even have to specify 'this' - the language figures it out for you. Ruby uses a naming convention to refer to attributes inside a method (attribute names start with @) One of the guiding principles of Python is "explicit is better than implicit" and the explicit declaration and use of 'self' is consistent with this. Kent From pyro9219 at gmail.com Thu Sep 14 01:39:22 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 13 Sep 2006 16:39:22 -0700 Subject: [Tutor] Input mask for console? Message-ID: <1158190762.25247.23.camel@localhost> I need either a way to mask the input from a console, or a method to not display the typed characters to the screen. Someone point me in the right direction? Thanks. From kent37 at tds.net Thu Sep 14 01:48:58 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Sep 2006 19:48:58 -0400 Subject: [Tutor] Input mask for console? In-Reply-To: <1158190762.25247.23.camel@localhost> References: <1158190762.25247.23.camel@localhost> Message-ID: <450898EA.4030806@tds.net> Chris Hengge wrote: > I need either a way to mask the input from a console, or a method to not > display the typed characters to the screen. Someone point me in the > right direction? getpass.getpass() ? Kent From pyro9219 at gmail.com Thu Sep 14 02:54:24 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 13 Sep 2006 17:54:24 -0700 Subject: [Tutor] Input mask for console? In-Reply-To: <450898EA.4030806@tds.net> References: <1158190762.25247.23.camel@localhost> <450898EA.4030806@tds.net> Message-ID: <1158195264.25247.26.camel@localhost> I'm assuming I can use that like usrpass = getpass.getpass(raw_input("Password: ")) On Wed, 2006-09-13 at 19:48 -0400, Kent Johnson wrote: > Chris Hengge wrote: > > I need either a way to mask the input from a console, or a method to not > > display the typed characters to the screen. Someone point me in the > > right direction? > > getpass.getpass() ? > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From pyro9219 at gmail.com Thu Sep 14 02:55:40 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 13 Sep 2006 17:55:40 -0700 Subject: [Tutor] Input mask for console? In-Reply-To: <450898EA.4030806@tds.net> References: <1158190762.25247.23.camel@localhost> <450898EA.4030806@tds.net> Message-ID: <1158195340.25247.27.camel@localhost> nevermind.. figured it out.. Thanks. On Wed, 2006-09-13 at 19:48 -0400, Kent Johnson wrote: > Chris Hengge wrote: > > I need either a way to mask the input from a console, or a method to not > > display the typed characters to the screen. Someone point me in the > > right direction? > > getpass.getpass() ? > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From bgailer at alum.rpi.edu Thu Sep 14 06:33:44 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 13 Sep 2006 21:33:44 -0700 Subject: [Tutor] List manipulation In-Reply-To: <20060913204747.85059.qmail@web38113.mail.mud.yahoo.com> References: <20060913204747.85059.qmail@web38113.mail.mud.yahoo.com> Message-ID: <4508DBA8.9020505@alum.rpi.edu> try this: >>> test = ['10\t15', '16\t20', '25\t35', '45\t50','55\t60', '61\t65', '75\t80'] >>> t='\t'.join(test).split('\t') >>> t ['10', '15', '16', '20', '25', '35', '45', '50', '55', '60', '61', '65', '75', '80'] >>> t2=[int(i) for i in t] >>> t2 [10, 15, 16, 20, 25, 35, 45, 50, 55, 60, 61, 65, 75, 80] >>> l= t2[0] >>> for i in range(1,len(t2)-1,2): ... if t2[i+1]-t2[i]>1: ... print l, '\t', t2[i] ... l = t2[i+1] 10 20 25 35 45 50 55 65 >>> print l, '\t', t2[-1] 75 80 -- Bob Gailer 510-978-4454 From rabidpoobear at gmail.com Thu Sep 14 07:58:30 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 14 Sep 2006 00:58:30 -0500 Subject: [Tutor] Methods and classes In-Reply-To: <45088DA2.5040901@tds.net> References: <1158180026.25247.4.camel@localhost> <5e58f2e40609131418n4bcf7adfwc8ea85d967c49d85@mail.gmail.com> <1158184632.25247.14.camel@localhost> <450885AD.2020506@tds.net> <1158186609.25247.19.camel@localhost> <45088DA2.5040901@tds.net> Message-ID: <4508EF86.1050801@gmail.com> [snip some] >> So just make sure I always declare self for methods (functions in >> classes)? Is this unique to python? or do some other languages already >> include self, and just hide it from the programmer? >> > > All the OO languages I know have a similar concept. Python is more > explicit than most. Java has a 'this' variable that is magically defined > in the scope of any method. For most accesses to member variables and > methods you don't even have to specify 'this' - the language figures it > out for you. Ruby uses a naming convention to refer to attributes inside > a method (attribute names start with @) [snip some more] Note that you can call the class instance that's passed around to the functions whatever you want. 'self','fish', 'banana', 'octopus', 's'. However, if you attempt to name it something other than 'self', or occasionally 's', other programmers might get scared. Especially if you name it 'int' or something :) HTH, -Luke > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From josipl2000 at yahoo.com Thu Sep 14 09:40:20 2006 From: josipl2000 at yahoo.com (josip) Date: Thu, 14 Sep 2006 00:40:20 -0700 (PDT) Subject: [Tutor] what happens when... In-Reply-To: <5e58f2e40609131421n2ce21fc1v9c9aad60ce506517@mail.gmail.com> Message-ID: <20060914074020.93266.qmail@web60818.mail.yahoo.com> When I remove board I get message: global name 'board' is not defined. Ok I understand that. But I would like to get some explaination to understand better. Thanks! John Fouhy wrote: On 14/09/06, josip wrote: > > Hi all! > Can You explain me what happens when in this function I remove board arg: > def human_move(board, human)? > What is doing that argument? Have you tried removing the argument and running the code? What error message do you get? What do you think it means? -- John. --------------------------------- Stay in the know. Pulse on the new Yahoo.com. Check it out. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060914/d6a3d747/attachment.html From ewald.ertl at hartter.com Thu Sep 14 09:10:32 2006 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Thu, 14 Sep 2006 09:10:32 +0200 Subject: [Tutor] Using my own installed python version in my directory tree. In-Reply-To: References: Message-ID: <45090068.2080604@hartter.com> Hi Ziad Rahhal wrote: > Hi, > > I installed pythin on Linux operating system but on my own tree > directory. Now I want to get rid (not deleting) > the default python installation, which means I want my own python > version to be recognized when I use "python" command. > > PYTHONPATH has nothing to do with that since it just points to modules. > I tried to set the PATH to $HOME/python/bin but this > didn't work. > Who did you set the PATH? I'm using different installations of python on solaris. PATH=/where/python/is:$PATH export PATH After setting the PATH variable, does "which python" find your desired python interpreter? HTH Ewald From derickvn at gmail.com Thu Sep 14 11:07:24 2006 From: derickvn at gmail.com (Derick Van Niekerk) Date: Thu, 14 Sep 2006 11:07:24 +0200 Subject: [Tutor] Clipboard manager for windows Message-ID: <32dab3890609140207v1310f1cdt1f2772fb1f296343@mail.gmail.com> Hey, I came accross this explanation of how the windows clipboard can be handled with Python: http://www.bigbold.com/snippets/posts/show/724 I want to write myself a simple text filter for pasting csv into excel, pasting syntax highlighted code as html and custom formatting text with regular expressions before pasting it. There are free programs that come close to what I need but the filters aren't as customizable as I'd like - allthough they are more complicated than I need. Take a look at http://www.clipmagic.com/ and http://www.snapfiles.com/get/clippy.html Clippy is the closest to what I need. So I need a way to hijaak the Ctrl-C and Ctrl-V shortcuts and have my application run in the system tray. I don't need a gui other than changing the context menu (which I believe is done in the registry) - although, I'd probably need to use wxPython for using the system tray - unless by catching the shortcut keys, I can call the program... Any ideas? Anybody ever done something like this? -d- -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060914/d0a1fdb4/attachment.htm From kent37 at tds.net Thu Sep 14 11:51:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 14 Sep 2006 05:51:05 -0400 Subject: [Tutor] List manipulation In-Reply-To: <20060913204747.85059.qmail@web38113.mail.mud.yahoo.com> References: <20060913204747.85059.qmail@web38113.mail.mud.yahoo.com> Message-ID: <45092609.2040703@tds.net> Srinivas Iyyer wrote: > Thank you Bob for your email. > Sorry for the confusion. > here is what I ment: > > test = ['10\t15', '16\t20', '25\t35', '45\t50', > '55\t60', '61\t65', '75\t80'] >>> I would get: >>> 10 20 >>> 25 35 >>> 45 50 >>> 55 65 >>> 75 80 Here is my take on it: test = ['10\t15', '16\t20', '25\t35', '45\t50','55\t60', '61\t65', '75\t80'] pairs = [ map(int, x.split('\t')) for x in test ] i = iter(pairs) last = i.next() for current in i: if current[0] == last[1]+1: last = [last[0], current[1]] else: print last last = current print last You can also wrap this in a generator which yields the desired pairs, so they can be printed or put in a list or whatever: def compress(pairs): i = iter(pairs) last = i.next() for current in i: if current[0] == last[1]+1: last = [last[0], current[1]] else: yield last last = current yield last for pair in compress(pairs): print pair Kent From kent37 at tds.net Thu Sep 14 11:59:57 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 14 Sep 2006 05:59:57 -0400 Subject: [Tutor] GDAL- Help In-Reply-To: References: Message-ID: <4509281D.1060205@tds.net> Nagendra Singh wrote: > Hi, > > I am just starting to learn Python and I want to perform some GIS > tasks which requires the gdal module (http://www.gdal.org/). I have > installed FWTools which also comes with a built in Python interface > but I also have a stand alone version of Python which I use. I am > trying to use the gdal module but I keep getting an error message that > gdal module is not found,even after appending the module using the > sys.path.append command. Can you anyone please let me know how do I > use the gdal module in the python I have (I dowlloaded it from > activestate) or I have to use the Python which comes with gdal but it > does not offer me the IDE. I would look at how GDAL is installed in the FWTools Python and try to duplicate that installation in the other Python. Look for files and directories in Lib\site-packages and copy them to the site-packages for your other install. Kent From nimrodx at slingshot.co.nz Thu Sep 14 12:20:06 2006 From: nimrodx at slingshot.co.nz (nimrodx) Date: Thu, 14 Sep 2006 22:20:06 +1200 Subject: [Tutor] How do I open my browser from within a Python program In-Reply-To: <44E136E3.1020307@gmail.com> References: <5E5EE09E-2C03-11DB-B3EC-000A95EA5592@well.com> <44E136E3.1020307@gmail.com> Message-ID: <45092CD6.1000203@slingshot.co.nz> Basically a dumb question I can't seem to find the answer to. How do I execute a bash command from within a python program. I've been looking through my book on python, and the docs, but can't seem to find something so basic (sure it is there, but I am not looking for the correct terms, I guess). Sorry, Matt From kent37 at tds.net Thu Sep 14 12:29:33 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 14 Sep 2006 06:29:33 -0400 Subject: [Tutor] How do I open my browser from within a Python program In-Reply-To: <45092CD6.1000203@slingshot.co.nz> References: <5E5EE09E-2C03-11DB-B3EC-000A95EA5592@well.com> <44E136E3.1020307@gmail.com> <45092CD6.1000203@slingshot.co.nz> Message-ID: <45092F0D.3000101@tds.net> nimrodx wrote: > Basically a dumb question I can't seem to find the answer to. > > How do I execute a bash command from within a python program. To open your browser you can use the webbrowser module. To run any external program use os.system(). To run an actual bash command (as opposed to starting an external program as you might do with bash) you would have to run bash as the external program; I'm not sure of the details on that. Kent From simon at brunningonline.net Thu Sep 14 12:33:13 2006 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 14 Sep 2006 11:33:13 +0100 Subject: [Tutor] How do I open my browser from within a Python program In-Reply-To: <45092CD6.1000203@slingshot.co.nz> References: <5E5EE09E-2C03-11DB-B3EC-000A95EA5592@well.com> <44E136E3.1020307@gmail.com> <45092CD6.1000203@slingshot.co.nz> Message-ID: <8c7f10c60609140333o52c95b8m185ba490f30e222c@mail.gmail.com> On 9/14/06, nimrodx wrote: > Basically a dumb question I can't seem to find the answer to. > > How do I execute a bash command from within a python program. Well, this question doesn't match the subject line. So, *two* answers. To open a web browser from within a python program, you want something like: import webbrowser webbrowser.open('www.google.com') To run a shell command - well, it depends. If you don't care about reading the output or so on, you can just do: import os os.system('ls') If you want to access the input and/or output streams, or to wait for the shell command to finish, or anything even remotely complex, look at the subprocess module. -- Cheers, Simon B, simon at brunningonline.net From tiagosaboga at terra.com.br Thu Sep 14 15:11:58 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Thu, 14 Sep 2006 10:11:58 -0300 Subject: [Tutor] Input mask for console? In-Reply-To: <1158195340.25247.27.camel@localhost> References: <1158190762.25247.23.camel@localhost> <450898EA.4030806@tds.net> <1158195340.25247.27.camel@localhost> Message-ID: <200609141011.59135.tiagosaboga@terra.com.br> Em Quarta 13 Setembro 2006 21:55, Chris Hengge escreveu: > nevermind.. figured it out.. Thanks. Hi Chris, It's not just for you, but I'd like to make a comment. When you write to this list, remember that other people read your questions too, and may be interested in the answers. By the way, I've learned a lot here just by reading the q&a. But if we want it to be really useful to everybody, we should try to post good questions (in your case, it was ok, but it could be better: you could have given the example of the password in the first mail) *and* post the choosen solution. Thanks! Tiago. > > On Wed, 2006-09-13 at 19:48 -0400, Kent Johnson wrote: > > Chris Hengge wrote: > > > I need either a way to mask the input from a console, or a method to > > > not display the typed characters to the screen. Someone point me in the > > > right direction? > > > > getpass.getpass() ? > > > > Kent > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From hmm at woolgathering.cx Thu Sep 14 16:49:35 2006 From: hmm at woolgathering.cx (William O'Higgins Witteman) Date: Thu, 14 Sep 2006 10:49:35 -0400 Subject: [Tutor] Excluding branches while walking directory tree In-Reply-To: <45082501.1070006@tds.net> References: <20060913151544.GA6574@sillyrabbi.dyndns.org> <45082501.1070006@tds.net> Message-ID: <20060914144935.GA10265@sillyrabbi.dyndns.org> On Wed, Sep 13, 2006 at 11:34:25AM -0400, Kent Johnson wrote: >William O'Higgins Witteman wrote: >> I have to walk a directory tree and examine files within it. I have a >> set of directory names and filename patterns that I must skip while >> doing this walk. How do I create a set of rules to skip files or >> directory branches? I'm looking for something reasonably scalable, >> 'cause I'm sure to need to update these rules in the future. First, thanks to Kent and Dave for their thoughts - a big help and much appreciated. Notes and results below, for archival posterity (so at least *I'll* know where to look for it :-) >def matchesAny(name, tests): > for test in tests: > if fnmatch.fnmatch(name, test): > return True > return False fnmatch was a good choice for this in my case, because I have to do case-insensitive matching of very simple patterns, but re or glob would provide more power if needed. I originally put the return False inside the conditional with else - but that meant that unless my name matched on the last test in tests, it would always return False. Not what I wanted. The above works very nicely without the return False line. >for dirpath, dirnames, filenames in os.walk(baseDir): > # Note use of slice assignment - you have to modify the caller's list > dirnames[:] = [ name for name in dirnames if not matchesAny(name, >dirsToSkip) ] > > filenames = [name for name in filenames if not matchesAny(name, >filesToSkip) ] > > for name in filenames: > # whatever file processing you want to do goes here The above approach was not quite what I needed, because I had a list of exclusion criteria and a list of inclusion criteria, but both could be applied to the whole path. Therefore, I used this approach: for dirpath, dirnames, filenames in os.walk(fs_path): """Filter the list of filenames to exclude elements in ToSkip""" filenames[:] = [name for name in filenames if not matches(os.path.join(dirpath,name),ToSkip)] """Filter the list of filenames to exclude elements not in ToKeep""" filenames[:] = [name for name in filenames if matches(os.path.join(dirpath,name),ToKeep)] for fname in filenames: # do what needs to be done This is getting me just the results I was looking for, and I have to say, I'm pretty pleased. Thanks again. -- yours, William From kent37 at tds.net Thu Sep 14 17:21:24 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 14 Sep 2006 11:21:24 -0400 Subject: [Tutor] Excluding branches while walking directory tree In-Reply-To: <20060914144935.GA10265@sillyrabbi.dyndns.org> References: <20060913151544.GA6574@sillyrabbi.dyndns.org> <45082501.1070006@tds.net> <20060914144935.GA10265@sillyrabbi.dyndns.org> Message-ID: <45097374.8080604@tds.net> William O'Higgins Witteman wrote: > On Wed, Sep 13, 2006 at 11:34:25AM -0400, Kent Johnson wrote: >> William O'Higgins Witteman wrote: >>> I have to walk a directory tree and examine files within it. I have a >>> set of directory names and filename patterns that I must skip while >>> doing this walk. How do I create a set of rules to skip files or >>> directory branches? I'm looking for something reasonably scalable, >>> 'cause I'm sure to need to update these rules in the future. > > First, thanks to Kent and Dave for their thoughts - a big help and much > appreciated. Notes and results below, for archival posterity (so at > least *I'll* know where to look for it :-) > >> def matchesAny(name, tests): >> for test in tests: >> if fnmatch.fnmatch(name, test): >> return True >> return False > > fnmatch was a good choice for this in my case, because I have to do > case-insensitive matching of very simple patterns, but re or glob would > provide more power if needed. > I originally put the return False inside > the conditional with else - but that meant that unless my name matched > on the last test in tests, it would always return False. Not what I > wanted. The above works very nicely without the return False line. If you leave out the return False you get an implicit return None. None is interpreted as False in a conditional so it has the same result. I would prefer to make it explicit. > >> for dirpath, dirnames, filenames in os.walk(baseDir): >> # Note use of slice assignment - you have to modify the caller's list >> dirnames[:] = [ name for name in dirnames if not matchesAny(name, >> dirsToSkip) ] >> >> filenames = [name for name in filenames if not matchesAny(name, >> filesToSkip) ] >> >> for name in filenames: >> # whatever file processing you want to do goes here > > The above approach was not quite what I needed, because I had a list of > exclusion criteria and a list of inclusion criteria, but both could be > applied to the whole path. Therefore, I used this approach: > > for dirpath, dirnames, filenames in os.walk(fs_path): > """Filter the list of filenames to exclude elements in ToSkip""" > filenames[:] = [name for name in filenames if not matches(os.path.join(dirpath,name),ToSkip)] > """Filter the list of filenames to exclude elements not in ToKeep""" > filenames[:] = [name for name in filenames if matches(os.path.join(dirpath,name),ToKeep)] > > for fname in filenames: > # do what needs to be done Another way to write this that might be a little easier to read is this: for fname in filenames: if matches(os.path.join(dirpath,name),ToSkip): continue if not matches(os.path.join(dirpath,name),ToKeep): continue # process the file or even if matches(os.path.join(dirpath,name),ToSkip) or not matches(os.path.join(dirpath,name),ToKeep): continue > > This is getting me just the results I was looking for, and I have to > say, I'm pretty pleased. Thanks again. Python rocks :-) Kent From allison.william at comcast.net Thu Sep 14 18:14:27 2006 From: allison.william at comcast.net (William Allison) Date: Thu, 14 Sep 2006 12:14:27 -0400 Subject: [Tutor] <> and chomp Message-ID: <1158250467.8990.6.camel@powerbook.lovemonkey.net> Hi, I'm new to programming and started with Perl but have been reading a lot of good things about Python. Thought I would switch before I have too much time invested in Perl. Anyway, my question is, is there something in Python similar to the diamond operator and chomp from Perl? I'm trying to read in from a file line by line and get rid of the '\n' at the end of each line. Thanks, Will From janos.juhasz at VELUX.com Thu Sep 14 18:14:45 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Thu, 14 Sep 2006 18:14:45 +0200 Subject: [Tutor] Clipboard manager for windows Message-ID: Hi Derick, >So I need a way to hijaak the Ctrl-C and Ctrl-V shortcuts and have my >application run in the system tray. I don't need a gui other than changing >the context menu (which I believe is done in the registry) - although, I'd >probably need to use wxPython for using the system tray - unless by catching >the shortcut keys, I can call the program... I have tested it without hijaak the Ctrl-C and Ctrl-V It is seem to be easier to set up a shortcut to in-place filtering on the current content of the clipboard. I just have played with the sample you showed: ### text.py My small clipboard coverter ### import win32clipboard as w import win32con import re def getText(): w.OpenClipboard() d=w.GetClipboardData(win32con.CF_TEXT) w.CloseClipboard() return d def setText(aType,aString): w.OpenClipboard() w.EmptyClipboard() w.SetClipboardData(aType,aString) w.CloseClipboard() def myFilter(text): comma = re.compile(',') return comma.sub('\t', text) def myTester(text): ### context sensitivity return ',' in text text = getText() if myTester(text): setText(win32con.CF_TEXT, myFilter(text)) ### My small clipboard coverter ### I have saved this python script into my devel folder, created a shortcut on the windows desktop, set up a shortcut key for it with Ctrl-Alt-T. When I start this program with the shortcut key, it simple makes the replace in-place on the current content of the clipboard, that can be put into excel after it. Copy this to the clipboard: a,b,c,d,e 1,2,3,4,5 run the script Paste the clipboard to excel Viola :) You can make it with wxPython and give the choice for the user on the visual surface to choose from more filters. It also could be interesting, to make the tab delimited clipboard content from the filenames. >>> w.OpenClipboard() >>> w.GetClipboardData(win32con.CF_HDROP) (u'D:\\devel\\tutor\\data.txt',) >>> w.CloseClipboard() Yours sincerely, ______________________________ J?nos Juh?sz -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060914/f86d58a9/attachment-0001.html From david at graniteweb.com Thu Sep 14 18:25:04 2006 From: david at graniteweb.com (David Rock) Date: Thu, 14 Sep 2006 11:25:04 -0500 Subject: [Tutor] <> and chomp In-Reply-To: <1158250467.8990.6.camel@powerbook.lovemonkey.net> References: <1158250467.8990.6.camel@powerbook.lovemonkey.net> Message-ID: <20060914162504.GA4922@wdfs.graniteweb.com> * William Allison [2006-09-14 12:14]: > Hi, > I'm new to programming and started with Perl but have been reading a lot > of good things about Python. Thought I would switch before I have too > much time invested in Perl. > Anyway, my question is, is there something in Python similar to the > diamond operator and chomp from Perl? I'm trying to read in from a file > line by line and get rid of the '\n' at the end of each line. fileinput() is similar to <> http://docs.python.org/lib/module-fileinput.html rstrip() is similar to chomp http://docs.python.org/lib/string-methods.html#l2h-201 These aren't exact matches, but they are close. -- David Rock david at graniteweb.com From kent37 at tds.net Thu Sep 14 18:34:37 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 14 Sep 2006 12:34:37 -0400 Subject: [Tutor] <> and chomp In-Reply-To: <1158250467.8990.6.camel@powerbook.lovemonkey.net> References: <1158250467.8990.6.camel@powerbook.lovemonkey.net> Message-ID: <4509849D.5090604@tds.net> William Allison wrote: > Hi, > I'm new to programming and started with Perl but have been reading a lot > of good things about Python. Thought I would switch before I have too > much time invested in Perl. > Anyway, my question is, is there something in Python similar to the > diamond operator and chomp from Perl? I'm trying to read in from a file > line by line and get rid of the '\n' at the end of each line. for line in open('somefile.txt'): line = line.rstrip('\n') # do something with line You could also use line = line.rstrip() which removes all trailing white space including \n, or line.strip() which removes leading and trailing white space. Kent From dkuhlman at rexx.com Thu Sep 14 18:43:04 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 14 Sep 2006 09:43:04 -0700 Subject: [Tutor] <> and chomp In-Reply-To: <1158250467.8990.6.camel@powerbook.lovemonkey.net> References: <1158250467.8990.6.camel@powerbook.lovemonkey.net> Message-ID: <20060914164304.GA36082@cutter.rexx.com> On Thu, Sep 14, 2006 at 12:14:27PM -0400, William Allison wrote: > Hi, > I'm new to programming and started with Perl but have been reading a lot > of good things about Python. Thought I would switch before I have too > much time invested in Perl. > Anyway, my question is, is there something in Python similar to the > diamond operator and chomp from Perl? I'm trying to read in from a file > line by line and get rid of the '\n' at the end of each line. > Thanks, > Will Consider: infile = open('infilename.txt', 'r') for line in infile: line = line.rstrip('\n') o o o infile.close() A few notes: - See http://docs.python.org/lib/built-in-funcs.html for more on built-in functions and open() in particular. - See http://docs.python.org/lib/string-methods.html for more on string operations and rstrip() in particular. - rstrip() with no arguments strips all whitespace on the right. - A file object (returned by the open() function) is an iterator; it obeys the iterator protocol. That's why you can use it in the "for" statement above. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From fedekiller at gmail.com Thu Sep 14 20:43:19 2006 From: fedekiller at gmail.com (federico ramirez) Date: Thu, 14 Sep 2006 15:43:19 -0300 Subject: [Tutor] show all dbm data Message-ID: <26a78a3c0609141143j39b72039i9810c6182b25e09f@mail.gmail.com> Hi, im have just started programming python with cgi and i will try to use dbm as a db to practise But i cant figure out how to diplay all the data from it.. this is the code im using ///////////// #!/usr/bin/python print "Content-Type: text/html\n\n" import cgi, dbm def startpage(title): print ''' ''',title,''' ''' def endpage(): print """ """ def main(): form = cgi.FieldStorage() if(form.has_key("name") and form["name"].value != ""): try: db = dbm.open("dbm", "c") db["name"] = form["name"].value db.close() print "Info saved. Now, read it?" except: print cgi.print_exceptions() elif(form.has_key("read") and form["read"].value == "true"): try: db = dbm.open("dbm", "r") for key in db.keys(): print key except: print cgi.print_exceptions() else: print """
""" startpage("Test Page") main() endpage() ///////////// Thanks in advance -- Best Regards. fedekiller -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060914/8e5f5a8b/attachment.html From project5 at redrival.net Thu Sep 14 20:57:53 2006 From: project5 at redrival.net (Andrei) Date: Thu, 14 Sep 2006 20:57:53 +0200 Subject: [Tutor] python for web developing In-Reply-To: <26a78a3c0609131029i49da17e4m1fd6355c8cd91326@mail.gmail.com> References: <26a78a3c0609131029i49da17e4m1fd6355c8cd91326@mail.gmail.com> Message-ID: federico ramirez wrote: > Hello! I have heard that python is very good for web development, but > you need frameworks, like django or turbogears. There are also more lightweight frameworks, like web.py (http://webpy.org). > Im a php programmer, and i want to make another dinamic site with sql, > in python, but i need sql object or other sql... > And i cant get a host with it, a free host just to test it. If you want to test, I think your own PC can do the job just fine. I don't know of any free generic Python hosts. Webfaction (run by the author of CherryPy, which is part of TurboGears) seems to have decent support for all kinds of Python things, but it's paid - if they allow a 1-month account, you could try it out for very little money over there. Yours, Andrei From timothyh at email.arizona.edu Fri Sep 15 00:38:04 2006 From: timothyh at email.arizona.edu (timothyh at email.arizona.edu) Date: Thu, 14 Sep 2006 15:38:04 -0700 Subject: [Tutor] (no subject) Message-ID: <20060914153804.ygeyo404scsw48ck@www.email.arizona.edu> This is the first time I have posted to this list so I hope I am asking appropriate question in acceptable way. Want I want to do is take a file and cut it into pieces so each piece is a new unique file; the new files would be one line (newline) from the file I want to cut up. The file I want to cut up has 3900 lines. This is as far as I have got. >>> output = open('/Users/timothy/Desktop/d' , 'w') >>> input = open('/Users/timothy/Desktop/t' , 'r') >>> l = input.readlines() >>> output.writelines(l) >>> output.close() What I did was copy file r to file d. What I think I need is a for or while expression that as each readlines is occuring it will be output as one seperate file. Also I think I need to import sys.stdout and somehow have the readlines be piped through that or maybe sys.argv used in some way, but these are rather vague intuitions---can't think how to put this together. Is what I want to do stated clearly and is this the sort of questions to ask here? Thank-you, Timothy From alan.gauld at btinternet.com Fri Sep 15 01:06:57 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 15 Sep 2006 00:06:57 +0100 Subject: [Tutor] what happens when... References: <20060913175436.83265.qmail@web60815.mail.yahoo.com> Message-ID: def human_move(human): # <= here is board removed legal = legal_moves(board) where does the board come from here? If you had it as a parameter then thats where it would come from. Without a parameter you need to have a global variable called board. The parameters are the communications context between your function and the world outside. Everything that your function needs to operate should be passed into it (or local to it.) At least thats the ideal. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From pyro9219 at gmail.com Fri Sep 15 01:10:06 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 14 Sep 2006 16:10:06 -0700 Subject: [Tutor] Input mask for console? In-Reply-To: <200609141011.59135.tiagosaboga@terra.com.br> References: <1158190762.25247.23.camel@localhost> <450898EA.4030806@tds.net> <1158195340.25247.27.camel@localhost> <200609141011.59135.tiagosaboga@terra.com.br> Message-ID: The chosen solution was posted by kent... he said getpass.getpass(). As far as a "sample" password... how do I display something I was asking how to hide? =P >>> Enter Password: "nothing seen here" =D On 9/14/06, Tiago Saboga wrote: > > Em Quarta 13 Setembro 2006 21:55, Chris Hengge escreveu: > > nevermind.. figured it out.. Thanks. > > Hi Chris, > > It's not just for you, but I'd like to make a comment. When you write to > this > list, remember that other people read your questions too, and may be > interested in the answers. By the way, I've learned a lot here just by > reading the q&a. But if we want it to be really useful to everybody, we > should try to post good questions (in your case, it was ok, but it could > be > better: you could have given the example of the password in the first > mail) > *and* post the choosen solution. > > Thanks! > > Tiago. > > > > > > On Wed, 2006-09-13 at 19:48 -0400, Kent Johnson wrote: > > > Chris Hengge wrote: > > > > I need either a way to mask the input from a console, or a method to > > > > not display the typed characters to the screen. Someone point me in > the > > > > right direction? > > > > > > getpass.getpass() ? > > > > > > Kent > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060914/62682948/attachment.htm From pyro9219 at gmail.com Fri Sep 15 01:12:00 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 14 Sep 2006 16:12:00 -0700 Subject: [Tutor] pymssql or ODBC Message-ID: Does anyone know how to make pymssql use windows authentication? Also, can anyone point me to a simple ODBC guide for SQL? I'd like to use ODBC if I can so that users of my software dont have to install extra libraries to use my utilities. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060914/54078b06/attachment.html From john at fouhy.net Fri Sep 15 01:17:30 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 15 Sep 2006 11:17:30 +1200 Subject: [Tutor] (no subject) In-Reply-To: <20060914153804.ygeyo404scsw48ck@www.email.arizona.edu> References: <20060914153804.ygeyo404scsw48ck@www.email.arizona.edu> Message-ID: <5e58f2e40609141617o1ebc8866mec654b6227adabda@mail.gmail.com> On 15/09/06, timothyh at email.arizona.edu wrote: > This is the first time I have posted to this list so I hope I am asking > appropriate question in acceptable way. Want I want to do is take a file and > cut it into pieces so each piece is a new unique file; the new files would be > one line (newline) from the file I want to cut up. The file I want to cut up > has 3900 lines. This is as far as I have got. So, you want to create 3900 different files, then? What do you want to call these files? You can iterate through each line of a file like this: input = open('/Users/timothy/Desktop/t' , 'r') for line in input: # ... So, in the body of the for loop, all you would need to do is decide what to call the new file, open the file, write line to it, and then close it. -- John. From rabidpoobear at gmail.com Fri Sep 15 01:25:56 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 14 Sep 2006 18:25:56 -0500 Subject: [Tutor] (no subject) In-Reply-To: <5e58f2e40609141617o1ebc8866mec654b6227adabda@mail.gmail.com> References: <20060914153804.ygeyo404scsw48ck@www.email.arizona.edu> <5e58f2e40609141617o1ebc8866mec654b6227adabda@mail.gmail.com> Message-ID: <4509E504.8000201@gmail.com> John Fouhy wrote: > On 15/09/06, timothyh at email.arizona.edu wrote: > >> This is the first time I have posted to this list so I hope I am asking >> appropriate question in acceptable way. Want I want to do is take a file and >> cut it into pieces so each piece is a new unique file; the new files would be >> one line (newline) from the file I want to cut up. The file I want to cut up >> has 3900 lines. This is as far as I have got. >> > > So, you want to create 3900 different files, then? > > What do you want to call these files? > > You can iterate through each line of a file like this: > > input = open('/Users/timothy/Desktop/t' , 'r') > for line in input: > # ... > Good example, except you shouldn't use 'input' since it's a builtin. :D Cheers. -Luke > So, in the body of the for loop, all you would need to do is decide > what to call the new file, open the file, write line to it, and then > close it. > > From alan.gauld at btinternet.com Fri Sep 15 01:38:47 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 15 Sep 2006 00:38:47 +0100 Subject: [Tutor] Methods and classes References: <1158180026.25247.4.camel@localhost> <5e58f2e40609131418n4bcf7adfwc8ea85d967c49d85@mail.gmail.com><1158184632.25247.14.camel@localhost> <450885AD.2020506@tds.net> Message-ID: "Kent Johnson" wrote > You have to distinguish between a method (a function that is part of > a > class definition) and a standalone function (not part of any class). > Python allows both. Standalone functions don't have a 'self' > parameter; > class methods always do (you can give it a different name but if you > omit it you will get a runtime error when you call the method). Just to be picky, instance methods need a self parameter. class methods (ie methods that belong to the class as a whole rather than the individual instances(objects)) do not need a self parameter. >>> class C: ... def s_m(x): print x ... s_m = staticmethod(s_m) # make it a static or class method ... def __init__(self,y): self.y = y ... def i_m(self,x): print x, self.y ... >>> c = C(27) >>> C.s_m(42) # call via class 42 >>> c.s_m(42) # call via instance 42 >>> c.i_m(42) 42 27 >>> And just to be even more picky Python actually distinguishes between static methods (as above) and what it specifically calls class methods, whereby the latter have an attribute similar to self, but instead of holding the instance it holds a reference to the original class object! (most OOP languages do not have such fine grained distinctions on class methods) So to summarise there are 4 types of function/method definition: 1) Ordinary functions - can have any parameters, including none 2) static methods - ordinary functions bound to a class object 3) class methods - static methods with a class reference as first parameter 4) instance methods - a function bound to an instance of the class and with an instance reference as the first parameter. 2,3 and 4 must all be defined inside a class definition. [ And if you use decorators you can add to that list, but I won't go there! :-) ] Finally the double underscore that you refer to is a Python convention (but strongly adhered to) which indicates a special function used by Python internally and not normally called by the programmer.. __init__ is the initialisation function called automatically when an instance is created. Because it is specifc to the instance it has a self at the front. It can also take other values which will initialise internal values of the instance, like my self.y above. Others allow you to define how standard operators will work for your own classes, thus __add__, __mul__, __cmp__ etc If you define an __add__() method in your class, you can then add two instances using the + sign: class M: def __add__(self,another): return 42 m = M() n = M() print m+n # python calls M.__add__(m,n) under the covers HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Sep 15 01:44:55 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 15 Sep 2006 00:44:55 +0100 Subject: [Tutor] show all dbm data References: <26a78a3c0609141143j39b72039i9810c6182b25e09f@mail.gmail.com> Message-ID: > Hi, im have just started programming python with cgi and i will try > to use > dbm as a db to practise dbm is pretty low level, I'd recommend using the shelve module as a layer above dbm. Basically shelve makes a file look like a dictionary. Not the answer you asked for but since you don't intend to use dbm long term its probably a better solution! Alan G. From allison.william at comcast.net Fri Sep 15 02:06:53 2006 From: allison.william at comcast.net (allison.william at comcast.net) Date: Fri, 15 Sep 2006 00:06:53 +0000 Subject: [Tutor] <> and chomp Message-ID: <091520060006.7886.4509EE9D000C278D00001ECE2209224627030E0704040799D202019C0704040E@comcast.net> Thanks for all the responses guys. I was actually able to figure out the infile = open('infilename.txt', 'r') for line in infile: Just wasn't sure if it was Pythonic or not. Had no clue about the line = line.rstrip('\n') so thanks again. I'll get to reading those links. P.S. David, I'm sure you're right. I'll eventually learn both. From fedekiller at gmail.com Fri Sep 15 02:11:24 2006 From: fedekiller at gmail.com (federico ramirez) Date: Thu, 14 Sep 2006 21:11:24 -0300 Subject: [Tutor] arrays Message-ID: <26a78a3c0609141711t218c9dcblde200dc7cc73b760@mail.gmail.com> Hi all! Im started with python some days ago, im trying to make a basic cgi script, with dbm, and dbm returns a dictionary witout order, so i put it in an array to order the keys and then display it in order but..python orders the array like this ['_1', '_10', '_11', '_12', '_13', '_2', '_3', '_4', '_5', '_6', '_7', '_8', '_9'] and i want ['_1', '_2', '_3', '_4', '_5', '_6', '_7', '_8', '_9','_10', '_11', '_12', '_13'] here its the code i use /////////////////////////////// #!/usr/bin/python print "Content-Type: text/html\n\n" import cgi, dbm def startpage(title): print ''' ''',title,''' ''' def endpage(): print """ """ def main(): form = cgi.FieldStorage() if(form.has_key("name") and form["name"].value != ""): db = dbm.open("dbm", "c") db.close() dbread = dbm.open("dbm", "r") leng = len(dbread)+1 dbread.close() db = dbm.open("dbm", "c") name = "_"+str(leng) db[name] = form["name"].value db.close() print "Info saved. Now, read it?" elif(form.has_key("read") and form["read"].value == "true"): db = dbm.open("dbm", "r") arr = [] for key in db.keys(): arr += [key] arr.sort() arr.reverse() for i in range(len(db)): print db[arr[i]],'
' db.close() else: print """
""" startpage("Test Page") main() endpage() ////////////////////////////// Thanks in advanced -- Best Regards. fedekiller -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060914/40104f4c/attachment.htm From bgailer at alum.rpi.edu Fri Sep 15 02:43:56 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 14 Sep 2006 17:43:56 -0700 Subject: [Tutor] How to split a file (was (no subject)) In-Reply-To: <20060914153804.ygeyo404scsw48ck@www.email.arizona.edu> References: <20060914153804.ygeyo404scsw48ck@www.email.arizona.edu> Message-ID: <4509F74C.90809@alum.rpi.edu> timothyh at email.arizona.edu wrote: > This is the first time I have posted to this list so I hope I am asking > appropriate question in acceptable way. Want I want to do is take a file and > cut it into pieces so each piece is a new unique file; the new files would be > one line (newline) from the file I want to cut up. The file I want to cut up > has 3900 lines. This is as far as I have got. Others have provided the "answer". Since you are new to the list I will add the request that you provide a meaningful subject line so we can track the various threads. -- Bob Gailer 510-978-4454 From john at fouhy.net Fri Sep 15 02:55:21 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 15 Sep 2006 12:55:21 +1200 Subject: [Tutor] arrays In-Reply-To: <26a78a3c0609141711t218c9dcblde200dc7cc73b760@mail.gmail.com> References: <26a78a3c0609141711t218c9dcblde200dc7cc73b760@mail.gmail.com> Message-ID: <5e58f2e40609141755v2ec03c30k4cfc37a838fcc934@mail.gmail.com> On 15/09/06, federico ramirez wrote: > an array to order the keys and then display it in order but..python orders > the array like this > > ['_1', '_10', '_11', '_12', '_13', '_2', '_3', '_4', '_5', '_6', '_7', '_8', > '_9'] > > and i want > > ['_1', '_2', '_3', '_4', '_5', '_6', '_7', '_8', '_9','_10', '_11', '_12', > '_13'] Hi, First, just a terminology note -- in python, these are called lists, not arrays. > arr = [] > for key in db.keys(): > arr += [key] > arr.sort() > arr.reverse() db.keys() returns a _new_ list, so there is no need to do this step; you could just write: arr = db.keys() Now, since your keys are strings, python is sorting them lexicographically, which is why (for instance) '_10' comes before '_2'. You need to tell python to change its sort order. You can do this in a couple of ways. If you have python2.4 or greater, you can use the key= keyword argument to sort, like this: def keyToInt(s): """Convert '_10' to 10, '_2' to 2, etc. """ return int(s[1:]) arr.sort(key=keyToInt) If you have an earlier version of python, you can define your own comparison function: def myCmp(x, y): return cmp(keyToInt(x), keyToInt(y)) arr.sort(myCmp) You can also use the decorate-sort-undecorate idiom, which may be faster than a custom comparison function if the list is very large. decorated = [(keyToInt(s), s) for s in arr] decorated.sort() arr = [x[1] for x in decorated] > for i in range(len(db)): > print db[arr[i]],'
' In python, you can iterate over lists directly. ie, since arr is your list of keys: for key in arr: print db[key], '
' HTH! -- John. From tim at johnsons-web.com Fri Sep 15 03:13:18 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Thu, 14 Sep 2006 17:13:18 -0800 Subject: [Tutor] Problems serving up PDF In-Reply-To: <20060914153804.ygeyo404scsw48ck@www.email.arizona.edu> References: <20060914153804.ygeyo404scsw48ck@www.email.arizona.edu> Message-ID: <20060915011318.GA19434@johnsons-web.com> Hi: This is *not* really a python problem, but :-) since this is such an helpful list and others may have the same issue... I have a python script which searches a server for a pdf file and if found, reads the file to stdout, as one would read html to stdout. The question is really about the proper content-type: Both of the following functions have been tried: def pdf_header1(file_name,length): """ Serve a PDF document via CGI with content length.""" print ( 'Content-type: application/pdf\n' 'Content-Length: %d\n' 'Content-Disposition: attachment;filename="%s"\n' ) % (length,file_name) def pdf_header(file_name,length): """ Serve a PDF document via CGI with content length.""" print ( 'Content-type: application/pdf\n' 'Content-Disposition: inline; filename=%s\n' 'Content-length: %d\n' ) % (file_name,length) Regardless of which is used, on Mozilla, I have the following response: A dialog that names the file, identifies the filetype, and gives a choice of whether to download or open the file. when the choice is made, progress is reported via another window and the selected action occurs when download is finished. On Internet Explorer 6, Windows XP, the user experience is different. IE ignores the file name, and does no progress reporting, but does "understand" the file type. Does anyone have any experience with this issue? Or could anyone recommend a more appropriate place to post this question? Thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From rabidpoobear at gmail.com Fri Sep 15 03:33:14 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 14 Sep 2006 20:33:14 -0500 Subject: [Tutor] Problems serving up PDF In-Reply-To: <20060915011318.GA19434@johnsons-web.com> References: <20060914153804.ygeyo404scsw48ck@www.email.arizona.edu> <20060915011318.GA19434@johnsons-web.com> Message-ID: <450A02DA.4060202@gmail.com> Tim Johnson wrote: > Hi: > > This is *not* really a python problem, but :-) since this > is such an helpful list and others may have the same issue... > > I have a python script which searches a server for a pdf file > and if found, reads the file to stdout, as one would read html > to stdout. > > The question is really about the proper content-type: > > Both of the following functions have been tried: > > def pdf_header1(file_name,length): > """ Serve a PDF document via CGI with content length.""" > print ( > 'Content-type: application/pdf\n' > 'Content-Length: %d\n' > 'Content-Disposition: attachment;filename="%s"\n' > ) % (length,file_name) > > def pdf_header(file_name,length): > """ Serve a PDF document via CGI with content length.""" > print ( > 'Content-type: application/pdf\n' > 'Content-Disposition: inline; filename=%s\n' > 'Content-length: %d\n' > ) % (file_name,length) > > You have a cgi script on your server that searches itself for a file and serves it to the user? One note, you should be using \r\n instead of \n. Also, you're putting \r\n\r\n after your header, right? > Regardless of which is used, on Mozilla, I have the following > response: > A dialog that names the file, identifies the filetype, and > gives a choice of whether to download or open the file. > when the choice is made, progress is reported via another > window and the selected action occurs when download is finished. > Sounds like it's working to me. > On Internet Explorer 6, Windows XP, the user experience is different. > IE ignores the file name, and does no progress reporting, but does > "understand" the file type. > Sounds like it's working to me. As far as I can tell, it seems to me like you have some file (example .wmv) that I.E. is saying 'okay I know how to open this' and it tries to do something with it. Firefox, humble as it is, admits that it doesn't know what to do and just lets you download it. If this is the case, then it's a configuration issue with IE that's making it attempt to open the file. You could just as well configure Firefox to automatically open these files too, although that doesn't mean that it'll work :) So unless you can be more specific, I'd say that it's just a difference in the browser and not a problem with your code at all. Do I not understand correctly? HTH, -Luke > Does anyone have any experience with this issue? Or could anyone > recommend a more appropriate place to post this question? > Thanks > tim > > From Gideon.STREET at ergon.com.au Fri Sep 15 03:08:14 2006 From: Gideon.STREET at ergon.com.au (STREET Gideon (SPARQ)) Date: Fri, 15 Sep 2006 11:08:14 +1000 Subject: [Tutor] RfC822 or email module Message-ID: <5A504BF2C0C9F5438ACBF61D35D49FFC0A25B5@ebnewem01.ergon> Morning all, I'm currently trying to figure out a way of downloading email and passing it into a SQLite database. I've got the downloading email side worked out using a variation of popmail.py from one of the python books I've got. Also worked out how to talk to the database from Alan Gauld's tutor (Thanks Alan, your webpage is probably one of most valuable pages I've come across). What I'm trying to do is split out the email headers (from, date and subject) and store them in their respective fields and the message body in another field. Was wondering which python module, email of rfc822, would be the most useful? Lot's of doco around these two but there appears to be some overlap. Cheers Gideon This e-mail (including any attachments) may contain confidential or privileged information and is intended for the sole use of the person(s) to whom it is addressed. If you are not the intended recipient, or the person responsible for delivering this message to the intended recipient, please notify the sender of the message or send an e-mail to mailto:help.desk at ergon.com.au immediately, and delete all copies. Any unauthorised review, use, alteration, disclosure or distribution of this e-mail by an unintended recipient is prohibited. Ergon Energy accepts no responsibility for the content of any e-mail sent by an employee which is of a personal nature. Ergon Energy Corporation Limited ABN 50 087 646 062 Ergon Energy Pty Ltd ABN 66 078 875 902 From tim at johnsons-web.com Fri Sep 15 03:53:00 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Thu, 14 Sep 2006 17:53:00 -0800 Subject: [Tutor] Problems serving up PDF In-Reply-To: <450A02DA.4060202@gmail.com> References: <20060914153804.ygeyo404scsw48ck@www.email.arizona.edu> <20060915011318.GA19434@johnsons-web.com> <450A02DA.4060202@gmail.com> Message-ID: <20060915015300.GB19434@johnsons-web.com> * Luke Paireepinart [060914 17:36]: > Tim Johnson wrote: > >Hi: > > > >This is *not* really a python problem, but :-) since this > >is such an helpful list and others may have the same issue... > > > >I have a python script which searches a server for a pdf file > >and if found, reads the file to stdout, as one would read html > >to stdout. > > > >The question is really about the proper content-type: > > > >Both of the following functions have been tried: > > > >def pdf_header1(file_name,length): > > """ Serve a PDF document via CGI with content length.""" > > print ( > > 'Content-type: application/pdf\n' > > 'Content-Length: %d\n' > > 'Content-Disposition: attachment;filename="%s"\n' > > ) % (length,file_name) > > > >def pdf_header(file_name,length): > > """ Serve a PDF document via CGI with content length.""" > > print ( > > 'Content-type: application/pdf\n' > > 'Content-Disposition: inline; filename=%s\n' > > 'Content-length: %d\n' > > ) % (file_name,length) > > > > Hi Luke: > You have a cgi script on your server that searches itself for a file and > serves it to the user? Correct. > One note, you should be using \r\n instead of \n. Both development and deployment are on a linux OS, so this is the correct procedure. However, I don't think that using '\r' does any harm on *nix.... in fact, it would be the more portable approach. Thanks for pointing that out. > Also, you're putting \r\n\r\n after your header, right? Not sure what you mean. Either of the functions provide the header. Could you explain further? regards tim > >Regardless of which is used, on Mozilla, I have the following > >response: > > A dialog that names the file, identifies the filetype, and > > gives a choice of whether to download or open the file. > > when the choice is made, progress is reported via another > > window and the selected action occurs when download is finished. > > > Sounds like it's working to me. > >On Internet Explorer 6, Windows XP, the user experience is different. > >IE ignores the file name, and does no progress reporting, but does > >"understand" the file type. > > > Sounds like it's working to me. > > > As far as I can tell, it seems to me like you have some file (example .wmv) > that I.E. is saying 'okay I know how to open this' and it tries to do > something with it. > Firefox, humble as it is, admits that it doesn't know what to do and > just lets you download it. > If this is the case, then it's a configuration issue with IE that's > making it attempt to open the file. > You could just as well configure Firefox to automatically open these > files too, although > that doesn't mean that it'll work :) > > So unless you can be more specific, I'd say that it's just a difference > in the browser and not a problem > with your code at all. Do I not understand correctly? > HTH, > -Luke > >Does anyone have any experience with this issue? Or could anyone > >recommend a more appropriate place to post this question? > >Thanks > >tim > > > > -- Tim Johnson http://www.alaska-internet-solutions.com From tim at johnsons-web.com Fri Sep 15 04:01:16 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Thu, 14 Sep 2006 18:01:16 -0800 Subject: [Tutor] Problems serving up PDF In-Reply-To: <450A02DA.4060202@gmail.com> References: <20060914153804.ygeyo404scsw48ck@www.email.arizona.edu> <20060915011318.GA19434@johnsons-web.com> <450A02DA.4060202@gmail.com> Message-ID: <20060915020116.GC19434@johnsons-web.com> * Luke Paireepinart [060914 17:37]: > > > Sounds like it's working to me. > > On Internet Explorer 6, Windows XP, the user experience is different. > > IE ignores the file name, and does no progress reporting, but does > > "understand" the file type. > > > Sounds like it's working to me. > > > As far as I can tell, it seems to me like you have some file (example .wmv) > that I.E. is saying 'okay I know how to open this' and it tries to do > something with it. > Firefox, humble as it is, admits that it doesn't know what to do and > just lets you download it. > If this is the case, then it's a configuration issue with IE that's > making it attempt to open the file. > You could just as well configure Firefox to automatically open these > files too, although > that doesn't mean that it'll work :) > > So unless you can be more specific, I'd say that it's just a difference > in the browser and not a problem > with your code at all. Do I not understand correctly? > HTH, Hey Luke: I also posted this to a forum: One expert response reads like this: "I think that's just the way Mozilla acts." Actually, I like the way Firefox does it. Looks like we just live with the differences. thanks again tim -- Tim Johnson http://www.alaska-internet-solutions.com From kermit at polaris.net Fri Sep 15 04:21:34 2006 From: kermit at polaris.net (Kermit Rose) Date: Thu, 14 Sep 2006 22:21:34 -0400 Subject: [Tutor] tuples versus lists Message-ID: <450A0E2E.1010904@polaris.net> Hello Brian. Today I read through chapter five of the python tutorial and discovered that tuples are not the same thing as lists. This surprised me. I do not see any difference in the capability of lists and tuples. Why would you use one in preference to the other? Kermit < kermit at polaris.net > From tim at johnsons-web.com Fri Sep 15 04:42:15 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Thu, 14 Sep 2006 18:42:15 -0800 Subject: [Tutor] tuples versus lists In-Reply-To: <450A0E2E.1010904@polaris.net> References: <450A0E2E.1010904@polaris.net> Message-ID: <20060915024215.GE19434@johnsons-web.com> * Kermit Rose [060914 18:29]: > Hello Brian. > > Today I read through chapter five of the python tutorial and discovered > that tuples are not the same thing as lists. > > This surprised me. > > I do not see any difference in the capability of lists and tuples. Hi Kermit: Tuples are "read-only" - you can't modify a tuple, you can produce a tuple from a list by using the tuple() function. you can produce a list from a tuple by using the list() function - but the original tuple is unchanged. You can return multiple values from a function using tuples. > > Why would you use one in preference to the other? I use tuples as above and where I don't want data changed... tim -- Tim Johnson http://www.alaska-internet-solutions.com From arcege at gmail.com Fri Sep 15 04:59:28 2006 From: arcege at gmail.com (Michael P. Reilly) Date: Thu, 14 Sep 2006 22:59:28 -0400 Subject: [Tutor] tuples versus lists In-Reply-To: <20060915024215.GE19434@johnsons-web.com> References: <450A0E2E.1010904@polaris.net> <20060915024215.GE19434@johnsons-web.com> Message-ID: <7e5ba9220609141959m2929b1e5wbbc4f6eda233fc73@mail.gmail.com> Tuples, like other immutable data types, are hashable (assuming the contents are immutable as well), and so they can be used as keys to dictionaries. Lists cannot be used this way. >>> {['a']: 'a'} Traceback (most recent call last): File "", line 1, in ? TypeError: list objects are unhashable >>> {('a',): 'a'} {('a',): 'a'} >>> -Arcege On 9/14/06, Tim Johnson wrote: > > * Kermit Rose [060914 18:29]: > > Hello Brian. > > > > Today I read through chapter five of the python tutorial and discovered > > that tuples are not the same thing as lists. > > > > This surprised me. > > > > I do not see any difference in the capability of lists and tuples. > > Hi Kermit: > > Tuples are "read-only" - you can't modify a tuple, > > you can produce a tuple from a list by using the > tuple() function. > you can produce a list from a tuple by using the > list() function - but the original tuple is unchanged. > > You can return multiple values from a function > using tuples. > > > > Why would you use one in preference to the other? > > I use tuples as above and where I don't want data > changed... > > tim > -- > Tim Johnson > http://www.alaska-internet-solutions.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060914/ce77ee81/attachment.html From rabidpoobear at gmail.com Fri Sep 15 05:07:04 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 14 Sep 2006 22:07:04 -0500 Subject: [Tutor] Problems serving up PDF In-Reply-To: <20060915015300.GB19434@johnsons-web.com> References: <20060914153804.ygeyo404scsw48ck@www.email.arizona.edu> <20060915011318.GA19434@johnsons-web.com> <450A02DA.4060202@gmail.com> <20060915015300.GB19434@johnsons-web.com> Message-ID: <450A18D8.9080501@gmail.com> >> One note, you should be using \r\n instead of \n. >> > > Both development and deployment are on a linux OS, so > this is the correct procedure. However, I don't think that > using '\r' does any harm on *nix.... > in fact, it would be the more portable approach. > Thanks for pointing that out. > > Yes, but when developing a server-side CGI script that's returning HTML with headers, you're supposed to always use '\r\n' no matter what platforms the browsers or the server run on. It's part of some specification I'd guess. >> Also, you're putting \r\n\r\n after your header, right? >> > > Not sure what you mean. Either of the functions provide the > header. Could you explain further? > regards > tim > I by no means claim to be an expert at web development. However, I wrote a few simple CGI scripts, and when you're making a header, it goes something like this: Content-type: text/plain\r\n \r\n \r\n \r\n \r\n hello \r\n \r\n \r\n Hi\r\n \r\n \r\n You need those two extra returns so that the browser knows it's done reading the header and it should start decoding the html code. That's all I was referring to. I don't know if you are supposed to use \r\n always or just in the header section, but I bet browsers would handle either case just fine. That's just my opinion on all this stuff. Use \n if it works, I guess. If you think I might be right, investigate further. HTH, -Luke > [snip] > > From john at fouhy.net Fri Sep 15 05:14:12 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 15 Sep 2006 15:14:12 +1200 Subject: [Tutor] tuples versus lists In-Reply-To: <7e5ba9220609141959m2929b1e5wbbc4f6eda233fc73@mail.gmail.com> References: <450A0E2E.1010904@polaris.net> <20060915024215.GE19434@johnsons-web.com> <7e5ba9220609141959m2929b1e5wbbc4f6eda233fc73@mail.gmail.com> Message-ID: <5e58f2e40609142014w5e98f041ye9a73b40b2d76f10@mail.gmail.com> Generally, you should use a tuple when you have different things that you want to clump together to make one data structure. Whereas you should use a list when you have multiple things that are the same, that you want to iterate over. -- John. From pyro9219 at gmail.com Fri Sep 15 05:28:16 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 14 Sep 2006 20:28:16 -0700 Subject: [Tutor] pymssql or ODBC In-Reply-To: References: Message-ID: <1158290896.5189.0.camel@localhost> 4.5 hours... all I'm seeing are a few other libraries, none of which mention having windows authentication :/ On Thu, 2006-09-14 at 16:12 -0700, Chris Hengge wrote: > Does anyone know how to make pymssql use windows authentication? > > Also, can anyone point me to a simple ODBC guide for SQL? > > I'd like to use ODBC if I can so that users of my software dont have > to install extra libraries to use my utilities. > > Thanks. From rabidpoobear at gmail.com Fri Sep 15 05:53:27 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 14 Sep 2006 22:53:27 -0500 Subject: [Tutor] pymssql or ODBC In-Reply-To: <1158290896.5189.0.camel@localhost> References: <1158290896.5189.0.camel@localhost> Message-ID: <450A23B7.2040008@gmail.com> Chris Hengge wrote: > 4.5 hours... all I'm seeing are a few other libraries, none of which > mention having windows authentication :/ > > On Thu, 2006-09-14 at 16:12 -0700, Chris Hengge wrote: > >> Does anyone know how to make pymssql use windows authentication? >> >> No, but if you know how to do it using mssql syntax it's probably the same for python. AFAICT the db libraries just give you an interface into the db's interpreter (if you'd call it that?) and you pass it all the stuff you want it to do. Is that not how pymssql works? >> Also, can anyone point me to a simple ODBC guide for SQL? >> >> I'd like to use ODBC if I can so that users of my software dont have >> to install extra libraries to use my utilities. >> >> Thanks. >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From pyro9219 at gmail.com Fri Sep 15 06:35:47 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 14 Sep 2006 21:35:47 -0700 Subject: [Tutor] pymssql or ODBC In-Reply-To: <450A23B7.2040008@gmail.com> References: <1158290896.5189.0.camel@localhost> <450A23B7.2040008@gmail.com> Message-ID: <1158294947.5189.3.camel@localhost> I'm not sure how it works... all the modules I've seen just seem to be wrappers for odbc... but I can't find any information on connection strings.. I guess I could just try the same connection string I use for c#. On Thu, 2006-09-14 at 22:53 -0500, Luke Paireepinart wrote: > Chris Hengge wrote: > > 4.5 hours... all I'm seeing are a few other libraries, none of which > > mention having windows authentication :/ > > > > On Thu, 2006-09-14 at 16:12 -0700, Chris Hengge wrote: > > > >> Does anyone know how to make pymssql use windows authentication? > >> > >> > No, but if you know how to do it using mssql syntax it's probably the > same for python. > AFAICT the db libraries just give you an interface into the db's > interpreter (if you'd call it that?) > and you pass it all the stuff you want it to do. Is that not how > pymssql works? > >> Also, can anyone point me to a simple ODBC guide for SQL? > >> > >> I'd like to use ODBC if I can so that users of my software dont have > >> to install extra libraries to use my utilities. > >> > >> Thanks. > >> > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > From pyro9219 at gmail.com Fri Sep 15 06:39:00 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 14 Sep 2006 21:39:00 -0700 Subject: [Tutor] pymssql or ODBC In-Reply-To: <450A23B7.2040008@gmail.com> References: <1158290896.5189.0.camel@localhost> <450A23B7.2040008@gmail.com> Message-ID: <1158295140.5189.4.camel@localhost> Now that I've looked, its just a wrapper for _mssql, but this still isn't a solution. On Thu, 2006-09-14 at 22:53 -0500, Luke Paireepinart wrote: > Chris Hengge wrote: > > 4.5 hours... all I'm seeing are a few other libraries, none of which > > mention having windows authentication :/ > > > > On Thu, 2006-09-14 at 16:12 -0700, Chris Hengge wrote: > > > >> Does anyone know how to make pymssql use windows authentication? > >> > >> > No, but if you know how to do it using mssql syntax it's probably the > same for python. > AFAICT the db libraries just give you an interface into the db's > interpreter (if you'd call it that?) > and you pass it all the stuff you want it to do. Is that not how > pymssql works? > >> Also, can anyone point me to a simple ODBC guide for SQL? > >> > >> I'd like to use ODBC if I can so that users of my software dont have > >> to install extra libraries to use my utilities. > >> > >> Thanks. > >> > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > From bgailer at alum.rpi.edu Fri Sep 15 08:14:20 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 14 Sep 2006 23:14:20 -0700 Subject: [Tutor] tuples versus lists In-Reply-To: <5e58f2e40609142014w5e98f041ye9a73b40b2d76f10@mail.gmail.com> References: <450A0E2E.1010904@polaris.net> <20060915024215.GE19434@johnsons-web.com> <7e5ba9220609141959m2929b1e5wbbc4f6eda233fc73@mail.gmail.com> <5e58f2e40609142014w5e98f041ye9a73b40b2d76f10@mail.gmail.com> Message-ID: <450A44BC.8010900@alum.rpi.edu> John Fouhy wrote: > Generally, you should use a tuple when you have different things that > you want to clump together to make one data structure. Whereas you > should use a list when you have multiple things that are the same, > that you want to iterate over. > Different perspective: tuples are immutable, lists are not. One may change a list by various techniques; one may not change a tuple. tuples may be used as dictionary keys; lists may not tuples are found on the right of % (formatting); lists are not -- Bob Gailer 510-978-4454 From pyro9219 at gmail.com Fri Sep 15 08:50:52 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 14 Sep 2006 23:50:52 -0700 Subject: [Tutor] pymssql or ODBC In-Reply-To: <450A23B7.2040008@gmail.com> References: <1158290896.5189.0.camel@localhost> <450A23B7.2040008@gmail.com> Message-ID: <1158303052.5189.7.camel@localhost> OK, so ODBC wont work.. thats not what I thought it was apparently... So... the question remains... how do I use Windows built in authorization in my connection string for an MS SQL2000 server? On Thu, 2006-09-14 at 22:53 -0500, Luke Paireepinart wrote: > Chris Hengge wrote: > > 4.5 hours... all I'm seeing are a few other libraries, none of which > > mention having windows authentication :/ > > > > On Thu, 2006-09-14 at 16:12 -0700, Chris Hengge wrote: > > > >> Does anyone know how to make pymssql use windows authentication? > >> > >> > No, but if you know how to do it using mssql syntax it's probably the > same for python. > AFAICT the db libraries just give you an interface into the db's > interpreter (if you'd call it that?) > and you pass it all the stuff you want it to do. Is that not how > pymssql works? > >> Also, can anyone point me to a simple ODBC guide for SQL? > >> > >> I'd like to use ODBC if I can so that users of my software dont have > >> to install extra libraries to use my utilities. > >> > >> Thanks. > >> > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > From pyro9219 at gmail.com Fri Sep 15 09:19:00 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 15 Sep 2006 00:19:00 -0700 Subject: [Tutor] pymssql or ODBC In-Reply-To: <450A4DFA.6080704@omc-international.com.au> References: <450A4DFA.6080704@omc-international.com.au> Message-ID: <1158304740.5189.11.camel@localhost> looking at your link, is your con wrong? for example... the one on the link you provided is written: con = ("Driver={SQL Server};", "Server=whatever", etc... I am not at work so I dont have the server to run this code against, but it looks like you are doing what I've been trying to accomplish :] On Fri, 2006-09-15 at 16:53 +1000, Joe Healy wrote: > On windows we tend to use: > > import dbi, odbc > > con = odbc.odbc("driver={*SQL* Server};server=(local);database=DBNAME;uid=sa;pwd=;") > cur = con.cursor() > > cur.execute("begin tran") > > # your code here > > > > cur.execute("commit") > > cur.close() > > > I think if you leave off the uid and pwd parts, it will use windows authentication. (maybe) > > I have never managed to find much documentation on this. > > I tend to use http://www.carlprothman.net/Default.aspx?tabid=90 for connection strings. > > Once we have the cursor object it is just the python db api. > > Hope that helps. > > Joe > > > > Chris Hengge wrote: > > Does anyone know how to make pymssql use windows authentication? > > > > Also, can anyone point me to a simple ODBC guide for SQL? > > > > I'd like to use ODBC if I can so that users of my software dont have > > to install extra libraries to use my utilities. > > > > Thanks. > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > From rabidpoobear at gmail.com Fri Sep 15 09:24:23 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 15 Sep 2006 02:24:23 -0500 Subject: [Tutor] pymssql or ODBC In-Reply-To: <1158304740.5189.11.camel@localhost> References: <450A4DFA.6080704@omc-international.com.au> <1158304740.5189.11.camel@localhost> Message-ID: <450A5527.8010701@gmail.com> Chris Hengge wrote: > looking at your link, is your con wrong? for example... > the one on the link you provided is written: > con = ("Driver={SQL Server};", "Server=whatever", etc... > It looks to me like these are all separate commands (I.E. They're separated by a semicolon) So the way you showed and the method Joe used should be equivalent (except his is shorter and yours is more readable :) HTH, -Luke > I am not at work so I dont have the server to run this code against, but > it looks like you are doing what I've been trying to accomplish :] > From pyro9219 at gmail.com Fri Sep 15 10:28:34 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 15 Sep 2006 01:28:34 -0700 Subject: [Tutor] pymssql or ODBC In-Reply-To: <450A5527.8010701@gmail.com> References: <450A4DFA.6080704@omc-international.com.au> <1158304740.5189.11.camel@localhost> <450A5527.8010701@gmail.com> Message-ID: <1158308914.5189.12.camel@localhost> The originally posted code I was refering to also said *SQL* for the driver... which I'm not sure about.. On Fri, 2006-09-15 at 02:24 -0500, Luke Paireepinart wrote: > Chris Hengge wrote: > > looking at your link, is your con wrong? for example... > > the one on the link you provided is written: > > con = ("Driver={SQL Server};", "Server=whatever", etc... > > > It looks to me like these are all separate commands (I.E. They're > separated by a semicolon) > So the way you showed and the method Joe used should be equivalent > (except his is shorter and yours is more readable :) > HTH, > -Luke > > I am not at work so I dont have the server to run this code against, but > > it looks like you are doing what I've been trying to accomplish :] > > > From emilia12 at mail.bg Fri Sep 15 10:35:37 2006 From: emilia12 at mail.bg (emilia12 at mail.bg) Date: Fri, 15 Sep 2006 11:35:37 +0300 Subject: [Tutor] UnicodeEncodeError Message-ID: <1158309337.756823ee41fdc@mail.bg> Hi list, i am using site-package (webPy) that generates "UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-6: ordinal not in range(128)". The full message is: Traceback (most recent call last): File "c:\python24\lib\site-packages\web.py", line 1786, in run_wsgi_app result = self.server.app(env, self.wsgi_start_response) File "c:\python24\lib\site-packages\web.py", line 1662, in wsgifunc result = func() File "c:\python24\lib\site-packages\web.py", line 1642, in func = lambda: handle(inp, fvars) File "c:\python24\lib\site-packages\web.py", line 920, in handle return tocall(*([urllib.unquote(x) for x in args] + fna)) File "wb03.py", line 24, in GET web.render('view.html') File "c:\python24\lib\site-packages\web.py", line 1543, in render return output(str(compiled_tmpl)) File "c:\Python24\Lib\site-packages\Cheetah\Template.py", line 990, in __str__ def __str__(self): return getattr(self, mainMethName)() File "", line 93, in respond File "c:\python24\lib\site-packages\web.py", line 1496, in filter return htmlquote(str(val)) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-6: ordinal not in range(128) So, how can i fix this (from outside of this package)? The attempt with "# -*- coding: utf-8 -*-" does not solve this problem... cheers -e- ----------------------------- ??? ???? ???????? ??????????? :-) ??????? ?? ?????????? ???? - 1,50 ??./?????! www.SuperHosting.bg - ??????????? ??????? ??????? From tim.golden at viacom-outdoor.co.uk Fri Sep 15 10:41:32 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 15 Sep 2006 09:41:32 +0100 Subject: [Tutor] pymssql or ODBC Message-ID: [Chris Hengge] | Does anyone know how to make pymssql use windows authentication? I'm fairly sure, from previous experience and a brief perusal of the source, that pymssql doesn't offer the possibility of pass-through authentication. When I use it, I have to ask my DBA to set up a specific user. The usual place to look for connection strings for ODBC, ADO etc. is http://connectionstrings.com. I just tried downloading the latest mxODBC and using the connection string from there, only to get an internal error... I'll try a new download just in case. But you've also got ADO: the adodbapi module, while unmaintained, does in fact work. It's a mite quirky, due partly from having to work round variations in ADO versions. But we do use it for pass-through authentication. (connectionstrings.com again for DSN). TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From tim.golden at viacom-outdoor.co.uk Fri Sep 15 10:59:54 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 15 Sep 2006 09:59:54 +0100 Subject: [Tutor] pymssql or ODBC Message-ID: | Does anyone know how to make pymssql use windows authentication? | | Also, can anyone point me to a simple ODBC guide for SQL? OK, bit of a summary. If it's not answering your questions, hopefully it'll answer someone else's! 1) mxODBC [http://www.egenix.com/files/python/mxODBC.html] NB: Needs commercial license for non-personal use from mx.ODBC import Windows as odbc db = odbc.DriverConnect ("Driver={SQL Server};Server=VODEV1;Database=EVOBACK;Trusted_Connection=yes;") q = db.cursor () q.execute ("SELECT SYSTEM_USER") for row in q.fetchall (): print row 2) adodbapi [http://adodbapi.sourceforge.net/] NB Appears to be unmaintained import adodbapi db = adodbapi.connect ("Provider=SQLOLEDB;Data Source=VODEV1;Initial Catalog=EVOBACK;Integrated Security=SSPI;") q = db.cursor () q.execute ("SELECT SYSTEM_USER") for row in q.fetchall (): print row 3) pymssql [http://pymssql.sourceforge.net/] NB Currentish (last release Feb 2006) doesn't support Windows auth doesn't handle Unicode v. well (cf some recent posts on c.l.py) the MS DLL it uses is deprecated import pymssql db = pymssql.connect (host="VODEV1",user='USER',password='PASSWORD',database='EVOBACK') q = db.cursor () q.execute ("SELECT SYSTEM_USER") for row in q.fetchall (): print row 4) ObjectCraft mssql [http://www.object-craft.com.au/projects/mssql/] NB Doesn't appear to be going any further no supplied DLL for > Python 2.3 same DLL issue as pymssql I've used it lots over the last few years and it's pretty solid import MSSQL db = MSSQL.connect ("VODEV1", "", "", "EVOBACK") q = db.cursor () q.execute ("SELECT SYSTEM_USER") for row in q.fetchall (): print row TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From simon at brunningonline.net Fri Sep 15 11:44:21 2006 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 15 Sep 2006 10:44:21 +0100 Subject: [Tutor] How do I open my browser from within a Python program In-Reply-To: References: <5E5EE09E-2C03-11DB-B3EC-000A95EA5592@well.com> <44E136E3.1020307@gmail.com> <45092CD6.1000203@slingshot.co.nz> <8c7f10c60609140333o52c95b8m185ba490f30e222c@mail.gmail.com> Message-ID: <8c7f10c60609150244hf77b81co9502d85b59449cb@mail.gmail.com> On 9/15/06, Will Shattuck wrote: > On 9/14/06, Simon Brunning wrote: > > > > To open a web browser from within a python program, you want something like: > > > > import webbrowser > > webbrowser.open('www.google.com') > > > > I learned something tonight :) I only have 5 or 10 minutes here and > there to do any learning with python. So when I saw this my interest > was raised. So I started IDLE, and tried it out. It didn't work as > above so, I looked for the python module to make sure I was typing > everything correctly. The only thing I missed was that there should > be double quotes instead of single quotes. Why, I don't know yet as > I'm not that far, but it kind of makes sense from my dabbling with > programming over the last 5 years. > > import webbrowser > webbrowser.open("www.google.com") I think you must have had some other issue. In Python, string literals can be delimited by either singe or double quotes - the resulting string is identical. (The difference is that in a single quoted strung, you can use double quote characters without quoting, and vice-versa. There's yet more to sting literals that this - raw stings, triple-quoted strings, unicode strings - see for details.) -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From kent37 at tds.net Fri Sep 15 11:58:17 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 15 Sep 2006 05:58:17 -0400 Subject: [Tutor] UnicodeEncodeError In-Reply-To: <1158309337.756823ee41fdc@mail.bg> References: <1158309337.756823ee41fdc@mail.bg> Message-ID: <450A7939.3010803@tds.net> emilia12 at mail.bg wrote: > Hi list, > > i am using site-package (webPy) that generates > "UnicodeEncodeError: 'ascii' codec can't encode characters > in position 0-6: ordinal not in range(128)". It looks like your data contains unicode strings. When you call str() on a unicode string it tries to encode it using the default encoding which is usually ascii. If the string contains non-ascii characters this attempt fails. The solution is probably to encode your data yourself using the codec of your choice, for example utf-8. I can't tell from the traceback where the data comes from but you need to do something like s = s.encode('utf-8') Kent > > The full message is: > Traceback (most recent call last): > File "c:\python24\lib\site-packages\web.py", line 1786, in > run_wsgi_app > result = self.server.app(env, self.wsgi_start_response) > File "c:\python24\lib\site-packages\web.py", line 1662, in > wsgifunc > result = func() > File "c:\python24\lib\site-packages\web.py", line 1642, in > > func = lambda: handle(inp, fvars) > File "c:\python24\lib\site-packages\web.py", line 920, in > handle > return tocall(*([urllib.unquote(x) for x in args] + > fna)) > File "wb03.py", line 24, in GET > web.render('view.html') > File "c:\python24\lib\site-packages\web.py", line 1543, in > render > return output(str(compiled_tmpl)) > File "c:\Python24\Lib\site-packages\Cheetah\Template.py", > line 990, in __str__ > def __str__(self): return getattr(self, mainMethName)() > File "", line 93, in respond > File "c:\python24\lib\site-packages\web.py", line 1496, in > filter > return htmlquote(str(val)) > UnicodeEncodeError: 'ascii' codec can't encode characters in > position 0-6: ordinal not in range(128) > > > So, how can i fix this (from outside of this package)? The > attempt with "# -*- coding: utf-8 -*-" does not solve this > problem... > > > cheers > -e- > > > ----------------------------- > > ??? ???? ???????? ??????????? :-) > ??????? ?? ?????????? ???? - 1,50 ??./?????! > www.SuperHosting.bg - ??????????? ??????? ??????? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From janos.juhasz at VELUX.com Fri Sep 15 13:52:23 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Fri, 15 Sep 2006 13:52:23 +0200 Subject: [Tutor] pymssql or ODBC In-Reply-To: Message-ID: I am using the next two solution for connecting to our mssql server when the odbc connection is set for all the PCs, I use this: import dbi, odbc cn = odbc.odbc('DSN=scalaDB;UID=query;PWD=query;DATABASE=DB') When there is no connection set and distributed, I usually choose this import win32com.client cn =win32com.client.Dispatch('ADODB.connection') cn.Provider='sqloledb' cn.Open('Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=production;Data Source=MyServername') To create the correct connection string I follow this simple method: -right click on the desktop and create a new text document -save it as connection.udl -double click on it, and it will be opened by windows to set up all the possible parameters -test the connection -open it with notepad and copy the string from it Yours sincerely, ______________________________ J?nos Juh?sz > [Chris Hengge] > | Does anyone know how to make pymssql use windows authentication? > I'm fairly sure, from previous experience and a brief > perusal of the source, that pymssql doesn't offer the > possibility of pass-through authentication. When I use > it, I have to ask my DBA to set up a specific user. > The usual place to look for connection strings for > ODBC, ADO etc. is http://connectionstrings.com. I just > tried downloading the latest mxODBC and using the connection > string from there, only to get an internal error... I'll try > a new download just in case. > But you've also got ADO: the adodbapi module, while unmaintained, > does in fact work. It's a mite quirky, due partly from having to > work round variations in ADO versions. But we do use it for > pass-through authentication. (connectionstrings.com again for DSN). From python at venix.com Fri Sep 15 14:25:08 2006 From: python at venix.com (Python) Date: Fri, 15 Sep 2006 08:25:08 -0400 Subject: [Tutor] Problems serving up PDF In-Reply-To: <20060915020116.GC19434@johnsons-web.com> References: <20060914153804.ygeyo404scsw48ck@www.email.arizona.edu> <20060915011318.GA19434@johnsons-web.com> <450A02DA.4060202@gmail.com> <20060915020116.GC19434@johnsons-web.com> Message-ID: <1158323108.9975.93.camel@www.venix.com> On Thu, 2006-09-14 at 18:01 -0800, Tim Johnson wrote: > * Luke Paireepinart [060914 17:37]: > > > > > Sounds like it's working to me. > > > On Internet Explorer 6, Windows XP, the user experience is different. > > > IE ignores the file name, and does no progress reporting, but does > > > "understand" the file type. > > > > > Sounds like it's working to me. > > > > > > As far as I can tell, it seems to me like you have some file (example .wmv) > > that I.E. is saying 'okay I know how to open this' and it tries to do > > something with it. > > Firefox, humble as it is, admits that it doesn't know what to do and > > just lets you download it. > > If this is the case, then it's a configuration issue with IE that's > > making it attempt to open the file. > > You could just as well configure Firefox to automatically open these > > files too, although > > that doesn't mean that it'll work :) > > > > So unless you can be more specific, I'd say that it's just a difference > > in the browser and not a problem > > with your code at all. Do I not understand correctly? > > HTH, > > Hey Luke: > I also posted this to a forum: > One expert response reads like this: > > "I think that's just the way Mozilla acts." > > Actually, I like the way Firefox does it. Looks like we just live > with the differences. > thanks again > tim There is a Firefox extension called TamperData that allows you to examine and change the headers. This extension is very handy for debugging these kinds of issues. My Apache web server returns these headers when I request a pdf file: Status=OK - 200 Date=Fri, 15 Sep 2006 12:03:37 GMT Server=Apache/2.0.53 (Fedora) Last-Modified=Tue, 06 Jun 2006 16:50:30 GMT Etag="68061-6a29d-c70c180" Accept-Ranges=bytes Content-Length=434845 Connection=close Content-Type=application/pdf X-Pad=avoid browser bug The last two should be of interest to you. I did not try to google X- Pad or "avoid browser bug", but google might provide more background. In any case, Tamper Data allows you to see what a working web site does to succeed. Imitation is the sincerest form of flattery. -- Lloyd Kvam Venix Corp From johan at accesstel.co.za Fri Sep 15 14:39:07 2006 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Fri, 15 Sep 2006 14:39:07 +0200 Subject: [Tutor] quick ? In-Reply-To: <45082161.2010207@alum.rpi.edu> References: <45082161.2010207@alum.rpi.edu> Message-ID: <450A9EEB.4080605@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060915/5cf7f86d/attachment.htm From hmm at woolgathering.cx Fri Sep 15 18:55:16 2006 From: hmm at woolgathering.cx (William O'Higgins Witteman) Date: Fri, 15 Sep 2006 12:55:16 -0400 Subject: [Tutor] Trying to catch an exception... Message-ID: <20060915165516.GA13683@sillyrabbi.dyndns.org> I am running a program (via py2exe) that is reading some XML files with xml.minidom. I am getting an error wherein I pull a value from a tag which (I think) happens to be empty. Thus, it throws this error: AttributeError: 'NoneType' object has no attribute 'data' Here's the code that creates this problem: def functionname(fileobject): try: xmldoc = minidom.parse(fileobject) except xml.parsers.expat.ExpatError, AttributeError: logit = "There is a malformed file: " + fileobject + "\n" logfile.write(logit) else: a = xmldoc.getElementsByTagName('date_modified') try: b = a[0].firstChild.data except xml.parsers.expat.ExpatError, AttributeError: logit = "There is a malformed file: " + fileobject + "\n" logfile.write(logit) I am wondering what I have to do to catch this exception - I'm assuming that the problem is that "a" is an empty object, and so it has not attributes. Thanks. -- yours, William From dkuhlman at rexx.com Fri Sep 15 22:11:43 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 15 Sep 2006 13:11:43 -0700 Subject: [Tutor] tuples versus lists In-Reply-To: <450A44BC.8010900@alum.rpi.edu> References: <450A0E2E.1010904@polaris.net> <20060915024215.GE19434@johnsons-web.com> <7e5ba9220609141959m2929b1e5wbbc4f6eda233fc73@mail.gmail.com> <5e58f2e40609142014w5e98f041ye9a73b40b2d76f10@mail.gmail.com> <450A44BC.8010900@alum.rpi.edu> Message-ID: <20060915201143.GB51767@cutter.rexx.com> On Thu, Sep 14, 2006 at 11:14:20PM -0700, Bob Gailer wrote: > John Fouhy wrote: > > Generally, you should use a tuple when you have different things that > > you want to clump together to make one data structure. Whereas you > > should use a list when you have multiple things that are the same, > > that you want to iterate over. > > > Different perspective: tuples are immutable, lists are not. One may > change a list by various techniques; one may not change a tuple. > Trying hard to be picky here ... It's good to remember that, although you cannot change a tupble itself, you can change the objects that the tuple references, *if* they are mutable. For example (in the ipython prompt): In [1]: d1 = {} In [2]: d2 = {} In [3]: t1 = (d1, d2) In [4]: In [4]: t1 Out[4]: ({}, {}) In [5]: t1[0]['name'] = 'dave' In [6]: In [6]: t1 Out[6]: ({'name': 'dave'}, {}) In [7]: > tuples may be used as dictionary keys; lists may not Good point. A dictionary with tuples as keys can be used to represent multi-dimensional, sparse arrays. > tuples are found on the right of % (formatting); lists are not A list can be used on the right side of the formatting operator, but python interprets it as a single object, not multiple objects to be fed into the formatting specifiers. So, for example, this gives an error: In [7]: 'item 1: %s and item 2: %s' % [11, 22] --------------------------------------------------------------------------- exceptions.TypeError Traceback (most recent call last) /home/dkuhlman/ TypeError: not enough arguments for format string In [8]: But, this does not: In [8]: 'item 1: %s' % [11, 22] Out[8]: 'item 1: [11, 22]' In [9]: Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From alan.gauld at btinternet.com Fri Sep 15 22:29:59 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 15 Sep 2006 21:29:59 +0100 Subject: [Tutor] Trying to catch an exception... References: <20060915165516.GA13683@sillyrabbi.dyndns.org> Message-ID: "William O'Higgins Witteman" wrote in message news:20060915165516.GA13683 at sillyrabbi.dyndns.org... >I am running a program (via py2exe) that is reading some XML files >with > xml.minidom. I am getting an error wherein I pull a value from a > tag > which (I think) happens to be empty. Thus, it throws this error: > > AttributeError: 'NoneType' object has no attribute 'data' > > Here's the code that creates this problem: > > def functionname(fileobject): > try: > xmldoc = minidom.parse(fileobject) > except xml.parsers.expat.ExpatError, AttributeError: > logit = "There is a malformed file: " + fileobject + "\n" > logfile.write(logit) > else: > a = xmldoc.getElementsByTagName('date_modified') > try: > b = a[0].firstChild.data > except xml.parsers.expat.ExpatError, AttributeError: > logit = "There is a malformed file: " + fileobject + "\n" > logfile.write(logit) > > I am wondering what I have to do to catch this exception - I'm > assuming > that the problem is that "a" is an empty object, and so it has not > attributes. Thanks. I'm not sure what your problem is but you could simplify the code by using a single try/except pair here, there is no advantage to using two as you show here.(At least i can't think of any) Your code would thus become: def functionname(fileobject): try: xmldoc = minidom.parse(fileobject) a = xmldoc.getElementsByTagName('date_modified') b = a[0].firstChild.data except xml.parsers.expat.ExpatError, AttributeError: logit = "There is a malformed file: " + fileobject + "\n" logfile.write(logit) But I might also put an 'if' check in the code: a = xmldoc.getElementsByTagName('date_modified') if a and a.firstChild: b = a[0].firstChild.data else: print 'no date_modified' # or set a default or whatever but then you would expect the except clause to pick that up. Sorry I can't be more help. Alan G. From kent37 at tds.net Sat Sep 16 05:58:22 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 15 Sep 2006 23:58:22 -0400 Subject: [Tutor] Trying to catch an exception... In-Reply-To: <20060915165516.GA13683@sillyrabbi.dyndns.org> References: <20060915165516.GA13683@sillyrabbi.dyndns.org> Message-ID: <450B765E.9020606@tds.net> William O'Higgins Witteman wrote: > I am running a program (via py2exe) that is reading some XML files with > xml.minidom. I am getting an error wherein I pull a value from a tag > which (I think) happens to be empty. Thus, it throws this error: > > AttributeError: 'NoneType' object has no attribute 'data' > > Here's the code that creates this problem: > > def functionname(fileobject): > try: > xmldoc = minidom.parse(fileobject) > except xml.parsers.expat.ExpatError, AttributeError: This should be written, except (xml.parsers.expat.ExpatError, AttributeError): The parentheses are important. The way you have written it, an instance of ExpatError, if it occurs, will be bound to the name AttributeError; AttributeErrors will not be caught at all. Kent > logit = "There is a malformed file: " + fileobject + "\n" > logfile.write(logit) > else: > a = xmldoc.getElementsByTagName('date_modified') > try: > b = a[0].firstChild.data > except xml.parsers.expat.ExpatError, AttributeError: > logit = "There is a malformed file: " + fileobject + "\n" > logfile.write(logit) > > I am wondering what I have to do to catch this exception - I'm assuming > that the problem is that "a" is an empty object, and so it has not > attributes. Thanks. From srini_iyyer_bio at yahoo.com Sat Sep 16 08:49:47 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Fri, 15 Sep 2006 23:49:47 -0700 (PDT) Subject: [Tutor] Limitation of range() function in Walking problem Message-ID: <20060916064947.4230.qmail@web38107.mail.mud.yahoo.com> Dear tutors: this question is in continuation of my previous question about list manipulations where Kent and Bob helped me. Thanks to you both. My aim was to walk along coordinates of exon of a gene on a chromosome. In simple terms: Coordinates of a variable G1: a1 : 3-8 b2 : 10-25 c3 : 7-18 d4 : 10-13 Now, since these coordinates are in ranges of others, I can define the extreames of the variables, which are 3 and 25. Example pictorially: 3-----8 10---------------25 7-------------18 10---13 Now, I have variables G1....Gn. Each variable may have individual pieces a1(n),b2(n),c3(n).....z(n). my kind of solution, which is very crappy (i assume): Sort the list: [3,8] [3,8] [10,25] sort [7,18] [7,18] --------> [10,13] [10,13] [10,25] I loop through each list and check if list[0] is in range of previous list list[1] AND if it is less or greater than. If less, I retain the greater number and loop through. The question to the forum is, I am using range() function to solve this. Since the numbers in the example are small, it worked. in the real world example , it did not work, because computer slowed down and eventually crashed. The range(81393417) is really big. question: 1. What to do If I have to check if a number is in range of 81393417. 2. Is there any alternative. 3. is solution that I have, is it appropriate. Please help. My real world example: kd ={'GeneID:1519': ['81393417\t81395369','81397635\t81397727','81398841\t81399004','81406661\t81406782','81408670\t81408837','81411616\t81411755','81412455\t81412563','81423012\t81423195'], 'GeneID:445347':['37788202\t37788789','37790730\t37790777','37793908\t37794237','37802146\t37802206''37788202\t37788789','37790730\t37790777','37793908\t37794237','37802146\t37802206']} kk = ['GeneID:1519','GeneID:1519','GeneID:445347'] for i in kk: if kd.has_key(i): pairs = [map(int,x.split('\t'))for x in kd[i]] pairs.sort() i = iter(pairs) last = i.next() for cur in pairs: if cur[0] in range(last[1]): if cur[1] > last[1]: last = [last[0],cur[1]] else: last = [last[0],last[1]] else: print last cur = last print last Thanks __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From rabidpoobear at gmail.com Sat Sep 16 08:57:33 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 16 Sep 2006 01:57:33 -0500 Subject: [Tutor] Limitation of range() function in Walking problem In-Reply-To: <20060916064947.4230.qmail@web38107.mail.mud.yahoo.com> References: <20060916064947.4230.qmail@web38107.mail.mud.yahoo.com> Message-ID: <450BA05D.50606@gmail.com> Srinivas Iyyer wrote: > Dear tutors: > > this question is in continuation of my previous > question about list manipulations where Kent and Bob > helped me. > Thanks to you both. > > My aim was to walk along coordinates of exon of a gene > on a chromosome. In simple terms: > > > Coordinates of a variable G1: > a1 : 3-8 > b2 : 10-25 > c3 : 7-18 > d4 : 10-13 > > Now, since these coordinates are in ranges of others, > I can define the extreames of the variables, which are > 3 and 25. > > Example pictorially: > > 3-----8 > 10---------------25 > 7-------------18 > 10---13 > > > Now, I have variables G1....Gn. Each variable may > have individual pieces a1(n),b2(n),c3(n).....z(n). > > my kind of solution, which is very crappy (i assume): > > Sort the list: > [3,8] [3,8] > [10,25] sort [7,18] > [7,18] --------> [10,13] > [10,13] [10,25] > > I loop through each list and check if list[0] is in > range of previous list list[1] AND if it is less or > greater than. If less, I retain the greater number and > loop through. > > The question to the forum is, I am using range() > function to solve this. Since the numbers in the > example are small, it worked. in the real world > example , it did not work, because computer slowed > down and eventually crashed. The range(81393417) is > really big. > > question: > 1. What to do If I have to check if a number is in > range of 81393417. > > 2. Is there any alternative. > The function 'range()' generates a list in memory of all the integers from 0 to n. This is a lot of memory, as you can probably tell. Try using an iteration function. example: 'xrange()' That won't generate the intermediate list that the for loop loops over, so it will be slightly slower over each iteration (since the function 'xrange()' is called every loop and it returns the next number) but it won't eat up all that memory > 3. is solution that I have, is it appropriate. > I don't know, I'm in the middle of writing some code and I don't want to forget what I was doing, so I didn't read any of yours. Hope the xrange tip helps, though. Another alternative is to use a while loop and a control variable that you just increment on each loop iteration. I'm guessing the reason it's crashing is because you're running out of memory and the computer's getting mad at you. -Luke > Please help. > > > My real world example: > > > kd ={'GeneID:1519': > ['81393417\t81395369','81397635\t81397727','81398841\t81399004','81406661\t81406782','81408670\t81408837','81411616\t81411755','81412455\t81412563','81423012\t81423195'], > > 'GeneID:445347':['37788202\t37788789','37790730\t37790777','37793908\t37794237','37802146\t37802206''37788202\t37788789','37790730\t37790777','37793908\t37794237','37802146\t37802206']} > > kk = ['GeneID:1519','GeneID:1519','GeneID:445347'] > > > for i in kk: > if kd.has_key(i): > pairs = [map(int,x.split('\t'))for x > in kd[i]] > pairs.sort() > i = iter(pairs) > last = i.next() > for cur in pairs: > if cur[0] in range(last[1]): > if cur[1] > last[1]: > last = > [last[0],cur[1]] > else: > last = > [last[0],last[1]] > else: > print last > cur = last > print last > > > > Thanks > > > > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From srini_iyyer_bio at yahoo.com Sat Sep 16 08:57:48 2006 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Fri, 15 Sep 2006 23:57:48 -0700 (PDT) Subject: [Tutor] List manipulation In-Reply-To: <45092609.2040703@tds.net> Message-ID: <20060916065748.95019.qmail@web38108.mail.mud.yahoo.com> Dear Kent and Bob, thank you for your solutions. It helped, however, based on your suggestions, I intended to solve a chromosome walking problem. I posted my question on subject name: 'Limitation of range() function in Walking problem'. Thanks again. Sri --- Kent Johnson wrote: > Srinivas Iyyer wrote: > > Thank you Bob for your email. > > Sorry for the confusion. > > here is what I ment: > > > > test = ['10\t15', '16\t20', '25\t35', '45\t50', > > '55\t60', '61\t65', '75\t80'] > > >>> I would get: > >>> 10 20 > >>> 25 35 > >>> 45 50 > >>> 55 65 > >>> 75 80 > > Here is my take on it: > > test = ['10\t15', '16\t20', '25\t35', > '45\t50','55\t60', '61\t65', '75\t80'] > > pairs = [ map(int, x.split('\t')) for x in test ] > > i = iter(pairs) > > last = i.next() > > for current in i: > if current[0] == last[1]+1: > last = [last[0], current[1]] > else: > print last > last = current > > print last > > > You can also wrap this in a generator which yields > the desired pairs, so > they can be printed or put in a list or whatever: > > def compress(pairs): > i = iter(pairs) > > last = i.next() > > for current in i: > if current[0] == last[1]+1: > last = [last[0], current[1]] > else: > yield last > last = current > > yield last > > > for pair in compress(pairs): > print pair > > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From alan.gauld at freenet.co.uk Sat Sep 16 09:44:49 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 16 Sep 2006 08:44:49 +0100 Subject: [Tutor] Limitation of range() function in Walking problem References: <20060916064947.4230.qmail@web38107.mail.mud.yahoo.com> Message-ID: <001b01c6d963$fd4735d0$0201a8c0@XPpro> > I loop through each list and check if list[0] is in > range of previous list list[1] AND if it is less or > greater than. If less, I retain the greater number and > loop through. ... > example are small, it worked. in the real world > example , it did not work, because computer slowed > down and eventually crashed. The range(81393417) is > really big. Rather than use 'in' just compare against the limits. if num in range(min, max): becomes if min < num < max: The first version has to construct a list size max then it has to cycle through the list comparing every entry with num. Because its a contiguous range you only want to compare with the bottom and top, which is much faster. HTH, Alan G. From project5 at redrival.net Sat Sep 16 09:52:22 2006 From: project5 at redrival.net (Andrei) Date: Sat, 16 Sep 2006 09:52:22 +0200 Subject: [Tutor] Limitation of range() function in Walking problem In-Reply-To: <20060916064947.4230.qmail@web38107.mail.mud.yahoo.com> References: <20060916064947.4230.qmail@web38107.mail.mud.yahoo.com> Message-ID: Srinivas Iyyer wrote: > Coordinates of a variable G1: > a1 : 3-8 > b2 : 10-25 > c3 : 7-18 > d4 : 10-13 > Now, I have variables G1....Gn. Each variable may > have individual pieces a1(n),b2(n),c3(n).....z(n). > > my kind of solution, which is very crappy (i assume): > > Sort the list: > [3,8] [3,8] > [10,25] sort [7,18] > [7,18] --------> [10,13] > [10,13] [10,25] > > The question to the forum is, I am using range() > function to solve this. Since the numbers in the > example are small, it worked. in the real world > example , it did not work, because computer slowed > down and eventually crashed. The range(81393417) is > really big. I'm not sure I fully understand the question - do you NEED to loop over the possible locations, or do you only need to determine the extremes of the 4 ranges? If you need a loop, xrange is probably the way to go, as Luke mentions. If you just need the extremes, you don't need a range(), because it can be done using zip: >>> a,b,c,d = [3,8], [10,25], [7,18], [10,13] >>> candidates = zip(a,b,c,d) # 'merges' the elements of the lists >>> print candidates # first item contains potential minimums [(3, 10, 7, 10), (8, 25, 18, 13)] # second item potential maxes >>> maxrange = [ min(candidates[0]), max(candidates[1]) ] >>> print maxrange [3, 25] Now if you have a non-continuous range, this will still give you the overlapping area. E.g. if you'd drop c3, it would not affect the result. If that's a problem, you could loop over the lists directly: def getMaxRange(locs): locs.sort() # sorts 'naturally' #print "sorted locs:", locs maxrange = locs[0][:] # guaranteed to start with min for loc in locs[1:]: # loop over rest of locs if loc[0] <= maxrange[1]: maxrange[1] = loc[1] else: print " discontinuity found for", loc return None return maxrange It's similar to your solution, but without the range - they're superfluous. Yours, Andrei From nelson1977 at gmail.com Sat Sep 16 15:18:41 2006 From: nelson1977 at gmail.com (nelson -) Date: Sat, 16 Sep 2006 15:18:41 +0200 Subject: [Tutor] ANN: pyfuzzylib 0.1.3 Released Message-ID: PyFuzzyLib is a library for fuzzy inference engine building. Using pyfuzzylib you can add fuzzy logic to your programs. The program is in it early stage of development, but it is still usable. Every sort of feedback is appreciated! the project homepage is http://sourceforge.net/projects/pyfuzzylib good afternoon, nelson From mjj at pythonin.dk Sat Sep 16 15:29:42 2006 From: mjj at pythonin.dk (Morten Juhl Johansen) Date: Sat, 16 Sep 2006 15:29:42 +0200 Subject: [Tutor] Lists in lists Message-ID: <450BFC46.1050508@pythonin.dk> # Newbie warning I am making a timeline program. It is fairly simple. I base it on appending lists to a list. Ex. [[year1, "headline1", "event text1"], [year2, "headline2", "event text2"]] This seemed like a brilliant idea when I did it. It is easy to sort. Now, if I want to OUTPUT it, how do I indicate that I want to extract first entry in a list in a list? How do I print the separate entries? Yours, Morten __ http://mjj.slacking.dk From project5 at redrival.net Sat Sep 16 16:23:22 2006 From: project5 at redrival.net (Andrei) Date: Sat, 16 Sep 2006 16:23:22 +0200 Subject: [Tutor] Lists in lists In-Reply-To: <450BFC46.1050508@pythonin.dk> References: <450BFC46.1050508@pythonin.dk> Message-ID: Morten Juhl Johansen wrote: > # Newbie warning > I am making a timeline program. It is fairly simple. > I base it on appending lists to a list. > Ex. > [[year1, "headline1", "event text1"], [year2, "headline2", "event text2"]] > > This seemed like a brilliant idea when I did it. It is easy to sort. > Now, if I want to OUTPUT it, how do I indicate that I want to extract > first entry in a list in a list? How do I print the separate entries? Just append the position indicators, e.g. "print MyList[0][1]" will take item #0 in MyList and request its item #1. It's equivalent to saying MySubList = MyList[0] print MySubList[1] In an interactive session: >>> li = [[1,2], [3,4]] >>> li[0] [1, 2] >>> li[0][0] 1 >>> li[0][1] 2 >>> li[1][1] 4 Yours, Andrei From perronbe at gmail.com Sat Sep 16 16:44:39 2006 From: perronbe at gmail.com (Brian Edward) Date: Sat, 16 Sep 2006 09:44:39 -0500 Subject: [Tutor] Data structure question / PyGoogle Message-ID: <1e6b5c080609160744p748c9a7cy49a4016a1849331c@mail.gmail.com> Hello all, I am new to Python (and programming in general) and am trying to get PyGoogle figured out for some specific research interests. Basically, I have done a simple search using PyGoogle and have some sitting in memory. I have an object data.results, which is apparently a list: >>> type(data.results) In this list, I have ten URL saved, which I can access by using the brackets and noting the specific elements. For example: >>> data.results[0].URL 'http://www.psychguides.com/gl-treatment_of_schizophrenia_1999.html' >>> data.results[1].URL 'http://www.psychguides.com/sche.pdf' My question is, how can I access all ten URLs in a single command. Specifically, why does the following statement not work: >>> data.results[0:10].URL Traceback (most recent call last): File "", line 1, in -toplevel- data.results[0:10].URL AttributeError: 'list' object has no attribute 'URL' Again, I am new to Python, so a watered-down, conceptual response to this would be greatly appreciated. Thanks in advance. Brian -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060916/882d26df/attachment.htm From alan.gauld at btinternet.com Sat Sep 16 17:18:44 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 16 Sep 2006 16:18:44 +0100 Subject: [Tutor] Data structure question / PyGoogle References: <1e6b5c080609160744p748c9a7cy49a4016a1849331c@mail.gmail.com> Message-ID: > In this list, I have ten URL saved, which I can access by using the > brackets > and noting the specific elements. For example: > >>>> data.results[0].URL > 'http://www.psychguides.com/gl-treatment_of_schizophrenia_1999.html' > My question is, how can I access all ten URLs in a single command. > Specifically, why does the following statement not work: > >>>> data.results[0:10].URL The list slice returns another list. And as the error says lists do not have a URL attribute. You can either write a loop to return the URLs urls = [] for url in data.results: urls.append(url.URL) or more Pythonically use a List Comprehension, which combines all of that in one line: urls = [url.URL for url in data.results] In general when you want to convert a list of something to another list of something, either a subset of the original or a transformed version, like here, use a list comprehension. newlist = [f(x) for x in oldlist ] > Again, I am new to Python, so a watered-down, conceptual response to > this > would be greatly appreciated. Thanks in advance. You can find more on list comrehensions in the functional programming topic of my tutor - about half way down the page... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From python at venix.com Sat Sep 16 17:22:39 2006 From: python at venix.com (Python) Date: Sat, 16 Sep 2006 11:22:39 -0400 Subject: [Tutor] Data structure question / PyGoogle In-Reply-To: <1e6b5c080609160744p748c9a7cy49a4016a1849331c@mail.gmail.com> References: <1e6b5c080609160744p748c9a7cy49a4016a1849331c@mail.gmail.com> Message-ID: <1158420159.9975.259.camel@www.venix.com> On Sat, 2006-09-16 at 09:44 -0500, Brian Edward wrote: > Hello all, > > I am new to Python (and programming in general) and am trying to get > PyGoogle figured out for some specific research interests. Basically, > I have done a simple search using PyGoogle and have some sitting in > memory. I have an object data.results, which is apparently a list: > > >>> type(data.results) > > > In this list, I have ten URL saved, which I can access by using the > brackets and noting the specific elements. For example: > > >>> data.results[0].URL > 'http://www.psychguides.com/gl-treatment_of_schizophrenia_1999.html' > > >>> data.results [1].URL > 'http://www.psychguides.com/sche.pdf' > > My question is, how can I access all ten URLs in a single command. > Specifically, why does the following statement not work: > > >>> data.results[0:10].URL You need to extract the URL from each item in the result list. Something like: urls = [r.URL for r in data.results] will extract a list of urls from your list of results. > > Traceback (most recent call last): > File "", line 1, in -toplevel- > data.results[0:10].URL > AttributeError: 'list' object has no attribute 'URL' > > > Again, I am new to Python, so a watered-down, conceptual response to > this would be greatly appreciated. Thanks in advance. data.results[0:10] simply copies the first 10 results from your original list into a new list. The new list does not have a URL attribute, as the error message tells us. The URL attribute belongs to the individual items in the list. You need to process each result in data.results to extract the URL. Your choices boil down to: for statement or the more functionally oriented map list comprehension generator expression (python 2.4 or later) For creating a new list from an existing list, a list comprehension is usually the best bet. The for statement approach would look something like: urls = [] for r in data.results: urls.append(r.URL) list comprehensions provide a simpler, more direct syntax. > > Brian > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From ziad.rahhal at gmail.com Sat Sep 16 17:54:39 2006 From: ziad.rahhal at gmail.com (Ziad Rahhal) Date: Sat, 16 Sep 2006 17:54:39 +0200 Subject: [Tutor] From byte[] to Image Message-ID: Hi, I convert an Image to bye array in Java (web-services) and send it to a python client. At the client side (python code) i receive the bytes, and then i need to transform them into the image again. Here is what I am doing: #************************************************************** # fileName is the path of the file stream = service.getFile(fileName) file = open("pic.jpeg", 'w') img = Image.frombuffer("1", (128, 128), stream) img.save(file) file.close() #************************************************************** The Java method is: "public byte[] getFile(String path)" This is not working. I am not able to get all the data of the image and for sure not able to form the complete image. Any solution for that? Thank you in advance, Ziad -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060916/096f1079/attachment.html From python at venix.com Sat Sep 16 18:12:16 2006 From: python at venix.com (Python) Date: Sat, 16 Sep 2006 12:12:16 -0400 Subject: [Tutor] Data structure question / PyGoogle In-Reply-To: <1e6b5c080609160831o7f06333en23d60ae94d41bf47@mail.gmail.com> References: <1e6b5c080609160744p748c9a7cy49a4016a1849331c@mail.gmail.com> <1158420159.9975.259.camel@www.venix.com> <1e6b5c080609160831o7f06333en23d60ae94d41bf47@mail.gmail.com> Message-ID: <1158423136.9975.267.camel@www.venix.com> (forwarding to list) On Sat, 2006-09-16 at 10:31 -0500, Brian Edward wrote: > Thanks for the quick reply! I really appreciate your assistance. Of > course, it will take some time to get this worked out, but your > explanation is very clear. > > Best, > Brian > > > On 9/16/06, Python wrote: > On Sat, 2006-09-16 at 09:44 -0500, Brian Edward wrote: > > Hello all, > > > > I am new to Python (and programming in general) and am > trying to get > > PyGoogle figured out for some specific research > interests. Basically, > > I have done a simple search using PyGoogle and have some > sitting in > > memory. I have an object data.results, which is apparently > a list: > > > > >>> type(data.results) > > > > > > In this list, I have ten URL saved, which I can access by > using the > > brackets and noting the specific elements. For example: > > > > >>> data.results[0].URL > > 'http://www.psychguides.com/gl- > treatment_of_schizophrenia_1999.html' > > > > >>> data.results [1].URL > > 'http://www.psychguides.com/sche.pdf' > > > > My question is, how can I access all ten URLs in a single > command. > > Specifically, why does the following statement not work: > > > > >>> data.results[0:10].URL > You need to extract the URL from each item in the result list. > Something like: > > urls = [r.URL for r in data.results] > > will extract a list of urls from your list of results. > > > > Traceback (most recent call last): > > File "", line 1, in -toplevel- > > data.results[0:10].URL > > AttributeError: 'list' object has no attribute 'URL' > > > > > > Again, I am new to Python, so a watered-down, conceptual > response to > > this would be greatly appreciated. Thanks in advance. > > data.results[0:10] simply copies the first 10 results from > your original > list into a new list. The new list does not have a URL > attribute, as > the error message tells us. The URL attribute belongs to the > individual > items in the list. > > You need to process each result in data.results to extract the > URL. > Your choices boil down to: > for statement > or the more functionally oriented > map > list comprehension > generator expression (python 2.4 or later) > > For creating a new list from an existing list, a list > comprehension is > usually the best bet. The for statement approach would look > something > like: > urls = [] > for r in data.results: > urls.append(r.URL) > > list comprehensions provide a simpler, more direct syntax. > > > > > > > Brian > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > -- > Lloyd Kvam > Venix Corp > > -- Lloyd Kvam Venix Corp From tim at johnsons-web.com Sat Sep 16 18:39:33 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Sat, 16 Sep 2006 08:39:33 -0800 Subject: [Tutor] Problems serving up PDF In-Reply-To: <1158323108.9975.93.camel@www.venix.com> References: <20060914153804.ygeyo404scsw48ck@www.email.arizona.edu> <20060915011318.GA19434@johnsons-web.com> <450A02DA.4060202@gmail.com> <20060915020116.GC19434@johnsons-web.com> <1158323108.9975.93.camel@www.venix.com> Message-ID: <20060916163933.GK19434@johnsons-web.com> * Python [060915 04:35]: > > There is a Firefox extension called TamperData that allows you to > examine and change the headers. This extension is very handy for > debugging these kinds of issues. My Apache web server returns these > headers when I request a pdf file: > > Status=OK - 200 > Date=Fri, 15 Sep 2006 12:03:37 GMT > Server=Apache/2.0.53 (Fedora) > Last-Modified=Tue, 06 Jun 2006 16:50:30 GMT > Etag="68061-6a29d-c70c180" > Accept-Ranges=bytes > Content-Length=434845 > Connection=close > Content-Type=application/pdf > X-Pad=avoid browser bug > > The last two should be of interest to you. I did not try to google X- > Pad or "avoid browser bug", but google might provide more background. > > In any case, Tamper Data allows you to see what a working web site does > to succeed. Imitation is the sincerest form of flattery. thanks. that is a very helpful tool. and I'm seeing that headers are consistant with what I've sent. Good tip! tim -- Tim Johnson http://www.alaska-internet-solutions.com From broek at cc.umanitoba.ca Sat Sep 16 20:30:57 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sat, 16 Sep 2006 13:30:57 -0500 Subject: [Tutor] Lists in lists In-Reply-To: <450BFC46.1050508@pythonin.dk> References: <450BFC46.1050508@pythonin.dk> Message-ID: <450C42E1.20604@cc.umanitoba.ca> Morten Juhl Johansen said unto the world upon 16/09/06 08:29 AM: > # Newbie warning > I am making a timeline program. It is fairly simple. > I base it on appending lists to a list. > Ex. > [[year1, "headline1", "event text1"], [year2, "headline2", "event text2"]] > > This seemed like a brilliant idea when I did it. It is easy to sort. > Now, if I want to OUTPUT it, how do I indicate that I want to extract > first entry in a list in a list? How do I print the separate entries? > > Yours, > Morten > Hi Morten, Andrei answered the question you asked; I'd like to make a suggestion involving a bit of reworking. You might think about structuring your timeline data as a dictionary, rather than a list. So: >>> timeline_data = { ... 800: ["Charlemagne Crowned Holy Roman Emperor", 'event_text'], ... 1066: ["Battle at Hastings", 'event_text']} This makes it very easy to access a given year's data: >>> timeline_data[800] ['Charlemagne Crowned Holy Roman Emperor', 'event_text'] and >>> timeline_data[800][0] 'Charlemagne Crowned Holy Roman Emperor' will get you the headline alone. You expressed a liking for the lists as they are easy to sort. On recent versions of python one can easily obtain a sorted list of dictionary keys, too: >>> d = {1:2, 3:4, 43545:32, -3434:42} >>> d {1: 2, 3: 4, -3434: 42, 43545: 32} >>> sorted(d) [-3434, 1, 3, 43545] >>> (Older versions of Python can do the same, but with a bit more keyboard action.) So, if you wanted to print the headlines in increasing year order: >>> for year in sorted(timeline_data): ... print timeline_data[year][0] ... Charlemagne Crowned Holy Roman Emperor Battle at Hastings >>> You say you are new to Python. Well, it might not now be obvious why dictionaries are especially useful, but they are *central* to the pythonic approach. The sooner you become comfortable with them, the better (IMHO). Best wishes, Brian vdB From alan.gauld at freenet.co.uk Sat Sep 16 23:29:27 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 16 Sep 2006 22:29:27 +0100 Subject: [Tutor] From byte[] to Image References: Message-ID: <002e01c6d9d7$30342e80$0201a8c0@XPpro> Hi Ziad, Can you give us a bit mor4e detail. > #************************************************************** > # fileName is the path of the file > stream = service.getFile(fileName) > > file = open("pic.jpeg", 'w') > > img = Image.frombuffer("1", (128, 128), stream) > img.save(file) Which library are you using here? Is it the PIL? > The Java method is: "public byte[] getFile(String path)" > > This is not working. I am not able to get all the data of the image > and for sure not able to form the complete image. Are you saying the Java code is not working? Or that the value you get back from the web service is not what you expected? Or that the resultant byte array is what you expected but it is not being transformed to an image correctly? I'm not 100% sure what the problem is here. Alan G. From kent37 at tds.net Sat Sep 16 23:31:22 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 16 Sep 2006 17:31:22 -0400 Subject: [Tutor] Lists in lists In-Reply-To: <450BFC46.1050508@pythonin.dk> References: <450BFC46.1050508@pythonin.dk> Message-ID: <450C6D2A.9040507@tds.net> Morten Juhl Johansen wrote: > # Newbie warning > I am making a timeline program. It is fairly simple. > I base it on appending lists to a list. > Ex. > [[year1, "headline1", "event text1"], [year2, "headline2", "event text2"]] > > This seemed like a brilliant idea when I did it. It is easy to sort. It's a fine idea > Now, if I want to OUTPUT it, how do I indicate that I want to extract > first entry in a list in a list? How do I print the separate entries? There are a couple of things to do. First, at the top level, you have a list and you want to process each element of the list. A for loop works well for this; it assigns each member of the list in turn to a named variable: In [2]: events=[[1863, "headline1", "event text1"], [1992, "headline2", "event text2"]] In [3]: for event in events: ...: print event ...: ...: [1863, 'headline1', 'event text1'] [1992, 'headline2', 'event text2'] Within the for loop the variable 'event' contains a simple list which can be accessed with normal subscripting: In [5]: for event in events: ...: print 'In', event[0], event[1], event[2] ...: ...: In 1863 headline1 event text1 In 1992 headline2 event text2 It's handy to assign names to the individual elements of the list. A variable named 'year' is a lot easier to understand than 'event[0]'. This is easy to do with tuple unpacking: In [6]: for event in events: ...: year, head, text = event ...: print 'In', year, head, text ...: ...: In 1863 headline1 event text1 In 1992 headline2 event text2 One final note - in Python it is more idiomatic - or at least closer to the intentions of the language designer - to use tuples for lists of dissimilar items. So it is a bit more idiomatic to express your initial list as a list of tuples: events=[(1863, "headline1", "event text1"), (1992, "headline2", "event text2")] It's not a big deal and it won't change the rest of the code at all, it's just a stylistic note. Kent From kent37 at tds.net Sat Sep 16 23:35:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 16 Sep 2006 17:35:05 -0400 Subject: [Tutor] Lists in lists In-Reply-To: <450C42E1.20604@cc.umanitoba.ca> References: <450BFC46.1050508@pythonin.dk> <450C42E1.20604@cc.umanitoba.ca> Message-ID: <450C6E09.7060405@tds.net> Brian van den Broek wrote: > Morten Juhl Johansen said unto the world upon 16/09/06 08:29 AM: >> # Newbie warning >> I am making a timeline program. It is fairly simple. >> I base it on appending lists to a list. >> Ex. >> [[year1, "headline1", "event text1"], [year2, "headline2", "event text2"]] >> >> This seemed like a brilliant idea when I did it. It is easy to sort. >> Now, if I want to OUTPUT it, how do I indicate that I want to extract >> first entry in a list in a list? How do I print the separate entries? >> >> Yours, >> Morten >> > > Hi Morten, > > Andrei answered the question you asked; I'd like to make a suggestion > involving a bit of reworking. > > You might think about structuring your timeline data as a dictionary, > rather than a list. So: > > >>> timeline_data = { > ... 800: ["Charlemagne Crowned Holy Roman Emperor", 'event_text'], > ... 1066: ["Battle at Hastings", 'event_text']} > > > This makes it very easy to access a given year's data: > > >>> timeline_data[800] > ['Charlemagne Crowned Holy Roman Emperor', 'event_text'] > > and > > >>> timeline_data[800][0] > 'Charlemagne Crowned Holy Roman Emperor' > > will get you the headline alone. > > You expressed a liking for the lists as they are easy to sort. On > recent versions of python one can easily obtain a sorted list of > dictionary keys, too: > > >>> d = {1:2, 3:4, 43545:32, -3434:42} > >>> d > {1: 2, 3: 4, -3434: 42, 43545: 32} > >>> sorted(d) > [-3434, 1, 3, 43545] > >>> > > (Older versions of Python can do the same, but with a bit more > keyboard action.) > > So, if you wanted to print the headlines in increasing year order: > > >>> for year in sorted(timeline_data): > ... print timeline_data[year][0] > ... > Charlemagne Crowned Holy Roman Emperor > Battle at Hastings > >>> > > > You say you are new to Python. Well, it might not now be obvious why > dictionaries are especially useful, but they are *central* to the > pythonic approach. The sooner you become comfortable with them, the > better (IMHO). I agree that dicts are extremely useful, but I don't think they add anything in this case unless there is actually a need for keyed access. A list of lists (or tuples) seems very appropriate to me. A good alternative might be a list of Bunches. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308 Kent From kent37 at tds.net Sat Sep 16 23:36:43 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 16 Sep 2006 17:36:43 -0400 Subject: [Tutor] Lists in lists In-Reply-To: <450C6D2A.9040507@tds.net> References: <450BFC46.1050508@pythonin.dk> <450C6D2A.9040507@tds.net> Message-ID: <450C6E6B.4060109@tds.net> Kent Johnson wrote: > It's handy to assign names to the individual elements of the list. A > variable named 'year' is a lot easier to understand than 'event[0]'. > This is easy to do with tuple unpacking: > > In [6]: for event in events: > ...: year, head, text = event > ...: print 'In', year, head, text > ...: > ...: > In 1863 headline1 event text1 > In 1992 headline2 event text2 The for loop and tuple unpacking can also be combined into the very elegant: for year, head, text in events: print 'In', year, head, text Kent From broek at cc.umanitoba.ca Sat Sep 16 23:48:32 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sat, 16 Sep 2006 16:48:32 -0500 Subject: [Tutor] Lists in lists In-Reply-To: <450C6E09.7060405@tds.net> References: <450BFC46.1050508@pythonin.dk> <450C42E1.20604@cc.umanitoba.ca> <450C6E09.7060405@tds.net> Message-ID: <450C7130.3050600@cc.umanitoba.ca> Kent Johnson said unto the world upon 16/09/06 04:35 PM: > Brian van den Broek wrote: >> Morten Juhl Johansen said unto the world upon 16/09/06 08:29 AM: >>> # Newbie warning >>> I am making a timeline program. It is fairly simple. >>> I base it on appending lists to a list. >>> Ex. >>> [[year1, "headline1", "event text1"], [year2, "headline2", "event text2"]] >>> >>> This seemed like a brilliant idea when I did it. It is easy to sort. >>> Now, if I want to OUTPUT it, how do I indicate that I want to extract >>> first entry in a list in a list? How do I print the separate entries? >>> >>> Yours, >>> Morten >>> >> Hi Morten, >> >> Andrei answered the question you asked; I'd like to make a suggestion >> involving a bit of reworking. >> >> You might think about structuring your timeline data as a dictionary, >> rather than a list. So: >> >> >>> timeline_data = { >> ... 800: ["Charlemagne Crowned Holy Roman Emperor", 'event_text'], >> ... 1066: ["Battle at Hastings", 'event_text']} >> >> >> This makes it very easy to access a given year's data: >> >> >>> timeline_data[800] >> ['Charlemagne Crowned Holy Roman Emperor', 'event_text'] >> >> and >> >> >>> timeline_data[800][0] >> 'Charlemagne Crowned Holy Roman Emperor' >> >> will get you the headline alone. >> >> You expressed a liking for the lists as they are easy to sort. On >> recent versions of python one can easily obtain a sorted list of >> dictionary keys, too: >> >> >>> d = {1:2, 3:4, 43545:32, -3434:42} >> >>> d >> {1: 2, 3: 4, -3434: 42, 43545: 32} >> >>> sorted(d) >> [-3434, 1, 3, 43545] >> >>> >> >> (Older versions of Python can do the same, but with a bit more >> keyboard action.) >> >> So, if you wanted to print the headlines in increasing year order: >> >> >>> for year in sorted(timeline_data): >> ... print timeline_data[year][0] >> ... >> Charlemagne Crowned Holy Roman Emperor >> Battle at Hastings >> >>> >> >> >> You say you are new to Python. Well, it might not now be obvious why >> dictionaries are especially useful, but they are *central* to the >> pythonic approach. The sooner you become comfortable with them, the >> better (IMHO). > > I agree that dicts are extremely useful, but I don't think they add > anything in this case unless there is actually a need for keyed access. > A list of lists (or tuples) seems very appropriate to me. A good > alternative might be a list of Bunches. > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308 > > Kent Hi Kent and all, I should have included the reason why I thought a dict might be better here. (I did send it in a private email after the post.) A lot of ways I could imagine the time-line data being used might involve wanting to access some one year, rather than the entire time-line. So, if you wanted to get the headline for the year 800, >>> print timeline_data[800][0] seems *way* better than something like: >>> for year_data in timeline_data_as_list_of_lists: ... if year_data[0] == 800: ... print year_data[1] ... break which would be what the original list structure seems to require. It may be a case of over-design for needs that won't arise, though. Best to all, Brian vdB From info at pythonin.dk Sun Sep 17 00:22:54 2006 From: info at pythonin.dk (PythonIn.dk) Date: Sun, 17 Sep 2006 00:22:54 +0200 Subject: [Tutor] Lists in lists In-Reply-To: <450C7130.3050600@cc.umanitoba.ca> References: <450BFC46.1050508@pythonin.dk> <450C42E1.20604@cc.umanitoba.ca> <450C6E09.7060405@tds.net> <450C7130.3050600@cc.umanitoba.ca> Message-ID: <450C793E.4020702@pythonin.dk> Thank you for your tips on my list list. I see how there are advantages to the different approaches. I expect to simply output the text and pipe it somewhere else - so, it is not actually an issue to access the individual posts. Yours, (probably back later) Morten From kent37 at tds.net Sun Sep 17 02:49:06 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 16 Sep 2006 20:49:06 -0400 Subject: [Tutor] Lists in lists In-Reply-To: <450C7130.3050600@cc.umanitoba.ca> References: <450BFC46.1050508@pythonin.dk> <450C42E1.20604@cc.umanitoba.ca> <450C6E09.7060405@tds.net> <450C7130.3050600@cc.umanitoba.ca> Message-ID: <450C9B82.3000007@tds.net> Brian van den Broek wrote: > Kent Johnson said unto the world upon 16/09/06 04:35 PM: >> Brian van den Broek wrote: >>> You say you are new to Python. Well, it might not now be obvious why >>> dictionaries are especially useful, but they are *central* to the >>> pythonic approach. The sooner you become comfortable with them, the >>> better (IMHO). >> I agree that dicts are extremely useful, but I don't think they add >> anything in this case unless there is actually a need for keyed access. >> A list of lists (or tuples) seems very appropriate to me. A good >> alternative might be a list of Bunches. >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308 >> >> Kent > > > Hi Kent and all, > > I should have included the reason why I thought a dict might be better > here. (I did send it in a private email after the post.) > > A lot of ways I could imagine the time-line data being used might > involve wanting to access some one year, rather than the entire time-line. Yes, I was a bit hasty in denouncing dicts, the best data structure does depend entirely on how it is to be used, and we don't know enough about this application to know. > >>> print timeline_data[800][0] > > seems *way* better than something like: > > >>> for year_data in timeline_data_as_list_of_lists: > ... if year_data[0] == 800: > ... print year_data[1] > ... break > > which would be what the original list structure seems to require. The thing is, though, how will you know that 800 is a valid year? You need a list of valid years. If you get that list from the dict keys, and iterate that, you haven't really gained anything over a list of tuples. Maybe you have a lot of items and the user enters a year and you want to print out the data you have on the year... Kent From samrobertsmith at gmail.com Sun Sep 17 03:03:59 2006 From: samrobertsmith at gmail.com (linda.s) Date: Sat, 16 Sep 2006 18:03:59 -0700 Subject: [Tutor] folder and module Message-ID: <1d987df30609161803q21771d24k3f8b1760db0fffa0@mail.gmail.com> Hi there, i have test.py under c:\try1\new; I want to import b and b.py is under c:\trytry. How to do it? Also, I import c and c.py is in the desktop folder but no error reported. Why? Thanks, Linda On 9/2/06, linda. s wrote: > I read something about random.seed() but still confused. i can > understand random.random() but it is very hard for me to understand > random.seed(0... can anyone explain an example? > Thanks a lot! > Linda > From fedekiller at gmail.com Sun Sep 17 04:45:55 2006 From: fedekiller at gmail.com (federico ramirez) Date: Sat, 16 Sep 2006 23:45:55 -0300 Subject: [Tutor] Cookie help Message-ID: <26a78a3c0609161945x33f307e2ja2edeca8fd9dd496@mail.gmail.com> Hey, im working on a cgi script, just a simple news system. And im stucked with the login system. GOD! I hate being a noob! Well, this is the login page ################################ #!/usr/bin/python import cgi, dbm, string, Cookie import config request = cgi.FieldStorage() def loginform(): print '''
Username
Password
 
''' def main(): C = Cookie.SimpleCookie() if(C.has_key("admin_user") and C.has_key("admin_pass")): admin = config.getadmin() if(C["admin_user"].value == admin[0] and C["admin_pass"].value == admin[1]): config.makepage("You are already logged!") else: config.makepage("Wrong cookies...") elif(request.has_key("Submit")): admin = config.getadmin() username = config.clean(request["user"].value) password = config.clean(request["pass"].value) if(username == admin[0] and password == admin[1]): C["admin_user"] = username C["admin_pass"] = password print C print "Content-Type: text/html\n\n" config.startpage() print "Bienvenido",username,'!' config.endpage() else: print "Content-Type: text/html\n\n" config.startpage() print "Incorrect username and password combination" config.endpage() else: print "Content-Type: text/html\n\n" config.startpage() loginform() config.endpage() main() ################################ That seems to work..but i cant get the cookies, i tried making this to get them but i have a 500 error -.- i hate it so much ################################# #!/usr/bin/python try: import Cookie print "Content-Type: text/html\n\n" C = Cookie.SimpleCookie() print C.["admin_user"].value except: cgi.print_exception() ################################### i tried that in different ways but i cant get it to work Help please :( -- Best Regards. fedekiller -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060916/dd78e94f/attachment.htm From willshattuck at gmail.com Sun Sep 17 05:10:21 2006 From: willshattuck at gmail.com (Will Shattuck) Date: Sat, 16 Sep 2006 20:10:21 -0700 Subject: [Tutor] Problems with Python Modules Message-ID: Hi all, I'm trying to install some python mud engines, but I keep running into problems with the software not seeing python modules. Could this be due to environment variables missing on my system? Here is an example of the most recent error message using the InnerSpace mud engine: ======================================== C:\muds\InnerSpace-0.9>python bin\bootstrap_server.py --verdir verbs\ Traceback (most recent call last): File "bin\bootstrap_server.py", line 13, in ? from twisted.scripts import mktap, twistd File "C:\Python24\lib\site-packages\twisted\scripts\twistd.py", line 6, in ? from twisted.python import log, syslog File "C:\Python24\lib\site-packages\twisted\python\syslog.py", line 5, in ? syslog = __import__('syslog') ImportError: No module named syslog ======================================== My system is new Dell D620 Latitude running WindowsXP Pro SP2, Python 2.4, I have installed the Twisted binary. I have another mud engine (ErisMUD) that doesn't see the SQLite modules I installed either. Here is my PATH at a command prompt in case you need it. Yes I have a lot of crud in my path :) ====================== PATH: PATH=C:\Python24;C:\orant\bin;C:\Perl\bin\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\Microsoft SQL Server\80\Tools\Binn\;C:\PROGRA~1\WONDER~1\Avantis\Common;C:\Program Files\Crimson Editor\;C:\Program Files\QuickTime\QTSystem\;C:\Program Files\VDMSound;c:\Program Files\Microsoft SQL Server\90\Tools\binn\ ====================== Thanks for any help. I just don't know where to start looking. Will -- Will Shattuck ( willshattuck.at.gmail.com ) Home Page: http://www.thewholeclan.com/will When you get to your wit's end, you'll find God lives there. From dkuhlman at rexx.com Sun Sep 17 05:25:11 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sat, 16 Sep 2006 20:25:11 -0700 Subject: [Tutor] Problems with Python Modules In-Reply-To: References: Message-ID: <20060917032511.GA86050@cutter.rexx.com> On Sat, Sep 16, 2006 at 08:10:21PM -0700, Will Shattuck wrote: > Hi all, > > I'm trying to install some python mud engines, but I keep running into > problems with the software not seeing python modules. Could this be > due to environment variables missing on my system? Here is an example > of the most recent error message using the InnerSpace mud engine: > > ======================================== > C:\muds\InnerSpace-0.9>python bin\bootstrap_server.py --verdir verbs\ > Traceback (most recent call last): > File "bin\bootstrap_server.py", line 13, in ? > from twisted.scripts import mktap, twistd > File "C:\Python24\lib\site-packages\twisted\scripts\twistd.py", line 6, in ? > from twisted.python import log, syslog > File "C:\Python24\lib\site-packages\twisted\python\syslog.py", line 5, in ? > syslog = __import__('syslog') > ImportError: No module named syslog > ======================================== Try adding this for debugging: import sys print sys.path That's a list of the directories where Python looks for modules to be imported. Are you sure that you want to import syslog from twisted.python? syslog is a module in the python standard library. Is there also a module named syslog in twisted.python? Dave [snip] -- Dave Kuhlman http://www.rexx.com/~dkuhlman From alan.gauld at freenet.co.uk Sun Sep 17 09:51:15 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 17 Sep 2006 08:51:15 +0100 Subject: [Tutor] folder and module References: <1d987df30609161803q21771d24k3f8b1760db0fffa0@mail.gmail.com> Message-ID: <001c01c6da2e$0dd966a0$0201a8c0@XPpro> Linda, > i have test.py under c:\try1\new; > I want to import b and b.py is under c:\trytry. How to do it? > Also, I import c and c.py is in the desktop folder but no error > reported. Python imports modules by looking for them in the folders listed in the variable sys.path. sys.path gets populated when Python starts up and includes some standard locations plus any you define in your PYTHONPATH environment variable. You can also modify sys.path yourself at run-time. But basically that means that any files you want to import must be located in a folder in sys.path So either you save them there, or you add the location to sys.path. Personally I save all the modules I will reuse across projects in a PROJECTS\Lib folder which I added to my PYTHONPATH environment variable. Modules that I want to import in the current project only I leave in the current directory. If your project is big you may want to subdivide the modules into a folder heirarchy and Python's package system allows you to do that. But since most beginners won't generate that many modules in a project I'll leave reading about packages as an excercise for the keen student! :-) Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ml.cyresse at gmail.com Sun Sep 17 10:09:51 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 17 Sep 2006 20:09:51 +1200 Subject: [Tutor] folder and module In-Reply-To: <001c01c6da2e$0dd966a0$0201a8c0@XPpro> References: <1d987df30609161803q21771d24k3f8b1760db0fffa0@mail.gmail.com> <001c01c6da2e$0dd966a0$0201a8c0@XPpro> Message-ID: Hi Linda, As Alan said, you can modify your sys.path at runtime - to clarify, a simple example is: >>> import sys >>> sys.path.append("c:/trytry") "import b" should now work. Regards, Liam Clarke On 9/17/06, Alan Gauld wrote: > Linda, > > > i have test.py under c:\try1\new; > > I want to import b and b.py is under c:\trytry. How to do it? > > Also, I import c and c.py is in the desktop folder but no error > > reported. > > Python imports modules by looking for them in the folders > listed in the variable sys.path. sys.path gets populated when > Python starts up and includes some standard locations plus > any you define in your PYTHONPATH environment variable. > > You can also modify sys.path yourself at run-time. > > But basically that means that any files you want to import > must be located in a folder in sys.path > > So either you save them there, or you add the location to > sys.path. > > Personally I save all the modules I will reuse across projects > in a PROJECTS\Lib folder which I added to my PYTHONPATH > environment variable. Modules that I want to import in the > current project only I leave in the current directory. > > If your project is big you may want to subdivide the modules > into a folder heirarchy and Python's package system allows > you to do that. But since most beginners won't generate that > many modules in a project I'll leave reading about packages > as an excercise for the keen student! :-) > > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From samrobertsmith at gmail.com Sun Sep 17 12:43:25 2006 From: samrobertsmith at gmail.com (linda.s) Date: Sun, 17 Sep 2006 03:43:25 -0700 Subject: [Tutor] folder and module In-Reply-To: <001c01c6da2e$0dd966a0$0201a8c0@XPpro> References: <1d987df30609161803q21771d24k3f8b1760db0fffa0@mail.gmail.com> <001c01c6da2e$0dd966a0$0201a8c0@XPpro> Message-ID: <1d987df30609170343x5303d347l7e01b78cd6f3d599@mail.gmail.com> > > i have test.py under c:\try1\new; > > I want to import b and b.py is under c:\trytry. How to do it? > > Also, I import c and c.py is in the desktop folder but no error > > reported. > > Python imports modules by looking for them in the folders > listed in the variable sys.path. sys.path gets populated when > Python starts up and includes some standard locations plus > any you define in your PYTHONPATH environment variable. > I checked my PYTHONPATH environment variable (both user variables and system variables) but I only see a directory (which is a downloaded python library's directory listed under PYTHONPATH in user variables . My questions are: 1. since the desktop directory is not listed in the PYTHONPATH , why there is no error report when I import a module which is in the desktop? 2. why there is no directory such as c:\python24 where I install the python? Thanks, Linda From kent37 at tds.net Sun Sep 17 13:04:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 17 Sep 2006 07:04:05 -0400 Subject: [Tutor] Cookie help In-Reply-To: <26a78a3c0609161945x33f307e2ja2edeca8fd9dd496@mail.gmail.com> References: <26a78a3c0609161945x33f307e2ja2edeca8fd9dd496@mail.gmail.com> Message-ID: <450D2BA5.6040505@tds.net> federico ramirez wrote: > Hey, im working on a cgi script, just a simple news system. > And im stucked with the login system. > GOD! I hate being a noob! > Well, this is the login page > > ################################ > #!/usr/bin/python > > import cgi, dbm, string, Cookie > import config > request = cgi.FieldStorage() > > def loginform(): > print '''
> > > > > > > > > > > > > >
Username
Password
 
>
''' > > def main(): > C = Cookie.SimpleCookie() > if(C.has_key("admin_user") and C.has_key("admin_pass")): > admin = config.getadmin() > if(C["admin_user"].value == admin[0] and C["admin_pass"].value > == admin[1]): > config.makepage("You are already logged!") > else: > config.makepage("Wrong cookies...") > elif(request.has_key("Submit")): > admin = config.getadmin() > username = config.clean(request["user"].value) > password = config.clean(request["pass"].value) > if(username == admin[0] and password == admin[1]): > C["admin_user"] = username > C["admin_pass"] = password > print C > print "Content-Type: text/html\n\n" > config.startpage() > print "Bienvenido",username,'!' > config.endpage () > else: > print "Content-Type: text/html\n\n" > config.startpage() > print "Incorrect username and password combination" > config.endpage () > else: > print "Content-Type: text/html\n\n" > config.startpage() > loginform() > config.endpage() > > main() > ################################ > > That seems to work..but i cant get the cookies, i tried making this to > get them but i have a 500 error -.- i hate it so much > > ################################# > #!/usr/bin/python > try: > import Cookie > print "Content-Type: text/html\n\n" > C = Cookie.SimpleCookie() > print C.["admin_user"].value > except: > cgi.print_exception() > ################################### > > i tried that in different ways but i cant get it to work You might be interested in this article and the associated logintools, either as an example or to use directly: http://www.voidspace.org.uk/python/articles/cgi_web_applications_two.shtml#who-are-you http://www.voidspace.org.uk/python/cgi.shtml#login According to the article you need to add if os.environ.has_key('HTTP_COOKIE'): thiscookie.load(os.environ['HTTP_COOKIE']) to your main() before you try to access the cookie values. Kent From samrobertsmith at gmail.com Sun Sep 17 13:05:45 2006 From: samrobertsmith at gmail.com (linda.s) Date: Sun, 17 Sep 2006 04:05:45 -0700 Subject: [Tutor] environment variables Message-ID: <1d987df30609170405n1201ca31u8547f03868be5182@mail.gmail.com> Hi there, I found the following paragraph in the web: environment variables on Windows come in two flavors: user variables and system variables. In particular, if there is a system variable PYTHONPATH and you are adding this as a user variable, start with the value in the system variable and add to it to define the user variable, since user variables override system variables. my question is: since user variables override system variables, why we need do anything related to python in the system variables? Why not delete the value in the system variable and add to it to define the user variable? Linda From ml.cyresse at gmail.com Sun Sep 17 13:06:20 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 17 Sep 2006 23:06:20 +1200 Subject: [Tutor] folder and module In-Reply-To: <1d987df30609170343x5303d347l7e01b78cd6f3d599@mail.gmail.com> References: <1d987df30609161803q21771d24k3f8b1760db0fffa0@mail.gmail.com> <001c01c6da2e$0dd966a0$0201a8c0@XPpro> <1d987df30609170343x5303d347l7e01b78cd6f3d599@mail.gmail.com> Message-ID: Hi Linda, At your Python prompt try the following: >>> import sys >>> print sys.path What directories are listed there? On 9/17/06, linda.s wrote: > > > i have test.py under c:\try1\new; > > > I want to import b and b.py is under c:\trytry. How to do it? > > > Also, I import c and c.py is in the desktop folder but no error > > > reported. > > > > Python imports modules by looking for them in the folders > > listed in the variable sys.path. sys.path gets populated when > > Python starts up and includes some standard locations plus > > any you define in your PYTHONPATH environment variable. > > > I checked my PYTHONPATH environment variable (both user variables and > system variables) but I only see a directory (which is a downloaded > python library's directory listed under PYTHONPATH in user variables . > My questions are: > 1. since the desktop directory is not listed in the PYTHONPATH , > why there is no error report when I import a module which is in the desktop? > 2. why there is no directory such as c:\python24 where I install the python? > Thanks, > Linda > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sun Sep 17 13:20:54 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 17 Sep 2006 07:20:54 -0400 Subject: [Tutor] Problems with Python Modules In-Reply-To: References: Message-ID: <450D2F96.4040400@tds.net> Will Shattuck wrote: > Hi all, > > I'm trying to install some python mud engines, but I keep running into > problems with the software not seeing python modules. Could this be > due to environment variables missing on my system? Here is an example > of the most recent error message using the InnerSpace mud engine: > > ======================================== > C:\muds\InnerSpace-0.9>python bin\bootstrap_server.py --verdir verbs\ > Traceback (most recent call last): > File "bin\bootstrap_server.py", line 13, in ? > from twisted.scripts import mktap, twistd > File "C:\Python24\lib\site-packages\twisted\scripts\twistd.py", line 6, in ? > from twisted.python import log, syslog > File "C:\Python24\lib\site-packages\twisted\python\syslog.py", line 5, in ? > syslog = __import__('syslog') > ImportError: No module named syslog > ======================================== > > My system is new Dell D620 Latitude running WindowsXP Pro SP2, Python > 2.4, I have installed the Twisted binary. syslog is a Unix module not available on Windows. twisted.python.syslog is importing the lib module syslog which is not available. Are you using a twisted release or did you check it out from Subversion? Looking at the history of twistd.py, the import of syslog was only in for two days before this was corrected (see http://twistedmatrix.com/trac/log/trunk/twisted/scripts/twistd.py). So if you are using twisted from SVN you should do a new checkout. If you are using a release then you might want to ask about this on the twisted mailing list. I have another mud engine > (ErisMUD) that doesn't see the SQLite modules I installed either. What error do you get for this one? > Here is my PATH at a command prompt in case you need it. Yes I have a > lot of crud in my path :) PATH is not used to search for Python modules, they are searched in PYTHONPATH. Kent From pythontut at pusspaws.net Sun Sep 17 15:20:35 2006 From: pythontut at pusspaws.net (Dave S) Date: Sun, 17 Sep 2006 14:20:35 +0100 Subject: [Tutor] exit app withour raise ? Message-ID: <200609171420.35866.pythontut@pusspaws.net> In the middle of an application, if someone presses the quit button I want to exit. At the moment i raise 'Quit button pressed' which works but spews a stack trace leading to the raise statement. Is there a neat way to just exit without a stack trace ? Dave From kent37 at tds.net Sun Sep 17 15:46:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 17 Sep 2006 09:46:59 -0400 Subject: [Tutor] exit app withour raise ? In-Reply-To: <200609171420.35866.pythontut@pusspaws.net> References: <200609171420.35866.pythontut@pusspaws.net> Message-ID: <450D51D3.2090402@tds.net> Dave S wrote: > In the middle of an application, if someone presses the quit button I want to > exit. At the moment i > > raise 'Quit button pressed' > > which works but spews a stack trace leading to the raise statement. Is there a > neat way to just exit without a stack trace ? sys.exit() Kent From alan.gauld at freenet.co.uk Sun Sep 17 16:54:24 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 17 Sep 2006 15:54:24 +0100 Subject: [Tutor] folder and module References: <1d987df30609161803q21771d24k3f8b1760db0fffa0@mail.gmail.com> <001c01c6da2e$0dd966a0$0201a8c0@XPpro> <1d987df30609170343x5303d347l7e01b78cd6f3d599@mail.gmail.com> Message-ID: <000301c6da69$2aaadda0$0201a8c0@XPpro> >> listed in the variable sys.path. sys.path gets populated when >> Python starts up and includes some standard locations plus >> any you define in your PYTHONPATH environment variable. >> > I checked my PYTHONPATH environment variable > My questions are: > 1. since the desktop directory is not listed in the PYTHONPATH , > why there is no error report when I import a module which is in the > desktop? > 2. why there is no directory such as c:\python24 where I install the > python? Notice i said it ioncluded some "standard locations" as well as Python Path. The standard library, sitepackages and current directory are all included. If you want to see the full set of locations python is loking in you need to print sys.path >>> import sys >>> print sys.path For example I get: Alan Gauld at XP-pro ~ $ printenv PYTHONPATH /cygdrive/d/Development/PROJECTS/Python And in Python >>> sys.path ['', '/cygdrive/d/Development/PROJECTS/Python', '/usr/lib/python24.zip', '/usr/l ib/python2.4', '/usr/lib/python2.4/plat-cygwin', '/usr/lib/python2.4/lib-tk', '/ usr/lib/python2.4/lib-dynload', '/usr/lib/python2.4/site-packages'] >>> So I have quite a lot more defined than what is in PYTHONPATH HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ziad.rahhal at gmail.com Sun Sep 17 18:26:16 2006 From: ziad.rahhal at gmail.com (Ziad Rahhal) Date: Sun, 17 Sep 2006 18:26:16 +0200 Subject: [Tutor] From byte[] to Image In-Reply-To: <002e01c6d9d7$30342e80$0201a8c0@XPpro> References: <002e01c6d9d7$30342e80$0201a8c0@XPpro> Message-ID: Hi Alan, The Library I am using is the PIL. And I read the Docs, they say the following about "frombuffer" operation: (Note that this function decodes pixel data only, not entire images. If you have an entire image file in a string, wrap it in a *StringIO* object, and use *open*to load it.) So I guess "frombuffer" must not be used in my case. The java method is working correctly but I am not able to form the picture in the right way at the client side using the PIL library. I am receiving an array of byte from "public byte[] getFile(String path)", but how to form the Image at the client side? By the way that is how I am sending the Image as byte array to the python client: public byte[] getFile(String fileName){ try{ File imgFile = new File(fileName); BufferedImage img = ImageIO.read(imgFile); ByteArrayOutputStream bas = newByteArrayOutputStream(); ImageIO.write(img, "jpg", bas); data = bas.toByteArray(); } catch (Exception e){ e.printStackTrace(); } System.out.println(data[2]); return data; } // end getFile I receive it at the client side in python: buffer = service.getFile(fileName) How to form the Image from here? It is a jpg Image constructed originally from vtk using Mesa library for off-screen rendering. Thank you again, Ziad On 9/16/06, Alan Gauld wrote: > > Hi Ziad, > > Can you give us a bit mor4e detail. > > > #************************************************************** > > # fileName is the path of the file > > stream = service.getFile(fileName) > > > > file = open("pic.jpeg", 'w') > > > > img = Image.frombuffer("1", (128, 128), stream) > > img.save(file) > > Which library are you using here? Is it the PIL? > > > The Java method is: "public byte[] getFile(String path)" > > > > This is not working. I am not able to get all the data of the image > > and for sure not able to form the complete image. > > Are you saying the Java code is not working? > Or that the value you get back from the web service is not > what you expected? Or that the resultant byte array is what > you expected but it is not being transformed to an image correctly? > > I'm not 100% sure what the problem is here. > > Alan G. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060917/821b8c4b/attachment.htm From alan.gauld at freenet.co.uk Sun Sep 17 18:52:50 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 17 Sep 2006 17:52:50 +0100 Subject: [Tutor] environment variables References: <1d987df30609170405n1201ca31u8547f03868be5182@mail.gmail.com> Message-ID: <001801c6da79$b6253eb0$0201a8c0@XPpro> > since user variables override system variables, why we need do > anything related to python in the system variables? Why not delete > the > value in the system variable and add to it to define the user > variable? System variables apply to all users, so if you want every user of the computer to have the same Python environment put it in the System list. Any individual who want to add their own values will have to copy the system value and add their own. But for most users the system list should suffice. HTH, Alan G From alan.gauld at freenet.co.uk Sun Sep 17 18:54:43 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 17 Sep 2006 17:54:43 +0100 Subject: [Tutor] exit app withour raise ? References: <200609171420.35866.pythontut@pusspaws.net> Message-ID: <002001c6da79$f9848f30$0201a8c0@XPpro> > In the middle of an application, if someone presses the quit button > I want to > exit. At the moment i > > raise 'Quit button pressed' > > which works but spews a stack trace leading to the raise statement. > Is there a > neat way to just exit without a stack trace ? raise SystemExit or more commonly import sys sys.exit() You can add an argument to exit and that will be the error value returned to the OS. Alan G. From alan.gauld at freenet.co.uk Sun Sep 17 18:57:08 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 17 Sep 2006 17:57:08 +0100 Subject: [Tutor] From byte[] to Image References: <002e01c6d9d7$30342e80$0201a8c0@XPpro> Message-ID: <003001c6da7a$4ffffe80$0201a8c0@XPpro> > (Note that this function decodes pixel data only, not entire images. > If you > have an entire image file in a string, wrap it in a *StringIO* > object, and > use > *open*to > load it.) > > So I guess "frombuffer" must not be used in my case. Looks like it, but did you try what it suggested, namely using a StringIO object and the open method? What happened? > The java method is working correctly but I am not able to form the > picture > in the right way at the client side using the PIL library. > I receive it at the client side in python: > buffer = service.getFile(fileName) I assume you tried printing buffer (or at least its len) to check that it was all there? Alan G. From pythontut at pusspaws.net Sun Sep 17 19:38:53 2006 From: pythontut at pusspaws.net (Dave S) Date: Sun, 17 Sep 2006 18:38:53 +0100 Subject: [Tutor] exit app withour raise ? In-Reply-To: <002001c6da79$f9848f30$0201a8c0@XPpro> References: <200609171420.35866.pythontut@pusspaws.net> <002001c6da79$f9848f30$0201a8c0@XPpro> Message-ID: <200609171838.53088.pythontut@pusspaws.net> On Sunday 17 September 2006 17:54, Alan Gauld wrote: > > In the middle of an application, if someone presses the quit button > > I want to > > exit. At the moment i > > > > raise 'Quit button pressed' > > > > which works but spews a stack trace leading to the raise statement. > > Is there a > > neat way to just exit without a stack trace ? > > raise SystemExit > > or more commonly > > import sys > > sys.exit() > > You can add an argument to exit and that will be the error value > returned > to the OS. > > Alan G. Thanks for that - it works great :) Dave From samrobertsmith at gmail.com Sun Sep 17 21:03:25 2006 From: samrobertsmith at gmail.com (linda.s) Date: Sun, 17 Sep 2006 12:03:25 -0700 Subject: [Tutor] folder and module In-Reply-To: <000301c6da69$2aaadda0$0201a8c0@XPpro> References: <1d987df30609161803q21771d24k3f8b1760db0fffa0@mail.gmail.com> <001c01c6da2e$0dd966a0$0201a8c0@XPpro> <1d987df30609170343x5303d347l7e01b78cd6f3d599@mail.gmail.com> <000301c6da69$2aaadda0$0201a8c0@XPpro> Message-ID: <1d987df30609171203o73d3dad0i2ee6e5b2064aa0df@mail.gmail.com> On 9/17/06, Alan Gauld wrote: > >> listed in the variable sys.path. sys.path gets populated when > >> Python starts up and includes some standard locations plus > >> any you define in your PYTHONPATH environment variable. > >> > > I checked my PYTHONPATH environment variable > > > My questions are: > > 1. since the desktop directory is not listed in the PYTHONPATH , > > why there is no error report when I import a module which is in the > > desktop? > > 2. why there is no directory such as c:\python24 where I install the > > python? > > Notice i said it ioncluded some "standard locations" as well as Python > Path. > > The standard library, sitepackages and current directory are all > included. > > If you want to see the full set of locations python is loking in you > need to print sys.path > > >>> import sys > >>> print sys.path > > For example I get: > > Alan Gauld at XP-pro ~ > $ printenv PYTHONPATH > /cygdrive/d/Development/PROJECTS/Python > > And in Python > > >>> sys.path > ['', '/cygdrive/d/Development/PROJECTS/Python', > '/usr/lib/python24.zip', '/usr/l > ib/python2.4', '/usr/lib/python2.4/plat-cygwin', > '/usr/lib/python2.4/lib-tk', '/ > usr/lib/python2.4/lib-dynload', '/usr/lib/python2.4/site-packages'] > >>> > > So I have quite a lot more defined than what is in PYTHONPATH I checked sys.path and environemntal variables: since the desktop directory is not listed in either of them, why there is no error report when I import a module which is in the desktop into test.py which is under a different folder? Linda From broek at cc.umanitoba.ca Sun Sep 17 21:39:54 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sun, 17 Sep 2006 14:39:54 -0500 Subject: [Tutor] folder and module In-Reply-To: <1d987df30609171203o73d3dad0i2ee6e5b2064aa0df@mail.gmail.com> References: <1d987df30609161803q21771d24k3f8b1760db0fffa0@mail.gmail.com> <001c01c6da2e$0dd966a0$0201a8c0@XPpro> <1d987df30609170343x5303d347l7e01b78cd6f3d599@mail.gmail.com> <000301c6da69$2aaadda0$0201a8c0@XPpro> <1d987df30609171203o73d3dad0i2ee6e5b2064aa0df@mail.gmail.com> Message-ID: <450DA48A.60108@cc.umanitoba.ca> linda.s said unto the world upon 17/09/06 02:03 PM: > I checked sys.path and environemntal variables: > since the desktop directory is not listed in either of them, > why there is no error report when I import a module which is in the > desktop into test.py which is under a different folder? > Linda > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hi Linda, what do you get when you try: >>> import os >>> os.getcwd() The current working directory is represented in sys.path as the first element: >>> import sys >>> sys.path[0] '' Not the most intuitive, perhaps. I suspect you are launching your Python environment from a desktop icon. That would explain why import can `see' your Desktop, even though it doesn't at first glance seem to be in sys.path. Best, Brian vdB From fedekiller at gmail.com Sun Sep 17 21:55:20 2006 From: fedekiller at gmail.com (federico ramirez) Date: Sun, 17 Sep 2006 16:55:20 -0300 Subject: [Tutor] i just cant do it Message-ID: <26a78a3c0609171255k77478bf2yaa66327111fc20a@mail.gmail.com> well, im very angry :( I cant get this to work When i try this it works #!/usr/bin/python import Cookie C = Cookie.SimpleCookie() C['adminuser'] = 'fedekiller' C['adminuser']['max-age'] = 60*60*24*7 print C print "Content-Type: text/html\n\n" print "Bienvenido",C['adminuser'].value,'!' but when i try this it doesnt #!/usr/bin/python import Cookie print "Content-Type: text/html\n\n" print "Bienvenido",C['adminuser'].value,'!' I dont know why... i know the cookie exists because firefox display it where all the cookies of that domains are. So, i need help with this please :( I know im a noob sorry U-U -- Best Regards. fedekiller -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060917/cc827380/attachment.html From broek at cc.umanitoba.ca Sun Sep 17 21:55:47 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sun, 17 Sep 2006 14:55:47 -0500 Subject: [Tutor] Lists in lists In-Reply-To: <450C9B82.3000007@tds.net> References: <450BFC46.1050508@pythonin.dk> <450C42E1.20604@cc.umanitoba.ca> <450C6E09.7060405@tds.net> <450C7130.3050600@cc.umanitoba.ca> <450C9B82.3000007@tds.net> Message-ID: <450DA843.60803@cc.umanitoba.ca> Kent Johnson said unto the world upon 16/09/06 07:49 PM: > Brian van den Broek wrote: >> Kent Johnson said unto the world upon 16/09/06 04:35 PM: >>> Brian van den Broek wrote: > >>>> You say you are new to Python. Well, it might not now be obvious why >>>> dictionaries are especially useful, but they are *central* to the >>>> pythonic approach. The sooner you become comfortable with them, the >>>> better (IMHO). >>> I agree that dicts are extremely useful, but I don't think they add >>> anything in this case unless there is actually a need for keyed >>> access. A list of lists (or tuples) seems very appropriate to me. A >>> good alternative might be a list of Bunches. >>> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308 >>> >>> Kent >> >> >> Hi Kent and all, >> >> I should have included the reason why I thought a dict might be better >> here. (I did send it in a private email after the post.) >> >> A lot of ways I could imagine the time-line data being used might >> involve wanting to access some one year, rather than the entire >> time-line. > > Yes, I was a bit hasty in denouncing dicts, the best data structure does > depend entirely on how it is to be used, and we don't know enough about > this application to know. Hi Kent and all, I absolutely agree that my suggestions did get a bit ahead of the spec :-) A combination of thinking about what *I* would want a yearly headline program to do and wanting to encourage comfort with dicts ASAP is what drove the suggestion. But, if the OP has a simpler spec than my imaginary one . . . . >> >>> print timeline_data[800][0] >> >> seems *way* better than something like: >> >> >>> for year_data in timeline_data_as_list_of_lists: >> ... if year_data[0] == 800: >> ... print year_data[1] >> ... break >> >> which would be what the original list structure seems to require. > > The thing is, though, how will you know that 800 is a valid year? You > need a list of valid years. If you get that list from the dict keys, and > iterate that, you haven't really gained anything over a list of tuples. > Maybe you have a lot of items and the user enters a year and you want to > print out the data you have on the year... def print_year_headline(year): try: print timeline_data[year][0] except KeyError: print "I am sorry; we have no data on year %s." %year allows for random access by year while handling the problem. But Kent's point about not getting too far ahead of the spec is surely right. To the OP: if Kent and I disagree, there are very good odds that Kent's the one to listen to ;-) Best to all, Brian vdB From rabidpoobear at gmail.com Sun Sep 17 22:08:50 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 17 Sep 2006 15:08:50 -0500 Subject: [Tutor] i just cant do it In-Reply-To: <26a78a3c0609171255k77478bf2yaa66327111fc20a@mail.gmail.com> References: <26a78a3c0609171255k77478bf2yaa66327111fc20a@mail.gmail.com> Message-ID: <450DAB52.9000908@gmail.com> federico ramirez wrote: > well, im very angry :( > I cant get this to work > > When i try this it works > > #!/usr/bin/python > > import Cookie > C = Cookie.SimpleCookie() > C['adminuser'] = 'fedekiller' > C['adminuser']['max-age'] = 60*60*24*7 > print C > print "Content-Type: text/html\n\n" > print "Bienvenido",C['adminuser'].value,'!' > Here you're defining a SimpleCookie object called 'C' then you're adding attributes to it. Later, when you print it, you're referencing the 'C' object. For example, when the python interpreter sees C['adminuser'] It says C -> instance of class SimpleCookie. instance.__getitem__('adminuser') returns 'fedekiller' #(this is the method of a class that's called whenever you attempt to #reference it as a dictionary.) > > but when i try this it doesnt > > #!/usr/bin/python > > import Cookie > print "Content-Type: text/html\n\n" > print "Bienvenido",C['adminuser'].value,'!' > Now here, the python interpreter says C -> ??? and it raises an exception, telling you that C is not defined. You never declared what 'C' was, so you can't expect python to read your mind ;) > I dont know why... i know the cookie exists because firefox display it > where all the cookies of that domains are. > So, i need help with this please :( In the future, if you include the traceback, instead of just saying 'it doesn't work,' you're _much_ more likely to get a helpful response. Otherwise you might just get 'need more info.' and the time until you get a useful reply will be longer because you'll have to write another e-mail to the list. Also, if you only have to send one e-mail before you get the reply you need, the traffic on the list is much smaller. In this particular example, it was easy to see what the problem was without running the code, but if someone has to run your code and debug it themselves they ( I ) won't enjoy doing this and won't actually help you. If you don't include tracebacks and such, it seems like you haven't attempted to debug it yourself. The tutor list is here to help you with problems that you have no idea how to solve, and you have to tell us what steps you took to _try_ to solve it, so we can tell you what the next step is. If we just give you answers to your questions, you won't have learned anything, right? :) > I know im a noob sorry U-U That's what the list is here for! But we also want to help you get un-newbied as fast as possible :) > > -- > Best Regards. > fedekiller -Luke From dyoo at hkn.eecs.berkeley.edu Sun Sep 17 22:19:22 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 17 Sep 2006 13:19:22 -0700 (PDT) Subject: [Tutor] python text adventures question In-Reply-To: <25C3F98C1CBB1E458E71AA65CAA32E69E5E627@YETI.bolton.ac.uk> References: <25C3F98C1CBB1E458E71AA65CAA32E69E5E627@YETI.bolton.ac.uk> Message-ID: > I came across the following and wondered if anyone had followed up on this [old message follows:] >> I just ran into the following link; it's a tutorial on writing >> adventure games (circa 1983): >> >> http://www.atariarchives.org/adventure >> >> Would anyone be interested in "porting" the examples over from BASIC to >> Python? It might make a fun project for us here on Tutor; a few of us >> appear to have been exposed to Basic in our past lives... *grin* Any >> takers? Hi Pete, Unfortunately, not to my knowledge: there may be people on the list who've done this privately though. I'll CCing tutor at python.org to see if anyone else has looked at this. Personally, I haven't had the time because of grad school committments. Best of wishes! From kent37 at tds.net Sun Sep 17 23:21:24 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 17 Sep 2006 17:21:24 -0400 Subject: [Tutor] i just cant do it In-Reply-To: <26a78a3c0609171255k77478bf2yaa66327111fc20a@mail.gmail.com> References: <26a78a3c0609171255k77478bf2yaa66327111fc20a@mail.gmail.com> Message-ID: <450DBC54.2020002@tds.net> federico ramirez wrote: > well, im very angry :( > I cant get this to work > > When i try this it works > > #!/usr/bin/python > > import Cookie > C = Cookie.SimpleCookie() > C['adminuser'] = 'fedekiller' > C['adminuser']['max-age'] = 60*60*24*7 > print C > print "Content-Type: text/html\n\n" > print "Bienvenido",C['adminuser'].value,'!' > > > but when i try this it doesnt > > #!/usr/bin/python > > import Cookie > print "Content-Type: text/html\n\n" > print "Bienvenido",C['adminuser'].value,'!' > > I dont know why... i know the cookie exists because firefox display it > where all the cookies of that domains are. > So, i need help with this please :( > I know im a noob sorry U-U Did you see my response to your previous post? Did you try what I said? Did it work? Kent From kent37 at tds.net Sun Sep 17 23:41:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 17 Sep 2006 17:41:15 -0400 Subject: [Tutor] Cookie help In-Reply-To: <26a78a3c0609161945x33f307e2ja2edeca8fd9dd496@mail.gmail.com> References: <26a78a3c0609161945x33f307e2ja2edeca8fd9dd496@mail.gmail.com> Message-ID: <450DC0FB.3020809@tds.net> federico ramirez wrote: > Hey, im working on a cgi script, just a simple news system. > And im stucked with the login system. > GOD! I hate being a noob! > Well, this is the login page > > ################################ > #!/usr/bin/python > > import cgi, dbm, string, Cookie > import config > request = cgi.FieldStorage() > > def loginform(): > print '''
> > > > > > > > > > > > > >
Username
Password
 
>
''' > > def main(): > C = Cookie.SimpleCookie() This makes a new cookie but it doesn't have any data in it - you have to get the data from the environment and put it in the cookie. Try this: if os.environ.has_key('HTTP_COOKIE'): thiscookie.load(os.environ['HTTP_COOKIE']) > if(C.has_key("admin_user") and C.has_key("admin_pass")): > admin = config.getadmin() > if(C["admin_user"].value == admin[0] and C["admin_pass"].value > == admin[1]): > config.makepage("You are already logged!") > else: > config.makepage("Wrong cookies...") > elif(request.has_key("Submit")): > admin = config.getadmin() > username = config.clean(request["user"].value) > password = config.clean(request["pass"].value) > if(username == admin[0] and password == admin[1]): > C["admin_user"] = username > C["admin_pass"] = password > print C > print "Content-Type: text/html\n\n" > config.startpage() > print "Bienvenido",username,'!' > config.endpage () > else: > print "Content-Type: text/html\n\n" > config.startpage() > print "Incorrect username and password combination" > config.endpage () > else: > print "Content-Type: text/html\n\n" > config.startpage() > loginform() > config.endpage() > > main() > ################################ > > That seems to work..but i cant get the cookies, i tried making this to > get them but i have a 500 error -.- i hate it so much > > ################################# > #!/usr/bin/python > try: > import Cookie > print "Content-Type: text/html\n\n" > C = Cookie.SimpleCookie() > print C.["admin_user"].value Most likely you get an error here; actually a SyntaxError because of the extra . after C. If you show us the tracebacks we can give more specific help. > except: > cgi.print_exception() > ################################### > > i tried that in different ways but i cant get it to work > > Help please :( > -- > Best Regards. > fedekiller > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Mon Sep 18 00:44:06 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 17 Sep 2006 23:44:06 +0100 Subject: [Tutor] i just cant do it References: <26a78a3c0609171255k77478bf2yaa66327111fc20a@mail.gmail.com> Message-ID: <005a01c6daaa$c8e2f390$0201a8c0@XPpro> > When i try this it works > > #!/usr/bin/python > > import Cookie > C = Cookie.SimpleCookie() > C['adminuser'] = 'fedekiller' > C['adminuser']['max-age'] = 60*60*24*7 > print C > print "Content-Type: text/html\n\n" > print "Bienvenido",C['adminuser'].value,'!' > > > but when i try this it doesnt Can you explain why you think it should work? What do yopu think it is doing? The code below is very obviously completely different to the code above, so what makes you think it should work? > #!/usr/bin/python > > import Cookie > print "Content-Type: text/html\n\n" > print "Bienvenido",C['adminuser'].value,'!' What is C? Where is it defined? > i know the cookie exists because firefox display it where > all the cookies of that domains are. Cookies exist as small files on your PC. A Python program needs to be given a clue as to which cookie you are interested in so that it can access that file. That's what the Cookie module helps you to do, but it needs to be more than simply imported. That just makes the tools available, it doesn't actually turn them on. HTH, Alan G. From patriciap.gu at gmail.com Mon Sep 18 01:31:44 2006 From: patriciap.gu at gmail.com (Patricia) Date: Sun, 17 Sep 2006 23:31:44 +0000 (UTC) Subject: [Tutor] urllib References: <450687DB.5050707@tds.net> Message-ID: Hi again, I was able to use urllib2_file, which is a wrapper to urllib2.urlopen(). It seems to work fine, and I'm able to retrieve the contents of the file using: afile = req.form.list[1].file.read() Now I have to store this text file (which is about 500k) and an id number into a mysql database in a web server. I have a table that has two columns user id (int) and mediumblob. The problem I have now is I don't know how to store them into the database. I've been looking for examples without any luck. I tried using load data infile, but it seems that I would need to have this client_side file stored in the server. I used load data local infile, and got some errors. I also thought about storing them like this: afile = req.form.list[1].file.read() cursor.execute("""insert into p_report (sales_order, file_cont ) values (%s, %s)""", (1, afile)) I really don't know which is the best way to do it. Which is the right approach? I'm really hoping someone can give me an idea how to do it because I'm finding this a frustrating. Thanks, Patricia From darkpaladin79 at gmail.com Mon Sep 18 01:38:29 2006 From: darkpaladin79 at gmail.com (Ivan Shevanski) Date: Sun, 17 Sep 2006 19:38:29 -0400 Subject: [Tutor] i just cant do it In-Reply-To: <005a01c6daaa$c8e2f390$0201a8c0@XPpro> References: <26a78a3c0609171255k77478bf2yaa66327111fc20a@mail.gmail.com> <005a01c6daaa$c8e2f390$0201a8c0@XPpro> Message-ID: <17d4ae400609171638r500d134dld4e9964ce3445be4@mail.gmail.com> (if I'm getting this right) Think of it as saving file 'hello.txt' in /usr/bin/some_random_folder _you_made Then in the terminal, you try to open the file by typing 'gedit hello.txt'. It has no idea where to look. [I'm a noob too, so if I got it wrong don't flame me too bad ;) ] On 9/17/06, Alan Gauld wrote: > > > When i try this it works > > > > #!/usr/bin/python > > > > import Cookie > > C = Cookie.SimpleCookie() > > C['adminuser'] = 'fedekiller' > > C['adminuser']['max-age'] = 60*60*24*7 > > print C > > print "Content-Type: text/html\n\n" > > print "Bienvenido",C['adminuser'].value,'!' > > > > > > but when i try this it doesnt > > Can you explain why you think it should work? > What do yopu think it is doing? > The code below is very obviously completely different to > the code above, so what makes you think it should work? > > > #!/usr/bin/python > > > > import Cookie > > print "Content-Type: text/html\n\n" > > print "Bienvenido",C['adminuser'].value,'!' > > What is C? Where is it defined? > > > i know the cookie exists because firefox display it where > > all the cookies of that domains are. > > Cookies exist as small files on your PC. A Python program > needs to be given a clue as to which cookie you are interested > in so that it can access that file. That's what the Cookie module > helps you to do, but it needs to be more than simply imported. > That just makes the tools available, it doesn't actually turn > them on. > > HTH, > > Alan G. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- -Ivan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060917/030cceb2/attachment.htm From rdm at rcblue.com Mon Sep 18 03:16:34 2006 From: rdm at rcblue.com (Dick Moores) Date: Sun, 17 Sep 2006 18:16:34 -0700 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: <001e01c6d37e$b2d2fe70$0201a8c0@XPpro> References: <3c6718980609080202mb07e256u9b950aa7dfd23f24@mail.gmail.com> <000b01c6d36c$8117ff00$0201a8c0@XPpro> <4501ACC5.5010402@tds.net> <001e01c6d37e$b2d2fe70$0201a8c0@XPpro> Message-ID: <7.0.1.0.2.20060917164611.05941e20@rcblue.com> I'm baaaack! I kept getting ideas for what I (and some of you) thought was a finished yen-USD.py. And some of the good advice I got was to move on to other things. I did for a while, but I kept thinking up new revisions. The script has more than doubled in length. I'd previously posted v4 at . Here's v10: New functions: again() divide2StringDecimals() multiply2StringDecimals() roundNumber() -- replaced setPrecision() printVariablesNotChanging() formatNumber() removeCommasFromNumbers() rather radically revised function: again() -- offers several more choices The most important change is that because I realized I wanted the program to be a general solution and give accurate answers for even very large amounts of Yen or USD, I decided to operate with (number) strings only, except when necessary in getRate() and getAmount() to error check user inputs. Those floats are not used in the calculations of Yen or USD. The most difficult function for me to write was roundNumber(), which of course couldn't rely on the use of the built-in round() or the formatting of strings (see the line "format = "%." + str(precision) + 'f'" in setPrecision() in v3). Lack of experience with the slicing of lists caused many headaches. I didn't succeed in debugging until I put in print statements wherever a value changes, and trying many different integer strings and places (the arguments of roundNumber()). A good lesson, I think. I hope some of the Tutors will take a look at the new functions, especially roundNumber(). Did I just reinvent the wheel? Should it be broken up into more sub-functions (there's only one now)? It works, but is it Pythonic? Etc. I'm also curious about multiply2StringDecimals() and divide2StringDecimals(). Again, am I reinventing the wheel with these? Is there a simpler way to multiply and divide big decimals with precision? Thanks in advance, Dick Moores From amadeo.bellotti at gmail.com Mon Sep 18 04:10:20 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Sun, 17 Sep 2006 22:10:20 -0400 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: <7.0.1.0.2.20060917164611.05941e20@rcblue.com> References: <3c6718980609080202mb07e256u9b950aa7dfd23f24@mail.gmail.com> <000b01c6d36c$8117ff00$0201a8c0@XPpro> <4501ACC5.5010402@tds.net> <001e01c6d37e$b2d2fe70$0201a8c0@XPpro> <7.0.1.0.2.20060917164611.05941e20@rcblue.com> Message-ID: ok i jsut wanted to say great program but i would like to see an acutal exchange rate like maybe get it from a website it would be so much nicer and easier to use also it would help linux users who run from console so they dont have to look up the current rate online On 9/17/06, Dick Moores wrote: > > I'm baaaack! > > I kept getting ideas for what I (and some of you) thought was a > finished yen-USD.py. And some of the good advice I got was to move on > to other things. I did for a while, but I kept thinking up new > revisions. The script has more than doubled in length. I'd previously > posted v4 at . > > Here's v10: > > New functions: > again() > divide2StringDecimals() > multiply2StringDecimals() > roundNumber() -- replaced setPrecision() > printVariablesNotChanging() > formatNumber() > removeCommasFromNumbers() > > rather radically revised function: > again() -- offers several more choices > > The most important change is that because I realized I wanted the > program to be a general solution and give accurate answers for even > very large amounts of Yen or USD, I decided to operate with (number) > strings only, except when necessary in getRate() and getAmount() to > error check user inputs. Those floats are not used in the > calculations of Yen or USD. > > The most difficult function for me to write was roundNumber(), which > of course couldn't rely on the use of the built-in round() or the > formatting of strings (see the line "format = "%." + str(precision) + > 'f'" in setPrecision() in v3). Lack of experience with the slicing > of lists caused many headaches. I didn't succeed in debugging until I > put in print statements wherever a value changes, and trying many > different integer strings and places (the arguments of > roundNumber()). A good lesson, I think. > > I hope some of the Tutors will take a look at the new functions, > especially roundNumber(). > Did I just reinvent the wheel? > Should it be broken up into more sub-functions (there's only one now)? > It works, but is it Pythonic? Etc. > > I'm also curious about multiply2StringDecimals() and > divide2StringDecimals(). > Again, am I reinventing the wheel with these? > Is there a simpler way to multiply and divide big decimals with precision? > > Thanks in advance, > > Dick Moores > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060917/2be7b7bb/attachment-0001.html From rdm at rcblue.com Mon Sep 18 04:23:52 2006 From: rdm at rcblue.com (Dick Moores) Date: Sun, 17 Sep 2006 19:23:52 -0700 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: References: <3c6718980609080202mb07e256u9b950aa7dfd23f24@mail.gmail.com> <000b01c6d36c$8117ff00$0201a8c0@XPpro> <4501ACC5.5010402@tds.net> <001e01c6d37e$b2d2fe70$0201a8c0@XPpro> <7.0.1.0.2.20060917164611.05941e20@rcblue.com> Message-ID: <7.0.1.0.2.20060917192032.06a31b98@rcblue.com> At 07:10 PM 9/17/2006, Amadeo Bellotti wrote: >ok i jsut wanted to say great program but i would like to see an >acutal exchange rate like maybe get it from a website it would be so >much nicer and easier to use also it would help linux users who run >from console so they dont have to look up the current rate online Thanks for the great suggestion. Right now I don't have the faintest idea how to implement it, but I'm sure going to try to learn how. Give me till Tuesday? ;) Dick From amonroe at columbus.rr.com Mon Sep 18 05:07:36 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun, 17 Sep 2006 23:07:36 -0400 Subject: [Tutor] python text adventures question In-Reply-To: References: <25C3F98C1CBB1E458E71AA65CAA32E69E5E627@YETI.bolton.ac.uk> Message-ID: <3113895362.20060917230736@columbus.rr.com> >>> I just ran into the following link; it's a tutorial on writing >>> adventure games (circa 1983): >>> >>> http://www.atariarchives.org/adventure >>> >>> Would anyone be interested in "porting" the examples over from BASIC to >>> Python? It might make a fun project for us here on Tutor; a few of us >>> appear to have been exposed to Basic in our past lives... *grin* Any >>> takers? > Hi Pete, > Unfortunately, not to my knowledge: there may be people on the list who've > done this privately though. I'll CCing tutor at python.org to see if anyone > else has looked at this. Personally, I haven't had the time because of > grad school committments. I have done a simple conversion of a similar BASIC text adventure. By following the layout of the BASIC code, I got a working, but very un-pythonic program :) If the mood strikes me someday, I would like to go back and pythonicise it. Alan From rabidpoobear at gmail.com Mon Sep 18 05:13:13 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 17 Sep 2006 22:13:13 -0500 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: <7.0.1.0.2.20060917164611.05941e20@rcblue.com> References: <3c6718980609080202mb07e256u9b950aa7dfd23f24@mail.gmail.com> <000b01c6d36c$8117ff00$0201a8c0@XPpro> <4501ACC5.5010402@tds.net> <001e01c6d37e$b2d2fe70$0201a8c0@XPpro> <7.0.1.0.2.20060917164611.05941e20@rcblue.com> Message-ID: <450E0EC9.5010401@gmail.com> Dick Moores wrote: > I'm baaaack! > > I kept getting ideas for what I (and some of you) thought was a > finished yen-USD.py. And some of the good advice I got was to move on > to other things. I did for a while, but I kept thinking up new > revisions. The script has more than doubled in length. I'd previously > posted v4 at . > > Here's v10: > > New functions: > again() > divide2StringDecimals() > multiply2StringDecimals() > roundNumber() -- replaced setPrecision() > printVariablesNotChanging() > formatNumber() > removeCommasFromNumbers() > > rather radically revised function: > again() -- offers several more choices > > The most important change is that because I realized I wanted the > program to be a general solution and give accurate answers for even > very large amounts of Yen or USD, I decided to operate with (number) > strings only, except when necessary in getRate() and getAmount() to > error check user inputs. Those floats are not used in the > calculations of Yen or USD. > > The most difficult function for me to write was roundNumber(), which > of course couldn't rely on the use of the built-in round() or the > formatting of strings (see the line "format = "%." + str(precision) + > 'f'" in setPrecision() in v3). Lack of experience with the slicing > of lists caused many headaches. I didn't succeed in debugging until I > put in print statements wherever a value changes, and trying many > different integer strings and places (the arguments of > roundNumber()). A good lesson, I think. > > A few notes: 1. in your roundNumber function, you define a function incrementDigit. I'm pretty sure that this function is destroyed and recreated every time you call the function roundNumber. This applies to divide2stringdecimals and other functions as well. Is this what you want? 2. in your remove commas from numbers function, you could simplify it: #from a = n.split(',') n = ''.join(a) return n #to return ''.join(a.split(',')) personally I like this more. > I hope some of the Tutors will take a look at the new functions, > especially roundNumber(). > Did I just reinvent the wheel? > I'm pretty sure you could set up a Context in the decimal module that will round and keep the precision where you specify. So if this is true, I guess you did reinvent the wheel. > Should it be broken up into more sub-functions (there's only one now)? > It works, but is it Pythonic? Etc. > I think you need to settle on a naming convention so your code's more readable. Your variables are sometimes named aRandomVariable, with the start of each new word capitalized, then in other places (like the variable 'slen' in numberCommas -> intCommas) they're not. Also, it's easier to differentiate between functions and variables if they're named a different way. Like a_variable_name = someFunction() That's just my opinion, of course, and you can do whatever you want :) Also, I've seen that you call the variable you store the split value in 'splt' Now while this approach may have its uses, it makes it more difficult to understand what's going on in your code (for me). If I were writing this software I might misread (or mistype!) split instead of splt, and not be able to figure out what the problem was while I was debugging, whereas if the variable were named 'num_str' or something, there's a smaller chance of confusion. And lastly :) props on the commenting. They were helpful and informative. > I'm also curious about multiply2StringDecimals() and divide2StringDecimals(). > Again, am I reinventing the wheel with these? > Is there a simpler way to multiply and divide big decimals with precision? > Well, the decimal module implements division and multiplication of decimal data type variables... Eg. #code: context = decimal.Context() #replace this line with your customized context... decimal.setcontext(context) d= decimal.Decimal('6') e = decimal.Decimal('3') print d/e #output: 2 Again, for the precision and such that you'll want for this, look into making a custom context. > Thanks in advance, > > Dick Moores > Sure :D -Luke From rabidpoobear at gmail.com Mon Sep 18 05:17:47 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 17 Sep 2006 22:17:47 -0500 Subject: [Tutor] python text adventures question In-Reply-To: <3113895362.20060917230736@columbus.rr.com> References: <25C3F98C1CBB1E458E71AA65CAA32E69E5E627@YETI.bolton.ac.uk> <3113895362.20060917230736@columbus.rr.com> Message-ID: <450E0FDB.9090403@gmail.com> R. Alan Monroe wrote: > >>>> I just ran into the following link; it's a tutorial on writing >>>> adventure games (circa 1983): >>>> >>>> http://www.atariarchives.org/adventure >>>> >>>> Would anyone be interested in "porting" the examples over from BASIC to >>>> Python? It might make a fun project for us here on Tutor; a few of us >>>> appear to have been exposed to Basic in our past lives... *grin* Any >>>> takers? >>>> I might attempt to do this eventually. Maybe during the winter break. That is, if I can take a break from the Wii! Teh Calculus 2 among other things are consuming quite a bit of my time at the moment, so I probably couldn't start on it this semester, but if I get around to working on this at all I'll shoot you an e-mail. Thanks for the link! -Luke From lavendula6654 at yahoo.com Mon Sep 18 06:06:42 2006 From: lavendula6654 at yahoo.com (Elaine) Date: Sun, 17 Sep 2006 21:06:42 -0700 (PDT) Subject: [Tutor] Python Course at Foothill College Message-ID: <20060918040642.89838.qmail@web31715.mail.mud.yahoo.com> If you would like to learn Python, Foothill College in Los Altos Hills, CA is offering a course starting Mon. evening, 25 Sept. The course is designed for students who are already familiar with some type of programming. Here is the course description: CIS 68K "INTRODUCTION TO PYTHON PROGRAMMING" 5 Units This course will introduce students to the Python language and environment. Python is a portable, interpreted, object-oriented programming language that is often compared to Perl, Java, Scheme and Tcl. The language has an elegant syntax, dynamic typing, and a small number of powerful, high-level data types. It also has modules, classes, and exceptions. The modules provide interfaces to many system calls and libraries, as well as to various windowing systems(X11, Motif, Tk, Mac, MFC). New built-in modules are easily written in C or C++. Such extension modules can define new functions and variables as well as new object types. Four hours lecture, four hours terminal time. If you would like to sign up for the class, please register beforehand by going to: http://www.foothill.fhda.edu/reg/index.php If you have questions, you can contact the instructor at: haightElaine at foothill.edu Thanks! -Elaine Haight __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From rabidpoobear at gmail.com Mon Sep 18 06:12:27 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 17 Sep 2006 23:12:27 -0500 Subject: [Tutor] Python Course at Foothill College In-Reply-To: <20060918040642.89838.qmail@web31715.mail.mud.yahoo.com> References: <20060918040642.89838.qmail@web31715.mail.mud.yahoo.com> Message-ID: <450E1CAB.4030201@gmail.com> Elaine wrote: > If you would like to learn Python, Foothill College in > Los Altos Hills, CA is offering a course starting > Mon. evening, 25 Sept. The course is designed for > students who are already familiar with some type of > programming. Here is the course description: > > CIS 68K "INTRODUCTION TO PYTHON PROGRAMMING" 5 Units CIS is Computer Information Systems at my school. CIS is part of the business school and doesn't have much to do with Computer Science. Is that how it is there as well? If so, do you have Computer Science courses in Python as well? (I don't live anywhere near CA, I'm just interested.) Wish my school used Python. -Luke From sisson.j at gmail.com Mon Sep 18 00:46:21 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Sun, 17 Sep 2006 17:46:21 -0500 Subject: [Tutor] Python Course at Foothill College In-Reply-To: <450E1CAB.4030201@gmail.com> References: <20060918040642.89838.qmail@web31715.mail.mud.yahoo.com> <450E1CAB.4030201@gmail.com> Message-ID: <450DD03D.9070109@gmail.com> I'll have to second that...my school is wrapped up with Java, C#, and Scheme. Python has all about ruined me for programming in other languages, and I really wish Python was taught/allowed at my school. I'm currently working on a team for CSC 480 (Senior Project - Design Phase) and we're forced to choke down Microsoft design models (I'm an avid open source advocate...(http://www.catb.org/~esr/writings/cathedral-bazaar/ for a paper by Eric S. Raymond that, for me, hits the nail on the head).) *sigh* Perhaps when I start grad school I'll be in a position to use my favored language...until then I guess .NET wins. By the way, CIS at my school is a hybrid between business and computer science. It's basically a lightweight computer science degree combined with a lightweight business degree. From a computer science standpoint, it does cover the fundamentals (architectures, programming, data structures, algorithms, etc...) but does not include the senior project course series, advanced database admin, Windows admin, etc... Luke Paireepinart wrote: > Elaine wrote: > >> If you would like to learn Python, Foothill College in >> Los Altos Hills, CA is offering a course starting >> Mon. evening, 25 Sept. The course is designed for >> students who are already familiar with some type of >> programming. Here is the course description: >> >> CIS 68K "INTRODUCTION TO PYTHON PROGRAMMING" 5 Units >> > > CIS is Computer Information Systems at my school. > CIS is part of the business school and doesn't have much to do with > Computer Science. > Is that how it is there as well? > If so, do you have Computer Science courses in Python as well? > (I don't live anywhere near CA, I'm just interested.) > Wish my school used Python. > -Luke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From lavendula6654 at yahoo.com Mon Sep 18 07:02:16 2006 From: lavendula6654 at yahoo.com (Elaine) Date: Sun, 17 Sep 2006 22:02:16 -0700 (PDT) Subject: [Tutor] Python Course at Foothill College In-Reply-To: <450E1CAB.4030201@gmail.com> Message-ID: <20060918050216.42856.qmail@web31710.mail.mud.yahoo.com> Foothill is a community college (2-year college), and CIS is computer information systems. I always teach the fundamentals like how to write efficient, modifiable and documented software. This is an introductory course, so we won't be covering data structures and algorithms. We will cover files, Exceptions, Classes. regular expressions and Tkinter, et al. Thanks for the interest! -Elaine --- Luke Paireepinart wrote: > Elaine wrote: > > If you would like to learn Python, Foothill > College in > > Los Altos Hills, CA is offering a course starting > > Mon. evening, 25 Sept. The course is designed for > > students who are already familiar with some type > of > > programming. Here is the course description: > > > > CIS 68K "INTRODUCTION TO PYTHON PROGRAMMING" 5 > Units > > CIS is Computer Information Systems at my school. > CIS is part of the business school and doesn't have > much to do with > Computer Science. > Is that how it is there as well? > If so, do you have Computer Science courses in > Python as well? > (I don't live anywhere near CA, I'm just > interested.) > Wish my school used Python. > -Luke > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From rdm at rcblue.com Mon Sep 18 09:08:56 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 18 Sep 2006 00:08:56 -0700 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: <450E0EC9.5010401@gmail.com> References: <3c6718980609080202mb07e256u9b950aa7dfd23f24@mail.gmail.com> <000b01c6d36c$8117ff00$0201a8c0@XPpro> <4501ACC5.5010402@tds.net> <001e01c6d37e$b2d2fe70$0201a8c0@XPpro> <7.0.1.0.2.20060917164611.05941e20@rcblue.com> <450E0EC9.5010401@gmail.com> Message-ID: <7.0.1.0.2.20060917230119.0622f448@rcblue.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060918/84c42697/attachment-0001.htm From alan.gauld at freenet.co.uk Mon Sep 18 09:42:26 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 18 Sep 2006 08:42:26 +0100 Subject: [Tutor] Fw: i just cant do it Message-ID: <001401c6daf5$fd1592d0$0201a8c0@XPpro> ----- Original Message ----- From: "federico ramirez" To: "Alan Gauld" Sent: Monday, September 18, 2006 12:43 AM Subject: Re: [Tutor] i just cant do it > Nope...sorry i tried what they said in that article but it didnt > work :( >>_< > > 2006/9/17, Alan Gauld : >> >> >> > Sorry, in the first code i set the cookie and then display it but >> > in >> > the >> > second i assume that the cookie is created and just want to read >> > it, >> > but >> > nothing happens >> >> Correct. >> I notice Luke also sent a reply. >> >> Between the two replies do you understand what you now need to do >> differently in the second case to recreate the cookie from its >> file? >> >> Alan G. >> >> >> > #!/usr/bin/python >> >> > >> >> > import Cookie >> >> > C = Cookie.SimpleCookie() >> >> > C['adminuser'] = 'fedekiller' >> >> > C['adminuser']['max-age'] = 60*60*24*7 >> >> > print C >> >> > print "Content-Type: text/html\n\n" >> >> > print "Bienvenido",C['adminuser'].value,'!' >> >> > >> >> > >> >> > but when i try this it doesnt >> >> >> >> Can you explain why you think it should work? >> >> What do yopu think it is doing? >> >> The code below is very obviously completely different to >> >> the code above, so what makes you think it should work? >> >> >> >> > #!/usr/bin/python >> >> > >> >> > import Cookie >> >> > print "Content-Type: text/html\n\n" >> >> > print "Bienvenido",C['adminuser'].value,'!' >> >> >> >> What is C? Where is it defined? >> >> >> >> > i know the cookie exists because firefox display it where >> >> > all the cookies of that domains are. >> >> >> >> Cookies exist as small files on your PC. A Python program >> >> needs to be given a clue as to which cookie you are interested >> >> in so that it can access that file. That's what the Cookie >> >> module >> >> helps you to do, but it needs to be more than simply imported. >> >> That just makes the tools available, it doesn't actually turn >> >> them on. >> >> >> >> HTH, >> >> >> >> Alan G. >> >> >> > >> > >> > >> > -- >> > Best Regards. >> > fedekiller >> > >> >> > > > -- > Best Regards. > fedekiller > From alan.gauld at freenet.co.uk Mon Sep 18 09:50:48 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 18 Sep 2006 08:50:48 +0100 Subject: [Tutor] Python Course at Foothill College References: <20060918040642.89838.qmail@web31715.mail.mud.yahoo.com><450E1CAB.4030201@gmail.com> <450DD03D.9070109@gmail.com> Message-ID: <005401c6daf7$27f20eb0$0201a8c0@XPpro> > *sigh* Perhaps when I start grad school I'll be in a position to use > my > favored language...until then I guess .NET wins. Have you tried IronPython? Python for .NET... Alan G. From alan.gauld at freenet.co.uk Mon Sep 18 10:00:27 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 18 Sep 2006 09:00:27 +0100 Subject: [Tutor] Some questions about my yen-USD.py References: <3c6718980609080202mb07e256u9b950aa7dfd23f24@mail.gmail.com><000b01c6d36c$8117ff00$0201a8c0@XPpro> <4501ACC5.5010402@tds.net><001e01c6d37e$b2d2fe70$0201a8c0@XPpro><7.0.1.0.2.20060917164611.05941e20@rcblue.com><450E0EC9.5010401@gmail.com> <7.0.1.0.2.20060917230119.0622f448@rcblue.com> Message-ID: <005a01c6daf8$80f8ee60$0201a8c0@XPpro> >> 1. in your roundNumber function, you define a function >> incrementDigit. >> I'm pretty sure that this function is destroyed and recreated >> every time >> you call the function roundNumber. > I don't understand. What's another way? def f(): def g(): return 42 return g() def g(): return 42 def f() return g() The two bits of code do the same thing but the first constructs/deletes g() each time. > And what's the downside of the way I've done it? Its slow... > How do you keep from causing all that destruction and recreation? See above > And what's bad about it? Its slow But sometimes defining a function inside another function is what you want, because you need to limit visibility, or it needs to access variables that are local to the outer function. But unless you have a very clear idea of why you want to define a nested function its better to make them global. > No, I'll take your advice. But I hate to type underscores, > so is there another style I could use for functions that > would be different from the aRandomVariable style I > like for variables? Personally I don't differentiate variables and functions in Python (partly because Python doesn't - they are all just names) mainly because functions are usually obvious by dint of the parentheses used to call them. > Function Names > > Function names should be lowercase, with words separated by > underscores as necessary to improve readability. It may be the official style but in practice its not that widely followed. > So I guess I should start learning to type underscores accurately. Me too, I guess :-) Alan G. From samrobertsmith at gmail.com Mon Sep 18 11:26:59 2006 From: samrobertsmith at gmail.com (linda.s) Date: Mon, 18 Sep 2006 02:26:59 -0700 Subject: [Tutor] folder and module In-Reply-To: <450DA48A.60108@cc.umanitoba.ca> References: <1d987df30609161803q21771d24k3f8b1760db0fffa0@mail.gmail.com> <001c01c6da2e$0dd966a0$0201a8c0@XPpro> <1d987df30609170343x5303d347l7e01b78cd6f3d599@mail.gmail.com> <000301c6da69$2aaadda0$0201a8c0@XPpro> <1d987df30609171203o73d3dad0i2ee6e5b2064aa0df@mail.gmail.com> <450DA48A.60108@cc.umanitoba.ca> Message-ID: <1d987df30609180226vf388007x4dd35b66af4e2707@mail.gmail.com> > Hi Linda, > > what do you get when you try: > > >>> import os > >>> os.getcwd() > > The current working directory is represented in sys.path as the first > element: > > >>> import sys > >>> sys.path[0] > '' > > > Not the most intuitive, perhaps. > > I suspect you are launching your Python environment from a desktop > icon. That would explain why import can `see' your Desktop, even > though it doesn't at first glance seem to be in sys.path. You are right!!! I launched Python environment from a desktop icon. From ziad.rahhal at gmail.com Mon Sep 18 11:59:09 2006 From: ziad.rahhal at gmail.com (Ziad Rahhal) Date: Mon, 18 Sep 2006 11:59:09 +0200 Subject: [Tutor] From byte[] to Image In-Reply-To: <003001c6da7a$4ffffe80$0201a8c0@XPpro> References: <002e01c6d9d7$30342e80$0201a8c0@XPpro> <003001c6da7a$4ffffe80$0201a8c0@XPpro> Message-ID: I do the following: file = StringIO.StringIO(buffer) img = Image.open(file) img.save(file, 'JPEG') I get this error: img = Image.open(file) File "/home/rahhal/python/lib/python2.4/site-packages/PIL/Image.py", line 1745, in open raise IOError("cannot identify image file") IOError: cannot identify image file Yes I printed the contents of Buffer but how can I make sure if it is all there since the type I am receiving is different (temporarly, until I form the Image) from the original content of the Image itself. I will attach the buffer I am receiving and the original Image I am sending. On 9/17/06, Alan Gauld wrote: > > > (Note that this function decodes pixel data only, not entire images. > > If you > > have an entire image file in a string, wrap it in a *StringIO* > > object, and > > use > > *open* >to > > load it.) > > > > So I guess "frombuffer" must not be used in my case. > > Looks like it, but did you try what it suggested, namely using > a StringIO object and the open method? > > What happened? > > > The java method is working correctly but I am not able to form the > > picture > > in the right way at the client side using the PIL library. > > > I receive it at the client side in python: > > buffer = service.getFile(fileName) > > I assume you tried printing buffer (or at least its len) to check that > it was all there? > > Alan G. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060918/142981dc/attachment-0001.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: buffer Type: application/octet-stream Size: 11332 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060918/142981dc/attachment-0001.obj -------------- next part -------------- A non-text attachment was scrubbed... Name: out.jpg Type: image/jpeg Size: 27798 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060918/142981dc/attachment-0001.jpg From ziad.rahhal at gmail.com Mon Sep 18 12:50:23 2006 From: ziad.rahhal at gmail.com (Ziad Rahhal) Date: Mon, 18 Sep 2006 12:50:23 +0200 Subject: [Tutor] From byte[] to Image In-Reply-To: <003001c6da7a$4ffffe80$0201a8c0@XPpro> References: <002e01c6d9d7$30342e80$0201a8c0@XPpro> <003001c6da7a$4ffffe80$0201a8c0@XPpro> Message-ID: I do the following: file = StringIO.StringIO(buffer) img = Image.open(file) img.save(file, 'JPEG') I get this error: img = Image.open(file) File "/home/rahhal/python/lib/python2.4/site-packages/PIL/Image.py", line 1745, in open raise IOError("cannot identify image file") IOError: cannot identify image file Yes I printed the contents of Buffer but how can I make sure if it is all there since the type I am receiving is different (temporarly, until I form the Image) from the original content of the Image itself. I tried to attach the original image and the data (in the buffer) but the email bounced as it was too large. So I am sending the email again without attachments Regards, Ziad On 9/17/06, Alan Gauld wrote: > > > (Note that this function decodes pixel data only, not entire images. > > If you > > have an entire image file in a string, wrap it in a *StringIO* > > object, and > > use > > *open*< > file:///home/rahhal/Imaging-1.1.5/Docs/pythondoc-PIL.Image.html#PIL.Image.open-function > >to > > load it.) > > > > So I guess "frombuffer" must not be used in my case. > > Looks like it, but did you try what it suggested, namely using > a StringIO object and the open method? > > What happened? > > > The java method is working correctly but I am not able to form the > > picture > > in the right way at the client side using the PIL library. > > > I receive it at the client side in python: > > buffer = service.getFile(fileName) > > I assume you tried printing buffer (or at least its len) to check that > it was all there? > > Alan G. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060918/38eca319/attachment.html From kent37 at tds.net Mon Sep 18 14:20:35 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 18 Sep 2006 08:20:35 -0400 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: <7.0.1.0.2.20060917164611.05941e20@rcblue.com> References: <3c6718980609080202mb07e256u9b950aa7dfd23f24@mail.gmail.com> <000b01c6d36c$8117ff00$0201a8c0@XPpro> <4501ACC5.5010402@tds.net> <001e01c6d37e$b2d2fe70$0201a8c0@XPpro> <7.0.1.0.2.20060917164611.05941e20@rcblue.com> Message-ID: <450E8F13.6020208@tds.net> Dick Moores wrote: > I'm baaaack! > > I kept getting ideas for what I (and some of you) thought was a > finished yen-USD.py. And some of the good advice I got was to move on > to other things. I did for a while, but I kept thinking up new > revisions. The script has more than doubled in length. I'd previously > posted v4 at . > > Here's v10: > > New functions: > again() > divide2StringDecimals() > multiply2StringDecimals() > roundNumber() -- replaced setPrecision() > printVariablesNotChanging() > formatNumber() > removeCommasFromNumbers() > > rather radically revised function: > again() -- offers several more choices > > The most important change is that because I realized I wanted the > program to be a general solution and give accurate answers for even > very large amounts of Yen or USD, I decided to operate with (number) > strings only, except when necessary in getRate() and getAmount() to > error check user inputs. Those floats are not used in the > calculations of Yen or USD. You have greatly underused Decimal - it is capable of multiplication and division of fractional quantities directly: In [1]: from decimal import Decimal as D In [2]: x=D('1.23') In [3]: y=D('4.5') In [4]: x*y Out[4]: Decimal("5.535") In [5]: x/y Out[5]: Decimal("0.2733333333333333333333333333") > > The most difficult function for me to write was roundNumber(), which > of course couldn't rely on the use of the built-in round() or the > formatting of strings (see the line "format = "%." + str(precision) + > 'f'" in setPrecision() in v3). Lack of experience with the slicing > of lists caused many headaches. I didn't succeed in debugging until I > put in print statements wherever a value changes, and trying many > different integer strings and places (the arguments of > roundNumber()). A good lesson, I think. The recipes page in the docs for Decimal include a moneyfmt() function that rounds to a specified number of places and inserts a separator char. Kent > > I hope some of the Tutors will take a look at the new functions, > especially roundNumber(). > Did I just reinvent the wheel? Yes :-) > Should it be broken up into more sub-functions (there's only one now)? > It works, but is it Pythonic? Etc. > > I'm also curious about multiply2StringDecimals() and divide2StringDecimals(). > Again, am I reinventing the wheel with these? > Is there a simpler way to multiply and divide big decimals with precision? > > Thanks in advance, > > Dick Moores > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Mon Sep 18 14:35:54 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 18 Sep 2006 08:35:54 -0400 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: <005a01c6daf8$80f8ee60$0201a8c0@XPpro> References: <3c6718980609080202mb07e256u9b950aa7dfd23f24@mail.gmail.com><000b01c6d36c$8117ff00$0201a8c0@XPpro> <4501ACC5.5010402@tds.net><001e01c6d37e$b2d2fe70$0201a8c0@XPpro><7.0.1.0.2.20060917164611.05941e20@rcblue.com><450E0EC9.5010401@gmail.com> <7.0.1.0.2.20060917230119.0622f448@rcblue.com> <005a01c6daf8$80f8ee60$0201a8c0@XPpro> Message-ID: <450E92AA.4010104@tds.net> Alan Gauld wrote: >>> 1. in your roundNumber function, you define a function >>> incrementDigit. >>> I'm pretty sure that this function is destroyed and recreated >>> every time >>> you call the function roundNumber. >> I don't understand. What's another way? > > def f(): > def g(): return 42 > return g() > > def g(): return 42 > def f() return g() > > The two bits of code do the same thing but the first > constructs/deletes g() each time. > >> And what's the downside of the way I've done it? > > Its slow... Actually it is not particularly slow. The actual function code is created once, when the module is compiled; creating a function object and binding it to a name is pretty fast. There is a good discussion here: http://tinyurl.com/gzfyl Kent From rdm at rcblue.com Mon Sep 18 15:07:10 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 18 Sep 2006 06:07:10 -0700 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: <005a01c6daf8$80f8ee60$0201a8c0@XPpro> References: <3c6718980609080202mb07e256u9b950aa7dfd23f24@mail.gmail.com> <000b01c6d36c$8117ff00$0201a8c0@XPpro> <4501ACC5.5010402@tds.net> <001e01c6d37e$b2d2fe70$0201a8c0@XPpro> <7.0.1.0.2.20060917164611.05941e20@rcblue.com> <450E0EC9.5010401@gmail.com> <7.0.1.0.2.20060917230119.0622f448@rcblue.com> <005a01c6daf8$80f8ee60$0201a8c0@XPpro> Message-ID: <7.0.1.0.2.20060918060254.05c797d8@rcblue.com> At 01:00 AM 9/18/2006, Alan Gauld wrote: > >> 1. in your roundNumber function, you define a function > >> incrementDigit. > >> I'm pretty sure that this function is destroyed and recreated > >> every time > >> you call the function roundNumber. > > I don't understand. What's another way? > >def f(): > def g(): return 42 > return g() > >def g(): return 42 >def f() return g() > >The two bits of code do the same thing but the first >constructs/deletes g() each time. Hm. That's what I get for knowing little computer science. > > And what's the downside of the way I've done it? > >Its slow... Doesn't seem slow to me. But I take your point. > > How do you keep from causing all that destruction and recreation? > >See above > > > And what's bad about it? > >Its slow > >But sometimes defining a function inside another function is >what you want, because you need to limit visibility, or it needs >to access variables that are local to the outer function. >But unless you have a very clear idea of why you want to >define a nested function its better to make them global. > > > No, I'll take your advice. But I hate to type underscores, > > so is there another style I could use for functions that > > would be different from the aRandomVariable style I > > like for variables? > >Personally I don't differentiate variables and functions >in Python (partly because Python doesn't - they are >all just names) mainly because functions are usually >obvious by dint of the parentheses used to call them. > > > Function Names > > > > Function names should be lowercase, with words separated by > > underscores as necessary to improve readability. > >It may be the official style but in practice its not that widely >followed. > > > So I guess I should start learning to type underscores accurately. > >Me too, I guess :-) Thanks, Alan. Dick From rdm at rcblue.com Mon Sep 18 15:44:55 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 18 Sep 2006 06:44:55 -0700 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: <450E8F13.6020208@tds.net> References: <3c6718980609080202mb07e256u9b950aa7dfd23f24@mail.gmail.com> <000b01c6d36c$8117ff00$0201a8c0@XPpro> <4501ACC5.5010402@tds.net> <001e01c6d37e$b2d2fe70$0201a8c0@XPpro> <7.0.1.0.2.20060917164611.05941e20@rcblue.com> <450E8F13.6020208@tds.net> Message-ID: <7.0.1.0.2.20060918061506.05d743e8@rcblue.com> At 05:20 AM 9/18/2006, Kent Johnson wrote: >You have greatly underused Decimal - it is capable of multiplication and >division of fractional quantities directly: > >In [1]: from decimal import Decimal as D > >In [2]: x=D('1.23') > >In [3]: y=D('4.5') > >In [4]: x*y >Out[4]: Decimal("5.535") > >In [5]: x/y >Out[5]: Decimal("0.2733333333333333333333333333") And sqrt() as well, which I definitely thought was not possible. Well, you settled that. I don't know why I didn't see it. > > of course couldn't rely on the use of the built-in round() or the > > formatting of strings (see the line "format = "%." + str(precision) + > > 'f'" in setPrecision() in v3). Lack of experience with the slicing > > of lists caused many headaches. I didn't succeed in debugging until I > > put in print statements wherever a value changes, and trying many > > different integer strings and places (the arguments of > > roundNumber()). A good lesson, I think. > >The recipes page in the docs for Decimal include a moneyfmt() function >that rounds to a specified number of places and inserts a separator char. I'd seen the recipes in the docs, but couldn't make much sense out of them. I think I can now. Or at least more sense than before. Thanks, Kent. Dick From rabidpoobear at gmail.com Mon Sep 18 15:49:42 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 18 Sep 2006 08:49:42 -0500 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: <7.0.1.0.2.20060918060254.05c797d8@rcblue.com> References: <3c6718980609080202mb07e256u9b950aa7dfd23f24@mail.gmail.com> <000b01c6d36c$8117ff00$0201a8c0@XPpro> <4501ACC5.5010402@tds.net> <001e01c6d37e$b2d2fe70$0201a8c0@XPpro> <7.0.1.0.2.20060917164611.05941e20@rcblue.com> <450E0EC9.5010401@gmail.com> <7.0.1.0.2.20060917230119.0622f448@rcblue.com> <005a01c6daf8$80f8ee60$0201a8c0@XPpro> <7.0.1.0.2.20060918060254.05c797d8@rcblue.com> Message-ID: <450EA3F6.3010001@gmail.com> Dick Moores wrote: > At 01:00 AM 9/18/2006, Alan Gauld wrote: > >>>> 1. in your roundNumber function, you define a function >>>> incrementDigit. >>>> I'm pretty sure that this function is destroyed and recreated >>>> every time >>>> you call the function roundNumber. >>>> >>> I don't understand. What's another way? >>> >> def f(): >> def g(): return 42 >> return g() >> >> def g(): return 42 >> def f() return g() >> Alan meant 'def f(): return g()' on that last line there I think :) > > Doesn't seem slow to me. But I take your point. > Well, there's the whole Python idiom of 'readability > speed'. It really doesn't matter how fast something is if it increases readability (unless the slower speed really makes a difference, like that guy's program that used range() instead of xrange() and crashed the computer!) However, nested functions are not very common, so for me, they are just distracting. As Kent said, it may not be that slow to do this, either, and in your particular program, if you choose to use nested functions it shouldn't make any noticeable speed difference. If you were going to parse 100,000 text files and change any occurrences of $xx.xx into Yen from a given conversion rate, then you'd probably want it to be as efficient as possible, but if someone's just converting one value, they're not really going to notice if it's .001 seconds slower, right? >> >>> No, I'll take your advice. But I hate to type underscores, >>> so is there another style I could use for functions that >>> would be different from the aRandomVariable style I >>> like for variables? >>> Yeah, underscores are kind of bothersome. That's what I usually end up using, though. >> >>> Function Names >>> >>> Function names should be lowercase, with words separated by >>> underscores as necessary to improve readability. >>> >> It may be the official style but in practice its not that widely >> followed. >> Yeah, I haven't seen too much of that going on. Most pieces of Python code I read have some crazy syntax that I've never seen before. I learn new things every day :D -Luke From rabidpoobear at gmail.com Mon Sep 18 15:56:36 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 18 Sep 2006 08:56:36 -0500 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: <7.0.1.0.2.20060918061506.05d743e8@rcblue.com> References: <3c6718980609080202mb07e256u9b950aa7dfd23f24@mail.gmail.com> <000b01c6d36c$8117ff00$0201a8c0@XPpro> <4501ACC5.5010402@tds.net> <001e01c6d37e$b2d2fe70$0201a8c0@XPpro> <7.0.1.0.2.20060917164611.05941e20@rcblue.com> <450E8F13.6020208@tds.net> <7.0.1.0.2.20060918061506.05d743e8@rcblue.com> Message-ID: <450EA594.1060700@gmail.com> Dick Moores wrote: > At 05:20 AM 9/18/2006, Kent Johnson wrote: > > >> You have greatly underused Decimal - it is capable of multiplication and >> division of fractional quantities directly: >> >> In [1]: from decimal import Decimal as D >> >> In [2]: x=D('1.23') >> >> In [3]: y=D('4.5') >> >> In [4]: x*y >> Out[4]: Decimal("5.535") >> >> In [5]: x/y >> Out[5]: Decimal("0.2733333333333333333333333333") >> > > And sqrt() as well, which I definitely thought was not possible. > > > Well, you settled that. I don't know why I didn't see it. > Perhaps you had some preconceptions about the limits of the Decimal module, and upon preliminary investigations something confirmed this for you, so you didn't actually look in-depth for a way to do what you were trying to do because it seemed at first glance like Decimal wasn't the right tool (maybe you saw an example that didn't fully utilize Decimal or something.) Or, alternatively, you cheated and skimmed over the docs, and didn't see something important the first time around :) > >>> of course couldn't rely on the use of the built-in round() or the >>> formatting of strings (see the line "format = "%." + str(precision) + >>> 'f'" in setPrecision() in v3). Lack of experience with the slicing >>> of lists caused many headaches. I didn't succeed in debugging until I >>> put in print statements wherever a value changes, and trying many >>> different integer strings and places (the arguments of >>> roundNumber()). A good lesson, I think. >>> >> The recipes page in the docs for Decimal include a moneyfmt() function >> that rounds to a specified number of places and inserts a separator char. >> > > I'd seen the recipes in the docs, but couldn't make much sense out of > them. I think I can now. Or at least more sense than before. > > Yes, even though a portion of your program has functionality in the Decimal module already, coding anything is good practice. For example, my dream is to one day write a NES emulator in Python, and this has already been done dozens of times in C, C++, Java, even Visual Basic. I don't care, my goal is the same whether or not I'm reinventing the wheel. :) I know of no NES emulator in Python, though, so I guess i'm not really reinventing the wheel after all (if anyone asks, tell them I'm porting that Java emulator :) > Thanks, Kent. > > Dick > > Have a good day! I have to get my butt to class now. 4 minutes! eek. -Luke From rdm at rcblue.com Mon Sep 18 16:28:04 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 18 Sep 2006 07:28:04 -0700 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: <450EA594.1060700@gmail.com> References: <3c6718980609080202mb07e256u9b950aa7dfd23f24@mail.gmail.com> <000b01c6d36c$8117ff00$0201a8c0@XPpro> <4501ACC5.5010402@tds.net> <001e01c6d37e$b2d2fe70$0201a8c0@XPpro> <7.0.1.0.2.20060917164611.05941e20@rcblue.com> <450E8F13.6020208@tds.net> <7.0.1.0.2.20060918061506.05d743e8@rcblue.com> <450EA594.1060700@gmail.com> Message-ID: <7.0.1.0.2.20060918070748.044c7ec8@rcblue.com> At 06:56 AM 9/18/2006, Luke Paireepinart wrote: >Dick Moores wrote: >>At 05:20 AM 9/18/2006, Kent Johnson wrote: >> >> >>>You have greatly underused Decimal - it is capable of multiplication and >>>division of fractional quantities directly: >>> >>>In [1]: from decimal import Decimal as D >>> >>>In [2]: x=D('1.23') >>> >>>In [3]: y=D('4.5') >>> >>>In [4]: x*y >>>Out[4]: Decimal("5.535") >>> >>>In [5]: x/y >>>Out[5]: Decimal("0.2733333333333333333333333333") >>> >> >>And sqrt() as well, which I definitely thought was not possible. >> >> >>Well, you settled that. I don't know why I didn't see it. >> >Perhaps you had some preconceptions about the limits of the Decimal >module, and upon >preliminary investigations something confirmed this for you, so you >didn't actually look in-depth >for a way to do what you were trying to do because it seemed at >first glance like Decimal wasn't the right tool >(maybe you saw an example that didn't fully utilize Decimal or something.) >Or, alternatively, you cheated and skimmed over the docs, and didn't >see something important the first time around :) A little of both, I think, but more of the former. >> >>>>of course couldn't rely on the use of the built-in round() or the >>>>formatting of strings (see the line "format = "%." + str(precision) + >>>>'f'" in setPrecision() in v3). Lack of experience with the slicing >>>>of lists caused many headaches. I didn't succeed in debugging until I >>>>put in print statements wherever a value changes, and trying many >>>>different integer strings and places (the arguments of >>>>roundNumber()). A good lesson, I think. >>>> >>>The recipes page in the docs for Decimal include a moneyfmt() function >>>that rounds to a specified number of places and inserts a separator char. >>> >> >>I'd seen the recipes in the docs, but couldn't make much sense out >>of them. I think I can now. Or at least more sense than before. >> >> >Yes, even though a portion of your program has functionality in the >Decimal module already, >coding anything is good practice. For example, my dream is to one >day write a NES emulator in Python, >and this has already been done dozens of times in C, C++, Java, >even Visual Basic. I don't care, my goal is the same >whether or not I'm reinventing the wheel. :) I know of no NES >emulator in Python, though, so I guess i'm not really >reinventing the wheel after all (if anyone asks, tell them I'm >porting that Java emulator :) I learned a lot in spending the time I did on roundNumber(). Dick From alan.gauld at freenet.co.uk Mon Sep 18 17:38:12 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 18 Sep 2006 16:38:12 +0100 Subject: [Tutor] Some questions about my yen-USD.py References: <3c6718980609080202mb07e256u9b950aa7dfd23f24@mail.gmail.com><000b01c6d36c$8117ff00$0201a8c0@XPpro> <4501ACC5.5010402@tds.net><001e01c6d37e$b2d2fe70$0201a8c0@XPpro><7.0.1.0.2.20060917164611.05941e20@rcblue.com><450E0EC9.5010401@gmail.com> <7.0.1.0.2.20060917230119.0622f448@rcblue.com><005a01c6daf8$80f8ee60$0201a8c0@XPpro> <450E92AA.4010104@tds.net> Message-ID: <002201c6db38$8c1ead30$0201a8c0@XPpro> >>> And what's the downside of the way I've done it? >> >> Its slow... > > Actually it is not particularly slow. The actual function code is > created once, when the module is compiled; creating a function > object and binding it to a name is pretty fast. There is a good > discussion here: > http://tinyurl.com/gzfyl > Absolutely, I should have said its "slower", all things are relative. For this application it probably makes no difference in real terms. Alan G. From amadeo.bellotti at gmail.com Mon Sep 18 22:15:42 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Mon, 18 Sep 2006 16:15:42 -0400 Subject: [Tutor] Some questions about my yen-USD.py In-Reply-To: <7.0.1.0.2.20060917192032.06a31b98@rcblue.com> References: <3c6718980609080202mb07e256u9b950aa7dfd23f24@mail.gmail.com> <000b01c6d36c$8117ff00$0201a8c0@XPpro> <4501ACC5.5010402@tds.net> <001e01c6d37e$b2d2fe70$0201a8c0@XPpro> <7.0.1.0.2.20060917164611.05941e20@rcblue.com> <7.0.1.0.2.20060917192032.06a31b98@rcblue.com> Message-ID: thats fine its just my dad would need that and it would be easier for him if he had the exchange rate bulit in On 9/17/06, Dick Moores wrote: > > At 07:10 PM 9/17/2006, Amadeo Bellotti wrote: > >ok i jsut wanted to say great program but i would like to see an > >acutal exchange rate like maybe get it from a website it would be so > >much nicer and easier to use also it would help linux users who run > >from console so they dont have to look up the current rate online > > Thanks for the great suggestion. Right now I don't have the faintest > idea how to implement it, but I'm sure going to try to learn how. > Give me till Tuesday? ;) > > Dick > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060918/42f54edd/attachment.htm From andrew.arobert at gmail.com Tue Sep 19 00:46:16 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Mon, 18 Sep 2006 18:46:16 -0400 Subject: [Tutor] Help with parsing In-Reply-To: <3671C2002ECC9149B2B5509290F533A6406946@fiscex.FISCHERINTERNATIONAL.COM> References: <3671C2002ECC9149B2B5509290F533A6406946@fiscex.FISCHERINTERNATIONAL.COM> Message-ID: <450F21B8.5060907@townisp.com> Bryan Leber wrote: > > Hello, I am trying to create a script that reads from the command line > and puts the sysargv into a list. I have this part done. I have added > code for testing and one of those testing procedures is to print the > list out in a text file. Not all field are required and may not have > information in them. A sample text file looks like this: > > > > PATCH_NUMBER: 9999 > > BUG_NUMBER: 4534 > > FEATURE_AFFECTED: Admin login > > OVERVEIW: The icon of the submit has changed > > > > Now what I need to accomplish is to search through this list and if > FEATURE_AFFECTED or OVERVIEW do not have values(i.e. Admin login or > The icon of the submit changed) then I need to print a message and > then exit. Right now I have something like this > > > > Size = len(argsList) > > If size = 4 > > For i in argsList > > If i[2] == None: > > Print ?please enter criteria? > > Sys.exit() > > Elif i[3] == None: > > Print ?please enter criteria? > > Sys.exit() > > Else: > > Sys.exit() > > > > Any help would be appreciated. Thanks > > > > > > **/Bryan Leber/** > > Developer > > Fischer International Corporation > > www.fischerinternational.com > > bryan.leber at fischerinternational.com > > > Cell:(239)963-5267 > > > > Secure Your Risk. Increase Your Bottom Line. ? > > > > ------------------------------------------------------------------------ > > This mail message may contain confidential and privileged information > from Fischer International which is protected. Any unauthorized > review, use, disclosure or distribution by any means is prohibited. > If you are not the intended recipient, please contact the sender by > reply email and destroy all copies of the original message > > ------------------------------------------------------------------------ I recommend that you check out the optparse.module from OptionParser It does what you are looking for in a concise method. See http://docs.python.org/lib/module-optparse.html From ajkadri at googlemail.com Tue Sep 19 01:37:08 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Tue, 19 Sep 2006 00:37:08 +0100 Subject: [Tutor] How to convert a decimal integer into binary Message-ID: Can anyone help me with teh problem of "converting a decimal number into its binary equivalent"?? Thanks in anticipation. Regards, Asrar Kadri ------------------------------------------------------------------------------ Winners are willing to do things that losers wont do. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060919/ffc1819a/attachment.html From rabidpoobear at gmail.com Tue Sep 19 02:11:26 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 18 Sep 2006 19:11:26 -0500 Subject: [Tutor] How to convert a decimal integer into binary In-Reply-To: References: Message-ID: <450F35AE.7020800@gmail.com> Asrarahmed Kadri wrote: > Can anyone help me with teh problem of "converting a decimal number > into its binary equivalent"?? > How is your decimal number stored? > Thanks in anticipation. > > Regards, > Asrar Kadri > > ------------------------------------------------------------------------------ > > Winners are willing to do things that losers wont do. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rabidpoobear at gmail.com Tue Sep 19 02:22:00 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 18 Sep 2006 19:22:00 -0500 Subject: [Tutor] How to convert a decimal integer into binary In-Reply-To: References: Message-ID: <450F3828.2050102@gmail.com> Asrarahmed Kadri wrote: > Can anyone help me with teh problem of "converting a decimal number > into its binary equivalent"?? > Ah, sorry, I didn't read the subject line, just the e-mail. You said a decimal integer into binary. I thought you meant any random decimal value. My bad :) You should be able to find a tutorial on this on-line somewhere. you know that decimal: 1 = binary: 0001 decimal: 2 = binary: 0010 decimal: 4 = binary: 0100 decimal: 8 = binary: 1000 Do you see the pattern here? It's powers of 2. I don't have time to write an example program, but see what you can do. Basically, if I remember correctly, you have to find the smallest power of 2 that is greater than your number, then repeatedly divide then mod the integer for each binary digit. > Thanks in anticipation. sure. > > Regards, > Asrar Kadri -Luke From hughstewart at optushome.com.au Mon Sep 18 02:27:45 2006 From: hughstewart at optushome.com.au (Hugh Stewart) Date: Mon, 18 Sep 2006 10:27:45 +1000 Subject: [Tutor] wikibooks Message-ID: <001801c6dab9$430761c0$d400a8c0@co3041095a> Hi All, The following site maybe of interest: http://en.wikibooks.org/wiki/Wikibooks:Computing_department Hugh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060918/92153cd6/attachment.htm From alan.gauld at btinternet.com Tue Sep 19 10:40:59 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Sep 2006 09:40:59 +0100 Subject: [Tutor] How to convert a decimal integer into binary References: <450F3828.2050102@gmail.com> Message-ID: > You should be able to find a tutorial on this on-line somewhere. > > you know that > decimal: 1 = binary: 0001 > decimal: 2 = binary: 0010 > decimal: 4 = binary: 0100 > decimal: 8 = binary: 1000 > > Do you see the pattern here? > It's powers of 2. You can use the math approach or a slightly simpler way from a computing point of view is to convert to octal first then print the binary representation of each octal number(3 bits). You can store the octal numbers and their binary representations in a dictionary - only 8 entries And you can convert to octal using int() Some ideas to try... Alan G. From alan.gauld at btinternet.com Tue Sep 19 10:47:01 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Sep 2006 09:47:01 +0100 Subject: [Tutor] Help with parsing References: <3671C2002ECC9149B2B5509290F533A6406946@fiscex.FISCHERINTERNATIONAL.COM> <450F21B8.5060907@townisp.com> Message-ID: I missed the OP on this so if its already been done to death, my apologies. But its such an important point I'll risk repeating it... > Bryan Leber wrote: >> then exit. Right now I have something like this >> >> Size = len(argsList) >> If size = 4 This is obviously pseudo code but in future when posting it would be better to send real code samples. Python is case sensitive, so the above pair of lines will fail since Size and size are different variables. This could lead a tutor off down a blind alley if you don't send real code (or at least syntactically correct code!). >> For i in argsList Similarly 'for' needs to be lowercase, etc etc... Alan G. From emilia12 at mail.bg Tue Sep 19 13:20:31 2006 From: emilia12 at mail.bg (emilia12 at mail.bg) Date: Tue, 19 Sep 2006 14:20:31 +0300 Subject: [Tutor] [tutor] string encode Message-ID: <1158664831.a55973684e05c@mail.bg> hi list is there a way to solve the error in case of : # ... return str(val) #where val is unicode (eg val = u'u') so, how register(?) all imported modules to convert all unicodes to str() with a coder, for eg. encode('cp1251') thanks in advance -e- ----------------------------- ??? ? ???? ???????? ??? ????? "?????? ?? L ?? 22 ????????? ? ??????. http://www.buntatnal.com/ From dyoo at hkn.eecs.berkeley.edu Tue Sep 19 15:36:31 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 19 Sep 2006 06:36:31 -0700 (PDT) Subject: [Tutor] [tutor] string encode In-Reply-To: <1158664831.a55973684e05c@mail.bg> References: <1158664831.a55973684e05c@mail.bg> Message-ID: On Tue, 19 Sep 2006, emilia12 at mail.bg wrote: > so, how register(?) all imported modules to convert all unicodes to > str() with a coder, for eg. encode('cp1251') Hi Emilia, Unfortunately, this isn't so clean: changing the systemwide default encoding may cause things to break. See: http://faassen.n--tree.net/blog/view/weblog/2005/08/02/0 for some discussion on the pitfalls. From cimjls at yahoo.com Tue Sep 19 16:01:03 2006 From: cimjls at yahoo.com (cimjls) Date: Tue, 19 Sep 2006 07:01:03 -0700 (PDT) Subject: [Tutor] Programming Question Message-ID: <20060919140103.86279.qmail@web36706.mail.mud.yahoo.com> Here is what I need to do: Create an IF branching statement that will take the users input from 1-10 and return the English word for the number. (1 is One, 2 is Two, etc.) If the user enters a value outside of the range of 1-10, display an error message, and ask the user to enter a valid selection. Here is what I have so far: # Print the word for a number 1-10 entered by the user # If there is an incorrect value entered print an error message # and have them type in a correct value print "\nThis program prints the English word for a number entered between 1 and 10." print "\nIf an incorrect value is entered you will get an error message and be asked to enter a correct value." raw_input("\n\nPlease press enter to continue.") number = int(raw_input("Please enter a number between 1 and 10: ")) if number < 1: print "That is an incorrect number. Please try again." raw_input("Please enter a number between 1 and 10: ") if number > 10: print "That is an incorrect number. Please try again." raw_input("Please enter a number between 1 and 10: ") elif number == 1: print "One" elif number == 2: print "Two" elif number == 3: print "Three" elif number == 4: print "Four" elif number == 5: print "Five" elif number == 6: print "Six" elif number == 7: print "Seven" elif number == 8: print "Eight" elif number == 9: print "Nine" elif number == 10: print "Ten" raw_input("\n\nPress the enter key to exit.") How do I get it to work after an incorrect number is entered? I am stuck on this and would appreciate and help or suggestions? Thanks, Josh __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From inadauer at gmail.com Tue Sep 19 16:20:44 2006 From: inadauer at gmail.com (naoki inada) Date: Tue, 19 Sep 2006 23:20:44 +0900 Subject: [Tutor] Programming Question In-Reply-To: <20060919140103.86279.qmail@web36706.mail.mud.yahoo.com> References: <20060919140103.86279.qmail@web36706.mail.mud.yahoo.com> Message-ID: <81dd9a9a0609190720g6467b37fp8a4ca7c32c30dcd9@mail.gmail.com> > How do I get it to work after an incorrect number is > entered? I am stuck on this and would appreciate and > help or suggestions? Use exception >>> try: ... int("hoge") ... except(ValueError): ... print('incorrect') ... incorrect > elif number == 1: > print "One" > elif number == 2: > print "Two" > elif ... Using table is more smart way. NUMBER_STRINGS = ['Zero', 'One', 'Two', 'Three', ...] print NUMBER_STRINGS[number] From kent37 at tds.net Tue Sep 19 16:30:17 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 19 Sep 2006 10:30:17 -0400 Subject: [Tutor] Programming Question In-Reply-To: <20060919140103.86279.qmail@web36706.mail.mud.yahoo.com> References: <20060919140103.86279.qmail@web36706.mail.mud.yahoo.com> Message-ID: <450FFEF9.5070909@tds.net> cimjls wrote: > Here is what I need to do: > > Create an IF branching statement that will take the > users input from 1-10 and return the English word for > the number. (1 is One, 2 is Two, etc.) If the user > enters a value outside of the range of 1-10, display > an error message, and ask the user to enter a valid > selection. > > Here is what I have so far: > > # Print the word for a number 1-10 entered by the user > # If there is an incorrect value entered print an > error message > # and have them type in a correct value > > print "\nThis program prints the English word for a > number entered between 1 and 10." > print "\nIf an incorrect value is entered you will get > an error message and be asked to enter a correct > value." > raw_input("\n\nPlease press enter to continue.") > > > number = int(raw_input("Please enter a number between > 1 and 10: ")) > if number < 1: > print "That is an incorrect number. Please try > again." > raw_input("Please enter a number between 1 and 10: > ") > if number > 10: > print "That is an incorrect number. Please try > again." > raw_input("Please enter a number between 1 and 10: > ") > elif number == 1: > print "One" > elif number == 2: > print "Two" > elif number == 3: > print "Three" > elif number == 4: > print "Four" > elif number == 5: > print "Five" > elif number == 6: > print "Six" > elif number == 7: > print "Seven" > elif number == 8: > print "Eight" > elif number == 9: > print "Nine" > elif number == 10: > print "Ten" > > > raw_input("\n\nPress the enter key to exit.") > > How do I get it to work after an incorrect number is > entered? I am stuck on this and would appreciate and > help or suggestions? What happens when you try an incorrect number? You will generally get better help on this list when you are very specific about what happens, instead of saying it doesn't work. This looks like homework so I will just give some hints. There is a difference between how you use the first raw_input() call and the ones you make when the data is bad; can you see it? Do you know about while loops yet? If so, what happens if the user enters a bad number the second time? Can you fix it with a while loop? Kent From hugonz-lists at h-lab.net Tue Sep 19 17:11:44 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?=22Hugo_Gonz=E1lez_M=2E=22?=) Date: Tue, 19 Sep 2006 10:11:44 -0500 Subject: [Tutor] Programming Question Message-ID: <451008B0.1070408@h-lab.net> > if number > 10: > print "That is an incorrect number. Please try > again." Maybe you could do better if you check for all valid numbers first, and finally if no valid number has been entered, then print an error message, instead of checking for all possibilities of error. Hint: check that you can use an "else" statement at the end. > elif number == 9: > print "Nine" > elif number == 10: > print "Ten" > > > raw_input("\n\nPress the enter key to exit.") > > How do I get it to work after an incorrect number is > entered? I am stuck on this and would appreciate and > help or suggestions? Well, there are structures that are useful for repeating stuff, have you heard of "while" and "for"? Try to read up on how to use them, and you can incorporate them in your program flow. Have you seen Alan's tutorial? It's at: http://www.freenetpages.co.uk/hp/alan.gauld/ Check the chapter on loops and the on on branching. Hope that helps, Hugo From hugonz at h-lab.net Tue Sep 19 17:08:41 2006 From: hugonz at h-lab.net (=?ISO-8859-1?Q?=22Hugo_Gonz=E1lez_M=2E=22?=) Date: Tue, 19 Sep 2006 10:08:41 -0500 Subject: [Tutor] Programming Question In-Reply-To: <20060919140103.86279.qmail@web36706.mail.mud.yahoo.com> References: <20060919140103.86279.qmail@web36706.mail.mud.yahoo.com> Message-ID: <451007F9.6020701@h-lab.net> cimjls wrote: > > number = int(raw_input("Please enter a number between > 1 and 10: ")) > if number < 1: > print "That is an incorrect number. Please try > again." > raw_input("Please enter a number between 1 and 10: > ") > if number > 10: > print "That is an incorrect number. Please try > again." Maybe you could do better if you check for all valid numbers first, and finally if no valid number has been entered, then print an error message, instead of checking for all possibilities of error. Hint: check that you can use an "else" statement at the end. > elif number == 9: > print "Nine" > elif number == 10: > print "Ten" > > > raw_input("\n\nPress the enter key to exit.") > > How do I get it to work after an incorrect number is > entered? I am stuck on this and would appreciate and > help or suggestions? Well, there are structures that are useful for repeating stuff, have you heard of "while" and "for"? Try to read up on how to use them, and you can incorporate them in your program flow. Have you seen Alan's tutorial? It's at: http://www.freenetpages.co.uk/hp/alan.gauld/ Check the chapter on loops and the on on branching. Hope that helps, Hugo From wescpy at gmail.com Wed Sep 20 00:22:43 2006 From: wescpy at gmail.com (wesley chun) Date: Tue, 19 Sep 2006 15:22:43 -0700 Subject: [Tutor] How to convert a decimal integer into binary In-Reply-To: References: Message-ID: <78b3a9580609191522x30608b5bx80648a261a896f7d@mail.gmail.com> > Can anyone help me with teh problem of "converting a decimal number into its > binary equivalent"?? this sounds like a homework problem, so no code here. however, the answer is trivial once you realize that all integers are natively available in any base, whether it be 2, 8, 10, 16, etc. since you want base two, the easiest way to solve your problem is to display each bit (Binary digIT [or is that BInary digiT?]) one at a time. the best way to solve your problem is through an iterative process. you may have to tweak your initial solution(s), but you would be well on your way there! good luck! -- wesley ps. this is a standard programming exercise... it's even in "Core Python" (see below) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From faranuddin at gmail.com Wed Sep 20 13:33:28 2006 From: faranuddin at gmail.com (Faran) Date: Wed, 20 Sep 2006 16:33:28 +0500 Subject: [Tutor] Python CGI Script Message-ID: <45112708.5020705@gmail.com> I Have a CGI Script Which is working perfectly when run from the python interpreter, i m using the Content-type: application/x-www-url-form-encoded , i use it to send data from flash apps to python script. i checked the script with content-type: text/html , and browsers printed the output perfectly, but when i use the application content type, it gives the error, normally , firefox just prints everything, so i dont know whats wrong. heres the script, i m using the M ySQLdb for the Database Connection. Why isnt it Working? import MySQLdb as sql import cgi,cgitb cgitb.enable() class Listing: def __init__(self): form = cgi.FieldStorage() self.DBid = form.getvalue("DBid") self.tableid = form.getvalue("tableid") self.rangeid1 = form.getvalue("StartRange") self.rangeid2 = form.getvalue("EndRange") conn = sql.connect('localhost','root','xxxxxxx',db=self.DBid) self.cursor = conn.cursor() self.conn = conn self.list1 = [] self.list2 = [] self.list3 = [] self.list4 = [] self.list5 = [] self.list6 = [] self.outputstring = "" def listquery(self): query1 = """SELECT ABC FROM %s limit %s,%s"""\ % (self.tableid,self.rangeid1,self.rangeid2) query2 = """SELECT DEF FROM %s limit %s,%s"""\ % (self.tableid,self.rangeid1,self.rangeid2) query3 = """SELECT GHI FROM %s limit %s,%s"""\ % (self.tableid,self.rangeid1,self.rangeid2) query4 = """SELECT JKL FROM %s limit %s,%s"""\ % (self.tableid,self.rangeid1,self.rangeid2) query5 = """SELECT MNO FROM %s limit %s,%s"""\ % (self.tableid,self.rangeid1,self.rangeid2) query6 = """SELECT PQR FROM %s limit %s,%s"""\ % (self.tableid,self.rangeid1,self.rangeid2) self.list1 = self.queryexecute(query1) self.list2 = self.queryexecute(query2) self.list3 = self.queryexecute(query3) self.list4 = self.queryexecute(query4) self.listt5 = self.queryexecute(query5) self.list6 = self.queryexecute(query6) def queryexecute(self,query): templist = [] self.cursor.execute(query,) for a in self.cursor.fetchall(): templist.extend(a) return templist def outputappend(self,listtoappend,appname): tempstring = "" for a in range(0,len(listtoappend)): tempstring += appname + str(a+1) + "x" + "=" +\ listtoappend[a] + "&" return tempstring def output(self): self.outputstring += self.outputappend(self.list1,"list1") self.outputstring += self.outputappend(self.list2,"list2") self.outputstring += self.outputappend(self.list3,"list3") self.outputstring += self.outputappend(self.list4,"list4") self.outputstring += self.outputappend(self.list5,"list5") self.outputstring += self.outputappend(self.list6,"list6") print """Content-type: application/x-www-url-form-encoded\n""" print """%s""" % (self.outputstring) def clear(self): self.cursor.close() self.conn.close() x = Listing() x.listquery() x.output() x.clear() From kent37 at tds.net Wed Sep 20 14:05:14 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 20 Sep 2006 08:05:14 -0400 Subject: [Tutor] Python CGI Script In-Reply-To: <45112708.5020705@gmail.com> References: <45112708.5020705@gmail.com> Message-ID: <45112E7A.3080809@tds.net> Faran wrote: > I Have a CGI Script Which is working perfectly when run from the python > interpreter, i m using the Content-type: > application/x-www-url-form-encoded , i use it to send data from flash > apps to python script. i checked the script with content-type: text/html > , and browsers printed the output perfectly, but when i use the > application content type, it gives the error, normally , firefox just > prints everything, so i dont know whats wrong. heres the script, i m > using the M ySQLdb for the Database Connection. Why isnt it Working? It seems a bit unusual to use that content type to return data to the browser, it is usually used for form submissions. I'm not sure why it doesn't work but I have a couple of note below. > > import MySQLdb as sql > import cgi,cgitb > > cgitb.enable() > > class Listing: > def __init__(self): > > form = cgi.FieldStorage() > self.DBid = form.getvalue("DBid") > self.tableid = form.getvalue("tableid") > self.rangeid1 = form.getvalue("StartRange") > self.rangeid2 = form.getvalue("EndRange") > > conn = sql.connect('localhost','root','xxxxxxx',db=self.DBid) > self.cursor = conn.cursor() > self.conn = conn > self.list1 = [] > self.list2 = [] > self.list3 = [] > self.list4 = [] > self.list5 = [] > self.list6 = [] > self.outputstring = "" > > def listquery(self): > query1 = """SELECT ABC FROM %s limit %s,%s"""\ > % (self.tableid,self.rangeid1,self.rangeid2) > query2 = """SELECT DEF FROM %s limit %s,%s"""\ > % (self.tableid,self.rangeid1,self.rangeid2) > query3 = """SELECT GHI FROM %s limit %s,%s"""\ > % (self.tableid,self.rangeid1,self.rangeid2) > query4 = """SELECT JKL FROM %s limit %s,%s"""\ > % (self.tableid,self.rangeid1,self.rangeid2) > query5 = """SELECT MNO FROM %s limit %s,%s"""\ > % (self.tableid,self.rangeid1,self.rangeid2) > query6 = """SELECT PQR FROM %s limit %s,%s"""\ > % (self.tableid,self.rangeid1,self.rangeid2) > > self.list1 = self.queryexecute(query1) > self.list2 = self.queryexecute(query2) > self.list3 = self.queryexecute(query3) > self.list4 = self.queryexecute(query4) > self.listt5 = self.queryexecute(query5) > self.list6 = self.queryexecute(query6) > > def queryexecute(self,query): > templist = [] > self.cursor.execute(query,) > for a in self.cursor.fetchall(): > templist.extend(a) > > return templist > def outputappend(self,listtoappend,appname): > tempstring = "" > for a in range(0,len(listtoappend)): > tempstring += appname + str(a+1) + "x" + "=" +\ > listtoappend[a] + "&" You should call urllib.quote_plus(listtoappend[a]) to make sure special characters are correctly escaped. > return tempstring > > def output(self): > > self.outputstring += self.outputappend(self.list1,"list1") > self.outputstring += self.outputappend(self.list2,"list2") > self.outputstring += self.outputappend(self.list3,"list3") > self.outputstring += self.outputappend(self.list4,"list4") > self.outputstring += self.outputappend(self.list5,"list5") > self.outputstring += self.outputappend(self.list6,"list6") > print """Content-type: application/x-www-url-form-encoded\n""" You should have '\r\n\r\n' after the header, not just '\n'. > print """%s""" % (self.outputstring) Could just be print self.outputstring HTH, Kent > > def clear(self): > self.cursor.close() > self.conn.close() > > x = Listing() > x.listquery() > x.output() > x.clear() > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From accelerateddevelopment at gmail.com Wed Sep 20 18:57:01 2006 From: accelerateddevelopment at gmail.com (Sebastian Smith) Date: Wed, 20 Sep 2006 17:57:01 +0100 Subject: [Tutor] Python and Gecko Message-ID: Hello All! I am not a Python expert at all but I am learning when I have time. I am currently working my way through 'wxPython in Action' and really liking it, I have been using Learning to Program as my central text. Anyway, I was wondering if there is anyway to use the Mozilla Gecko engine in Python? Or the KHTML engine would be okay as well. Basically I would like to be able to fully render web pages inside a wxPython application. I wrote a brutally simple web browser using wxPython (25 lines, not including imported modules) and after I posted it on my blog I was slammed with traffic (36,000+ hits in 48 hours, my hosting company was very, very upset). The rendering this browser acheives is just HTML with no support for CSS or any other fancy stuff, this is why I would like to try it with a proper rendering engine. I put the browser up on Google Code to save my bandwidth: http://code.google.com/p/the-bonsai-python-project/ Any advice or help from the pyGuru's would be greatly appreciated. There does seem to be some interest in this sort of thing (which surprised me). Thank you all, Ben. From wescpy at gmail.com Wed Sep 20 19:39:59 2006 From: wescpy at gmail.com (wesley chun) Date: Wed, 20 Sep 2006 10:39:59 -0700 Subject: [Tutor] How to convert a decimal integer into binary In-Reply-To: References: <78b3a9580609191522x30608b5bx80648a261a896f7d@mail.gmail.com> Message-ID: <78b3a9580609201039s177f4e13r117943804f21d9ad@mail.gmail.com> > I came across some code, which uses bit operator. I could not understand how > the logic of that code. If anyone knows to convert the decimal into binary > using BIT OPERATOR, then please help me. please reply to the list, not just me. since this is your homework assignment, i cannot give you the answer, but i will tell you that there are six bit operators (not one): - << left shift - >> right shirt - & bitwise AND - | bitwise OR - ^ bitwise XOR (eXclusive OR) - ~ bit inversion your solution will likely include (at least) one of the shifters and (at least) one of the bitwise operators. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From dyoo at hkn.eecs.berkeley.edu Wed Sep 20 20:32:13 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 20 Sep 2006 11:32:13 -0700 (PDT) Subject: [Tutor] Python CGI Script In-Reply-To: <45112708.5020705@gmail.com> References: <45112708.5020705@gmail.com> Message-ID: > query1 = """SELECT ABC FROM %s limit %s,%s"""\ > % (self.tableid,self.rangeid1,self.rangeid2) Just as a note: please don't do this! *grin* Don't build query strings up like this: this is very prone to an SQL injection attack. See: http://mail.python.org/pipermail/tutor/2003-April/022010.html which talks about this a bit more. From Barry.Carroll at psc.com Wed Sep 20 22:18:59 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Wed, 20 Sep 2006 13:18:59 -0700 Subject: [Tutor] Overloading the assignment operator in a class Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C374C@eugsrv400.psc.pscnet.com> Greetings: I have a class that implements a die (singular or dice). Here is the class definition: >>>>>>> class Die(object): """Implements a gaming die. Attributes: n: the number of sides Must correspond to the number of sides on a physical die. value: The die face currently facing up. Guaranteed to be in the range 1 <= value <= n. Methods: init: instantiate a die roll: roll the die; set and return the new value set: set the die's value to an arbitrary, in range, value __repr__ __lt__ __le__ __eq__ __ne__ __gt__ __ge__ __cmp__ """ def __init__(self, nsides = 6, firstval = 'r'): """create a die usage: x = die(n, firstval) -> an 'n'-sided die with value='firstval' Arguments: nsides: the number of sides valid: 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 30, 50, 100 default: 6 Must correspond to the number of sides on a physical die. Using an invalid value causes an exception. firstval: the die's initial value; valid: 'r' - random value between 1 and n n - specified value; must be between 1 and n Using an invalid value causes an exception. default: 'r' """ validn = (3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 30, 50, 100) if nsides not in validn: errmsg = "No die has %s sides. Valid values are: %s." raise ValueError(errmsg % (nsides, validn)) self.n = nsides if firstval == 'r': self.value = randint(1, self.n) elif isinstance(firstval, int): if 1 <= firstval <= self.n: self.value = firstval else: errmsg = "%s is not between 1 and %s." raise ValueError (errmsg % (firstval, self.n)) else: errmsg = "%s is invalid. Valid entries are '%s' " \ "or an integer between 1 and %s." raise ValueError(errmsg % (firstval, 'r', self.n)) def roll(self): """roll the die; set and return the new value""" self.value = randint(1, self.n) return self.value def set(self, newval): """set the die's new value IF between 1 and n; else raise exception """ if isinstance(newval, int): if 1 <= newval <= self.n: self.value = newval else: errmsg = "%s is not between 1 and %s." raise ValueError (errmsg % (newval, self.n)) else: errmsg = "%s is invalid. Valid entries are ' " \ "integers between 1 and %s." raise ValueError(errmsg % (newval, self.n)) # special methods def __cast(self, other): if isinstance(other, Die): return other.value else: return other def __repr__(self): return repr(self.value) def __lt__(self, other): return self.value < self.__cast(other) def __le__(self, other): return self.value <= self.__cast(other) def __eq__(self, other): return self.value == self.__cast(other) def __ne__(self, other): return self.value != self.__cast(other) def __gt__(self, other): return self.value > self.__cast(other) def __ge__(self, other): return self.value >= self.__cast(other) def __cmp__(self, other): return cmp(self.value, self.__cast(other)) >>>>>>> This all seems to work okay. I want the assignment operator ('=') to call the set method transparently on Die instances, as in this fictitious example: ####### @BCARROLL[Python]|2> mydie = Die(6,3) @BCARROLL[Python]|3> mydie.n <3> 6 @BCARROLL[Python]|4> mydie.value <4> 3 @BCARROLL[Python]|5> mydie <5> 3 @BCARROLL[Python]|6> mydie = 5 @BCARROLL[Python]|7> mydie <7> 5 @BCARROLL[Python]|8> mydie.value 8> 5 @BCARROLL[Python]|9> ####### Above, the statement "mydie = 5" resets mydie.value and preserves mydie as a Die instance. The actual (undesired) behavior rebinds the mydie to the int object, and the Die instance is lost: >>>>>>> @BCARROLL[Python]|2> mydie = Die(6,3) @BCARROLL[Python]|3> mydie.n <3> 6 @BCARROLL[Python]|4> mydie.value <4> 3 @BCARROLL[Python]|5> mydie <5> 3 @BCARROLL[Python]|6> mydie = 5 @BCARROLL[Python]|7> mydie <7> 5 @BCARROLL[Python]|8> mydie.value --------------------------------------------------------------------------- exceptions.AttributeError Traceback (most recent call last) \\psc.pscnet.com\shares\home\bgcarroll\My Documents\My Projects\study\Python\ AttributeError: 'int' object has no attribute 'value' @BCARROLL[Python]|9> >>>>>>> How do I overload the '=' operator to give the desired behavior? Regards, ? Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From alan.gauld at btinternet.com Wed Sep 20 23:15:11 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 20 Sep 2006 22:15:11 +0100 Subject: [Tutor] Overloading the assignment operator in a class References: <2BBAEE949D384D40A2B851287ADB6A432C374C@eugsrv400.psc.pscnet.com> Message-ID: > This all seems to work okay. > > I want the assignment operator ('=') There is no assignment operator in Python, assignment is a binding of an object to a name. > to call the > set method transparently on Die instances, > as in this fictitious example: @BCARROLL[Python]|6> mydie = 5 @BCARROLL[Python]|7> mydie <7> 5 But you can fake this by coercing the integer into a new Die object. As if you had actually done mydie = Die(mydie.n,5) And I believe you can do that by implementing the __coerce__ method. - but I've never tried it... HTH, Alan G. From jordangreenberg at gmail.com Wed Sep 20 23:22:38 2006 From: jordangreenberg at gmail.com (Jordan Greenberg) Date: Wed, 20 Sep 2006 17:22:38 -0400 Subject: [Tutor] Overloading the assignment operator in a class In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C374C@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A432C374C@eugsrv400.psc.pscnet.com> Message-ID: <4511B11E.2040400@gmail.com> Carroll, Barry wrote: > Greetings: > > I have a class that implements a die (singular or dice). Here is the class definition: > How do I overload the '=' operator to give the desired behavior? > > Regards, > > Barry AFAIK, you can't. Unlike, say, Java or C++, the assignment operator is not operating on an object, but instead a name. Consider: in C++ we define variables to a type: int myInt; Die myDie; etc, etc. We don't do this is python. Instead we assign an *object* to an *name* myInt=5 myDie=Die(6, 3) so that myDie is a name for the Die object you've just created. But you can also do this in python: myDie="Some string" Its not assigning to the myDie object, just the name myDie, so that now myDie is a name for a string containing "Some String" In other languages, its reasonable to think of variables as containers. That thinking isn't valid in Python. In Python, what you'd think of as 'variables' are just names for objects. (If you know C++, think pointers, sort of. myDie isn't the Die Object, its just a reference as to where the object is. Assigning to a pointer doesn't change the object, but what the pointer is pointing to.) Hope this helps, Jordan Greenberg From jordangreenberg at gmail.com Wed Sep 20 23:45:05 2006 From: jordangreenberg at gmail.com (Jordan Greenberg) Date: Wed, 20 Sep 2006 17:45:05 -0400 Subject: [Tutor] Overloading the assignment operator in a class In-Reply-To: References: <2BBAEE949D384D40A2B851287ADB6A432C374C@eugsrv400.psc.pscnet.com> Message-ID: <4511B661.5090506@gmail.com> Alan Gauld wrote: >> This all seems to work okay. >> >> I want the assignment operator ('=') > > There is no assignment operator in Python, assignment is a > binding of an object to a name. > >> to call the >> set method transparently on Die instances, >> as in this fictitious example: > > @BCARROLL[Python]|6> mydie = 5 > @BCARROLL[Python]|7> mydie > <7> 5 > > But you can fake this by coercing the integer into a new > Die object. As if you had actually done > > > mydie = Die(mydie.n,5) > > And I believe you can do that by implementing the __coerce__ > method. - but I've never tried it... > > HTH, > > Alan G. > If you can do that with __coerce__, I'm not clever enough to figure out how. IIRC, Python only calls __coerce__ if you're using arithmetic operators on different types, and only if the operator in question isn't overloaded to handle this case. Ex: In [1]: class coerceTest: ...: def __init__(self, val): ...: self.val=val ...: ...: def __coerce__(self, other): ...: return self.val, other In [2]: test=coerceTest(5) In [3]: test Out[3]: <__main__.coerceTest instance at 0x00E29620> In [4]: result=test+10 In [5]: result Out[5]: 15 In [6]: test=5 In [7]: test Out[7]: 5 (I could've written a test to show that __coerce__ is only called when no __add__ is defined, but I'm lazy and its time to leave work!) -Jordan Greenberg From Mike.Hansen at atmel.com Wed Sep 20 23:46:47 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Wed, 20 Sep 2006 15:46:47 -0600 Subject: [Tutor] Python CGI Script Message-ID: <57B026980605A64F9B23484C5659E32E2E837B@poccso.US.ad.atmel.com> > -----Original Message----- > Subject: Re: [Tutor] Python CGI Script > > > query1 = """SELECT ABC FROM %s limit %s,%s"""\ > > % (self.tableid,self.rangeid1,self.rangeid2) > > Just as a note: please don't do this! *grin* > > Don't build query strings up like this: this is very prone to an SQL > injection attack. See: > > http://mail.python.org/pipermail/tutor/2003-April/022010.html > > which talks about this a bit more. > _______________________________________________ > I just wanted to verify what I believe to be correct way of doing this. sql_statement = "INSERT INTO images (image) VALUES (%s)" cur.execute(sql_statement, (data_obj, )) Is it just moving the variable substitution to the execute statement as a tuple, so it will perform the proper quoting? Thanks, Mike From python at venix.com Thu Sep 21 00:27:46 2006 From: python at venix.com (Python) Date: Wed, 20 Sep 2006 18:27:46 -0400 Subject: [Tutor] Python CGI Script In-Reply-To: <57B026980605A64F9B23484C5659E32E2E837B@poccso.US.ad.atmel.com> References: <57B026980605A64F9B23484C5659E32E2E837B@poccso.US.ad.atmel.com> Message-ID: <1158791266.22684.168.camel@www.venix.com> On Wed, 2006-09-20 at 15:46 -0600, Mike Hansen wrote: > > > -----Original Message----- > > Subject: Re: [Tutor] Python CGI Script > > > > > query1 = """SELECT ABC FROM %s limit %s,%s"""\ > > > % (self.tableid,self.rangeid1,self.rangeid2) > > > > Just as a note: please don't do this! *grin* > > > > Don't build query strings up like this: this is very prone to an SQL > > injection attack. See: > > > > http://mail.python.org/pipermail/tutor/2003-April/022010.html > > > > which talks about this a bit more. > > _______________________________________________ > > > > I just wanted to verify what I believe to be correct way of doing this. > > sql_statement = "INSERT INTO images (image) VALUES (%s)" > cur.execute(sql_statement, (data_obj, )) > > Is it just moving the variable substitution to the execute statement as > a tuple, so it will perform the proper quoting? Yes, this looks good. (Looks like MySQL paramstyle.) > > Thanks, > > Mike > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From wescpy at gmail.com Thu Sep 21 00:40:13 2006 From: wescpy at gmail.com (wesley chun) Date: Wed, 20 Sep 2006 15:40:13 -0700 Subject: [Tutor] Overloading the assignment operator in a class In-Reply-To: References: <2BBAEE949D384D40A2B851287ADB6A432C374C@eugsrv400.psc.pscnet.com> Message-ID: <78b3a9580609201540saba75f0jf90b12653246cb5c@mail.gmail.com> On 9/20/06, Alan Gauld wrote: > > This all seems to work okay. > > > > I want the assignment operator ('=') > > There is no assignment operator in Python, assignment is a > binding of an object to a name. as others have mentioned, the assignment operator is used to assign an object to a name in the current namespace... IOW, you cannot "overload the assignment operator." __coerce__() is used for arithmetic operations, so this won't work either. what you really want to do is to allow (validated) access to mydie.value (e.g., self.value). instead of "mydie = 5" -- which is taking the 'mydie' name and reassigning it to the integer object that has a value of 5 (thus losing the reference to your instance object, decrementing its reference count, etc.), you want to allow the user to do something like: mydie.value = 5 ... BUT, you want that value to be validated before it actually assigns it to the mydie.value instance attribute. here is where properties become useful. you can create a getter, setter, and even a deleter and doc string if you want. here's how you use it... add the following to your class: def get_value(self): return self.__value # pretty much your set() method def set_value(self, newval): assert isinstance(newval, int), 'must be an int!' assert 1 <= newval <= self.n, 'invalid value!' self.__value = newval value = property(get_value, set_value, doc='value of mydie') ----- in actuality, the value is stored in self.__value, but access is via self.value. this should give you what you need provided you are happy with using "mydie.value = ..." vs. "mydie = ...", the latter of which will never work the way you want. with the addition of the above code, you can leave __init__() and roll() alone as the self.value = ... assignment will still call your property methods to do the assigning. (also note that roll() does not have to return self.value unless that is desired.) now, even with properties, the bad news is that someone can be sneaky and do something like "mydie.set_value(200)" to try and get around doing "mydie.value = 200". in other words, you cannot restrict access to the property methods. the good news is that there is a workaround to this. i have an example in one of the newly-written sections in (the 2nd ed of) my book that was inspired by the following cookbook recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 the crux of this recipe is that it is very much like using a closure to get your cake and eat it too. you stick your getter (and perhaps setter) into another scope which is then rendered inaccessible to the instance. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From tim at johnsons-web.com Thu Sep 21 02:09:19 2006 From: tim at johnsons-web.com (Tim Johnson) Date: Wed, 20 Sep 2006 16:09:19 -0800 Subject: [Tutor] Paramstyle/sql injection [was Python CGI Script] In-Reply-To: References: <45112708.5020705@gmail.com> Message-ID: <20060921000919.GG8564@johnsons-web.com> * Danny Yoo [060920 10:41]: > > query1 = """SELECT ABC FROM %s limit %s,%s"""\ > > % (self.tableid,self.rangeid1,self.rangeid2) > > Just as a note: please don't do this! *grin* > > Don't build query strings up like this: this is very prone to an SQL > injection attack. See: > > http://mail.python.org/pipermail/tutor/2003-April/022010.html I'm glad you brought this up: Was talking to my partner about this. He's a perl programmer, and he told me that (if I understood him correctly) that the programmer is required by perl to use the 'prepare' function in the perl DBI prior to sending a select statement. If not done (again, if I understood him correctly) an exception is thrown. Is this correct? Now I'm off to writting a little 'script nanny' to check my python files for usage of Paramstyle. thanks tim > which talks about this a bit more. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From dyoo at hkn.eecs.berkeley.edu Thu Sep 21 04:06:58 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 20 Sep 2006 19:06:58 -0700 (PDT) Subject: [Tutor] Paramstyle/sql injection [was Python CGI Script] In-Reply-To: <20060921000919.GG8564@johnsons-web.com> References: <45112708.5020705@gmail.com> <20060921000919.GG8564@johnsons-web.com> Message-ID: > Was talking to my partner about this. He's a perl programmer, and he > told me that (if I understood him correctly) that the programmer is > required by perl to use the 'prepare' function in the perl DBI prior to > sending a select statement. Hi Tim, Yes. That being said, Perl's prepare() statement is no guarantee to safe code. It leaves one to face interpolation temptation: ## Perl my $sth = $dbh->prepare("delete from some_table where name='$field_value'"); $sth->execute(); is just as dangerous as: ## Python cursor = conn.cursor() cursor.execute("delete from some_table where name = '%s'" % field_value) The lesson is that, in the absence of some automated lint-like tool support that can tell us "no you silly, don't do that", we humans are going to have to pick up the slack. We can write bad code in pretty much any language. Programmer education is something we need to do until then. Most of the developer communities around these languages have been around long enough to understand this common risk of SQL injection. In summary: if we're going to work with databases, we should use prepared statements unless we have a very good reason not to. From kent37 at tds.net Thu Sep 21 04:29:04 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 20 Sep 2006 22:29:04 -0400 Subject: [Tutor] Overloading the assignment operator in a class In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C374C@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A432C374C@eugsrv400.psc.pscnet.com> Message-ID: <4511F8F0.3030909@tds.net> Carroll, Barry wrote: > How do I overload the '=' operator to give the desired behavior? This classic essay talks about the meaning of assignment in Python: http://www.effbot.org/zone/python-objects.htm Also I don't think there is any need to overload __lt__, etc.; just __cmp__ is enough, it will be used if the others are omitted. Details of why you might want to use the "rich" comparison operators are here: http://www.amk.ca/python/2.1/index.html#SECTION000500000000000000000 Kent From ml.cyresse at gmail.com Thu Sep 21 09:56:17 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 21 Sep 2006 19:56:17 +1200 Subject: [Tutor] [Plone-Users] Changing possible Smart Folder Criteria? In-Reply-To: References: Message-ID: Ah, Unfortunately, doesn't cover events that started yesterday, but are running for the next week... On 9/21/06, Dan Busarow wrote: > > On Sep 20, 2006, at 6:38 PM, cyresse at Safe-mail.net wrote: > > > Hi all, > > > > I have a Smart Folder which is grabbing events based on date, and > > I'd like the criteria to be: > > > > event.startDate <= today > > > > AND > > > > event.endDate > now > > > > The current criteria I have for each date Less than/More than/On > > the day Now/1 day - 2 years in the past/in the future; that is, the > > standard. > > > > Is is possible to change or create my own relative date criterion? > > So I could select - > > > > "Less than or equal to Today"? > > How about "Less than" "1 day" "in the future" > > Dan > > > ------------------------------------------------------------------------- > Take Surveys. Earn Cash. Influence the Future of IT > Join SourceForge.net's Techsay panel and you'll get the chance to share your > opinions on IT & business topics through brief surveys -- and earn cash > http://www.techsay.com/default.php?page=join.php&p=sourceforge&CID=DEVDEV > _______________________________________________ > Plone-Users mailing list > Plone-Users at lists.sourceforge.net > https://lists.sourceforge.net/lists/listinfo/plone-users > From alan.gauld at freenet.co.uk Thu Sep 21 10:47:03 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 21 Sep 2006 09:47:03 +0100 Subject: [Tutor] Overloading the assignment operator in a class References: <2BBAEE949D384D40A2B851287ADB6A432C374C@eugsrv400.psc.pscnet.com> <4511B661.5090506@gmail.com> Message-ID: <002b01c6dd5a$8409aea0$0201a8c0@XPpro> >> mydie = Die(mydie.n,5) >> >> And I believe you can do that by implementing the __coerce__ >> method. - but I've never tried it... > > If you can do that with __coerce__, I'm not clever enough to figure > out > how. IIRC, Python only calls __coerce__ if you're using arithmetic > operators on different types, and only if the operator in question > isn't > overloaded to handle this case. You are quite right, Python doesn't know that you don't really want to to just assign an integer. It is only in an expression that python can guess what you mean. So the only way to do it would be explicitly myDie = Die(myDie.n, 5) Alan G. From alan.gauld at freenet.co.uk Thu Sep 21 10:50:42 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 21 Sep 2006 09:50:42 +0100 Subject: [Tutor] Python CGI Script References: <57B026980605A64F9B23484C5659E32E2E837B@poccso.US.ad.atmel.com> Message-ID: <002f01c6dd5b$07512a40$0201a8c0@XPpro> > sql_statement = "INSERT INTO images (image) VALUES (%s)" > cur.execute(sql_statement, (data_obj, )) > >Is it just moving the variable substitution to the execute statement >as > a tuple, so it will perform the proper quoting? Nope, the syntax changes slightly, and I believe depends on the database driver you use. For SqlLite (and I think for MySql) its a question mark > sql_statement = "INSERT INTO images (image) VALUES (?)" > cur.execute(sql_statement, data_obj) And I don;t think you need the tuple form unless you have multiple values. And you can do it in one line too: cur.execute("INSERT INTO images (image) VALUES (?)", data_obj) Alan G. From artificiallystupid at yahoo.com Thu Sep 21 06:21:25 2006 From: artificiallystupid at yahoo.com (Johnston Jiaa) Date: Wed, 20 Sep 2006 21:21:25 -0700 (PDT) Subject: [Tutor] Tkinter GUI Grid Layout Manager Message-ID: <20060921042126.6594.qmail@web50415.mail.yahoo.com> I am trying to get 3 buttons, equally separated along the top of the window. How do I get them to all be the same size and how do I make them so that they are equidistant to each other? Along with those three buttons, I am trying to get a text box, near the middle of the window. Every time I attempt to put this in, it messes up the position of the top buttons. My code follows: # Top "Mode" Widgets # Settings Button self.settings_bttn = Button(self, text = "Settings") self.settings_bttn.grid(row = 0, column = 2, columnspan = 2, sticky = EW) # Statistics Button self.stats_bttn = Button(self, text = "Statistics") self.stats_bttn.grid(row = 0, column = 5, columnspan = 2, sticky = EW) # Procrastinate Button self.proc_bttn = Button(self, text = "Procrastinate") self.proc_bttn.grid(row = 0, column = 8, columnspan = 2, sticky = EW) # Top-Mid Separator self.top_mid_sep_lbl = Label(self, text = "------------------------------------------------------------------------------------------------------") self.top_mid_sep_lbl.grid(row = 1, column = 0, columnspan = 10, sticky = EW) # Mid Assignments Widgets # Assignments Text Display self.assign_disp_txt = Text(self, width = 30, height = 18, wrap = WORD) self.assign_disp_txt.grid(row =3, column = 1, columnspan = 5, sticky = W) Thanks, Johnston Jiaa --------------------------------- Do you Yahoo!? Everyone is raving about the all-new Yahoo! Mail. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060920/3daf733c/attachment.htm From sanelson at gmail.com Thu Sep 21 12:18:03 2006 From: sanelson at gmail.com (Steve Nelson) Date: Thu, 21 Sep 2006 11:18:03 +0100 Subject: [Tutor] Filesystem Usage Message-ID: Hello chums, How can I go about getting info similar to that which the UNIX df command provides - of filesystem usage and inode usage? I could just shell out and run a df command, but I would rather use python bindings. What's the recommendation? S. From kent37 at tds.net Thu Sep 21 14:02:03 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Sep 2006 08:02:03 -0400 Subject: [Tutor] Tkinter GUI Grid Layout Manager In-Reply-To: <20060921042126.6594.qmail@web50415.mail.yahoo.com> References: <20060921042126.6594.qmail@web50415.mail.yahoo.com> Message-ID: <45127F3B.1020600@tds.net> Johnston Jiaa wrote: > I am trying to get 3 buttons, equally separated along the top of the > window. How do I get them to all be the same size and how do I make > them so that they are equidistant to each other? > > Along with those three buttons, I am trying to get a text box, near the > middle of the window. Every time I attempt to put this in, it messes up > the position of the top buttons. The problem is, when you add the text box, it forces the size of the grid columns to change which affects the size and spacing of the buttons. The way to avoid that is to put the buttons in their own Frame, with its own layout. Here is an example based on your code. I also used explicit padding to put space between the buttons: from Tkinter import * top = Tk() # Top "Mode" Widgets in their own panel # Settings Button buttonPanel = Frame() settings_bttn = Button(buttonPanel, text = "Settings") settings_bttn.grid(row = 0, column=0, padx=10, sticky = EW) # Statistics Button stats_bttn = Button(buttonPanel, text = "Statistics") stats_bttn.grid(row = 0, column=1, padx=10, sticky = EW) # Procrastinate Button proc_bttn = Button(buttonPanel, text = "Procrastinate") proc_bttn.grid(row = 0, column=2, padx=10, sticky = EW) # Top-Mid Separator top_mid_sep_lbl = Label(buttonPanel, text = "------------------------------------------------------------------------------------------------------") top_mid_sep_lbl.grid(row = 1, column = 0, columnspan = 3, sticky = EW) # Top-Mid Separator top_mid_sep_lbl = Label(buttonPanel, text = "------------------------------------------------------------------------------------------------------") top_mid_sep_lbl.grid(row = 1, column = 0, columnspan = 10, sticky = EW) buttonPanel.pack(side='top') # Mid Assignments Widgets # Assignments Text Display assign_disp_txt = Text(top, width = 30, height = 18, wrap = WORD) assign_disp_txt.pack() top.mainloop() Kent From klappnase at freenet.de Thu Sep 21 14:05:16 2006 From: klappnase at freenet.de (Michael Lange) Date: Thu, 21 Sep 2006 14:05:16 +0200 Subject: [Tutor] Tkinter GUI Grid Layout Manager In-Reply-To: <20060921042126.6594.qmail@web50415.mail.yahoo.com> References: <20060921042126.6594.qmail@web50415.mail.yahoo.com> Message-ID: <20060921140516.418453c0.klappnase@freenet.de> On Wed, 20 Sep 2006 21:21:25 -0700 (PDT) Johnston Jiaa wrote: > I am trying to get 3 buttons, equally separated along the top of the window. How do I get them to all be the same size and how do I make them so that they are equidistant to each other? > > Along with those three buttons, I am trying to get a text box, near the middle of the window. Every time I attempt to put this in, it messes up the position of the top buttons. My code follows: > > # Top "Mode" Widgets > # Settings Button > self.settings_bttn = Button(self, text = "Settings") > self.settings_bttn.grid(row = 0, column = 2, columnspan = 2, sticky = EW) > > # Statistics Button > self.stats_bttn = Button(self, text = "Statistics") > self.stats_bttn.grid(row = 0, column = 5, columnspan = 2, sticky = EW) > > # Procrastinate Button > self.proc_bttn = Button(self, text = "Procrastinate") > self.proc_bttn.grid(row = 0, column = 8, columnspan = 2, sticky = EW) > > > # Top-Mid Separator > self.top_mid_sep_lbl = Label(self, text = "------------------------------------------------------------------------------------------------------") > self.top_mid_sep_lbl.grid(row = 1, column = 0, columnspan = 10, sticky = EW) > > > # Mid Assignments Widgets > # Assignments Text Display > self.assign_disp_txt = Text(self, width = 30, height = 18, wrap = WORD) > self.assign_disp_txt.grid(row =3, column = 1, columnspan = 5, sticky = W) > > Hi Johnston, in order for the columns to actually expand you will have to use grid_columnconfigure(column, weight=1), in order to make sure all buttons have the same size you can calculate the maximum size of all buttons and pass it to grid_columnconfigure() as minsize before actually gridding them, like max = 0 for b in (self.settings_bttn, self.stats_bttn, self.proc_bttn): w = b.winfo_reqwidth() if w > max: max = w self.grid_columnconfigure(0, weight=1, minsize=max) # etc. self.settings_bttn.grid(row = 0, column = 2, columnspan = 2, sticky = EW) I hope this helps Michael From Mike.Hansen at atmel.com Thu Sep 21 16:38:40 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Thu, 21 Sep 2006 08:38:40 -0600 Subject: [Tutor] Python CGI Script Message-ID: <57B026980605A64F9B23484C5659E32E2E83D2@poccso.US.ad.atmel.com> > -----Original Message----- > From: Alan Gauld [mailto:alan.gauld at freenet.co.uk] > Sent: Thursday, September 21, 2006 2:51 AM > To: Mike Hansen; tutor at python.org > Subject: Re: [Tutor] Python CGI Script > > > sql_statement = "INSERT INTO images (image) VALUES (%s)" > > cur.execute(sql_statement, (data_obj, )) > > > >Is it just moving the variable substitution to the execute statement > >as > > a tuple, so it will perform the proper quoting? > > Nope, the syntax changes slightly, and I believe depends on the > database driver you use. For SqlLite (and I think for MySql) its a > question mark > > > sql_statement = "INSERT INTO images (image) VALUES (?)" > > cur.execute(sql_statement, data_obj) > > And I don;t think you need the tuple form unless you have multiple > values. > And you can do it in one line too: > > cur.execute("INSERT INTO images (image) VALUES (?)", data_obj) > > Alan G. > > In my case, I'm using psycopg2 for PostgreSQL. I just did a test, and it doesn't seem to like the ? syntax. I'll check the documentation to see if there's a setting to have it use the ? syntax. Thanks, Mike From python at venix.com Thu Sep 21 17:05:41 2006 From: python at venix.com (Python) Date: Thu, 21 Sep 2006 11:05:41 -0400 Subject: [Tutor] Python CGI Script In-Reply-To: <57B026980605A64F9B23484C5659E32E2E83D2@poccso.US.ad.atmel.com> References: <57B026980605A64F9B23484C5659E32E2E83D2@poccso.US.ad.atmel.com> Message-ID: <1158851141.22684.196.camel@www.venix.com> On Thu, 2006-09-21 at 08:38 -0600, Mike Hansen wrote: > > > -----Original Message----- > > From: Alan Gauld [mailto:alan.gauld at freenet.co.uk] > > Sent: Thursday, September 21, 2006 2:51 AM > > To: Mike Hansen; tutor at python.org > > Subject: Re: [Tutor] Python CGI Script > > > > > sql_statement = "INSERT INTO images (image) VALUES (%s)" > > > cur.execute(sql_statement, (data_obj, )) > > > > > >Is it just moving the variable substitution to the execute statement > > >as > > > a tuple, so it will perform the proper quoting? > > > > Nope, the syntax changes slightly, and I believe depends on the > > database driver you use. For SqlLite (and I think for MySql) its a > > question mark > > > > > sql_statement = "INSERT INTO images (image) VALUES (?)" > > > cur.execute(sql_statement, data_obj) > > > > And I don;t think you need the tuple form unless you have multiple > > values. > > And you can do it in one line too: > > > > cur.execute("INSERT INTO images (image) VALUES (?)", data_obj) > > > > Alan G. > > > > > > In my case, I'm using psycopg2 for PostgreSQL. I just did a test, and it > doesn't seem to like the ? syntax. I'll check the documentation to see > if there's a setting to have it use the ? syntax. The paramstyle attribute in the module will tell you. >>> import MySQLdb >>> MySQLdb.paramstyle 'format' Which means use %s to mark parameter placement. The details below say 'format' == ANSI C printf codes which Python also uses. However, so far as I know, MySQLdb only uses the %s. The parameters get substituted into the SQL string. You'll need to see what the psycopg2.paramstyle tells you. (I think it is pyformat. Params would be provided in a dict.) http://www.python.org/dev/peps/pep-0249/ Provides *all* the details. I've exerpted the paramstyle block below. paramstyle String constant stating the type of parameter marker formatting expected by the interface. Possible values are [2]: 'qmark' Question mark style, e.g. '...WHERE name=?' 'numeric' Numeric, positional style, e.g. '...WHERE name=:1' 'named' Named style, e.g. '...WHERE name=:name' 'format' ANSI C printf format codes, e.g. '...WHERE name=%s' 'pyformat' Python extended format codes, e.g. '...WHERE name=%(name)s' > > Thanks, > > Mike > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From paulino1 at sapo.pt Thu Sep 21 19:05:32 2006 From: paulino1 at sapo.pt (paulino1 at sapo.pt) Date: Thu, 21 Sep 2006 18:05:32 +0100 Subject: [Tutor] python intall error Message-ID: <1158858332.66tbwmg1jips@w7.mail.sapo.pt> When trying to install python in windows I get this error message: "The installer encoutered an unexpected error, installing this package. This may indicate a problem with this package. The error code is 2356" I've found this error both with python-2.4.3.msi and python-2.5.msi in diferent machines with and without administrator privileges. Is it a bug? From pythontut at pusspaws.net Thu Sep 21 22:41:06 2006 From: pythontut at pusspaws.net (Dave S) Date: Thu, 21 Sep 2006 21:41:06 +0100 Subject: [Tutor] module file copy ? Message-ID: <200609212141.06050.pythontut@pusspaws.net> OK have I missed it - but which module is file copy in ? I looked all around OS but no luck - I can find rename(src, dst) but that's about it. Cheers Dave From Mike.Hansen at atmel.com Thu Sep 21 22:48:16 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Thu, 21 Sep 2006 14:48:16 -0600 Subject: [Tutor] module file copy ? Message-ID: <57B026980605A64F9B23484C5659E32E2E843F@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Dave S > Sent: Thursday, September 21, 2006 2:41 PM > To: Python Tutor > Subject: [Tutor] module file copy ? > > OK have I missed it - but which module is file copy in ? I > looked all around > OS but no luck - I can find rename(src, dst) but that's about it. > > Cheers > > Dave > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > I think I had the same problem when I started using Python. It's the shutil module. shutil.copyfile(src, dst) Mike From alan.gauld at freenet.co.uk Fri Sep 22 00:09:51 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 21 Sep 2006 23:09:51 +0100 Subject: [Tutor] Tkinter GUI Grid Layout Manager References: <20060921042126.6594.qmail@web50415.mail.yahoo.com> Message-ID: <001f01c6ddca$a9635730$0201a8c0@XPpro> My top tip for doing anything requiring precise layout control in Tkinter is use lots of Frames. Use grids pr packer inside the frames as appropriate, but control the layout of the controls inside a frame, then control the layout pof the frames inside the main window and life generally gets easier IMHO. In your case I'd have a frame for the 3 buttons, then another frame for the text widget. grid the buttons inside the frame, pack the text widget. Then grid the frames inside the main window. Putting borders and relief effects round the frames can significantly improve the look of a Tkinter app too. Alan G. ----- Original Message ----- From: "Johnston Jiaa" To: Sent: Thursday, September 21, 2006 5:21 AM Subject: [Tutor] Tkinter GUI Grid Layout Manager >I am trying to get 3 buttons, equally separated along the top of the >window. How do I get them to all be the same size and how do I make >them so that they are equidistant to each other? > > Along with those three buttons, I am trying to get a text box, near > the middle of the window. Every time I attempt to put this in, it > messes up the position of the top buttons. My code follows: > > # Top "Mode" Widgets > # Settings Button > self.settings_bttn = Button(self, text = "Settings") > self.settings_bttn.grid(row = 0, column = 2, columnspan = 2, > sticky = EW) > > # Statistics Button > self.stats_bttn = Button(self, text = "Statistics") > self.stats_bttn.grid(row = 0, column = 5, columnspan = 2, sticky > = EW) > > # Procrastinate Button > self.proc_bttn = Button(self, text = "Procrastinate") > self.proc_bttn.grid(row = 0, column = 8, columnspan = 2, sticky = > EW) > > > # Top-Mid Separator > self.top_mid_sep_lbl = Label(self, text = > "------------------------------------------------------------------------------------------------------") > self.top_mid_sep_lbl.grid(row = 1, column = 0, columnspan = 10, > sticky = EW) > > > # Mid Assignments Widgets > # Assignments Text Display > self.assign_disp_txt = Text(self, width = 30, height = 18, wrap = > WORD) > self.assign_disp_txt.grid(row =3, column = 1, columnspan = 5, > sticky = W) > > > Thanks, Johnston Jiaa > > > --------------------------------- > Do you Yahoo!? > Everyone is raving about the all-new Yahoo! Mail. From wescpy at gmail.com Fri Sep 22 08:03:56 2006 From: wescpy at gmail.com (wesley chun) Date: Thu, 21 Sep 2006 23:03:56 -0700 Subject: [Tutor] Filesystem Usage In-Reply-To: References: Message-ID: <78b3a9580609212303r4c04a799uaec4b166c7f95668@mail.gmail.com> > How can I go about getting info similar to that which the UNIX df > command provides - of filesystem usage and inode usage? I could just > shell out and run a df command, but I would rather use python > bindings. this sounds like it will require some work to implement 'df' in Python, *and* it would be slower than its C counterpart. rather than just purely shelling out [with os.system() say], i'd use the one of the {os,popen2}.popen*() functions or the subprocess module and actually call 'df' but use Python to communicate with it (sending it stuff via stdin and receiving output from it [stdout or stderr]). hope this helps a little! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From pythontut at pusspaws.net Fri Sep 22 09:22:29 2006 From: pythontut at pusspaws.net (Dave S) Date: Fri, 22 Sep 2006 08:22:29 +0100 Subject: [Tutor] module file copy ? In-Reply-To: <57B026980605A64F9B23484C5659E32E2E843F@poccso.US.ad.atmel.com> References: <57B026980605A64F9B23484C5659E32E2E843F@poccso.US.ad.atmel.com> Message-ID: <200609220822.30052.pythontut@pusspaws.net> On Thursday 21 September 2006 21:48, Mike Hansen wrote: > > -----Original Message----- > > From: tutor-bounces at python.org > > [mailto:tutor-bounces at python.org] On Behalf Of Dave S > > Sent: Thursday, September 21, 2006 2:41 PM > > To: Python Tutor > > Subject: [Tutor] module file copy ? > > > > OK have I missed it - but which module is file copy in ? I > > looked all around > > OS but no luck - I can find rename(src, dst) but that's about it. > > > > Cheers > > > > Dave > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > I think I had the same problem when I started using Python. > > It's the shutil module. > shutil.copyfile(src, dst) > Thats tucked away. thanks for pointing it out Dave > Mike > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Fri Sep 22 10:28:48 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 22 Sep 2006 09:28:48 +0100 Subject: [Tutor] Python CGI Script References: <57B026980605A64F9B23484C5659E32E2E83D2@poccso.US.ad.atmel.com> Message-ID: <001701c6de21$21e460e0$0201a8c0@XPpro> > > cur.execute("INSERT INTO images (image) VALUES (?)", data_obj) > >In my case, I'm using psycopg2 for PostgreSQL. I just did a test, > and it doesn't seem to like the ? syntax. I'll check the > documentation > to see if there's a setting to have it use the ? syntax. It may well be the Python conventioin of a % sign in that case, I was just flagging up that some drivers use different markers. The key thing is, as you say, to check the driver docs to find out what syntax it needs and use it, not to try to force it into any particular flavour.. Alan G. From alan.gauld at freenet.co.uk Fri Sep 22 10:33:11 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 22 Sep 2006 09:33:11 +0100 Subject: [Tutor] python intall error References: <1158858332.66tbwmg1jips@w7.mail.sapo.pt> Message-ID: <002201c6de21$d4c7d1b0$0201a8c0@XPpro> Hi Paulino, I've seen it being mentioned here before, but not sure what the answer is. I'd try reporting it on the main Python newsgroup where the gurus hang out... I'd also try uninstalling all things Pythonic and downloading a fresh copy and trying again. If its any consolation I have a similar problem with Adobe Photoshop Elements 4, it refuses to install on one of my XP machines but works perfectly on my other two. Guess which one I actually need to have it on though :-( Alan G ----- Original Message ----- From: To: Sent: Thursday, September 21, 2006 6:05 PM Subject: [Tutor] python intall error > When trying to install python in windows I get this error message: > "The installer encoutered an unexpected error, installing this > package. This may > indicate a problem with this package. The error code is 2356" > > I've found this error both with python-2.4.3.msi and python-2.5.msi > in diferent > machines with and without administrator privileges. > > > Is it a bug? > > From alan.gauld at freenet.co.uk Fri Sep 22 10:34:55 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 22 Sep 2006 09:34:55 +0100 Subject: [Tutor] module file copy ? References: <200609212141.06050.pythontut@pusspaws.net> Message-ID: <002301c6de21$fb7a2150$0201a8c0@XPpro> Take a look in my OS topic on my tutor for a run through these file handling functions. > OK have I missed it - but which module is file copy in ? I looked > all around > OS but no luck - I can find rename(src, dst) but that's about it. But the quick answer is shutil Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sanelson at gmail.com Fri Sep 22 11:39:38 2006 From: sanelson at gmail.com (Steve Nelson) Date: Fri, 22 Sep 2006 10:39:38 +0100 Subject: [Tutor] Filesystem Usage In-Reply-To: <78b3a9580609212303r4c04a799uaec4b166c7f95668@mail.gmail.com> References: <78b3a9580609212303r4c04a799uaec4b166c7f95668@mail.gmail.com> Message-ID: On 9/22/06, wesley chun wrote: > this sounds like it will require some work to implement 'df' in > Python Mmm... although I have discovered a debian package called pydf whose source made interesting reading. > i'd use the one of > the {os,popen2}.popen*() functions or the subprocess module and > actually call 'df' but use Python to communicate with it (sending it > stuff via stdin and receiving output from it [stdout or stderr]). That sounds fascinating... and something to play with. In the end I just did: def fsUsage(dir): """Returns the % usage of a given filesystem""" stat = os.statvfs(dir) from statvfs import F_BLOCKS, F_BFREE total = stat[F_BLOCKS] avail = stat[F_BFREE] used = total-avail percent = used/total*100 return percent S. > > hope this helps a little! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > From dos.fool at gmail.com Fri Sep 22 04:44:58 2006 From: dos.fool at gmail.com (max .) Date: Thu, 21 Sep 2006 20:44:58 -0600 Subject: [Tutor] reading files Message-ID: <857e4c3d0609211944p7bb45e4araf895d924c99e489@mail.gmail.com> i cant understand the open command i tried the help command but still dont get i am trying to write twi programs one to keep track of money phone numbers... and another to randomly print a statmint from a file pleas dont just send a program i would like it if you could explain the command so that i dont have to keep bothering you :P From alan.gauld at btinternet.com Fri Sep 22 12:16:07 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 22 Sep 2006 11:16:07 +0100 Subject: [Tutor] reading files References: <857e4c3d0609211944p7bb45e4araf895d924c99e489@mail.gmail.com> Message-ID: >i cant understand the open command i tried the help command but still > dont get i am trying to write twi programs one to keep track of > money > phone numbers... and another to randomly print a statmint from a > file The built in open command opens a file. That is it creates a file object that you can manipulate in code. It takes a filename (or full path) as a first argument. It also takes a "mode2 as a second argument. You can open a file in various modes but the most common are read-only (argument is "r") and write-only(argument is "w") When you open the file it gives you a file object. The file object has various methods that you can call. So if you open a file for reading you can call the read() method to get the file contents returned as a string. If you opened it for writing you can call write() to write your data to the file. Opening a file to read requires that the file already exists, and does not change the file on the disk in any way. Opening a file to write will either create a new file on the disk or overwrite an existing file, destroying its existing contents. It is the programmers responsibility to manage the consequences by creating a backup file or whatever. If you did not understand that, reply to the list with the specific bits you didn't understand highlighted. You might also like to try reading my Handling Files topic in my tutorial which goes into more depth with examples. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From anilmrn at yahoo.com Sat Sep 23 00:34:24 2006 From: anilmrn at yahoo.com (anil maran) Date: Fri, 22 Sep 2006 17:34:24 -0500 (CDT) Subject: [Tutor] Help with cookies/auth Message-ID: <20060922223424.40128.qmail@web55209.mail.re4.yahoo.com> web.setcookie('user', '', 'Mon, 01-Jan-2000 00:00:00 GMT') File "", line 1 n-2000 00:00:00 GMT') compare datetime.datetime to int ^ SyntaxError: invalid syntax Im trying to set a cookie after logging an user in. If someone has some code for doing this it ll be great the code I use for storing passwds is this algo = 'sha1' salt = sha.new(str(random.random())).hexdigest()[:5] hsh = sha.new(salt+i.password).hexdigest() password_algo_salt_hash = '%s$%s$%s' % (algo, salt, hsh) web.insert('users', username = i.user, password = password_algo_salt_hash, ip=web.ctx.ip, rawpassword=i.password) web.setcookie('username', i.user,2629743)#expires in a month AS you can see i m just setting useranme as i.user, and so any one who can set a cookie can login, can you guys help me out in setting this cookie here is my stumbling block how do i verify the user is logged in after i set cookie, how do i get time for preparation of hash I m fairly new to python, review of code is also much appreciated. (hash(secret,user, time1),user,time2). time2 is time to expire wat is time1, is it stored so that this function described next can valid and create a matching hash, pls clarify Then there's a function that checks the cookie and returns the user object if the hashes match. thanks Anil Aaron wrote: """I'm going to be writing an authentication system for work this week; maybe I can release it. But what would it do? --- I'm not sure there's all that much to it. I know what reddit (and most modern websites) do is they have a login page that takes a username and password, checks it against a database, and then sets a cookie of (hash(secret,user, time),user,time). Then there's a function that checks the cookie and returns the user object if the hashes match. It doesn't seem like there's much that's generic in there.""" -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060922/edcfda02/attachment.html From cappy2112 at gmail.com Sat Sep 23 04:03:15 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Fri, 22 Sep 2006 19:03:15 -0700 Subject: [Tutor] Fatal error after RE-installing Python 2.3.4 Message-ID: <8249c4ac0609221903t6ee806f7l844ff53591b65bfa@mail.gmail.com> I've just started a job which has a massive python2.3.4-centric tools installation and configuration. I know what you're going to say, but I can't upgrade and be the only one with a newer version. There are close to 30 engineers using this same tools configuration, and it has been working fine for a long time. For now, we all have to live with the limitations and or bugs in 2.3.4. I'm running Windows XP, SP2, on a AMD 1.79Ghz MP 2200+. After editing/testing one of the python test scripts, I was about to check a small script change into cvs, when my mentor suggested running pychecker. When I did this, I saw a several pages full of warnings. For me not knowing the code base well enough to know what to expect, He thought this was odd, took the file, ran pychecker on his system, and only sees 4-5 warnings. We have the same version of Python, that being 2.3.4, the same version of pychecker which is 0.8.14. I had deleted and re-installed pychecker, and still saw the same warnings. I compared this to another machine, and again, I am the odd man out. I've deleted all the Python packages, pythonwin, and The core 2.3.4distribution, and re-installed everything from scratch. Now, When I launch Python from a cmd console, the following is reported C:\Windows\system32\cmd.exe- python The NTVDM CPU has encountered an illegal instruction. Chose close to terminate the application. Oddly enough, when I run Python.exe from the Program Files menu, it launches just fine. The virus scanner doesn't find any known viruses, and I've also disabled the virus checker after un-installing-reinstalling Python the last time. I've also tried downloading another copy of the installer. Does anyone have any ideas what is causing this and how to fix it? My job depends on me getting Python2.3.4 back to working order. thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060922/0a206b96/attachment.html From alan.gauld at btinternet.com Sat Sep 23 09:38:37 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Sep 2006 08:38:37 +0100 Subject: [Tutor] Fatal error after RE-installing Python 2.3.4 References: <8249c4ac0609221903t6ee806f7l844ff53591b65bfa@mail.gmail.com> Message-ID: > I've just started a job which has a massive python2.3.4-centric > tools > installation and configuration. > > I know what you're going to say, but I can't upgrade and be the only > one > with a newer version. There are close to 30 engineers using this > same tools > configuration, and it has been working fine for a long time. > For now, we all have to live with the limitations and or bugs in > 2.3.4. That's not too bad. At work I have to use v2.2 and there are no plans to upgrade. We only moved to 2.2 last year. Our admins are very cautious about upgrades and only do it when there is real business need or support becomes problematic. So 2.3.4 is quite recent really! :-) > C:\Windows\system32\cmd.exe- python > The NTVDM CPU has encountered an illegal instruction. > Chose close to terminate the application. > > > Oddly enough, when I run Python.exe from the Program Files menu, it > launches > just fine. > Have you installed in the same place as everybody else? Are your PATH settings the same? Otherwise I'm stumped and would tend to go for removing every reference to Python, including all registry entries. Then doing a fresh install. Hope it works out, Alan G. (Off on vacation, see ya guys....) From kent37 at tds.net Sat Sep 23 14:25:13 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 23 Sep 2006 08:25:13 -0400 Subject: [Tutor] Fatal error after RE-installing Python 2.3.4 In-Reply-To: <8249c4ac0609221903t6ee806f7l844ff53591b65bfa@mail.gmail.com> References: <8249c4ac0609221903t6ee806f7l844ff53591b65bfa@mail.gmail.com> Message-ID: <451527A9.2050708@tds.net> Tony Cappellini wrote: > > I've just started a job which has a massive python2.3.4-centric tools > installation and configuration. > > I know what you're going to say, but I can't upgrade and be the only one > with a newer version. There are close to 30 engineers using this same > tools configuration, and it has been working fine for a long time. > For now, we all have to live with the limitations and or bugs in 2.3.4. That's not so bad, judging from this thread you have lots of company: http://tinyurl.com/nlco7 Most of my work use of Python is with Jython which is still at 2.1...some days I would kill for a generator ;) > After editing/testing one of the python test scripts, I was about to check a small script change into cvs, when my mentor suggested running pychecker. When I did this, I saw a several pages full of warnings. > For me not knowing the code base well enough to know what to expect, He thought this was odd, took the file, ran pychecker on his system, and only sees 4-5 warnings. Were the extra warnings legitimate (i.e., the code really does have the condition being checked) or random (you look at the code and it has nothing to do with the warning)? Were the warnings all the same or just a few types? Maybe everyone else has pychecker configured to ignore those warnings - pychecker allows you to create a .pycheckrc file to configure it. > Now, When I launch Python from a cmd console, the following is reported > > C:\Windows\system32\cmd.exe- python > The NTVDM CPU has encountered an illegal instruction. > Chose close to terminate the application. I don't like to blame the hardware but this is pretty strange. Is it possible you have a hardware problem? It might be worth running a memory checker. Kent From ps_python at yahoo.com Sat Sep 23 17:34:56 2006 From: ps_python at yahoo.com (kumar s) Date: Sat, 23 Sep 2006 08:34:56 -0700 (PDT) Subject: [Tutor] looping problem Message-ID: <20060923153456.3400.qmail@web35815.mail.mud.yahoo.com> hi, the reason could be that I did not quite understand the concept of looping I have a list of 48 elements I want to create another two lists , listA and listB I want to loop through the list with 48 elements and select element with index 0,3,6,9,12 ..etc into listA select elements with index 2,5,8,11 etc into listB. Could any one help me how can I do that thankyou __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From jim at well.com Sat Sep 23 17:48:29 2006 From: jim at well.com (jim stockford) Date: Sat, 23 Sep 2006 08:48:29 -0700 Subject: [Tutor] looping problem In-Reply-To: <20060923153456.3400.qmail@web35815.mail.mud.yahoo.com> References: <20060923153456.3400.qmail@web35815.mail.mud.yahoo.com> Message-ID: keep a counter in your loop. is this a homework question? On Sep 23, 2006, at 8:34 AM, kumar s wrote: > hi, > > the reason could be that I did not quite understand > the concept of looping > > I have a list of 48 elements > > I want to create another two lists , listA and listB > > I want to loop through the list with 48 elements and > > select element with index 0,3,6,9,12 ..etc into listA > > select elements with index 2,5,8,11 etc into listB. > > > Could any one help me how can I do that > > thankyou > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ps_python at yahoo.com Sat Sep 23 18:03:02 2006 From: ps_python at yahoo.com (kumar s) Date: Sat, 23 Sep 2006 09:03:02 -0700 (PDT) Subject: [Tutor] looping problem In-Reply-To: Message-ID: <20060923160303.75569.qmail@web35813.mail.mud.yahoo.com> hi, thank you. this is not a homework question. I have a very huge file of fasta sequence. > GeneName xxxxxxxx \t yyyyyyyy AATTAAGGAAAAAA.......... (1000 lines) AATAAGGA >GeneName xxxxxxxx \t yyyyyyyy GGAGAGAGATTAAGAA (15000 lines) when I read this as: f2= open('myfile','r') dat = f2.read().split('\n') turned out to be very expensive deal on computer. Instead I tried this: dat = f2.read() (reading into jumbo file of 19,100,442,1342 lines is easy but getting into what i want is a problem). I want to create a dictionary where 'GeneName' as key and sequence of ATGC characters as value biglist = dat.split('\t') ['GeneName xxxxxxxx','yyyyyyyy','ATTAAGGCCAA'.......] Now I want to select ''GeneName xxxxxxxx' into listA and 'ATTAAGGCCAA' into listB so I want to select 0,3,6,9 elements into listA and 2,5,8,11 and so on elements into listB then I can do dict(zip(listA,listB)) however, the very loops concept is getting blanked out in my brain when I want to do this: for j in range(len(biglist)): from here .. I cannot think anything.. may be it is just mental block.. thats the reason I seek help on forum. Thanks --- jim stockford wrote: > > keep a counter in your loop. is this a homework > question? > > On Sep 23, 2006, at 8:34 AM, kumar s wrote: > > > hi, > > > > the reason could be that I did not quite > understand > > the concept of looping > > > > I have a list of 48 elements > > > > I want to create another two lists , listA and > listB > > > > I want to loop through the list with 48 elements > and > > > > select element with index 0,3,6,9,12 ..etc into > listA > > > > select elements with index 2,5,8,11 etc into > listB. > > > > > > Could any one help me how can I do that > > > > thankyou > > > > __________________________________________________ > > Do You Yahoo!? > > Tired of spam? Yahoo! Mail has the best spam > protection around > > http://mail.yahoo.com > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From bgailer at alum.rpi.edu Sat Sep 23 19:11:12 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 23 Sep 2006 10:11:12 -0700 Subject: [Tutor] looping problem In-Reply-To: <20060923160303.75569.qmail@web35813.mail.mud.yahoo.com> References: <20060923160303.75569.qmail@web35813.mail.mud.yahoo.com> Message-ID: <45156AB0.8050301@alum.rpi.edu> kumar s wrote: > [snip] > so I want to select 0,3,6,9 elements into listA > and 2,5,8,11 and so on elements into listB > > Here's a hint: for j in range(0, len(biglist), 3): # this will set j = 0, 3, 6, etc. -- Bob Gailer 510-978-4454 From python at venix.com Sat Sep 23 19:25:37 2006 From: python at venix.com (Python) Date: Sat, 23 Sep 2006 13:25:37 -0400 Subject: [Tutor] looping problem In-Reply-To: <20060923160303.75569.qmail@web35813.mail.mud.yahoo.com> References: <20060923160303.75569.qmail@web35813.mail.mud.yahoo.com> Message-ID: <1159032337.22684.360.camel@www.venix.com> On Sat, 2006-09-23 at 09:03 -0700, kumar s wrote: > hi, > > thank you. this is not a homework question. > > I have a very huge file of fasta sequence. > > > GeneName xxxxxxxx \t yyyyyyyy > AATTAAGGAAAAAA.......... > > > > > > (1000 lines) > AATAAGGA > >GeneName xxxxxxxx \t yyyyyyyy > GGAGAGAGATTAAGAA > (15000 lines) > > > > when I read this as: > > f2= open('myfile','r') > dat = f2.read().split('\n') > > turned out to be very expensive deal on computer. > > > Instead I tried this: > > dat = f2.read() > > (reading into jumbo file of 19,100,442,1342 lines is > easy but getting into what i want is a problem). > > > I want to create a dictionary where 'GeneName' as key > and sequence of ATGC characters as value > > > biglist = dat.split('\t') > ['GeneName xxxxxxxx','yyyyyyyy','ATTAAGGCCAA'.......] > > Now I want to select ''GeneName xxxxxxxx' into listA > and 'ATTAAGGCCAA' into listB > > so I want to select 0,3,6,9 elements into listA > and 2,5,8,11 and so on elements into listB > > then I can do dict(zip(listA,listB)) > > > > however, the very loops concept is getting blanked out > in my brain when I want to do this: > > for j in range(len(biglist)): > from here .. I cannot think anything.. slices may be the best way to go listA = biglist[0::3] # start from index 0 taking every third element listB = biglist[2::3] # start from index 2 taking every third element > > may be it is just mental block.. thats the reason I > seek help on forum. > > > Thanks > > > > > > --- jim stockford wrote: > > > > > keep a counter in your loop. is this a homework > > question? > > > > On Sep 23, 2006, at 8:34 AM, kumar s wrote: > > > > > hi, > > > > > > the reason could be that I did not quite > > understand > > > the concept of looping > > > > > > I have a list of 48 elements > > > > > > I want to create another two lists , listA and > > listB > > > > > > I want to loop through the list with 48 elements > > and > > > > > > select element with index 0,3,6,9,12 ..etc into > > listA > > > > > > select elements with index 2,5,8,11 etc into > > listB. > > > > > > > > > Could any one help me how can I do that > > > > > > thankyou > > > > > > __________________________________________________ > > > Do You Yahoo!? > > > Tired of spam? Yahoo! Mail has the best spam > > protection around > > > http://mail.yahoo.com > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From cappy2112 at gmail.com Sat Sep 23 20:32:59 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Sat, 23 Sep 2006 11:32:59 -0700 Subject: [Tutor] Tutor Digest, Vol 31, Issue 66 In-Reply-To: References: Message-ID: <8249c4ac0609231132x5c982af3lb0408363939e10cf@mail.gmail.com> > > Message: 4 > Date: Sat, 23 Sep 2006 08:38:37 +0100 > From: "Alan Gauld" > Subject: Re: [Tutor] Fatal error after RE-installing Python 2.3.4 > To: tutor at python.org > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > >>Have you installed in the same place as everybody else? Are your PATH > settings the same? I assume you mean the default install dir. C:\Python23. Yes We have a detailed installation prodcedure. Everyone is supposed to use this. I have verified the path with another working system. >>Otherwise I'm stumped and would tend to go for removing every reference to Python, including all registry >>entries. Doesn't the uninstall do this automatically? I selected the "Automatic" setting during the uninstall. I had a working Python isntallation for the last 2 weeks. I was able to run scripts just fine. Only after uninstalling and resinstalling did this problem show up. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060923/b5920679/attachment.htm From jim at well.com Sat Sep 23 20:39:35 2006 From: jim at well.com (jim stockford) Date: Sat, 23 Sep 2006 11:39:35 -0700 Subject: [Tutor] looping problem In-Reply-To: <20060923160303.75569.qmail@web35813.mail.mud.yahoo.com> References: <20060923160303.75569.qmail@web35813.mail.mud.yahoo.com> Message-ID: #!/usr/bin/python # or whatever is the absolute path to python on your system counter = 0 for i in "a","b","c","d","e","f","g" : if counter%3 == 0 : print i + " list one ", counter, counter%3 if counter%3 == 1 : print i + " list two ", counter, counter%3 if counter%3 == 2 : print i + " not used ", counter, counter%3 print "done" On Sep 23, 2006, at 9:03 AM, kumar s wrote: > hi, > > thank you. this is not a homework question. > > I have a very huge file of fasta sequence. > >> GeneName xxxxxxxx \t yyyyyyyy > AATTAAGGAAAAAA.......... > > (1000 lines) > AATAAGGA >> GeneName xxxxxxxx \t yyyyyyyy > GGAGAGAGATTAAGAA > (15000 lines) > > when I read this as: > > f2= open('myfile','r') > dat = f2.read().split('\n') > > turned out to be very expensive deal on computer. > > Instead I tried this: > > dat = f2.read() > > (reading into jumbo file of 19,100,442,1342 lines is > easy but getting into what i want is a problem). > > I want to create a dictionary where 'GeneName' as key > and sequence of ATGC characters as value > > biglist = dat.split('\t') > ['GeneName xxxxxxxx','yyyyyyyy','ATTAAGGCCAA'.......] > > Now I want to select ''GeneName xxxxxxxx' into listA > and 'ATTAAGGCCAA' into listB > > so I want to select 0,3,6,9 elements into listA > and 2,5,8,11 and so on elements into listB > > then I can do dict(zip(listA,listB)) > > however, the very loops concept is getting blanked out > in my brain when I want to do this: > > for j in range(len(biglist)): > from here .. I cannot think anything.. > > may be it is just mental block.. thats the reason I > seek help on forum. > > Thanks > > > --- jim stockford wrote: > >> keep a counter in your loop. is this a homework >> question? >> >> On Sep 23, 2006, at 8:34 AM, kumar s wrote: >> >>> hi, >>> >>> the reason could be that I did not quite >> understand >>> the concept of looping >>> >>> I have a list of 48 elements >>> >>> I want to create another two lists , listA and >> listB >>> >>> I want to loop through the list with 48 elements >> and >>> >>> select element with index 0,3,6,9,12 ..etc into >> listA >>> >>> select elements with index 2,5,8,11 etc into >> listB. >>> >>> >>> Could any one help me how can I do that >>> >>> thankyou >>> >>> __________________________________________________ >>> Do You Yahoo!? >>> Tired of spam? Yahoo! Mail has the best spam >> protection around >>> http://mail.yahoo.com >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > From kent37 at tds.net Sat Sep 23 22:24:23 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 23 Sep 2006 16:24:23 -0400 Subject: [Tutor] looping problem In-Reply-To: <20060923160303.75569.qmail@web35813.mail.mud.yahoo.com> References: <20060923160303.75569.qmail@web35813.mail.mud.yahoo.com> Message-ID: <451597F7.1080606@tds.net> kumar s wrote: > hi, > > thank you. this is not a homework question. > > I have a very huge file of fasta sequence. > > I want to create a dictionary where 'GeneName' as key > and sequence of ATGC characters as value > > > biglist = dat.split('\t') > ['GeneName xxxxxxxx','yyyyyyyy','ATTAAGGCCAA'.......] > > Now I want to select ''GeneName xxxxxxxx' into listA > and 'ATTAAGGCCAA' into listB > > so I want to select 0,3,6,9 elements into listA > and 2,5,8,11 and so on elements into listB > > then I can do dict(zip(listA,listB)) > > however, the very loops concept is getting blanked out > in my brain when I want to do this: > > for j in range(len(biglist)): > from here .. I cannot think anything.. > > may be it is just mental block.. thats the reason I > seek help on forum. Lloyd has pointed you to slicing as the answer to your immediate question. However for the larger question of reading FASTA files, you might want to look at CoreBio, this is a new library of Python modules for computational biology that looks pretty good. http://code.google.com/p/corebio/ CoreBio has built-in support for reading FASTA files into Seq objects. For example: In [1]: import corebio.seq_io In [2]: f=open(r'F:\Bio\BIOE48~1\KENTJO~1\SEQUEN~2\fasta\GI5082~1.FAS') In [3]: seqs = corebio.seq_io.read(f) seqs is now a list of Seq objects for each sequence in the original file In this case there is only one sequence but it will work for your file also. In [4]: for seq in seqs: ...: print seq.name ...: print seq ...: ...: gi|50826|emb|CAA28242.1| MIRTLLLSALVAGALSCGYPTYEVEDDVSRVVGGQEATPNTWPWQVSLQVLSSGRWRHNCGGSLVANNWVLTAAHCLSNYQTYRVLLGAHSLSNPGAGSAAVQVSKLVVHQRWNSQNVGNGYDIALIKLASPVTLSKNIQTACLPPAGTI LPRNYVCYVTGWGLLQTNGNSPDTLRQGRLLVVDYATCSSASWWGSSVKSSMVCAGGDGVTSSCNGDSGGPLNCRASNGQWQVHGIVSFGSSLGCNYPRKPSVFTRVSNYIDWINSVMARN In your case, you want a dict whose keys are the sequence name up to the first tab, and the values are the actual sequences. Something like this should work: d = dict( (seq.name.split('\t')[0], seq) for seq in seqs) The Seq class is a string subclass so putting the seq in the dict is what you want. There is also an iterator to read sequences one at a time, this might be a little faster and more memory efficient because it doesn't have to create the big list of all sequences. Something like this (untested): from corebio.seq_io.fasta_io import iterseq f = open(...) d = dict( (seq.name.split('\t')[0], seq) for seq in iterseq(f)) Kent From jsadino at hotmail.com Sat Sep 23 21:59:51 2006 From: jsadino at hotmail.com (Jeff Sadino) Date: Sat, 23 Sep 2006 13:59:51 -0600 Subject: [Tutor] (no subject) Message-ID: I would like to write a python script that runs an executable program. If I have a program here: C:\My Document\Program.exe how would I execute that program from within a python script? Thank you, Jeff Sadino From rabidpoobear at gmail.com Sat Sep 23 22:37:06 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 23 Sep 2006 15:37:06 -0500 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <45159AF2.5020008@gmail.com> Jeff Sadino wrote: > I would like to write a python script that runs an executable program. If I > have a program here: > > C:\My Document\Program.exe > > how would I execute that program from within a python script? > you could use the os module. os.system() lets you run system commands. Or maybe exec or spawn, but I don't know how to use those. > Thank you, > Jeff Sadino > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From amonroe at columbus.rr.com Sat Sep 23 22:38:36 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat, 23 Sep 2006 16:38:36 -0400 Subject: [Tutor] Tutor Digest, Vol 31, Issue 66 In-Reply-To: <8249c4ac0609231132x5c982af3lb0408363939e10cf@mail.gmail.com> References: <8249c4ac0609231132x5c982af3lb0408363939e10cf@mail.gmail.com> Message-ID: <175608954630.20060923163836@columbus.rr.com> >> >> Message: 4 >> Date: Sat, 23 Sep 2006 08:38:37 +0100 >> From: "Alan Gauld" >> Subject: Re: [Tutor] Fatal error after RE-installing Python 2.3.4 >> To: tutor at python.org >> Message-ID: >> Content-Type: text/plain; format=flowed; charset="iso-8859-1"; >> reply-type=original >> >> >>Have you installed in the same place as everybody else? Are your PATH >> settings the same? > I assume you mean the default install dir. C:\Python23. Yes > We have a detailed installation prodcedure. Everyone is supposed to use > this. > I have verified the path with another working system. >>>Otherwise I'm stumped and would tend to go for removing every reference to > Python, including all registry >>entries. > Doesn't the uninstall do this automatically? I selected the "Automatic" > setting during the uninstall. > I had a working Python isntallation for the last 2 weeks. I was able to run > scripts just fine. > Only after uninstalling and resinstalling did this problem show up. Usually you can track down the specific problem by comparing the results of Sysinterals Filemon/Regmon while launching something on a good and bad machine. Alan From john at fouhy.net Sun Sep 24 04:02:27 2006 From: john at fouhy.net (John Fouhy) Date: Sun, 24 Sep 2006 14:02:27 +1200 Subject: [Tutor] looping problem In-Reply-To: <1159032337.22684.360.camel@www.venix.com> References: <20060923160303.75569.qmail@web35813.mail.mud.yahoo.com> <1159032337.22684.360.camel@www.venix.com> Message-ID: <5e58f2e40609231902r36043374p89e834f95dfeca7f@mail.gmail.com> On 24/09/06, Python wrote: > slices may be the best way to go > listA = biglist[0::3] # start from index 0 taking every third element > listB = biglist[2::3] # start from index 2 taking every third element I'm not certain they would be.. If you do that, you will: 1. Create a really big list. 2. Go through the list, taking every third element. 3. Go through the list again, taking every third+2 element. If the list is really big, step 1. might take some time and/or space, and you would like to avoid it. If we have: f2= open('myfile','r') listA = [] listB = [] then we can iterate through f2 as follows: for i, line in enumerate(f2): if i % 3 == 0 then listA.append(line) elif i % 3 == 2 then listB.append(line) This may be faster.. (although I should like to see evidence before committing to that statement :-) ) -- John. From kent37 at tds.net Sun Sep 24 04:49:14 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 23 Sep 2006 22:49:14 -0400 Subject: [Tutor] looping problem In-Reply-To: <5e58f2e40609231902r36043374p89e834f95dfeca7f@mail.gmail.com> References: <20060923160303.75569.qmail@web35813.mail.mud.yahoo.com> <1159032337.22684.360.camel@www.venix.com> <5e58f2e40609231902r36043374p89e834f95dfeca7f@mail.gmail.com> Message-ID: <4515F22A.6030307@tds.net> John Fouhy wrote: > On 24/09/06, Python wrote: >> slices may be the best way to go >> listA = biglist[0::3] # start from index 0 taking every third element >> listB = biglist[2::3] # start from index 2 taking every third element > > I'm not certain they would be.. If you do that, you will: > > 1. Create a really big list. > 2. Go through the list, taking every third element. > 3. Go through the list again, taking every third+2 element. > > If the list is really big, step 1. might take some time and/or space, > and you would like to avoid it. That's a good point, though the OP didn't seem to have a problem with memory. > > If we have: > > f2= open('myfile','r') > listA = [] > listB = [] > > then we can iterate through f2 as follows: > > for i, line in enumerate(f2): > if i % 3 == 0 then > listA.append(line) > elif i % 3 == 2 then > listB.append(line) > > This may be faster.. > (although I should like to see evidence before committing to that > statement :-) ) Since the end goal seems to be to create a dictionary, there is really no need to create the intermediate lists at all. You could do something like this (following your file example): d = {} while 1: try: key, _, value = f2.next(), f2.next(), f2.next() d[key] = value except StopIteration: pass To do this with a list instead of a file use f2=iter(reallyBigList). Kent From anilmrn at yahoo.com Sun Sep 24 06:41:08 2006 From: anilmrn at yahoo.com (anil maran) Date: Sat, 23 Sep 2006 21:41:08 -0700 (PDT) Subject: [Tutor] UNICODE BEST RESPONSE Message-ID: <20060924044108.75880.qmail@web55203.mail.re4.yahoo.com> Hum, I don't have any problems, and I don't do anything special ... - I use PostgreSQL, so I created my database using UTF-8 encoding. - my Python modules start with "# -*- coding: utf-8 -*-". - all my modules and my templates are utf-8 encoded (I use Vim, so I use ":set encoding=utf-8", but it should work with any good text-editor). The only 'encoding trick' I use is when I want to print an exception, catched from a bad database query. I need to do something like this : =============== except Exception, detail: print "blablabla : %s" % str(detail).decode('latin1') return =============== ... since the exception message (which is in french) seems to be latin1 encoded. That's all :) pythonic Anil __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From cappy2112 at gmail.com Sun Sep 24 17:25:01 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Sun, 24 Sep 2006 08:25:01 -0700 Subject: [Tutor] Fatal error after RE-installing Python 2.3.4 Message-ID: <8249c4ac0609240825s28b23acej40a86c7f126c6772@mail.gmail.com> Message: 1 Date: Sat, 23 Sep 2006 08:25:13 -0400 From: Kent Johnson Subject: Re: [Tutor] Fatal error after RE-installing Python 2.3.4 Cc: tutor at python.org Message-ID: <451527A9.2050708 at tds.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed >>Were the extra warnings legitimate (i.e., the code really does have the Hard to say, since my system was the only one that exhibits this problem. But pychecker isn't really the concern, getting Python running is the main issue. >>Were the warnings all the same or just a few types? Many were the same- function/method not found. Bu tthis is ok, since many of the functions are assigned at runtime. >> Maybe everyone else has pychecker configured to ignore those warnings - pychecker allows you to create a >>.pycheckrc file to configure it. My system doesn't have this, neither did two other systems where I ran pychecker on the same file. This was the first thing I looked for. >>don't like to blame the hardware but this is pretty strange. Is it possible you have a hardware problem? >>It might be worth running a memory Doubtful, because I have been running python for the last 2 weeks. This only started happening on Friday, after I re-installed python & pythonwin. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060924/f13c1d8d/attachment.htm From wesbrooks at gmail.com Mon Sep 25 10:08:13 2006 From: wesbrooks at gmail.com (Wesley Brooks) Date: Mon, 25 Sep 2006 09:08:13 +0100 Subject: [Tutor] Efficient programming questions. Tuples vs Lists; Custom Objects vs Lists. Message-ID: Dear Python-Tutor members, I'm currently in the middle of re-writing a program for my research. I've been using python for the past three years now, my first language since a brief exposure to qbasic ten years ago. There are a couple of things I'm not sure about which I'll need to clear up before I present my work, I hope you can either help me or point me to literature / web reference which can help. Most of these are issues relating to a mix of speed of execution for the code, and scripting best practice. Firstly tuples vs lists. I'm guessing that lists use more memory than tuples as they provide more functions? Are they also more CPU intensive to use? Currently if I'm not likely to add or remove Items I use a tuple (eg, a coordinate in 3D space), but when I do I prefer using a list. This leads on to another question: If you use an object many times, for instance a list, does the interpreter remember that each new object is a list and when a function is called on a list look at one section of memory which details the list functions, or for each new object does it dedicate a new section of memory to the functions of that object? Secondly, a similar question to the first. A list object is something which is in the standard python library. I guess in a CPython distribution that this is C/C++ code being called by the python interpreter when the list object is used? If so then this would imply that a list object would be significantly quicker/less memory to use than an equivalent object scripted in python. I'm currently using lists extensively to hold basic information within objects with additional functions in the script to return information about items within the list. My code would be a lot more elegant and easier to read if I used custom objects for some of these but I'm worried they would be much slower. Would it be appropriate to write a function that inherited the methods of the List function? Would the new object retain the speed and efficiency of the standard list object methods? Lastly why can't python be compiled? I understand that there are certain situations where it is preferable to leave the script readable or byte code interpreted such as when programs are updated frequently over the net, or are being distributed to computers with different operating systems. What about situations where speed is critical? Is CPython's interpreter effectively a C program that carries out C functions as requested in the script? If so why is it not possible to have a program that reads in the whole python script, translates it to C and compiles it? Is it simply that the C functions are compiled already so carrying out a complete compile would gain minimal increases in performance? Thank you for your time and help. Yours Faithfully, Wesley Brooks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060925/19a4a549/attachment.html From rdm at rcblue.com Mon Sep 25 11:59:45 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 25 Sep 2006 02:59:45 -0700 Subject: [Tutor] Question about startswith() and endswith() in 2.5 Message-ID: <7.0.1.0.2.20060925013857.03a65758@rcblue.com> http://www.python.org/doc/lib/string-methods.html has ============================================= startswith( prefix[, start[, end]]) Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of suffixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position. Changed in version 2.5: Accept tuples as prefix. ============================================== and ================================================ endswith( suffix[, start[, end]]) Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position. Changed in version 2.5: Accept tuples as suffix. ================================================== Through experimentation I now see a use for a tuple in which start and end are indexes (as with the startswith() and endswith() of 2.4.3): >>> s = "qwerty" >>> >>> s.startswith("er",2,3) False >>> >>> s.startswith("er",2,4) True >>> but >>> s.startswith("er","q","ty") Traceback (most recent call last): File "", line 1, in s.startswith("er","q","ty") TypeError: slice indices must be integers or None or have an __index__ method On http://docs.python.org/whatsnew/other-lang.html I found ================================================== The startswith() and endswith() methods of string types now accept tuples of strings to check for. def is_image_file (filename): return filename.endswith(('.gif', '.jpg', '.tiff')) ==================================================== This is the only example I've been able to find in the documentation that uses the new tuple of strings, and I don't understand it. The function is_image_file() will return filenames ending in '.gif', but what do '.jpg' (as start) and '.tiff' (as end) do? What kind of data(?) would this function be applied to? A Python list of filenames? Thanks, Dick Moores From kent37 at tds.net Mon Sep 25 13:48:21 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 25 Sep 2006 07:48:21 -0400 Subject: [Tutor] Question about startswith() and endswith() in 2.5 In-Reply-To: <7.0.1.0.2.20060925013857.03a65758@rcblue.com> References: <7.0.1.0.2.20060925013857.03a65758@rcblue.com> Message-ID: <4517C205.6060202@tds.net> Dick Moores wrote: > >>> s.startswith("er","q","ty") > > Traceback (most recent call last): > File "", line 1, in > s.startswith("er","q","ty") > TypeError: slice indices must be integers or None or have an __index__ method > > On http://docs.python.org/whatsnew/other-lang.html I found > > ================================================== > The startswith() and endswith() methods of string types now accept > tuples of strings to check for. > > > def is_image_file (filename): > return filename.endswith(('.gif', '.jpg', '.tiff')) > > ==================================================== > > This is the only example I've been able to find in the documentation > that uses the new tuple of strings, and I don't understand it. The > function is_image_file() will return filenames ending in '.gif', but > what do '.jpg' (as start) and '.tiff' (as end) do? What kind of > data(?) would this function be applied to? A Python list of filenames? You're missing something. Do you see the doubled parentheses in the call to endswith()? filename.endswith(('.gif', '.jpg', '.tiff')) is a call to endswith() with a *single* argument, the tuple ('.gif', '.jpg', '.tiff'). The start and end arguments are omitted. On the other hand, your call s.startswith("er","q","ty") is a call to startswith() with three arguments, the strings 'er', 'q' and 'ty'. To write is_image_file() prior to 2.5 you would have to write something like this: def is_image_file(filename): for extn in ('.gif', '.jpg', '.tiff'): if filename.endswith(extn): return True return False Allowing the first argument to endswith() to be a tuple simplifies this common usage. Kent From project5 at redrival.net Mon Sep 25 13:50:26 2006 From: project5 at redrival.net (Andrei) Date: Mon, 25 Sep 2006 11:50:26 +0000 (UTC) Subject: [Tutor] Question about startswith() and endswith() in 2.5 References: <7.0.1.0.2.20060925013857.03a65758@rcblue.com> Message-ID: Dick Moores rcblue.com> writes: > endswith( suffix[, start[, end]]) > Return True if the string ends with the specified suffix, otherwise > return False. suffix can also be a tuple of suffixes to look for. > >>> s.startswith("er","q","ty") > > Traceback (most recent call last): > File "", line 1, in > s.startswith("er","q","ty") > TypeError: slice indices must be integers or None or have an __index__ method > def is_image_file (filename): > return filename.endswith(('.gif', '.jpg', '.tiff')) > function is_image_file() will return filenames ending in '.gif', but > what do '.jpg' (as start) and '.tiff' (as end) do? What kind of > data(?) would this function be applied to? A Python list of filenames? Note that endswith(('.gif', '.jpg', '.tiff')) is a function call with ONE parameter: the tuple ('.gif', '.jpg', '.tiff') - hence the double parentheses. This parameter is the suffix. The optional start and end parameters are not specified. You could read it like "if the filename ends with .gif or .jpg or .tiff". In older Python versions, you could implement the same functionality as: if s.endswith('.gif') or s.endswith('.jpg') or s.endswith('.tiff') This is in contrast with the example you give above, where startswith("er","q","ty") is a function call with three separate parameters, all of them strings. Since start ("q") and end ("ty") must be integers, this call crashes. Yours, Andrei From kent37 at tds.net Mon Sep 25 14:19:16 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 25 Sep 2006 08:19:16 -0400 Subject: [Tutor] Efficient programming questions. Tuples vs Lists; Custom Objects vs Lists. In-Reply-To: References: Message-ID: <4517C944.6090409@tds.net> Wesley Brooks wrote: > Firstly tuples vs lists. I'm guessing that lists use more memory than > tuples as they provide more functions? Are they also more CPU intensive > to use? First the requisite caveats about optimization: 1. Don't optimize until you have a demonstrated performance problem. 2. Don't optimize until you have profiled to identify the location of the bottleneck. 3. Timing your code is the only way to know if an optimization is successful. I don't know about memory usage. I haven't heard of a significant difference in timing between tuples and lists for data that doesn't change, but the best way to get a correct answer is to time operations of interest. See the timeit module for the best way to do this. For example, it seems that indexing a tuple is slightly slower than indexing a list: D:\Projects\e3po>python -m timeit -s "l = range(10)" "x=l[3]" 10000000 loops, best of 3: 0.0728 usec per loop D:\Projects\e3po>python -m timeit -s "l = tuple(range(10))" "x=l[3]" 10000000 loops, best of 3: 0.0797 usec per loop If you use tuples for something where you are changing the contents, so you have to create new tuples, my guess is that a list will be faster, but again, the only way to know for sure is to time it. For example, replacing an element of a tuple (which requires building a new tuple) is much more expensive than replacing an element of a list: D:\Projects\e3po>python -m timeit -s "l = range(10)" "l[3] = 5" 1000000 loops, best of 3: 0.087 usec per loop D:\Projects\e3po>python -m timeit -s "l = tuple(range(10))" "l= tuple(l[:3] + (5,) + l[4:])" 1000000 loops, best of 3: 1.05 usec per loop Similarly, extending a list, which can be done is place, is much less expensive than extending a tuple, which requires creating a new tuple: D:\Projects\e3po>python -m timeit -s "l = range(10)" "l.append(5)" 1000000 loops, best of 3: 0.262 usec per loop D:\Projects\e3po>python -m timeit -s "l = tuple(range(10))" "l= l+(5,)" 10000 loops, best of 3: 41.9 usec per loop > Currently if I'm not likely to add or remove Items I use a tuple > (eg, a coordinate in 3D space), but when I do I prefer using a list. > This leads on to another question: If you use an object many times, for > instance a list, does the interpreter remember that each new object is a > list and when a function is called on a list look at one section of > memory which details the list functions, or for each new object does it > dedicate a new section of memory to the functions of that object? In Python the methods of a class are stored with the class, not with instances of a class. When you create a new list, you use memory for the contents of the list and some overhead, but you don't create a new copy of all the list methods. > Secondly, a similar question to the first. A list object is something > which is in the standard python library. I guess in a CPython > distribution that this is C/C++ code being called by the python > interpreter when the list object is used? If so then this would imply > that a list object would be significantly quicker/less memory to use > than an equivalent object scripted in python. Quicker, yes; not sure about memory but it seems likely. It's pretty safe to say that code written in C and included with Python is faster than anything you can write. A major optimization technique is to move operations into built-in functions and classes. But again, the only way to know for sure is to test. D:\Projects\e3po>python -m timeit -s "import UserList;l = UserList.UserList(range(10))" "x=l[3]" 1000000 loops, best of 3: 0.697 usec per loop > I'm currently using lists > extensively to hold basic information within objects with additional > functions in the script to return information about items within the > list. My code would be a lot more elegant and easier to read if I used > custom objects for some of these but I'm worried they would be much > slower. Would it be appropriate to write a function that inherited the > methods of the List function? Would the new object retain the speed and > efficiency of the standard list object methods? You can subclass list. This should allow you to add custom operations but retain the speed of native lists. You can also write a wrapper class that contains a list and delegate many operations to it. (UserList in the standard library is an example of this.) In each case there will be a slight performance overhead but the basic list operations will still be fast. > > Lastly why can't python be compiled? I understand that there are certain > situations where it is preferable to leave the script readable or byte > code interpreted such as when programs are updated frequently over the > net, or are being distributed to computers with different operating > systems. What about situations where speed is critical? Is CPython's > interpreter effectively a C program that carries out C functions as > requested in the script? If so why is it not possible to have a program > that reads in the whole python script, translates it to C and compiles > it? Is it simply that the C functions are compiled already so carrying > out a complete compile would gain minimal increases in performance? The dynamic nature of Python makes it very hard to write a general Python compiler. This thread on c.l.py has a good summary of the issues and attempts to solve them: http://tinyurl.com/zsw9x If you have a performance problem, and you haven't been able to resolve it by tuning the Python code, you should look into these projects: psyco - dynamic runtime compiler, can generate significant speedups with very little effort pyrex - a Python-like language that makes it relatively easy to write Python extensions in C shedskin - compiles a restricted subset of Python to C++ http://mark.dufour.googlepages.com/home And of course you can also write a C extension that includes your time-critical code. Kent From project5 at redrival.net Mon Sep 25 14:42:52 2006 From: project5 at redrival.net (Andrei) Date: Mon, 25 Sep 2006 12:42:52 +0000 (UTC) Subject: [Tutor] =?utf-8?q?Efficient_programming_questions=2E_Tuples_vs_Li?= =?utf-8?q?sts=3B=09Custom_Objects_vs_Lists=2E?= References: Message-ID: Wesley Brooks gmail.com> writes: > Most of these are issues relating to a mix of speed of execution > for the code, and scripting best practice. Generally speaking, performance bottlenecks can be determined using the profile module. Things often turn out different than you might expect, so talking about performance in general terms like "is a tuple better than a list" may not be very useful. > Firstly tuples vs lists. I'm guessing that lists use more memory than tuples > as they provide more functions? Are they also more CPU intensive to use? Simple test: s = [(i, i+1, i+2, i+3, i+4, i+5, i+6) for i in xrange(500000)] s = [[i, i+1, i+2, i+3, i+4, i+5, i+6] for i in xrange(500000)] The second (lists) takes on my machine about 85 MB, while the tuples takes about 75 MB. Tuples seem a bit more memory efficient for this simple test, but not shockingly so. When it comes to CPU: lists and tuples have different capabilities, so I'm not sure how you'd compare their performance in a generic way. > Currently if I'm not likely to add or remove Items I use a tuple (eg, a > coordinate in 3D space), but when I do I prefer using a list. Tuples are immutable, meaning you have no choice if you need to add/remove/modify items :). > This leads on to another question: If you use an object many times, for > instance a list, does the interpreter remember that each new object is a list > and when a function is called on a list look at one section of memory which > details the list functions, or for each new object does it dedicate a new > section of memory to the functions of that object? OO languages usually do, but let's test. >>> s = [1, 2] >>> t = [3, 4] >>> id(s.append) == id(t.append) True Yep, it's the same method. > Secondly, a similar question to the first. A list object is something which is > in the standard python library. I guess in a CPython distribution that this is > C/C++ code being called by the python interpreter when the list object is Yes. > used? If so then this would imply that a list object would be significantly > quicker/less memory to use than an equivalent object scripted in python. I'm Python implements a lot of performance-sensitive parts (the language itself, but also of the standard library) in C. If you'd write your own equivalent functionality in Python (say a brand new string class), it will probably be slower. However, the point is that you don't write your own primitives: you use high-level, optimized primitives provided by Python and build useful functionality on top of them. > within the list. My code would be a lot more elegant and easier to read if I > used custom objects for some of these but I'm worried they would be much > slower. Would it be appropriate to write a function that inherited the methods Write a prototype and profile it. I don't know what you're trying to do, but I do think it's in principle better to have custom objects which encapsulate relevant behavior and data than to mess around with lists and procedures. > Lastly why can't python be compiled? I understand that there are certain It is compiled, but not to machine code. The dynamic nature of Python makes this a difficult task. There are efforts to mitigate this (in order of decreasing ease of use): - Psyco can make certain kinds of code a lot faster. It's trivial to use, but you'll have to profile in order to identify the bottlenecks. Apply Psyco to them and see if it helps. If the bottleneck is some library, it probably won't. - Pyrex is a Python-like language that compiles to C(++?). Handy if you want to get some performance-sensitive module in C with as little effort as possible. - IronPython compiles to .Net and from what I've read performs faster in certain tasks than CPython. Nothing revolutionary though. - There is a Python-like language with static typing available for .Net, called Boo. If used with static typing, it will have C#-ish performance IIRC. - PyPy is a reimplementation of Python in Python that aims to eventually be faster using some magic bootstrapping I don't quite understand :). It's not finished and currently slower than CPy. - ShedSkin is also a Python-to-C++ compiler, but I don't know what its current state is. > situations where speed is critical? Is CPython's interpreter effectively a C The typical course of action is to write in Python, identify problematic performance and see what you can do about it. Often the problem can be ameliorated by Psyco, algorithm improvements, implementing some caching mechanism, switching to a different module (e.g. use a different DB, or another XML parser) and as a last resort rewrite the performance-sensitive part in Pyrex or C. > program that carries out C functions as requested in the script? If so why is > it not possible to have a program that reads in the whole python script, > translates it to C and compiles it? Is it simply that the C functions are Because the script as you see it might not be what is executed. Python programs can be modified dynamically at runtime, e.g. I might add a method to an object based on user input, or add complete new classes, etc. Or I might call a method on a certain object, without knowing what that object is - it needs to examine the object at runtime to determine if the method is available. The potential compiler would have to handle all of these cases, meaning you'd end up with... well, CPython. Typical compiler efforts in the past have limited the flexibility of the language. Yours, Andrei From rdm at rcblue.com Mon Sep 25 16:07:26 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 25 Sep 2006 07:07:26 -0700 Subject: [Tutor] Question about startswith() and endswith() in 2.5 In-Reply-To: <4517C205.6060202@tds.net> References: <7.0.1.0.2.20060925013857.03a65758@rcblue.com> <4517C205.6060202@tds.net> Message-ID: <7.0.1.0.2.20060925065319.0702f3b0@rcblue.com> Thanks, Kent and Andrei! I sure did miss those doubled parentheses. >>> s = "qwerty" >>> >>> s.startswith(("er","z","ty","qw","98768976","uytruytr")) True >>> s.startswith(("er","z","ty","qe","98768976","uytruytr")) False >>> s.startswith(("er","z","rty","qe","98768976","uytruytr"), 2) True >>> s.startswith(("er","z","rty","qe","98768976","uytruytr"), 4) False >>> Dick From Barry.Carroll at psc.com Mon Sep 25 18:04:55 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 25 Sep 2006 09:04:55 -0700 Subject: [Tutor] Question about startswith() and endswith() in 2.5 Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3756@eugsrv400.psc.pscnet.com> > -----Original Message----- > Date: Mon, 25 Sep 2006 02:59:45 -0700 > From: Dick Moores > Subject: [Tutor] Question about startswith() and endswith() in 2.5 > To: tutor at python.org > Message-ID: <7.0.1.0.2.20060925013857.03a65758 at rcblue.com> > Content-Type: text/plain; charset="us-ascii"; format=flowed > > http://www.python.org/doc/lib/string-methods.html has > ============================================= > startswith( prefix[, start[, end]]) > Return True if string starts with the prefix, otherwise return False. > prefix can also be a tuple of suffixes to look for. With optional > start, test string beginning at that position. With optional end, > stop comparing string at that position. > > Changed in version 2.5: Accept tuples as prefix. > ============================================== > > and > > ================================================ > endswith( suffix[, start[, end]]) > Return True if the string ends with the specified suffix, otherwise > return False. suffix can also be a tuple of suffixes to look for. > With optional start, test beginning at that position. With optional > end, stop comparing at that position. > > Changed in version 2.5: Accept tuples as suffix. > ================================================== > > Through experimentation I now see a use for a tuple in which start > and end are indexes (as with the startswith() and endswith() of 2.4.3): > > >>> s = "qwerty" > >>> > >>> s.startswith("er",2,3) > False > >>> > >>> s.startswith("er",2,4) > True > >>> > > but > >>> s.startswith("er","q","ty") > > Traceback (most recent call last): > File "", line 1, in > s.startswith("er","q","ty") > TypeError: slice indices must be integers or None or have an __index__ > method > > On http://docs.python.org/whatsnew/other-lang.html I found > > ================================================== > The startswith() and endswith() methods of string types now accept > tuples of strings to check for. > > > def is_image_file (filename): > return filename.endswith(('.gif', '.jpg', '.tiff')) > > ==================================================== > > This is the only example I've been able to find in the documentation > that uses the new tuple of strings, and I don't understand it. The > function is_image_file() will return filenames ending in '.gif', but > what do '.jpg' (as start) and '.tiff' (as end) do? What kind of > data(?) would this function be applied to? A Python list of filenames? > > Thanks, > > Dick Moores > Hello, Dick. Let's compare your final startswith method and the endswith method in is_image_file: >>>>>>> s.startswith("er","q","ty") filename.endswith(('.gif', '.jpg', '.tiff')) >>>>>>> Notice that, while startswith has THREE parameters, endswith has only ONE. ('.gif', '.jpg', '.tiff') is a tuple, and the interpreter sees it as a single parameter. In other words your method is passing the following parameters: prefix = "er" start = "q" end = "ty while the example method is passing: suffix = ('.gif', '.jpg', '.tiff') start = None end = None Does that make sense? Good luck. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From rdm at rcblue.com Mon Sep 25 18:28:52 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 25 Sep 2006 09:28:52 -0700 Subject: [Tutor] Which psyco for Python 2.5? Message-ID: <7.0.1.0.2.20060925092213.0712ed00@rcblue.com> I installed Python 2.5 yesterday and now want to get psyco for it. At http://psyco.sourceforge.net/ there's an item dated 9/25 (today) that I'm wondering if the Tutors think is necessary to follow. It would be much easier for me to get Psyco 1.5.1 from http://sourceforge.net/project/showfiles.php?group_id=41036 and put it in my E:\Python25\Lib\site-packages, but should I? Or should I get the subversion source, for which I don't understand the installation process? Thanks, Dick Moores From rdm at rcblue.com Mon Sep 25 18:46:04 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 25 Sep 2006 09:46:04 -0700 Subject: [Tutor] Question about startswith() and endswith() in 2.5 In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C3756@eugsrv400.psc.pscne t.com> References: <2BBAEE949D384D40A2B851287ADB6A432C3756@eugsrv400.psc.pscnet.com> Message-ID: <7.0.1.0.2.20060925094432.0356ceb0@rcblue.com> At 09:04 AM 9/25/2006, Carroll, Barry wrote: >Hello, Dick. > >Let's compare your final startswith method and the endswith method in >is_image_file: > > >>>>>>> >s.startswith("er","q","ty") >filename.endswith(('.gif', '.jpg', '.tiff')) > >>>>>>> > >Notice that, while startswith has THREE parameters, endswith has only >ONE. ('.gif', '.jpg', '.tiff') is a tuple, and the interpreter sees it >as a single parameter. In other words your method is passing the >following parameters: > > prefix = "er" > start = "q" > end = "ty > >while the example method is passing: > > suffix = ('.gif', '.jpg', '.tiff') > start = None > end = None > >Does that make sense? Sure does now. Thanks, Barry Dick From kent37 at tds.net Mon Sep 25 18:46:21 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 25 Sep 2006 12:46:21 -0400 Subject: [Tutor] Which psyco for Python 2.5? In-Reply-To: <7.0.1.0.2.20060925092213.0712ed00@rcblue.com> References: <7.0.1.0.2.20060925092213.0712ed00@rcblue.com> Message-ID: <451807DD.70101@tds.net> Dick Moores wrote: > I installed Python 2.5 yesterday and now want to get psyco for it. At > http://psyco.sourceforge.net/ there's an item dated 9/25 (today) that > I'm wondering if the Tutors think is necessary to follow. It would be > much easier for me to get Psyco 1.5.1 from > http://sourceforge.net/project/showfiles.php?group_id=41036 and put > it in my E:\Python25\Lib\site-packages, but should I? Or should I get > the subversion source, for which I don't understand the installation process? Sounds like you should either figure out how to build it from source (sorry, can't help with that...) or stick with Python 2.4 until there is a binary release of psyco for 2.5. Unless using a package "which will probably crash any program using it" is acceptable to you... Kent From rdm at rcblue.com Mon Sep 25 19:03:34 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 25 Sep 2006 10:03:34 -0700 Subject: [Tutor] Which psyco for Python 2.5? In-Reply-To: <451807DD.70101@tds.net> References: <7.0.1.0.2.20060925092213.0712ed00@rcblue.com> <451807DD.70101@tds.net> Message-ID: <7.0.1.0.2.20060925100115.07125d10@rcblue.com> At 09:46 AM 9/25/2006, Kent Johnson wrote: >Dick Moores wrote: > > I installed Python 2.5 yesterday and now want to get psyco for it. At > > http://psyco.sourceforge.net/ there's an item dated 9/25 (today) that > > I'm wondering if the Tutors think is necessary to follow. It would be > > much easier for me to get Psyco 1.5.1 from > > http://sourceforge.net/project/showfiles.php?group_id=41036 and put > > it in my E:\Python25\Lib\site-packages, but should I? Or should I get > > the subversion source, for which I don't understand the > installation process? > >Sounds like you should either figure out how to build it from source >(sorry, can't help with that...) or stick with Python 2.4 until there is >a binary release of psyco for 2.5. Unless using a package "which will >probably crash any program using it" is acceptable to you... Damn. Thanks, Kent. I was hoping you'd pooh-pooh the advice. Dick From kent37 at tds.net Mon Sep 25 19:40:59 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 25 Sep 2006 13:40:59 -0400 Subject: [Tutor] Which psyco for Python 2.5? In-Reply-To: <7.0.1.0.2.20060925100115.07125d10@rcblue.com> References: <7.0.1.0.2.20060925092213.0712ed00@rcblue.com> <451807DD.70101@tds.net> <7.0.1.0.2.20060925100115.07125d10@rcblue.com> Message-ID: <451814AB.9010902@tds.net> Dick Moores wrote: > Damn. Thanks, Kent. I was hoping you'd pooh-pooh the advice. I don't really know anything about it other than what I read on the psyco site, but they should know whether it works or not...there *was* a change in the __index__ method for 2.5rc1, it is listed here: http://www.python.org/download/releases/2.5/NEWS.txt As far as the comment about Python 2.5 not being ready for prime time, I guess time will tell. I think he is correct that there were a lot of internal changes this time; whether that will translate to a less stable release, I have no idea. I have upgraded myself but most of my production code is in Jython so I don't really risk anything by the upgrade. Historically a 2.x.1 release has come out 2-4 months after each 2.x release. Kent Kent From rdm at rcblue.com Mon Sep 25 19:53:36 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 25 Sep 2006 10:53:36 -0700 Subject: [Tutor] Which psyco for Python 2.5? In-Reply-To: <451814AB.9010902@tds.net> References: <7.0.1.0.2.20060925092213.0712ed00@rcblue.com> <451807DD.70101@tds.net> <7.0.1.0.2.20060925100115.07125d10@rcblue.com> <451814AB.9010902@tds.net> Message-ID: <7.0.1.0.2.20060925105041.071b08c0@rcblue.com> At 10:40 AM 9/25/2006, you wrote: >Dick Moores wrote: > > Damn. Thanks, Kent. I was hoping you'd pooh-pooh the advice. > >I don't really know anything about it other than what I read on the >psyco site, but they should know whether it works or not...there *was* a >change in the __index__ method for 2.5rc1, it is listed here: >http://www.python.org/download/releases/2.5/NEWS.txt > >As far as the comment about Python 2.5 not being ready for prime time, I >guess time will tell. I think he is correct that there were a lot of >internal changes this time; whether that will translate to a less stable >release, I have no idea. I have upgraded myself but most of my >production code is in Jython so I don't really risk anything by the >upgrade. Historically a 2.x.1 release has come out 2-4 months after each >2.x release. Well, I'm just a Python putzer, so I'm not risking anything either. Thanks for your further advice, Kent. Dick From dos.fool at gmail.com Mon Sep 25 20:55:48 2006 From: dos.fool at gmail.com (max .) Date: Mon, 25 Sep 2006 12:55:48 -0600 Subject: [Tutor] opening files Message-ID: <857e4c3d0609251155u229c69e8sf61f9102a09f5775@mail.gmail.com> hello i cant understand how to open text files with python i have tried tutorials and evrything i just cant get pleas help From jmpurser at gmail.com Mon Sep 25 21:14:50 2006 From: jmpurser at gmail.com (John Purser) Date: Mon, 25 Sep 2006 12:14:50 -0700 Subject: [Tutor] opening files In-Reply-To: <857e4c3d0609251155u229c69e8sf61f9102a09f5775@mail.gmail.com> References: <857e4c3d0609251155u229c69e8sf61f9102a09f5775@mail.gmail.com> Message-ID: <1159211691.5395.3.camel@localhost.localdomain> On Mon, 2006-09-25 at 12:55 -0600, max . wrote: > hello i cant understand how to open text files with python > i have tried tutorials and evrything i just cant get pleas help > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Hello Max, my_file = open('c:\\path\to\file\file.txt', 'r') my_file.readlines() my_file.close() Really, it's so simple it's hard to come up with directions. Just do it. John Purser From dyoo at hkn.eecs.berkeley.edu Mon Sep 25 23:02:33 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 25 Sep 2006 14:02:33 -0700 (PDT) Subject: [Tutor] opening files In-Reply-To: <857e4c3d0609251155u229c69e8sf61f9102a09f5775@mail.gmail.com> References: <857e4c3d0609251155u229c69e8sf61f9102a09f5775@mail.gmail.com> Message-ID: On Mon, 25 Sep 2006, max . wrote: > hello i cant understand how to open text files with python > i have tried tutorials and evrything i just cant get pleas help Hi Max, Which tutorials are you trying? Have you looked at: http://www.freenetpages.co.uk/hp/alan.gauld/ There's a whole section in that tutorial that's devoted to handling files. Is there something in there that you don't understand? If so, ask questions about it. From dyoo at hkn.eecs.berkeley.edu Mon Sep 25 23:07:04 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 25 Sep 2006 14:07:04 -0700 (PDT) Subject: [Tutor] opening files In-Reply-To: <1159211691.5395.3.camel@localhost.localdomain> References: <857e4c3d0609251155u229c69e8sf61f9102a09f5775@mail.gmail.com> <1159211691.5395.3.camel@localhost.localdomain> Message-ID: > my_file = open('c:\\path\to\file\file.txt', 'r') > my_file.readlines() > my_file.close() > > Really, it's so simple it's hard to come up with directions. Hi John, In that case, we have to figure out why Max is getting stuck: it's not obvious at all at what step he's getting confused. Let's concentrate on isolating that confusion. I have no conceptual model of what Max already knows: * Does he know how to use functions? * Does he know about strings? * Does his tutorial material suck? * etc... so Max has to be a bit more forthcoming. From dyoo at hkn.eecs.berkeley.edu Tue Sep 26 03:43:20 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 25 Sep 2006 18:43:20 -0700 (PDT) Subject: [Tutor] opening files (fwd) Message-ID: ---------- Forwarded message ---------- Date: Mon, 25 Sep 2006 16:46:02 -0600 From: max . To: Danny Yoo Subject: Re: [Tutor] opening files ok srry i will give a bit more info i am working on a new mac mini :)) im still pretty new to python so allmost all my programs are math stuff and i would like to start writing more complex programs i know a bit about functions and strings but any help would be great python is my first programing language and i have been reading almost anything i can find on tutorial stuff let me know if you need any more info On 9/25/06, Danny Yoo wrote: > > my_file = open('c:\\path\to\file\file.txt', 'r') > > my_file.readlines() > > my_file.close() > > > > Really, it's so simple it's hard to come up with directions. > > Hi John, > > In that case, we have to figure out why Max is getting stuck: it's not > obvious at all at what step he's getting confused. Let's concentrate on > isolating that confusion. > > I have no conceptual model of what Max already knows: > > * Does he know how to use functions? > > * Does he know about strings? > > * Does his tutorial material suck? > > * etc... > > so Max has to be a bit more forthcoming. > From alvarezes at gmail.com Tue Sep 26 09:34:59 2006 From: alvarezes at gmail.com (Erly Alvarez) Date: Tue, 26 Sep 2006 16:34:59 +0900 Subject: [Tutor] EMACS Message-ID: I would like to know first of all, how to load the python mode into emacs. Thank you for your assistance. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060926/4eed69f9/attachment.html From paulino1 at sapo.pt Tue Sep 26 00:56:10 2006 From: paulino1 at sapo.pt (PA) Date: Mon, 25 Sep 2006 23:56:10 +0100 Subject: [Tutor] e-learning Python In-Reply-To: References: Message-ID: <1159224970.5931.2.camel@pa-desktop> Is there any site offering e-learning about Python? If not, the PSF should do it! From project5 at redrival.net Tue Sep 26 12:05:56 2006 From: project5 at redrival.net (Andrei) Date: Tue, 26 Sep 2006 10:05:56 +0000 (UTC) Subject: [Tutor] e-learning Python References: <1159224970.5931.2.camel@pa-desktop> Message-ID: PA sapo.pt> writes: > Is there any site offering e-learning about Python? > > If not, the PSF should do it! If you mean if there are any online tutorials: lots of them. Here's a very large list: http://www.awaretek.com/tutorials.html Yours, Andrei From baiju.m.mail at gmail.com Tue Sep 26 13:57:53 2006 From: baiju.m.mail at gmail.com (Baiju M) Date: Tue, 26 Sep 2006 17:27:53 +0530 Subject: [Tutor] EMACS In-Reply-To: References: Message-ID: <3171e4820609260457r58e7ce54y86c389c40e1289e8@mail.gmail.com> On 9/26/06, Erly Alvarez wrote: > I would like to know first of all, how to load the python mode into emacs. When you open a file with '.py' extension, python-mode will be automatically loaded. To explicitly load it: M-x python-mode Read this page more info: http://www.emacswiki.org/cgi-bin/wiki/PythonMode Regards, Baiju M From nathan.botts at cgu.edu Tue Sep 26 17:47:28 2006 From: nathan.botts at cgu.edu (Nathan Botts) Date: Tue, 26 Sep 2006 08:47:28 -0700 Subject: [Tutor] e-learning Python (PA) In-Reply-To: Message-ID: <003501c6e183$128f89c0$07e1ad86@Otto> That might depend on what you consider eLearning. I've found that the "How to Think Like a Computer Scientist" (http://ibiblio.org/obp/thinkCS/python/english2e/html/index.html) online book is a great learning guide. Or are you looking for something more interactive? -Nathan ---------------------------------------------------------------------- Message: 1 Date: Mon, 25 Sep 2006 23:56:10 +0100 From: PA Subject: [Tutor] e-learning Python To: tutor at python.org Message-ID: <1159224970.5931.2.camel at pa-desktop> Content-Type: text/plain Is there any site offering e-learning about Python? If not, the PSF should do it! ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 31, Issue 72 ************************************* From dyoo at hkn.eecs.berkeley.edu Wed Sep 27 02:49:02 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 26 Sep 2006 17:49:02 -0700 (PDT) Subject: [Tutor] opening files (fwd) In-Reply-To: References: Message-ID: > im still pretty new to python so allmost all my programs are math stuff > and i would like to start writing more complex programs i know a bit > about functions and strings Hi Max, Just to clarify: you can do a lot with Python even without using files. Take a look at Alan Gauld's tutorial, for example. Files come up after a few more of the prerequisite topics. I guess I'm trying to say: make sure you've looked at some of the prerequisites. It sounds like you're skipping ahead a bit. You should feel comfortable with at least these topics: functions - about how they take things in (input) and what they return (output), and how to use them effectively strings - what they are, how to manipulate them. sequences and loops - applying some action across a whole bunch of things Otherwise, working with files is going to be weird, because files show up as loopable "iterable" things that produce strings. If you know how to deal with lists of strings, making the transition to files shouldn't be too bad. Good luck! From tiagosaboga at terra.com.br Wed Sep 27 19:34:00 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Wed, 27 Sep 2006 14:34:00 -0300 Subject: [Tutor] importing module with non-standard name Message-ID: <200609271434.00237.tiagosaboga@terra.com.br> Hi! I'm still playing with man pages parsing, and following advices here, I'm using doclifter. But I want to use the installed version on my debian system, and not make it a part of my package. The problem is it isn't installed as a python module, but rather as an executable file lying in /usr/bin, and - there's the problem - with no .py extension. I've google'd about it, but I could not found any clear answer. Any ideas? Tiago. From kent37 at tds.net Wed Sep 27 19:51:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 27 Sep 2006 13:51:53 -0400 Subject: [Tutor] importing module with non-standard name In-Reply-To: <200609271434.00237.tiagosaboga@terra.com.br> References: <200609271434.00237.tiagosaboga@terra.com.br> Message-ID: <451ABA39.1050706@tds.net> Tiago Saboga wrote: > Hi! > > I'm still playing with man pages parsing, and following advices here, I'm > using doclifter. But I want to use the installed version on my debian system, > and not make it a part of my package. The problem is it isn't installed as a > python module, but rather as an executable file lying in /usr/bin, and - > there's the problem - with no .py extension. I've google'd about it, but I > could not found any clear answer. > > Any ideas? I think either execfile() or imp.load_source() or the suggestions here - http://tinyurl.com/mnzoo - will do what you want. Kent From pythontut at pusspaws.net Wed Sep 27 22:59:36 2006 From: pythontut at pusspaws.net (Dave S) Date: Wed, 27 Sep 2006 21:59:36 +0100 Subject: [Tutor] file open (take 2) Message-ID: <200609272159.36320.pythontut@pusspaws.net> Hi, I am trying to read in an ascii text file, do some alterations and write it back. file = open(self.config.get('pdf','cert') + '/cert.pdf' , 'r+') lines = file.readlines() ... process lines ... file.writelines(lines) file.close() works but ends up appending a second modified copy to the original ... as per the python ref. Am I right in thinking that the only way is to open with a 'r', close them open with a 'w' ? Cheers Dave From carroll at tjc.com Thu Sep 28 02:55:22 2006 From: carroll at tjc.com (Terry Carroll) Date: Wed, 27 Sep 2006 17:55:22 -0700 (PDT) Subject: [Tutor] file open (take 2) In-Reply-To: <200609272159.36320.pythontut@pusspaws.net> Message-ID: On Wed, 27 Sep 2006, Dave S wrote: > I am trying to read in an ascii text file, do some alterations and write it > back. > > file = open(self.config.get('pdf','cert') + '/cert.pdf' , 'r+') > lines = file.readlines() > > ... process lines ... > > file.writelines(lines) > file.close() > > works but ends up appending a second modified copy to the original ... as per > the python ref. I'm surprised it wors at all. When I use writelines on a file that's opened for read, I get an IOError. >>> f = open("glorp.txt","r") >>> lines = f.readlines() >>> lines.reverse() # just something to show the file's been changed >>> f.writelines(lines) Traceback (most recent call last): File "", line 1, in ? IOError: (0, 'Error') > Am I right in thinking that the only way is to open with a 'r', close them > open with a 'w' ? Yup: >>> f = open("glorp.txt","r") >>> lines = f.readlines() >>> lines.reverse() >>> f.close() >>> f = open("glorp.txt","w") >>> f.writelines(lines) >>> f.close() From rabidpoobear at gmail.com Thu Sep 28 03:24:20 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 27 Sep 2006 20:24:20 -0500 Subject: [Tutor] file open (take 2) In-Reply-To: References: Message-ID: <451B2444.40403@gmail.com> >> I am trying to read in an ascii text file, do some alterations and write it >> back. >> Sounds like a pretty useful thing to do :) >> file = open(self.config.get('pdf','cert') + '/cert.pdf' , 'r+') >> lines = file.readlines() >> Not sure what self.config.get here is doing, but that's not exactly pertinent to the discussion. >> ... process lines ... >> >> file.writelines(lines) >> file.close() >> >> works but ends up appending a second modified copy to the original ... as per >> the python ref. >> > > I'm surprised it wors at all. When I use writelines on a file that's > opened for read, I get an IOError. > Notice the "r+" mode that Dave is using. > >>>> f = open("glorp.txt","r") >>>> lines = f.readlines() >>>> lines.reverse() # just something to show the file's been changed >>>> f.writelines(lines) >>>> > Traceback (most recent call last): > File "", line 1, in ? > IOError: (0, 'Error') > Here Terry's using "r". "r+" means open for reading and appending. "r" is just normal reading. > >> Am I right in thinking that the only way is to open with a 'r', close then >> open with a 'w' ? >> I believe Dave could somehow remove the contents of the file, and put back in what he wants, but it's probably easier to just reopen the file. From arcege at gmail.com Thu Sep 28 04:01:39 2006 From: arcege at gmail.com (Michael P. Reilly) Date: Wed, 27 Sep 2006 22:01:39 -0400 Subject: [Tutor] file open (take 2) In-Reply-To: <200609272159.36320.pythontut@pusspaws.net> References: <200609272159.36320.pythontut@pusspaws.net> Message-ID: <7e5ba9220609271901j5d61cb9udd11fd275c83423a@mail.gmail.com> On 9/27/06, Dave S wrote: > > Hi, > > I am trying to read in an ascii text file, do some alterations and write > it > back. > > file = open(self.config.get('pdf','cert') + '/cert.pdf' , 'r+') > lines = file.readlines() > > ... process lines ... > > file.writelines(lines) > file.close() > > works but ends up appending a second modified copy to the original ... as > per > the python ref. You need to add a file.rewind() or file.seek(0) before you start writing. Am I right in thinking that the only way is to open with a 'r', close them > open with a 'w' ? It is not the only way. In fact, it is not the best way. It is actually unsafe. What you will want to do is write to a temporary file and then replace the existing file with the temporary file. file = open(self.config.get('pdf','cert') + '/cert.pdf' , 'r') lines = file.readlines() ... process lines ... outfile = open(self.config.get('pdf', 'cert') + '/cert.pdf.tmp', 'w') outfile.writelines(lines) outfile.close() file.close() os.rename(self.config.get('pdf', 'cert') + '/cert.pdf.tmp', self.config.get('pdf', 'cert') + '/cert.pdf') The reason this is unsafe is two fold. 1. If the is a problem during execution, the original file is untouched. 2. With r+ or a+, if the new contents is shorter than the written file, then you might have additional data following the new contents. Cheers > > Dave > > -Arcege -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060927/fc5d8de3/attachment.html From samrobertsmith at gmail.com Thu Sep 28 06:46:48 2006 From: samrobertsmith at gmail.com (linda.s) Date: Wed, 27 Sep 2006 21:46:48 -0700 Subject: [Tutor] about mainloop Message-ID: <1d987df30609272146w1364bffbl7911351d9dc23133@mail.gmail.com> I comment out root.mainloop() in my windows machine's Python 2.4 IDLE, everything is OK. But if I do the same thing in Mac machine's Python 2.4 IDLE, I can not see any map.Why? From rabidpoobear at gmail.com Thu Sep 28 07:16:14 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 28 Sep 2006 00:16:14 -0500 Subject: [Tutor] about mainloop In-Reply-To: <1d987df30609272146w1364bffbl7911351d9dc23133@mail.gmail.com> References: <1d987df30609272146w1364bffbl7911351d9dc23133@mail.gmail.com> Message-ID: <451B5A9E.8060200@gmail.com> linda.s wrote: > I comment out > root.mainloop() > in my windows machine's Python 2.4 IDLE, everything is OK. > But if I do the same thing in Mac machine's Python 2.4 IDLE, > I can not see any map.Why? > When you edit a .py file on a windows machine (by right-clicking and hitting 'edit with idle') it starts the IDLE IDE without the subprocess. This means that whenever a program is run in IDLE, it's run in the same interpreter IDLE uses (this may not be exactly true) However, if you were to start IDLE from the start menu, and load the file by itself, it would have the subprocess option enabled, where a separate process containing a python interpreter that's isolated from IDLE's is run. Since IDLE is written in TKinter, it has its own mainloop running. If you're running a program without the subprocess module, and you try to use a mainloop in it, weird things will happen, because your mainloop will conflict with the one IDLE's already using. That's why you can comment out the mainloop on windows files if you right-click->edit them. The reason the subprocess isn't enabled by default on right-click-> edit is that it was causing some problem with windows or something. There's a way to make it where subprocess is always enabled, but earlier discussions on this subject have suggested that if you need the subprocess to be enabled, you should start IDLE independently and load the program you're testing. I'm guessing that these problems don't appear on the Mac version, so they just have the subprocess always running. You can confirm this if you see =============RESTART============== in your IDLE shell whenever you run a program. TK apps need a mainloop to display, so if on Mac it's running in a separate process, it can't use the mainloop IDLE is already running. HTH, -Luke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From shashikant.ramakrish at smartm.com Thu Sep 28 02:45:54 2006 From: shashikant.ramakrish at smartm.com (Ramakrishnan, Shashikanth) Date: Thu, 28 Sep 2006 08:45:54 +0800 Subject: [Tutor] Hi, need help on terminal input Message-ID: <03FD694839148D47BC2364E8A52A72F27BD46A@sr-png-exc02.smartm.internal> Hi, Does anybody know how to create a pygtk widget which can accept and diplay input from a serial port? Thanks and Rgds, Shashikanth Ramakrishnan Embedded Product Division Cell: +6-0122977087 e-mail :shashikanth.ramakrishnan at smartm.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060928/bd01d766/attachment.html From pythontut at pusspaws.net Thu Sep 28 16:56:23 2006 From: pythontut at pusspaws.net (Dave S) Date: Thu, 28 Sep 2006 15:56:23 +0100 Subject: [Tutor] file open (take 2) In-Reply-To: <200609272159.36320.pythontut@pusspaws.net> References: <200609272159.36320.pythontut@pusspaws.net> Message-ID: <200609281556.23595.pythontut@pusspaws.net> On Wednesday 27 September 2006 21:59, Dave S wrote: > Hi, > > I am trying to read in an ascii text file, do some alterations and write it > back. > > file = open(self.config.get('pdf','cert') + '/cert.pdf' , 'r+') > lines = file.readlines() > > ... process lines ... > > file.writelines(lines) > file.close() > > works but ends up appending a second modified copy to the original ... as > per the python ref. > > Am I right in thinking that the only way is to open with a 'r', close them > open with a 'w' ? > > Cheers > > Dave > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Thanks for all your input - that's great - I also learnt about file.rewind() and file.seek(0) :) Thanks once again Dave From pythontut at pusspaws.net Thu Sep 28 17:10:20 2006 From: pythontut at pusspaws.net (Dave S) Date: Thu, 28 Sep 2006 16:10:20 +0100 Subject: [Tutor] getting 'pwd' for XP ? Message-ID: <200609281610.20635.pythontut@pusspaws.net> I currently running XP (like a fish out of water :) and I need to know the dir that the python script is executed from. a linux 'pwd' How can I achieve this - I have looked in sys & os & os.path but found nothing suitable Dave From david at graniteweb.com Thu Sep 28 17:24:11 2006 From: david at graniteweb.com (David Rock) Date: Thu, 28 Sep 2006 10:24:11 -0500 Subject: [Tutor] getting 'pwd' for XP ? In-Reply-To: <200609281610.20635.pythontut@pusspaws.net> References: <200609281610.20635.pythontut@pusspaws.net> Message-ID: <20060928152411.GC11951@wdfs.graniteweb.com> * Dave S [2006-09-28 16:10]: > I currently running XP (like a fish out of water :) and I need to know the dir > that the python script is executed from. a linux 'pwd' How can I achieve > this - I have looked in sys & os & os.path but found nothing suitable os.getcwd() http://docs.python.org/lib/os-file-dir.html -- David Rock david at graniteweb.com From shantanoo at gmail.com Thu Sep 28 17:42:42 2006 From: shantanoo at gmail.com (Shantanoo Mahajan) Date: Thu, 28 Sep 2006 21:12:42 +0530 Subject: [Tutor] getting 'pwd' for XP ? In-Reply-To: <200609281610.20635.pythontut@pusspaws.net> References: <200609281610.20635.pythontut@pusspaws.net> Message-ID: <20060928154242.GA6680@madhosh.dhoomketu.net.in> +++ Dave S [28-09-06 16:10 +0100]: | I currently running XP (like a fish out of water :) and I need to know the dir | that the python script is executed from. a linux 'pwd' How can I achieve | this - I have looked in sys & os & os.path but found nothing suitable ==================== Python 2.4.3 (#2, Sep 26 2006, 15:27:42) [GCC 3.4.4 [FreeBSD] 20050518] on freebsd6 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.getcwd() '/tmp' >>> ==================== -- An idea that is not dangerous is unworthy to be called an idea at all. ~Elbert Hubbard From rdm at rcblue.com Thu Sep 28 19:32:58 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 28 Sep 2006 10:32:58 -0700 Subject: [Tutor] 2.5's new conditional expression syntax Message-ID: <7.0.1.0.2.20060928102238.06f35c40@rcblue.com> I've been looking hard at 2.5's new conditional expression syntax (), and didn't understand the examples there, so I tried making up my own: >>> x = (1 if 2 == 2 else 3) >>> x 1 >>> y = (1 if 2 == 1 else 3) >>> y 3 >>> But it would help to see an example I could understand that also shows the syntax's usefulness. Could someone cook up one for me? Thanks, Dick Moores From kent37 at tds.net Thu Sep 28 19:53:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 28 Sep 2006 13:53:56 -0400 Subject: [Tutor] 2.5's new conditional expression syntax In-Reply-To: <7.0.1.0.2.20060928102238.06f35c40@rcblue.com> References: <7.0.1.0.2.20060928102238.06f35c40@rcblue.com> Message-ID: <451C0C34.3030009@tds.net> Dick Moores wrote: > I've been looking hard at 2.5's new conditional expression syntax > (), and didn't > understand the examples there, so I tried making up my own: > > >>> x = (1 if 2 == 2 else 3) > >>> x > 1 > >>> y = (1 if 2 == 1 else 3) > >>> y > 3 > >>> > > But it would help to see an example I could understand that also > shows the syntax's usefulness. Could someone cook up one for me? It's just a shortcut - a compact way to write a conditional. The old way to do this (in some cases) was to use and...or. Here are some examples from the project I am working on: batchTypes = types and types*len(batch) or None default = course and course.status or 'In Development' ps.setBoolean(ix, val and 1 or 0) which could be rewritten as batchTypes = types*len(batch) if types else None default = course.status if course else 'In Development' ps.setBoolean(ix, 1 if val else 0) Without either shortcut, these could be written out as e.g. if types: batchTypes = types*len(batch) else: batchTypes = None The new syntax has a few improvements over the old method: - it is more robust. The old syntax only works if the first value (after 'and') is True when evaluated as a boolean; the new syntax avoids this trap. Workarounds that make the old method work in all conditions are awkward and ugly. - it is arguably more readable, at least for the common usage shown above where there is a common case and an exceptional case. When the overall expression is more complex, the simple if: else: is more unwieldy, e.g. expectedLen = len(expectedCourses) + (cat and 1 or 0) which would be written as if cat: expectedLen = len(expectedCourses) + 1 else: expectedLen = len(expectedCourses) or maybe expectedLen = len(expectedCourses) if cat: expectedLen += 1 Kent From pythontut at pusspaws.net Thu Sep 28 19:58:06 2006 From: pythontut at pusspaws.net (Dave S) Date: Thu, 28 Sep 2006 18:58:06 +0100 Subject: [Tutor] getting 'pwd' for XP ? In-Reply-To: <20060928154242.GA6680@madhosh.dhoomketu.net.in> References: <200609281610.20635.pythontut@pusspaws.net> <20060928154242.GA6680@madhosh.dhoomketu.net.in> Message-ID: <200609281858.06680.pythontut@pusspaws.net> On Thursday 28 September 2006 16:42, Shantanoo Mahajan wrote: > +++ Dave S [28-09-06 16:10 +0100]: > | I currently running XP (like a fish out of water :) and I need to know > | the dir that the python script is executed from. a linux 'pwd' How can I > | achieve this - I have looked in sys & os & os.path but found nothing > | suitable > > ==================== > Python 2.4.3 (#2, Sep 26 2006, 15:27:42) > [GCC 3.4.4 [FreeBSD] 20050518] on freebsd6 > Type "help", "copyright", "credits" or "license" for more information. > > >>> import os > >>> os.getcwd() > > '/tmp' > > ==================== os.getcwd() it is - must have missed it - thanks Dave From nephish at gmail.com Thu Sep 28 20:31:39 2006 From: nephish at gmail.com (shawn bright) Date: Thu, 28 Sep 2006 13:31:39 -0500 Subject: [Tutor] revisiting struct module Message-ID: <384c93600609281131n1a1d0a7i2129c9fa1a440b82@mail.gmail.com> Hey there, I am writing this because there is something that I am not understanding about the struct module. I have to send a message over a socket. The message has to be exactly 4 bytes, and the last bit has to be the value of 200. so like this: null,null,null,200 would be the message, and the 200 has to be an unsigned long int. I know the stream of info that I am supposed to send the server is big endian. I also know that I should be using the struct.pack(), but I don't know how to set this up. This is actually only part of the message, but I am trying to learn this as i go. thanks for any tips. shawn -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060928/363cbc12/attachment.htm From rdm at rcblue.com Thu Sep 28 20:31:33 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 28 Sep 2006 11:31:33 -0700 Subject: [Tutor] How to get at the list that set() seems to produce? Message-ID: <7.0.1.0.2.20060928105913.06eefc58@rcblue.com> I'm very interested in the data type, set. Python 2.5: >>> lst = [9,23,45,9,45,78,23,78] >>> set(lst) set([9, 45, 78, 23]) >>> s = "etywtqyertwytqywetrtwyetrqywetry" >>> set(s) set(['e', 'q', 'r', 't', 'w', 'y']) >>> I'm wondering if there isn't a way to get at what seems to be the list of unique elements set() seems to produce. For example, I would think it might be useful if the "list" of set([9, 45, 78, 23]) could be extracted, for sorting, taking the mean, etc. And it might be nice if the "list" of set(['e', 'q', 'r', 't', 'w', 'y']) could be converted into the sorted string, "eqrtwy". But note: >>> set(['e', 'q', 'r', 't', 'w', 'y'])[:] Traceback (most recent call last): File "", line 1, in TypeError: 'set' object is unsubscriptable >>> set(['e', 'q', 'r', 't', 'w', 'y'])[0] Traceback (most recent call last): File "", line 1, in TypeError: 'set' object is unindexable >>> To be sure I'm clear, I'm not asking how to do the above things in other ways (I know how)--I'm just wondering why set() was set up (pun) so they can't be done with its help. Or can they? Dick Moores From kent37 at tds.net Thu Sep 28 20:55:57 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 28 Sep 2006 14:55:57 -0400 Subject: [Tutor] How to get at the list that set() seems to produce? In-Reply-To: <7.0.1.0.2.20060928105913.06eefc58@rcblue.com> References: <7.0.1.0.2.20060928105913.06eefc58@rcblue.com> Message-ID: <451C1ABD.1090809@tds.net> Dick Moores wrote: > I'm very interested in the data type, set. > > Python 2.5: > >>> lst = [9,23,45,9,45,78,23,78] > >>> set(lst) > set([9, 45, 78, 23]) > >>> s = "etywtqyertwytqywetrtwyetrqywetry" > >>> set(s) > set(['e', 'q', 'r', 't', 'w', 'y']) > >>> > > I'm wondering if there isn't a way to get at what seems to be the > list of unique elements set() seems to produce. For example, I would > think it might be useful if the "list" of set([9, 45, 78, 23]) could > be extracted, for sorting, taking the mean, etc. You just have to ask: In [1]: lst = [9,23,45,9,45,78,23,78] In [2]: set(lst) Out[2]: set([9, 45, 78, 23]) In [3]: list(set(lst)) Out[3]: [9, 45, 78, 23] > And it might be nice > if the "list" of set(['e', 'q', 'r', 't', 'w', 'y']) could be > converted into the sorted string, "eqrtwy". In [4]: s = "etywtqyertwytqywetrtwyetrqywetry" In [5]: ''.join(sorted(set(s))) Out[5]: 'eqrtwy' The key concept is that a set is iterable - it's not a list, but in contexts that accept an iterable it will work the same as a list. Kent From rdm at rcblue.com Thu Sep 28 20:58:26 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 28 Sep 2006 11:58:26 -0700 Subject: [Tutor] 2.5's new conditional expression syntax In-Reply-To: <451C0C34.3030009@tds.net> References: <7.0.1.0.2.20060928102238.06f35c40@rcblue.com> <451C0C34.3030009@tds.net> Message-ID: <7.0.1.0.2.20060928115626.06f1d1a8@rcblue.com> Kent, Your examples took a lot of study, but I think I'm catching on. Thanks very much. Dick At 10:53 AM 9/28/2006, Kent Johnson wrote: >Dick Moores wrote: > > I've been looking hard at 2.5's new conditional expression syntax > > (), and didn't > > understand the examples there, so I tried making up my own: > > > > >>> x = (1 if 2 == 2 else 3) > > >>> x > > 1 > > >>> y = (1 if 2 == 1 else 3) > > >>> y > > 3 > > >>> > > > > But it would help to see an example I could understand that also > > shows the syntax's usefulness. Could someone cook up one for me? > >It's just a shortcut - a compact way to write a conditional. The old way >to do this (in some cases) was to use and...or. Here are some examples >from the project I am working on: > >batchTypes = types and types*len(batch) or None >default = course and course.status or 'In Development' >ps.setBoolean(ix, val and 1 or 0) > >which could be rewritten as >batchTypes = types*len(batch) if types else None >default = course.status if course else 'In Development' >ps.setBoolean(ix, 1 if val else 0) > >Without either shortcut, these could be written out as e.g. >if types: > batchTypes = types*len(batch) >else: > batchTypes = None > >The new syntax has a few improvements over the old method: >- it is more robust. The old syntax only works if the first value (after >'and') is True when evaluated as a boolean; the new syntax avoids this >trap. Workarounds that make the old method work in all conditions are >awkward and ugly. >- it is arguably more readable, at least for the common usage shown >above where there is a common case and an exceptional case. > >When the overall expression is more complex, the simple if: else: is >more unwieldy, e.g. > >expectedLen = len(expectedCourses) + (cat and 1 or 0) > >which would be written as >if cat: > expectedLen = len(expectedCourses) + 1 >else: > expectedLen = len(expectedCourses) > >or maybe >expectedLen = len(expectedCourses) >if cat: > expectedLen += 1 > >Kent From dyoo at hkn.eecs.berkeley.edu Thu Sep 28 21:17:48 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 28 Sep 2006 12:17:48 -0700 (PDT) Subject: [Tutor] How to get at the list that set() seems to produce? In-Reply-To: <7.0.1.0.2.20060928105913.06eefc58@rcblue.com> References: <7.0.1.0.2.20060928105913.06eefc58@rcblue.com> Message-ID: > I'm wondering if there isn't a way to get at what seems to be the > list of unique elements set() seems to produce. Here you go: ############################################# >>> list(set(['e', 'q', 'r', 't', 'w', 'y'])) ['e', 'q', 'r', 't', 'w', 'y'] ############################################# Just to head off any confusion here: this is not type coersion or type casting. list() is just a regular function that takes an iterable and returns a list of that iterable's elements. We can just as easily "listify" other iterable things such as strings. ############################## >>> list("foobar") ['f', 'o', 'o', 'b', 'a', 'r'] ############################## > >>> set(['e', 'q', 'r', 't', 'w', 'y'])[:] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'set' object is unsubscriptable > >>> set(['e', 'q', 'r', 't', 'w', 'y'])[0] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'set' object is unindexable > > To be sure I'm clear, I'm not asking how to do the above things in > other ways (I know how)--I'm just wondering why set() was set up > (pun) so they can't be done with its help. A "set" is a concept that provides support for operations that are listed in: http://www.python.org/doc/lib/types-set.html When we say something is a "set", we don't automatically assume that it can be indexed or sliced. The reason for that is because sets may not necessarily be represented as lists; a perfectly good implementation of sets can be implemented using something else entirely such as binary trees or dictionaries. Concretely, if we use a dictionary implementation for the concept of a set, then asking for a set's slice or element index is a "nonsensical" operation: what is it supposed to mean, if all the elements are scattered around in no particularly meaningful order? So that's a good reason to leave sequencing-dependent operations outside of the definition of a set. From rdm at rcblue.com Thu Sep 28 21:35:08 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 28 Sep 2006 12:35:08 -0700 Subject: [Tutor] How to get at the list that set() seems to produce? In-Reply-To: <451C1ABD.1090809@tds.net> References: <7.0.1.0.2.20060928105913.06eefc58@rcblue.com> <451C1ABD.1090809@tds.net> Message-ID: <7.0.1.0.2.20060928121330.06f2d7f0@rcblue.com> At 11:55 AM 9/28/2006, Kent Johnson wrote: >Dick Moores wrote: > > I'm very interested in the data type, set. > > > > Python 2.5: > > >>> lst = [9,23,45,9,45,78,23,78] > > >>> set(lst) > > set([9, 45, 78, 23]) > > >>> s = "etywtqyertwytqywetrtwyetrqywetry" > > >>> set(s) > > set(['e', 'q', 'r', 't', 'w', 'y']) > > >>> > > > > I'm wondering if there isn't a way to get at what seems to be the > > list of unique elements set() seems to produce. For example, I would > > think it might be useful if the "list" of set([9, 45, 78, 23]) could > > be extracted, for sorting, taking the mean, etc. > >You just have to ask: (as usual, I'm glad I did :) ) >In [1]: lst = [9,23,45,9,45,78,23,78] > >In [2]: set(lst) >Out[2]: set([9, 45, 78, 23]) > >In [3]: list(set(lst)) >Out[3]: [9, 45, 78, 23] > > > And it might be nice > > if the "list" of set(['e', 'q', 'r', 't', 'w', 'y']) could be > > converted into the sorted string, "eqrtwy". > >In [4]: s = "etywtqyertwytqywetrtwyetrqywetry" > >In [5]: ''.join(sorted(set(s))) >Out[5]: 'eqrtwy' > >The key concept is that a set is iterable - it's not a list, but in >contexts that accept an iterable it will work the same as a list. Got it. Thanks much, Kent. Dick From tiagosaboga at terra.com.br Thu Sep 28 22:57:19 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Thu, 28 Sep 2006 17:57:19 -0300 Subject: [Tutor] importing module with non-standard name In-Reply-To: <451ABA39.1050706@tds.net> References: <200609271434.00237.tiagosaboga@terra.com.br> <451ABA39.1050706@tds.net> Message-ID: <200609281757.20405.tiagosaboga@terra.com.br> Em Quarta 27 Setembro 2006 14:51, Kent Johnson escreveu: > Tiago Saboga wrote: > > Hi! > > > > I'm still playing with man pages parsing, and following advices here, I'm > > using doclifter. But I want to use the installed version on my debian > > system, and not make it a part of my package. The problem is it isn't > > installed as a python module, but rather as an executable file lying in > > /usr/bin, and - there's the problem - with no .py extension. I've > > google'd about it, but I could not found any clear answer. > > > > Any ideas? > > I think either execfile() or imp.load_source() or the suggestions here - > http://tinyurl.com/mnzoo - will do what you want. Great! I'd found this thread before, but in another page, and I couldn't reach the last messages... Thanks, Tiago. From wescpy at gmail.com Fri Sep 29 00:25:01 2006 From: wescpy at gmail.com (wesley chun) Date: Thu, 28 Sep 2006 15:25:01 -0700 Subject: [Tutor] 2.5's new conditional expression syntax In-Reply-To: <7.0.1.0.2.20060928102238.06f35c40@rcblue.com> References: <7.0.1.0.2.20060928102238.06f35c40@rcblue.com> Message-ID: <78b3a9580609281525t66985625u792e22b2f77abd56@mail.gmail.com> On 9/28/06, Dick Moores wrote: > I've been looking hard at 2.5's new conditional expression syntax > (), and didn't > understand the examples there... > : > But it would help to see an example I could understand that also > shows the syntax's usefulness. Could someone cook up one for me? here is an example from "Core Python:" WITHOUT conditional expressions: >>> x = 4 >>> y = 3 >>> if x < y: ... smaller = x ... else: ... smaller = y ... >>> smaller 3 WITH conditional expressions: >>> smaller = x if x < y else y >>> smaller 3 hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From rdm at rcblue.com Fri Sep 29 01:08:49 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 28 Sep 2006 16:08:49 -0700 Subject: [Tutor] 2.5's new conditional expression syntax In-Reply-To: <78b3a9580609281525t66985625u792e22b2f77abd56@mail.gmail.co m> References: <7.0.1.0.2.20060928102238.06f35c40@rcblue.com> <78b3a9580609281525t66985625u792e22b2f77abd56@mail.gmail.com> Message-ID: <7.0.1.0.2.20060928155257.06f4a940@rcblue.com> At 03:25 PM 9/28/2006, wesley chun wrote: >On 9/28/06, Dick Moores wrote: >>I've been looking hard at 2.5's new conditional expression syntax >>(), and didn't >>understand the examples there... >> : >>But it would help to see an example I could understand that also >>shows the syntax's usefulness. Could someone cook up one for me? > >here is an example from "Core Python:" > >WITHOUT conditional expressions: > >>>>x = 4 >>>>y = 3 >>>>if x < y: >... smaller = x >... else: >... smaller = y >... >>>>smaller >3 > >WITH conditional expressions: >>>>smaller = x if x < y else y >>>>smaller >3 > >hope this helps! That's very clear. Thanks, Wesley. And if you wanted to know which is smaller, x or y: x = 8**9 y = 9**8 smaller = "x" if x < y else "y" print smaller, "is smaller" I think I'm getting the hang of it! BTW I'm told your book will arrive on my front porch in a couple of days. I'm looking forward to it! () Dick From paulino1 at sapo.pt Thu Sep 28 22:35:41 2006 From: paulino1 at sapo.pt (Paulino) Date: Thu, 28 Sep 2006 21:35:41 +0100 Subject: [Tutor] e-learning Python In-Reply-To: References: Message-ID: <451C321D.8030303@sapo.pt> Yes I'm looking for something more interactive, but didn't find anything yet. Lerning by one's self has it's limitations... tutor-request at python.org escreveu: > > Message: 1 > Date: Tue, 26 Sep 2006 10:05:56 +0000 (UTC) > From: Andrei > Subject: Re: [Tutor] e-learning Python > To: tutor at python.org > Message-ID: > Content-Type: text/plain; charset=us-ascii > > PA sapo.pt> writes: > > >> Is there any site offering e-learning about Python? >> >> If not, the PSF should do it! >> > > If you mean if there are any online tutorials: lots of them. Here's a very large > list: http://www.awaretek.com/tutorials.html > > Yours, > > Andrei > > > > > > Message: 3 > Date: Tue, 26 Sep 2006 08:47:28 -0700 > From: "Nathan Botts" > Subject: Re: [Tutor] e-learning Python (PA) > To: > Message-ID: <003501c6e183$128f89c0$07e1ad86 at Otto> > Content-Type: text/plain; charset="us-ascii" > > That might depend on what you consider eLearning. I've found that the "How > to Think Like a Computer Scientist" > (http://ibiblio.org/obp/thinkCS/python/english2e/html/index.html) online > book is a great learning guide. Or are you looking for something more > interactive? > > -Nathan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060928/51934b7d/attachment.html From rabidpoobear at gmail.com Fri Sep 29 01:30:04 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 28 Sep 2006 18:30:04 -0500 Subject: [Tutor] revisiting struct module In-Reply-To: <384c93600609281131n1a1d0a7i2129c9fa1a440b82@mail.gmail.com> References: <384c93600609281131n1a1d0a7i2129c9fa1a440b82@mail.gmail.com> Message-ID: <451C5AFC.2050703@gmail.com> shawn bright wrote: > Hey there, > I am writing this because there is something that I am not > understanding about the struct module. Okay, let's see what we can do. > I have to send a message over a socket. The message has to be exactly > 4 bytes, and the last bit has to be the value of 200. Okay, that makes sense. Except you used the term 'last bit'. Do I understand you to mean 'the last part' and not 'the last bit (0/1)'? > so like this: > null,null,null,200 would be the message, and the 200 has to be an > unsigned long int. Hmm, an unsigned long int? Isn't that 4 bytes? Do you mean astr = chr(0)+chr(0)+chr(0)+chr(200) ? I can't really answer your specific question without this information. > > I know the stream of info that I am supposed to send the server is big > endian. > I also know that I should be using the struct.pack(), but I don't know > how to set this up. Basically, if the first 3 elements of the messages are null _characters_ and the 200 is an unsigned long int (which is more than a 4-byte string) formatstr = '>cccL' packedstruct = struct.pack(formatstr,chr(0),chr(0),chr(0),200) Is probably how you'd do it. > > This is actually only part of the message, but I am trying to learn > this as i go. Sounds like a plan. HTH, -Luke From nephish at gmail.com Fri Sep 29 03:27:32 2006 From: nephish at gmail.com (shawn bright) Date: Thu, 28 Sep 2006 20:27:32 -0500 Subject: [Tutor] revisiting struct module In-Reply-To: <451C5AFC.2050703@gmail.com> References: <384c93600609281131n1a1d0a7i2129c9fa1a440b82@mail.gmail.com> <451C5AFC.2050703@gmail.com> Message-ID: <384c93600609281827t5c21078csdf967dd4253f9a13@mail.gmail.com> Luke ! That worked ! Man, if you knew how i have pulled my hair out over this for a while. I did not wind up using the struct at all. I really thought that I was supposed to, but once i made the message with ord. Like ord(0)+ord(0)+ord(0)+ord(200)... it worked. So i guess this means that it doesn't matter if its big endian or not ? anyway, thanks for lots of help, i would have replied sooner, but i was tinkering. -sk On 9/28/06, Luke Paireepinart wrote: > > shawn bright wrote: > > Hey there, > > I am writing this because there is something that I am not > > understanding about the struct module. > Okay, let's see what we can do. > > I have to send a message over a socket. The message has to be exactly > > 4 bytes, and the last bit has to be the value of 200. > Okay, that makes sense. > Except you used the term 'last bit'. Do I understand you to mean 'the > last part' and not 'the last bit (0/1)'? > > so like this: > > null,null,null,200 would be the message, and the 200 has to be an > > unsigned long int. > Hmm, an unsigned long int? Isn't that 4 bytes? > Do you mean > astr = chr(0)+chr(0)+chr(0)+chr(200) > ? > I can't really answer your specific question without this information. > > > > I know the stream of info that I am supposed to send the server is big > > endian. > > I also know that I should be using the struct.pack(), but I don't know > > how to set this up. > Basically, if the first 3 elements of the messages are null _characters_ > and the 200 is an unsigned long int (which is more than a 4-byte string) > formatstr = '>cccL' > packedstruct = struct.pack(formatstr,chr(0),chr(0),chr(0),200) > > Is probably how you'd do it. > > > > This is actually only part of the message, but I am trying to learn > > this as i go. > Sounds like a plan. > HTH, > -Luke > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060928/bfd3c573/attachment-0001.html From rabidpoobear at gmail.com Fri Sep 29 04:49:08 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 28 Sep 2006 21:49:08 -0500 Subject: [Tutor] revisiting struct module In-Reply-To: <384c93600609281827t5c21078csdf967dd4253f9a13@mail.gmail.com> References: <384c93600609281131n1a1d0a7i2129c9fa1a440b82@mail.gmail.com> <451C5AFC.2050703@gmail.com> <384c93600609281827t5c21078csdf967dd4253f9a13@mail.gmail.com> Message-ID: <451C89A4.8020509@gmail.com> shawn bright wrote: > Luke ! > !!!! > That worked ! > Man, if you knew how i have pulled my hair out over this for a while. Well, I don't know how your experience in particular has been, but I know I've had moments like that quite often. That's what the tutor list is for :) > I did not wind up using the struct at all. I really thought that I was > supposed to, but once i made the message with ord. Like > ord(0)+ord(0)+ord(0)+ord(200)... it worked. do you mean chr? ord and chr do opposite things... so ord('a') will be 96 or something, whereas chr(96) will be 'a' Anyway, yeah, this is an easier way to do it if you have short strings. I tried to make an ID3v1.1 tag editor (tags on mp3 files that tell you artist info, etc) without using struct and it was fairly long code. If I'd just used struct it would've been a few lines. > So i guess this means that it doesn't matter if its big endian or not ? hmm... well, endianness is only taken into account if you have things that are more than one byte long. For example, the integer 2882400018 base10 is ABCDEF12 base16. If you were going to store this in a little-endian system (smallest first) it would be stored as 12-EF-CD-AB whereas on a big-endian (biggest first :D ) it would be stored as AB-CD-EF-12 Which is the way that numbers are usually written (in the United States, at least) Keep in mind that 2 hex digits is 1 byte, because 16^2(2 digits in base 16) == 255(1 digit in base 256 ;))== 2^8(8 digits in binary) and you know 8 bits is a byte (usually) and 1 bit is a single binary digit. So don't think that it'd be stored as 21FEDCBA on a little-endian, because every group-of-two hex digits is a single byte. you can't just do 'int(str(number).reverse())' or something :) However, since you're using chr(0) which is hex 00 and chr(200) which is hex C8 well, they're both one-digit long. so 00-00-00-C8 would be chr(0)+chr(0)+chr(0)+chr(200) on both little- and big-endian storage systems. So yes, the endianness does matter if you're not storing single-byte items. you should probably learn how to use struct if you need this functionality. To make this clearer, if it's still confusing, suppose you needed to store a long unsigned integer at the end of this 4-byte string we have. say it's the number AB. On big-endian, this would be stored as (including your previous data) 00-00-00-C8-00-00-00-AB On little-endian, it would be 00-00-00-C8-AB-00-00-00 See, it's not the overall string that has a particular endianness, but actually the specific items you're storing in it. That's why you'd want to use struct.pack(). If you decided you needed to change endianness for something, you wouldn't have to change your code very much at all. Just change the > to a < in the format string you pass to struct.pack() and it'll handle the rest. > > anyway, thanks for lots of help, i would have replied sooner, but i > was tinkering. Sure! I wouldn't want you to stop tinkering just for politeness. we programmers need as few distractions as possible, right? ;) Well, glad that helped, hope that this extra info clears up any confusion you may have. P.S. --- What are you making? :) -Luke From wescpy at gmail.com Fri Sep 29 05:30:19 2006 From: wescpy at gmail.com (wesley chun) Date: Thu, 28 Sep 2006 20:30:19 -0700 Subject: [Tutor] 2.5's new conditional expression syntax In-Reply-To: <7.0.1.0.2.20060928155257.06f4a940@rcblue.com> References: <7.0.1.0.2.20060928102238.06f35c40@rcblue.com> <78b3a9580609281525t66985625u792e22b2f77abd56@mail.gmail.com> <7.0.1.0.2.20060928155257.06f4a940@rcblue.com> Message-ID: <78b3a9580609282030t60ad763fr1a58fd9122f77d0e@mail.gmail.com> > That's very clear. Thanks, Wesley. > And if you wanted to know which is smaller, x or y: > > x = 8**9 > y = 9**8 > smaller = "x" if x < y else "y" > print smaller, "is smaller" > > I think I'm getting the hang of it! your example is correct. if you had a background in C programming, you would recognize the syntax of the "ternary operator:" smaller = x < y ? x : y guido chose Python's syntax... smaller = x if x < y else y ... because "smaller = x" would be the typical case (the conditional expression usually should evaluate to True), and evaluation to False is a special (or inoften) case. if this is true, then the syntax is easier to follow this way. there is some explanation of this in the PEP and CLP threads. > BTW I'm told your book will arrive on my front porch in a couple of > days. I'm looking forward to it! () sigh... i still haven't gotten mine from the publisher yet. i think you'll get yours before i get mine!!! cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From shantanoo at gmail.com Thu Sep 28 20:44:16 2006 From: shantanoo at gmail.com (Shantanoo Mahajan) Date: Fri, 29 Sep 2006 00:14:16 +0530 Subject: [Tutor] getting 'pwd' for XP ? In-Reply-To: <20060928154242.GA6680@madhosh.dhoomketu.net.in> References: <200609281610.20635.pythontut@pusspaws.net> <20060928154242.GA6680@madhosh.dhoomketu.net.in> Message-ID: <20060928184416.GA48645@madhosh.dhoomketu.net.in> +++ Shantanoo Mahajan [28-09-06 21:12 +0530]: | +++ Dave S [28-09-06 16:10 +0100]: | | I currently running XP (like a fish out of water :) and I need to know the dir | | that the python script is executed from. a linux 'pwd' How can I achieve | | this - I have looked in sys & os & os.path but found nothing suitable | | ==================== | Python 2.4.3 (#2, Sep 26 2006, 15:27:42) | [GCC 3.4.4 [FreeBSD] 20050518] on freebsd6 | Type "help", "copyright", "credits" or "license" for more information. | >>> import os | >>> os.getcwd() | '/tmp' | >>> | ==================== And I do not remember exactly whether it will work or not, but you may try 'cd' instead of 'pwd' on windows. I do not have windows machine to test, so cannot confirm whether it works or not. -- Research is what I'm doing when I don't know what I'm doing. ~Wernher von Braun From project5 at redrival.net Fri Sep 29 08:56:33 2006 From: project5 at redrival.net (Andrei) Date: Fri, 29 Sep 2006 06:56:33 +0000 (UTC) Subject: [Tutor] e-learning Python References: <451C321D.8030303@sapo.pt> Message-ID: Paulino sapo.pt> writes: > Yes I'm looking for something more interactive, but didn't find > anything yet. > Lerning by one's self has it's limitations... I don't know of any such course. Probably the closest thing to it is picking a tutorial, work through it on your own and ask on this list when you get stuck/confused - there are many fine tutorials for different knowledge levels, so self-study should get you quite far. People also regularly post small scripts they do while learning and ask for feedback, which is a lot like getting your homework reviewed by a teacher in a more classical approach. Yours, Andrei From jim at well.com Fri Sep 29 15:24:31 2006 From: jim at well.com (jim stockford) Date: Fri, 29 Sep 2006 06:24:31 -0700 Subject: [Tutor] what.built-in Message-ID: from http://docs.python.org/lib/built-in-funcs.html some functions are always available--the built-in functions. (from elsewhere) everything in python is an object. -------------------- hey, from abs() to zip() there's type() and super() and str() and setattr() and ... dir() and... they're the built-ins my question: what.abs() what.zip() etc.? I think there must be a base object, a la java or Nextstep, that supports these functions. what is it? maybe it's not practical, but it's driving me nuts anyway. thanks in advance. From kent37 at tds.net Fri Sep 29 15:44:25 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 29 Sep 2006 09:44:25 -0400 Subject: [Tutor] what.built-in In-Reply-To: References: Message-ID: <451D2339.5010703@tds.net> jim stockford wrote: > from > http://docs.python.org/lib/built-in-funcs.html > some functions are always available--the built-in functions. > > (from elsewhere) everything in python is an object. > > -------------------- > > hey, from abs() to zip() there's type() and super() and str() > and setattr() and ... dir() and... they're the built-ins > > my question: what.abs() what.zip() etc.? > > I think there must be a base object, a la java or Nextstep, > that supports these functions. what is it? > > maybe it's not practical, but it's driving me nuts anyway. > thanks in advance. They are attributes of the __builtins__ module which is searched as the last element of the name search path (local scope, nested scope(s), global (module) scope, __builtins__). In [3]: __builtins__ Out[3]: References: Message-ID: <451D23BD.3000603@gmail.com> jim stockford wrote: > from > http://docs.python.org/lib/built-in-funcs.html > some functions are always available--the built-in functions. > > (from elsewhere) everything in python is an object. > > -------------------- > > hey, from abs() to zip() there's type() and super() and str() > and setattr() and ... dir() and... they're the built-ins > > my question: what.abs() what.zip() etc.? > > I think there must be a base object, a la java or Nextstep, > that supports these functions. what is it? > > maybe it's not practical, but it's driving me nuts anyway. > thanks in advance. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Hi Jim, in Python function are objects also. >>> def test_func(): ... return 1 >>> abs.__class__.__name__ 'builtin_function_or_method' >>> test_func.__class__.__name__ 'function' >>> from types import FunctionType, BuiltinFunctionType >>> isinstance(abs, BuiltinFunctionType) True >>> isinstance(test_func, FunctionType) True Each function is an object. When you call foo() It's actually shorthand for foo.__call__() Try the dir() command - it lists all attributes of an object. For instance: >>> dir(abs) ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__str__'] >>> dir(test_func) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] This means that unlike Java you can pass functions as arguments to other functions/methods - it also means you don't need to wrap everything in a class unnecessarily - in Python you only use a class when you need a class, not because Sun decided that classes were good. ;-) Regards, Liam Clarke From abli at freemail.hu Fri Sep 29 15:54:32 2006 From: abli at freemail.hu (Abel Daniel) Date: Fri, 29 Sep 2006 15:54:32 +0200 Subject: [Tutor] Looking for an edutainment-type introduction to programming book Message-ID: Hi! I'm looking for a book to give to my younger brother as a birthday present. He is 13 years old, had some experience with logo (but not much, so he knows about simple instructions and loops, but not about, say, algorithms), and is fairly comfortable around computers. He sometimes mentions that he would like to learn programming, but so far my only attempt to teach him was an absolute failure, due mostly to my total lack of pedagogical skills. (I tried to start with the concept of abstract objects, with predictable effects...) What I am looking for is a book thats: 1) simple, and fun enough so that he can learn from it without my continous assistence. (Of course, I can answer questions, but the idea is that I don't want to walk him through all of it.) 2) doesn't look like it is teaching programming -- it should be more like "playing with the computer, and having fun" style, with the "learning programming" being a sort of side-effect. Ideally it would use python, but thats not that strict a requirement, squeak or logo might be acceptable, as well. (Although I'm prejudiced towards python, that being my favourite programming language.) Similarly, being a book isn't a requirement either, so a pdf, or an online tutorial would be fine as well, although a book would be better. I tried to search for such books, but I mostly found 'now we are going to learn programming' types, and I would like something more subtle, and more motivating than that. Any suggestions? -- Abel Daniel From tomdrak at gmail.com Fri Sep 29 16:54:43 2006 From: tomdrak at gmail.com (tomd) Date: Fri, 29 Sep 2006 16:54:43 +0200 Subject: [Tutor] Looking for an edutainment-type introduction to programming book In-Reply-To: Message-ID: <2006929165443.248363@oem-up3sjowr2u8> If he is into games, you could try to look at Python Programming for the Absolute Beginner, from Michael Dawson. It teaches Python through programming a set of simple games. -- Tom, http://www.vscripts.net on Fri, 29 Sep 2006 15:54:32 +0200, you wrote: > 1) simple, and fun enough so that he can learn from it without my > continous assistence. (Of course, I can answer questions, but the idea > is that I don't want to walk him through all of it.) > > 2) doesn't look like it is teaching programming -- it should be more > like "playing with the computer, and having fun" style, with the > "learning programming" being a sort of side-effect. From marc_a_poulin at yahoo.com Fri Sep 29 18:07:53 2006 From: marc_a_poulin at yahoo.com (Marc Poulin) Date: Fri, 29 Sep 2006 09:07:53 -0700 (PDT) Subject: [Tutor] Looking for an edutainment-type introduction to programming book In-Reply-To: Message-ID: <20060929160753.33288.qmail@web34101.mail.mud.yahoo.com> Look here: www.ceebot.com Not a book, but it might be what you are looking for. --- Abel Daniel wrote: > > Hi! > > I'm looking for a book to give to my younger brother > as a birthday > present. He is 13 years old, had some experience > with logo (but not > much, so he knows about simple instructions and > loops, but not about, > say, algorithms), and is fairly comfortable around > computers. He > sometimes mentions that he would like to learn > programming, but so far > my only attempt to teach him was an absolute > failure, due mostly to my > total lack of pedagogical skills. (I tried to start > with the concept > of abstract objects, with predictable effects...) > > What I am looking for is a book thats: > > 1) simple, and fun enough so that he can learn from > it without my > continous assistence. (Of course, I can answer > questions, but the idea > is that I don't want to walk him through all of it.) > > 2) doesn't look like it is teaching programming -- > it should be more > like "playing with the computer, and having fun" > style, with the > "learning programming" being a sort of side-effect. > > Ideally it would use python, but thats not that > strict a requirement, > squeak or logo might be acceptable, as well. > (Although I'm prejudiced > towards python, that being my favourite programming > language.) > > Similarly, being a book isn't a requirement either, > so a pdf, or an > online tutorial would be fine as well, although a > book would be > better. > > I tried to search for such books, but I mostly found > 'now we are going > to learn programming' types, and I would like > something more subtle, > and more motivating than that. > > > Any suggestions? > > -- > Abel Daniel > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent37 at tds.net Fri Sep 29 18:16:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 29 Sep 2006 12:16:15 -0400 Subject: [Tutor] Looking for an edutainment-type introduction to programming book In-Reply-To: References: Message-ID: <451D46CF.1000300@tds.net> Abel Daniel wrote: > Hi! > > I'm looking for a book to give to my younger brother as a birthday > present. He is 13 years old, had some experience with logo (but not > much, so he knows about simple instructions and loops, but not about, > say, algorithms), and is fairly comfortable around computers. He > sometimes mentions that he would like to learn programming, but so far > my only attempt to teach him was an absolute failure, due mostly to my > total lack of pedagogical skills. (I tried to start with the concept > of abstract objects, with predictable effects...) I second the suggestion of Python Programming for the absolute beginner, definitely worth a look. Also he might be interested in Guido van Robot: http://gvr.sourceforge.net/ Kent From doug.shawhan at gmail.com Fri Sep 29 20:40:01 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Fri, 29 Sep 2006 13:40:01 -0500 Subject: [Tutor] python text adventures question In-Reply-To: <5e1ceb8a0609181514i3b45cbcdm6506edea639c3993@mail.gmail.com> References: <25C3F98C1CBB1E458E71AA65CAA32E69E5E627@YETI.bolton.ac.uk> <5e1ceb8a0609181512p225ad41eu60409266d5c3322d@mail.gmail.com> <5e1ceb8a0609181514i3b45cbcdm6506edea639c3993@mail.gmail.com> Message-ID: <5e1ceb8a0609291140pbf5a02ra40352a3643c7043@mail.gmail.com> I got a copy of Creating Adventure Games on Your Computer in the mail yesterday. Very fun! I set up a moodle class for the project. It seems like a good way to do such a thing. http://crackrabbit.com/moodle/ I realize that I am probably not anyone's idea of a programming howto writer, but hey! I had the space and it looks like a lot of fun. Code snippets will go under the WikiWiki and may be linked to from anywhere. Moodle is pretty neat, despite being written in PHP (WackaWacka). Anyway, sign up if you like the idea and I'll give you instructor ops. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060929/d2e11a9c/attachment.html From rabidpoobear at gmail.com Fri Sep 29 21:10:32 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 29 Sep 2006 14:10:32 -0500 Subject: [Tutor] python text adventures question In-Reply-To: <5e1ceb8a0609291140pbf5a02ra40352a3643c7043@mail.gmail.com> References: <25C3F98C1CBB1E458E71AA65CAA32E69E5E627@YETI.bolton.ac.uk> <5e1ceb8a0609181512p225ad41eu60409266d5c3322d@mail.gmail.com> <5e1ceb8a0609181514i3b45cbcdm6506edea639c3993@mail.gmail.com> <5e1ceb8a0609291140pbf5a02ra40352a3643c7043@mail.gmail.com> Message-ID: <451D6FA8.4000809@gmail.com> doug shawhan wrote: > I got a copy of Creating Adventure Games on Your Computer in the mail > yesterday. > > Very fun! I set up a moodle class for the project. It seems like a > good way to do such a thing. > > http://crackrabbit.com/moodle/ > > I realize that I am probably not anyone's idea of a programming howto > writer, but hey! I had the space and it looks like a lot of fun. > > Code snippets will go under the WikiWiki and may be linked to from > anywhere. Moodle is pretty neat, despite being written in PHP > (WackaWacka). > > Anyway, sign up if you like the idea and I'll give you instructor ops. I don't get it. What's the password? starts with a? password.startswith('a') == True? >_> Can you private e-mail me the password so I can see this? > > Thanks! From doug.shawhan at gmail.com Fri Sep 29 21:51:06 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Fri, 29 Sep 2006 14:51:06 -0500 Subject: [Tutor] python text adventures question In-Reply-To: <451D6FA8.4000809@gmail.com> References: <25C3F98C1CBB1E458E71AA65CAA32E69E5E627@YETI.bolton.ac.uk> <5e1ceb8a0609181512p225ad41eu60409266d5c3322d@mail.gmail.com> <5e1ceb8a0609181514i3b45cbcdm6506edea639c3993@mail.gmail.com> <5e1ceb8a0609291140pbf5a02ra40352a3643c7043@mail.gmail.com> <451D6FA8.4000809@gmail.com> Message-ID: <5e1ceb8a0609291251t633e33d6hb2223043d5ed1fb4@mail.gmail.com> Whoops, the password is 'ascii'. :-) Guess I could just take that off, couldn't I? On 9/29/06, Luke Paireepinart wrote: > > doug shawhan wrote: > > I got a copy of Creating Adventure Games on Your Computer in the mail > > yesterday. > > > > Very fun! I set up a moodle class for the project. It seems like a > > good way to do such a thing. > > > > http://crackrabbit.com/moodle/ > > > > I realize that I am probably not anyone's idea of a programming howto > > writer, but hey! I had the space and it looks like a lot of fun. > > > > Code snippets will go under the WikiWiki and may be linked to from > > anywhere. Moodle is pretty neat, despite being written in PHP > > (WackaWacka). > > > > Anyway, sign up if you like the idea and I'll give you instructor ops. > I don't get it. > What's the password? > starts with a? > password.startswith('a') == True? > >_> > Can you private e-mail me the password so I can see this? > > > > > Thanks! > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060929/a6ae2c91/attachment.htm From allison.william at comcast.net Sat Sep 30 00:55:45 2006 From: allison.william at comcast.net (William Allison) Date: Fri, 29 Sep 2006 18:55:45 -0400 Subject: [Tutor] Better way to substitute text? Message-ID: <451DA471.5080700@comcast.net> Hi, Just learning Python, on chapter 6 of Learning Python 2nd Ed. So, on to the question. Is there a better way to implement the code below? It scans a saved html file and highlights certain keywords is a bold, red font. It works, but I suppose I'm wondering if it's the "Pythonic" way. Thanks, Will #!/usr/bin/env python in_put = open('test.html', 'r') out_put = open('test_highlight.html', 'a') for line in in_put: line = line.replace("TWY", "TWY") line = line.replace("RWY", "RWY") line = line.replace("WIP", "WIP") out_put.write(line) in_put.close() out_put.close() From dyoo at hkn.eecs.berkeley.edu Sat Sep 30 08:13:39 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 29 Sep 2006 23:13:39 -0700 (PDT) Subject: [Tutor] Looking for an edutainment-type introduction to programming book In-Reply-To: References: Message-ID: > What I am looking for is a book thats: > > 1) simple, and fun enough so that he can learn from it without my > continous assistence. (Of course, I can answer questions, but the idea > is that I don't want to walk him through all of it.) > > 2) doesn't look like it is teaching programming -- it should be more > like "playing with the computer, and having fun" style, with the > "learning programming" being a sort of side-effect. Hi Abel, Under those restrictions, you may want to look at John Maeda's "Design by Numbers" book: http://dbn.media.mit.edu/whatisdbn.html http://dbn.media.mit.edu/ It's not Python, but it does seem interesting. The book itself is a great coffee table book, filled with lots of fascinating pictures. Frankly, it's probably not going to teach many general programming concepts, but it does give a sense of computation, and, of course, it's pretty. From rdm at rcblue.com Sat Sep 30 11:19:26 2006 From: rdm at rcblue.com (Dick Moores) Date: Sat, 30 Sep 2006 02:19:26 -0700 Subject: [Tutor] Looking for an edutainment-type introduction to programming book In-Reply-To: <451D46CF.1000300@tds.net> References: <451D46CF.1000300@tds.net> Message-ID: <7.0.1.0.2.20060930020956.0536eed8@rcblue.com> At 09:16 AM 9/29/2006, Kent Johnson wrote: >I second the suggestion of Python Programming for the absolute beginner, >definitely worth a look. Me, too, but make sure it's the 2nd edition. Dick From rdm at rcblue.com Sat Sep 30 12:09:50 2006 From: rdm at rcblue.com (Dick Moores) Date: Sat, 30 Sep 2006 03:09:50 -0700 Subject: [Tutor] Puzzled by print lst.sort() Message-ID: <7.0.1.0.2.20060930030312.07015bb8@rcblue.com> >>> lst = [5,3,7,6,2] >>> lst.sort() >>> lst [2, 3, 5, 6, 7] >>> lst = [5,3,7,6,2] >>> print lst.sort() None >>> lst [2, 3, 5, 6, 7] I'm wondering why "print lst.sort()" doesn't print the newly sorted list, but instead prints "None". In fact, the sorting has taken place because of "print lst.sort()". Is this behavior a Good Thing in Python? Dick From ml.cyresse at gmail.com Sat Sep 30 12:22:16 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 30 Sep 2006 22:22:16 +1200 Subject: [Tutor] Puzzled by print lst.sort() In-Reply-To: <7.0.1.0.2.20060930030312.07015bb8@rcblue.com> References: <7.0.1.0.2.20060930030312.07015bb8@rcblue.com> Message-ID: <451E4558.3000101@gmail.com> Dick Moores wrote: > >>> lst = [5,3,7,6,2] > >>> lst.sort() > >>> lst > [2, 3, 5, 6, 7] > >>> lst = [5,3,7,6,2] > >>> print lst.sort() > None > >>> lst > [2, 3, 5, 6, 7] > > I'm wondering why "print lst.sort()" doesn't print the newly sorted > list, but instead prints "None". In fact, the sorting has taken place > because of "print lst.sort()". Is this behavior a Good Thing in Python? > > Dick > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Hi Dick, A Python list sort is destructive, as you can see - it has modified lst. So, to emphasise that it is destructive, it returns None. You'll find this in most destructive methods and functions in Python. However, as of Python 2.4, there's a new built-in function that has the functionality you want: >>> x = [3,1,2] >>> y = sorted(x) >>> print y [1, 2, 3] >>> print x [3, 1, 2] You'll note that sorted() is *not *destructive - that is, x is not modified. Regards, Liam Clarke -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060930/1a19d582/attachment.html From reni.abraham at hccs.edu Fri Sep 29 21:01:53 2006 From: reni.abraham at hccs.edu (RENI ABRAHAM) Date: Fri, 29 Sep 2006 13:01:53 -0600 (GMT-06:00) Subject: [Tutor] Python Instructor Message-ID: <31139135.1159556513311.JavaMail.oracle@laredo> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060929/6f43a4bb/attachment.html From kent37 at tds.net Sat Sep 30 13:45:16 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 30 Sep 2006 07:45:16 -0400 Subject: [Tutor] Better way to substitute text? In-Reply-To: <451DA471.5080700@comcast.net> References: <451DA471.5080700@comcast.net> Message-ID: <451E58CC.9050207@tds.net> William Allison wrote: > Hi, > Just learning Python, on chapter 6 of Learning Python 2nd Ed. So, on to > the question. Is there a better way to > implement the code below? It scans a saved html file and highlights > certain keywords is a bold, red font. It works, > but I suppose I'm wondering if it's the "Pythonic" way. > Thanks, > Will > > #!/usr/bin/env python > > in_put = open('test.html', 'r') > out_put = open('test_highlight.html', 'a') > > for line in in_put: > line = line.replace("TWY", " color='#FF0000'>TWY") > line = line.replace("RWY", " color='#FF0000'>RWY") > line = line.replace("WIP", " color='#FF0000'>WIP") > out_put.write(line) > > in_put.close() > out_put.close() There is no need to process the file a line at a time unless it is too big to fit in memory. I would read it all at once: in_put = open('test.html', 'r') data = in_put.read() in_put.close() data = data.replace("TWY", "TWY") data = data.replace("RWY", "RWY") data = data.replace("WIP", "WIP") out_put = open('test_highlight.html', 'a') out_put.write(data) out_put.close() Since the replacements are so similar, you could do all three with a single regular expression replace: import re data = re.sub('TWY|RWY|WIP', r"\0", data) I don't see a strong reason to prefer any one of these; my preference is for the last because it is short and doesn't repeat the substitution text. Kent From kent37 at tds.net Sat Sep 30 13:46:55 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 30 Sep 2006 07:46:55 -0400 Subject: [Tutor] Python Instructor In-Reply-To: <31139135.1159556513311.JavaMail.oracle@laredo> References: <31139135.1159556513311.JavaMail.oracle@laredo> Message-ID: <451E592F.8020207@tds.net> RENI ABRAHAM wrote: > Hello, > > My name is Reni Abraham and am the department chair for DIgital Gaming > and Simualtion at Houston Community College. I am looking for a Python > instructor, ASAP. If you know anyone that can and insterested in > teaching Python, please send me their contact information. You might also want to post this to the Python job board and comp.lang.python. http://www.python.org/community/jobs/ Kent From rdm at rcblue.com Sat Sep 30 13:52:52 2006 From: rdm at rcblue.com (Dick Moores) Date: Sat, 30 Sep 2006 04:52:52 -0700 Subject: [Tutor] Puzzled by print lst.sort() In-Reply-To: <451E4558.3000101@gmail.com> References: <7.0.1.0.2.20060930030312.07015bb8@rcblue.com> <451E4558.3000101@gmail.com> Message-ID: <7.0.1.0.2.20060930044209.06497910@rcblue.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060930/bb5252ae/attachment.htm From ml.cyresse at gmail.com Sat Sep 30 14:07:42 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 01 Oct 2006 00:07:42 +1200 Subject: [Tutor] Puzzled by print lst.sort() In-Reply-To: <7.0.1.0.2.20060930044209.06497910@rcblue.com> References: <7.0.1.0.2.20060930030312.07015bb8@rcblue.com> <451E4558.3000101@gmail.com> <7.0.1.0.2.20060930044209.06497910@rcblue.com> Message-ID: <451E5E0E.2000002@gmail.com> Dick Moores wrote: > At 03:22 AM 9/30/2006, Liam Clarke wrote: >> Dick Moores wrote: >>> >>> >>> lst = [5,3,7,6,2] >>> >>> lst.sort() >>> >>> lst >>> [2, 3, 5, 6, 7] >>> >>> lst = [5,3,7,6,2] >>> >>> print lst.sort() >>> None >>> >>> lst >>> [2, 3, 5, 6, 7] >>> >>> I'm wondering why "print lst.sort()" doesn't print the newly >>> sorted >>> list, but instead prints "None". In fact, the sorting has taken >>> place >>> because of "print lst.sort()". Is this behavior a Good Thing in >>> Python? >>> >>> Dick >>> >>> _______________________________________________ >>> Tutor maillist - >>> Tutor at python.org >>> >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> Hi Dick, >> >> A Python list sort is destructive, as you can see - it has modified >> lst. So, to emphasise that it is destructive, it returns None. You'll >> find this in most destructive methods and functions in Python. > > OK, but returning the new list would seem to make more sense. Is the > reason sort() doesn't, really only that it is better to emphasize that > it is destructive? Hi Dick, According to the guy who runs Python, yup. Got to remember the downside to destructive functions is that everything in Python is a reference. For example: >>> a = [3,2,1] >>> b = a >>> b.sort() >>> print a [1, 2, 3] If you could use y = x.sort() to get a copy of the sorted list, you'd find that subtle bugs would appear and frustrate you. In functional languages like Common Lisp or Scheme, destructive functions are very clearly marked as such, (in Scheme, they use exclamation marks - (sort! x) to indicate a destructive version of (sort x).) as a key part of the functional paradigm is reducing side effects. I believe sorting in place has performance advantages too. It's covered in the official FAQ: http://www.python.org/doc/faq/general/#why-doesn-t-list-sort-return-the-sorted-list Regards, Liam Clarke >> However, as of Python 2.4, there's a new built-in function that has >> the functionality you want: >> >> >>> x = [3,1,2] >> >>> y = sorted(x) >> >>> print y >> [1, 2, 3] >> >>> print x >> [3, 1, 2] >> >> You'll note that sorted() is *not *destructive - that is, x is not >> modified. > > Didn't know about sorted(). Thanks, Liam. > > Dick > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ml.cyresse at gmail.com Sat Sep 30 14:08:37 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 01 Oct 2006 00:08:37 +1200 Subject: [Tutor] Puzzled by print lst.sort() In-Reply-To: <7.0.1.0.2.20060930044209.06497910@rcblue.com> References: <7.0.1.0.2.20060930030312.07015bb8@rcblue.com> <451E4558.3000101@gmail.com> <7.0.1.0.2.20060930044209.06497910@rcblue.com> Message-ID: <451E5E45.5000603@gmail.com> Dick Moores wrote: > At 03:22 AM 9/30/2006, Liam Clarke wrote: >> Dick Moores wrote: >>> >>> >>> lst = [5,3,7,6,2] >>> >>> lst.sort() >>> >>> lst >>> [2, 3, 5, 6, 7] >>> >>> lst = [5,3,7,6,2] >>> >>> print lst.sort() >>> None >>> >>> lst >>> [2, 3, 5, 6, 7] >>> >>> I'm wondering why "print lst.sort()" doesn't print the newly >>> sorted >>> list, but instead prints "None". In fact, the sorting has taken >>> place >>> because of "print lst.sort()". Is this behavior a Good Thing in >>> Python? >>> >>> Dick >>> >>> _______________________________________________ >>> Tutor maillist - >>> Tutor at python.org >>> >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> Hi Dick, >> >> A Python list sort is destructive, as you can see - it has modified >> lst. So, to emphasise that it is destructive, it returns None. You'll >> find this in most destructive methods and functions in Python. > > OK, but returning the new list would seem to make more sense. Is the > reason sort() doesn't, really only that it is better to emphasize that > it is destructive? > >> However, as of Python 2.4, there's a new built-in function that has >> the functionality you want: >> >> >>> x = [3,1,2] >> >>> y = sorted(x) >> >>> print y >> [1, 2, 3] >> >>> print x >> [3, 1, 2] >> >> You'll note that sorted() is *not *destructive - that is, x is not >> modified. > > Didn't know about sorted(). Thanks, Liam. > > Dick > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Oh, and PS - you'll find that list.reverse() also returns None. From shantanoo at gmail.com Sat Sep 30 08:45:21 2006 From: shantanoo at gmail.com (Shantanoo Mahajan) Date: Sat, 30 Sep 2006 12:15:21 +0530 Subject: [Tutor] Better way to substitute text? In-Reply-To: <451DA471.5080700@comcast.net> References: <451DA471.5080700@comcast.net> Message-ID: <20060930064521.GA1309@madhosh.dhoomketu.net.in> +++ William Allison [29-09-06 18:55 -0400]: | Hi, | Just learning Python, on chapter 6 of Learning Python 2nd Ed. So, on to | the question. Is there a better way to | implement the code below? It scans a saved html file and highlights | certain keywords is a bold, red font. It works, | but I suppose I'm wondering if it's the "Pythonic" way. | Thanks, | Will | | #!/usr/bin/env python | | in_put = open('test.html', 'r') | out_put = open('test_highlight.html', 'a') ===================================== | for line in in_put: | line = line.replace("TWY", "TWY") | line = line.replace("RWY", "RWY") | line = line.replace("WIP", "WIP") | out_put.write(line) ===================================== | | in_put.close() | out_put.close() replace_words = ['TWY', 'RWY', 'WIP'] for line in in_put: for replace_word in replace_words: out_put.write(line.replace(replace_word,""+replace_word+"")) You can furthur reduce for loops. Shantanoo -- Always have an answer to the question, "What would I do if I lost my job tomorrow?" From allison.william at comcast.net Sat Sep 30 16:10:02 2006 From: allison.william at comcast.net (William Allison) Date: Sat, 30 Sep 2006 10:10:02 -0400 Subject: [Tutor] Better way to substitute text? In-Reply-To: <20060930064521.GA1309@madhosh.dhoomketu.net.in> References: <451DA471.5080700@comcast.net> <20060930064521.GA1309@madhosh.dhoomketu.net.in> Message-ID: <451E7ABA.4060909@comcast.net> Shantanoo Mahajan wrote: > +++ William Allison [29-09-06 18:55 -0400]: > | Hi, > | Just learning Python, on chapter 6 of Learning Python 2nd Ed. So, on to > | the question. Is there a better way to > | implement the code below? It scans a saved html file and highlights > | certain keywords is a bold, red font. It works, > | but I suppose I'm wondering if it's the "Pythonic" way. > | Thanks, > | Will > | > | #!/usr/bin/env python > | > | in_put = open('test.html', 'r') > | out_put = open('test_highlight.html', 'a') > > ===================================== > | for line in in_put: > | line = line.replace("TWY", " | color='#FF0000'>TWY") > | line = line.replace("RWY", " | color='#FF0000'>RWY") > | line = line.replace("WIP", " | color='#FF0000'>WIP") > | out_put.write(line) > ===================================== > | > | in_put.close() > | out_put.close() > > > replace_words = ['TWY', 'RWY', 'WIP'] > for line in in_put: > for replace_word in replace_words: > out_put.write(line.replace(replace_word,""+replace_word+"")) > > You can furthur reduce for loops. > > Shantanoo > Thanks Shantanoo, I like that a lot better. Had to modify it just a little. replace_words = ['TWY', 'RWY', 'WIP'] for line in in_put: for replace_word in replace_words: line = line.replace(replace_word, "" + replace_word + "") out_put.write(line) I can never quite get when to use a nested loop. Thanks again, Will From David.Heiser at intelliden.com Sat Sep 30 17:40:17 2006 From: David.Heiser at intelliden.com (David Heiser) Date: Sat, 30 Sep 2006 09:40:17 -0600 Subject: [Tutor] Better way to substitute text? Message-ID: You can make it simpler by not splitting the input file into lines. Treat it as a single string. in_put = open('test.html', 'r').read() replace_words = ['TWY', 'RWY', 'WIP'] for replace_word in replace_words: in_put = in_put.replace(replace_word, "" + replace_word + "") open('test_highlight.html', 'a').write(in_put) -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of William Allison Sent: Saturday, September 30, 2006 8:10 AM To: tutor at python.org Subject: Re: [Tutor] Better way to substitute text? Shantanoo Mahajan wrote: > +++ William Allison [29-09-06 18:55 -0400]: > | Hi, > | Just learning Python, on chapter 6 of Learning Python 2nd Ed. So, > | on to > | the question. Is there a better way to > | implement the code below? It scans a saved html file and highlights > | certain keywords is a bold, red font. It works, > | but I suppose I'm wondering if it's the "Pythonic" way. > | Thanks, > | Will > | > | #!/usr/bin/env python > | > | in_put = open('test.html', 'r') > | out_put = open('test_highlight.html', 'a') > > ===================================== > | for line in in_put: > | line = line.replace("TWY", " | color='#FF0000'>TWY") > | line = line.replace("RWY", " | color='#FF0000'>RWY") > | line = line.replace("WIP", " | color='#FF0000'>WIP") > | out_put.write(line) > ===================================== > | > | in_put.close() > | out_put.close() > > > replace_words = ['TWY', 'RWY', 'WIP'] > for line in in_put: > for replace_word in replace_words: > out_put.write(line.replace(replace_word," color='#FF0000'>"+replace_word+"")) > > You can furthur reduce for loops. > > Shantanoo > Thanks Shantanoo, I like that a lot better. Had to modify it just a little. replace_words = ['TWY', 'RWY', 'WIP'] for line in in_put: for replace_word in replace_words: line = line.replace(replace_word, "" + replace_word + "") out_put.write(line) I can never quite get when to use a nested loop. Thanks again, Will _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From rdm at rcblue.com Sat Sep 30 19:47:26 2006 From: rdm at rcblue.com (Dick Moores) Date: Sat, 30 Sep 2006 10:47:26 -0700 Subject: [Tutor] Puzzled by print lst.sort() In-Reply-To: <451E5E0E.2000002@gmail.com> References: <7.0.1.0.2.20060930030312.07015bb8@rcblue.com> <451E4558.3000101@gmail.com> <7.0.1.0.2.20060930044209.06497910@rcblue.com> <451E5E0E.2000002@gmail.com> Message-ID: <7.0.1.0.2.20060930104527.06b19950@rcblue.com> At 05:07 AM 9/30/2006, Liam Clarke wrote: >Dick Moores wrote: > > At 03:22 AM 9/30/2006, Liam Clarke wrote: > >> Dick Moores wrote: > >> A Python list sort is destructive, as you can see - it has modified > >> lst. So, to emphasise that it is destructive, it returns None. You'll > >> find this in most destructive methods and functions in Python. > > > > OK, but returning the new list would seem to make more sense. Is the > > reason sort() doesn't, really only that it is better to emphasize that > > it is destructive? > >Hi Dick, > >According to the guy who runs Python, yup. Got to remember the downside >to destructive functions is that everything in Python is a reference. >For example: > > >>> a = [3,2,1] > >>> b = a > >>> b.sort() > >>> print a >[1, 2, 3] > >If you could use > >y = x.sort() > >to get a copy of the sorted list, you'd find that subtle bugs would >appear and frustrate you. In functional languages like Common Lisp or >Scheme, destructive functions are very clearly marked as such, (in >Scheme, they use exclamation marks - (sort! x) to indicate a destructive >version of (sort x).) as a key part of the functional paradigm is >reducing side effects. > >I believe sorting in place has performance advantages too. > >It's covered in the official FAQ: > >http://www.python.org/doc/faq/general/#why-doesn-t-list-sort-return-the-sorted-list Thanks for the further enlightenment, Liam. Dick From shantanoo at gmail.com Sat Sep 30 22:37:24 2006 From: shantanoo at gmail.com (Shantanoo Mahajan) Date: Sun, 1 Oct 2006 02:07:24 +0530 Subject: [Tutor] Puzzled by print lst.sort() In-Reply-To: <7.0.1.0.2.20060930104527.06b19950@rcblue.com> References: <7.0.1.0.2.20060930030312.07015bb8@rcblue.com> <451E4558.3000101@gmail.com> <7.0.1.0.2.20060930044209.06497910@rcblue.com> <451E5E0E.2000002@gmail.com> <7.0.1.0.2.20060930104527.06b19950@rcblue.com> Message-ID: <20060930203724.GB1458@madhosh.dhoomketu.net.in> +++ Dick Moores [30-09-06 10:47 -0700]: | At 05:07 AM 9/30/2006, Liam Clarke wrote: | >Dick Moores wrote: | > > At 03:22 AM 9/30/2006, Liam Clarke wrote: | > >> Dick Moores wrote: | | > >> A Python list sort is destructive, as you can see - it has modified | > >> lst. So, to emphasise that it is destructive, it returns None. You'll | > >> find this in most destructive methods and functions in Python. | > > | > > OK, but returning the new list would seem to make more sense. Is the | > > reason sort() doesn't, really only that it is better to emphasize that | > > it is destructive? | > | >Hi Dick, | > | >According to the guy who runs Python, yup. Got to remember the downside | >to destructive functions is that everything in Python is a reference. | >For example: | > | > >>> a = [3,2,1] | > >>> b = a | > >>> b.sort() | > >>> print a | >[1, 2, 3] | > | >If you could use | > | >y = x.sort() | > | >to get a copy of the sorted list, you'd find that subtle bugs would | >appear and frustrate you. In functional languages like Common Lisp or | >Scheme, destructive functions are very clearly marked as such, (in | >Scheme, they use exclamation marks - (sort! x) to indicate a destructive | >version of (sort x).) as a key part of the functional paradigm is | >reducing side effects. | > | >I believe sorting in place has performance advantages too. | > | >It's covered in the official FAQ: | > | >http://www.python.org/doc/faq/general/#why-doesn-t-list-sort-return-the-sorted-list | | Thanks for the further enlightenment, Liam. Maybe following is helpful: >>> a=[3,2,1] >>> b=a[:] >>> b.sort() >>> c=sorted(a) >>> print a,b,c >>> [3, 2, 1] [1, 2, 3] [1, 2, 3] >>> Shantanoo -- The world we have created is a product of our thinking; it cannot be changed without changing our thinking. ~Albert Einstein From allison.william at comcast.net Sat Sep 30 23:12:31 2006 From: allison.william at comcast.net (William Allison) Date: Sat, 30 Sep 2006 17:12:31 -0400 Subject: [Tutor] Better way to substitute text? In-Reply-To: References: Message-ID: <451EDDBF.4010805@comcast.net> Thanks David, I like that better than my original. I'll remember to NOT split the input file into lines in the future. Will David Heiser wrote: > You can make it simpler by not splitting the input file into lines. > Treat it as a single string. > > in_put = open('test.html', 'r').read() > > replace_words = ['TWY', 'RWY', 'WIP'] > for replace_word in replace_words: > in_put = in_put.replace(replace_word, " color='#FF0000'>" + replace_word + "") > > open('test_highlight.html', 'a').write(in_put) > > > > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On > Behalf Of William Allison > Sent: Saturday, September 30, 2006 8:10 AM > To: tutor at python.org > Subject: Re: [Tutor] Better way to substitute text? > > > Shantanoo Mahajan wrote: > >> +++ William Allison [29-09-06 18:55 -0400]: >> | Hi, >> | Just learning Python, on chapter 6 of Learning Python 2nd Ed. So, >> | on to >> | the question. Is there a better way to >> | implement the code below? It scans a saved html file and highlights >> > > >> | certain keywords is a bold, red font. It works, >> | but I suppose I'm wondering if it's the "Pythonic" way. >> | Thanks, >> | Will >> | >> | #!/usr/bin/env python >> | >> | in_put = open('test.html', 'r') >> | out_put = open('test_highlight.html', 'a') >> >> ===================================== >> | for line in in_put: >> | line = line.replace("TWY", "> | color='#FF0000'>TWY") >> | line = line.replace("RWY", "> | color='#FF0000'>RWY") >> | line = line.replace("WIP", "> | color='#FF0000'>WIP") >> | out_put.write(line) >> ===================================== >> | >> | in_put.close() >> | out_put.close() >> >> >> replace_words = ['TWY', 'RWY', 'WIP'] >> for line in in_put: >> for replace_word in replace_words: >> out_put.write(line.replace(replace_word,"> color='#FF0000'>"+replace_word+"")) >> >> You can furthur reduce for loops. >> >> Shantanoo >> >> > > Thanks Shantanoo, > I like that a lot better. Had to modify it just a little. > > replace_words = ['TWY', 'RWY', 'WIP'] > for line in in_put: > for replace_word in replace_words: > line = line.replace(replace_word, " color='#FF0000'>" + replace_word + "") > out_put.write(line) > > I can never quite get when to use a nested loop. > Thanks again, > Will > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From Daudet1 at aol.com Sat Sep 30 23:13:13 2006 From: Daudet1 at aol.com (Daudet1 at aol.com) Date: Sat, 30 Sep 2006 17:13:13 EDT Subject: [Tutor] Re: Monte Carlo method modules & references Message-ID: <581.60dfd21.325037e9@aol.com> Tutor, I am searching for monte carlo and two- person game, also monte carlo statistical ampling distribution. Thanks. Regards, William Baptiste eMail: daudet1 at aol.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060930/99e3245b/attachment.htm