Re: [Tutor] Encoding
Giorgio wrote: i am looking for more informations about encoding in python: i've read that Amazon SimpleDB accepts every string encoded in UTF-8. How can I encode a string? And, what's the default string encoding in python? I think the safest way is to use unicode strings in your application and convert them to byte strings if needed, using the encode and decode methods. the other question is about mysql DB: if i have a mysql field latin1 and extract his content in a python script, how can I handle it? if you have a byte string s encoded in 'latin1' you can simply call: s.decode('latin1') to get the unicode string. thankyou Giorgio Patrick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Encoding
Mmm ok. So all strings in the app are unicode by default? Depends on your python version. If you use python 2.x, you have to use a u before the string: s = u'Hallo World' Do you know if there is a function/method i can use to check encoding of a string? AFAIK such a function doesn't exist. Python3 solves this by using unicode strings by default. Patrick, ok. I should check if it's possible to save unicode strings in the DB. It is more an issue of your database adapter, than of your database. Do you think i'd better set my db to utf8? I don't need latin1, it's just the default value. I think the encoding of the db doesn't matter much in this case, but I would prefer utf-8 over latin-1. If you get an utf-8 encoded raw byte string you call .decode('utf-8'). In case of an latin-1 encoded string you call .decode('latin1') Thankyou Giorgio - Patrick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Encoding
Giorgio wrote: Depends on your python version. If you use python 2.x, you have to use a u before the string: s = u'Hallo World' Ok. So, let's go back to my first question: s = u'Hallo World' is unicode in python 2.x -> ok s = 'Hallo World' how is encoded? I am not 100% sure, but I think it depends on the encoding of your source file or the coding you specify. See PEP 263 http://www.python.org/dev/peps/pep-0263/ Well, the problem comes, i.e when i'm getting a string from an HTML form with POST. I don't and can't know the encoding, right? It depends on browser. Right, but you can do something about it. Tell the browser, which encoding you are going to accept: ... - Patrick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Resetting the namespace
I found this piece of code, which completely puzzles me, in the pdb module of the trunk: class Pdb(bdb.Bdb, cmd.Cmd): ... def _runscript(self, filename): # The script has to run in __main__ namespace (or imports from # __main__ will break). # # So we clear up the __main__ and set several special variables # (this gets rid of pdb's globals and cleans old variables on # restarts). import __main__ __main__.__dict__.clear() __main__.__dict__.update({"__name__": "__main__", "__file__": filename, "__builtins__": __builtins__, }) The intention of this code is to reset the namespace, before executing a script. When I try to do something similar, i.e. __main__.__dict__.clear(), I loose the __builtins__ variable in the namespace, e.g.: >>> import __main__ >>> print __builtins__ >>> __main__.__dict__.clear() >>> print __builtins__ Traceback (most recent call last): File "", line 1, in NameError: name '__builtins__' is not defined But for some reason the code mentioned above actually works in the case of pdb. Any ideas why? - Patrick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Declaring methods in modules.
ipAddress = "123.123.123.123" emails = ipAddress.GetEmailAddresses() Not exactly sure, what you want, but maybe something like this? class mystr(str): def GetEmailAddresses(self): return [str(self)] ipAddress = mystr("123.123.123.123") emails = ipAddress.GetEmailAddresses() - Patrick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sequences of letter
So far this is what I have: letras = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","x","y","z"] letra1 = 0 letra2 = 0 letra3 = 0 for i in letras: for j in letras: for k in letras: print letras[letra1]+letras[letra2]+letras[letra3] letra3=letra3+1 letra2=letra2+1 letra1=letra1+1 It goes all the way to aaz and then it gives me this error Traceback (most recent call last): File "/home/administrador/programacion/python/letras2.py", line 8, in print letras[letra1]+letras[letra2]+letras[letra3] IndexError: list index out of range You should consider resetting the letra-variables before each loop (not before every loop). - Patrick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pygtk
The official docs http://www.pygtk.org/pygtk2tutorial/index.html http://library.gnome.org/devel/pygtk/stable/ worked for me. - Patrick Ajith Gopinath schrieb: I will appreciate , if somebody guides me to a proper doc. on pygtk for 2.5/2.6. I am currently unable to find a good doc for the same :o( Thanks and regards ~|| a j i t || ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] include remote module
Maybe something like this helps you to solve your problem: # get code via http, etc. code = """ def blah(): print 'blah' print 'hello' blah() """ compiled_code = compile(code, 'filename', 'exec') exec(compiled_code) This way you could execute some code from a web client, but the client would be able to execute any code, he could even delete your hard drive. - Patrick Patrick schrieb: Hi Wayne Thanks for your help. I was thinking of the latter but now that I think of it, once you import a module it won't help to modify that module on the fly later anyways, right? I would need to re-import it. Sounds like reading it via http would be simpler. Thanks again-Patrick Wayne wrote: On Sat, Sep 12, 2009 at 7:55 AM, Patrick mailto:optoma...@rogers.com>> wrote: Strange question. Is it possible to include a module that is on another computer? I have been day-dreaming about a project that would allow web code to drive a desktop App. I know of one way, using sshfs, which allows you to mount an ssh location as a directory on your computer. Then it would effectively be a local filesystem. I don't know if there's something like that on Windows. Of course, what do you mean when you say "web code to drive a desktop app"? Do you mean you want to host some code that others can connect to that will change? Or do you mean you want people to connect to your server and it will run an app on your desktop? For the former it's not really necessary to include the mod on another computer. Just use the http libraries and download the file when the script runs. Then import it. HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sorting 2-d data
> But for sorting the list with the first element as key, I tried it using just mylist.sort() without the lambda, and its working also. Then why use the lambda? There is a little difference between those two variations. Example: >>> sorted([[1,2],[1,3],[1,1]]) [[1, 1], [1, 2], [1, 3]] >>> sorted([[1,2],[1,3],[1,1]], key=lambda x:x[0]) [[1, 2], [1, 3], [1, 1]] For sorting it is necessary to compare items. So for example [1,1] is compared to [1,2] As you see: >>> [1,1] < [1,2] True If you apply the lambda things change: >>> (lambda x: x[0])([1,1])<(lambda x:x[0])([1,2]) False >>> (lambda x: x[0])([1,1])==(lambda x:x[0])([1,2]) True This is because now only the first item of the list is compared. - Patrick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Image manipluation (On-the-fly thumbnail creation)
dan06 wrote: I've recently delved into python, about a week or so ago; I'm trying to figure out how to create on-the-fly thumbnails. Are there python standard library modules I could/should use or should I use external libraries like: GD, Gimp, or ImageMagick? When I needed thumbnails of my images, I created them using ImageMagick. ImageMagick is a very nice tool for editing images and since it is called from the command line it is easy to invoke it from a programming language. There are python-bindings for it, but I think they are not very actively maintained and so I wouldn't use them. Using PIL is another option and maybe more pythonic, but if you are familiar with ImageMagick it might be a good alternative. - Patrick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: Executing a command from a specific directory
Ansuman Dash schrieb: Hello Everybody, In Python scripting, how can I execute a command (which can be run from spcific directory) and then retrieve the result (after executing the command it give the command is executed successfull or not), so that I can validate it. Thanks, AD import os import subprocess os.chdir('/your/directory') p = subprocess.Popen("ls -l", shell=True, stdout=subprocess.PIPE) out = p.stdout.read() print out - Patrick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Using the time module to extract a semi-random number
Laurii wrote: Hello all, I am currently reading through the Tutorial for Non-Programers by Josh Cogliati. I have had great success until now. The exercise to modify a number guessing program from a fixed number "number = 78" to using the time module and use the seconds at the time the program is used to be the number. (i.e. if the clock on your computer says 7:35:25 then it would take the 25 and place it in "number". You can either use: import time number = int(time.strftime("%S")) or use real pseudo-random numbers: import random number = random.randint(0,59) The latter looks clearer to me. - Patrick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] real world decorators
John wrote: Hi, I think I understand what decorators are and how they work. Maybe it's just me but I don't know where I'd use them in my real world programming. I see how they work with profile or coverage but does anyone have real world uses. @classmethod, @staticmethod, @property, @abstractclass, @abstractproperty are in my opinion the most import. Some toolkits use them too. I mostly create wxPython apps and don't see where they might apply. The wx toolkit is designed to work with C++ and wxPython is just a language binding for it. As far as I know C++ doesn't support Decorators or something similar like it. So there won't be many uses for decorators in wx apps. I know the tutors will enlighten me! Some ideas for decorators, if you want to play around with them: @fireandforget Make a function call in another thread, so you can return immediately - without returning result. This could be for example useful to send an email without needing to wait, until it is sent. @cache Cache the results of a function in a dictionary. If the function is called look up the value of the cache first. This only works with side-effect free functions of course. @timeout Check if the execution time of a function exceeds a timeout limit. If so raise an exception. @ignoreexceptions In my opinion, you should avoid using decorators in productive code, if you don't have a good reason to do otherwise. Every decorator adds some sort of "magic" to your program and using too much "magic" will make it difficult to maintain. - Patrick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] code improvement
You could invert your if-expressions, e.g. instead of if query_company_name: ... you could write if not query_company_name: return adresses, company ... This way you could save some indentation. If you want to get rid of the for loops, you could look at list comprehensions, e.g. cmps = [ressource.get_resource(item, soft=True) for item in companies] - Patrick Norman Khine wrote: On Thu, Sep 24, 2009 at 10:25 PM, Kent Johnson wrote: On Thu, Sep 24, 2009 at 2:12 PM, Norman Khine wrote: Hello, I have this function in my class: http://paste.lisp.org/display/87659 Is there a better method to write the last bit of the code. Better in what way? What are these things? What is resource? Some context would be helpful, I seem to have misplaced my mindreader hat. Apologies for not being clear. I was thinking more that I may have one the too many 'for' loops at the end of the code. Here is a new version with more details. http://paste.lisp.org/display/87659#1 Thanks Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with alternate execution
wrobl...@cmich.edu wrote: Thank you for the reply.. I tried putting the print repr(n) before I defined 'n' with raw_input. My script looks like this-- def divisible(n): if n%3 == 0: print n, "is divisible by 3" else: print n, "is not divisible by 3" n= raw_input("enter a number= ") print repr(n) print divisible(n) I don't understand what the problem is The problem is raw_input gives you a string. So in your example n is a string and when it comes to n%3 python tries to format your string, but since you haven't any formating symbols in it, it fails. To fix your program, convert the n to int: divisible(int(n)) - Patrick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class Knights vs class Knights(object)
Wayne Werner wrote: and my question is what is the difference between the two? Is there a difference other than one is an object the other is an instance? I googled "python object vs. instance" and didn't find anything terribly useful. Yes there is a difference. One class inherits from object, the other doesn't. You may want to try to check this, e.g.: issubclass(Knight, object) So the first keyword you may want to google for is inheritance. The second keyword is old/new-style classes. Python 2 changed the way how classes work, but to be backward compatible the old mechanism still remained. If you want new style classes inherit from object. If you want to understand the details you may want to look up what metaclasses - your third keyword - are, old-style classes have the metaclass classobj, new-style classes type. You can check this using the builtin type-function. Beware that this is python 2 stuff. In python 3 class X: and class X(object): are the same. - Patrick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unexpected iterator
Jeff R. Allen wrote: a, b = 0 Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not iterable I understand why it doesn't work, but I don't understand the wording of the exception. Could someone explain how I accidentally introduced iteration into the picture with my syntax? I have a feeling there's an interesting lesson hidden in this example... To upack your variables a and b you need an iterable object on the right side, which returns you exactly 2 variables, e.g you could also write a, b = range(2) or create your own class class X: def __iter__(self): yield 0 yield 0 a,b = X() - Patrick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] scraping and saving in file
On 2010-12-29 10:54, Tommy Kaas wrote: It works fine but besides # I also get spaces between the columns in the text file. How do I avoid that? You could use the new print-function and the sep keyword argument, e.g.: from __future__ import print_function f = open("filename", "w") print("1", "2", "3", file=f, sep="") ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] GUI + python program
You have a lot of options: GUI: Any major gui toolkit will do the job. It's probobly easiest to stick with tkinter. HTML Template: Use a template language, e.g. mako or django templates Pdf Templates: Reportlab is an option. File Access: Of course you could just open a file and write to it, but it probably gets messy. I would recommend using a database. Sqlite is maybe a good choice, or sqlalchemy. - Patrick On 2011-02-14 20:55, Mitch Seymour wrote: Hello, I am trying to design a program and GUI that will allow the user to select from a series of options and, depending on which options are selected in the GUI, information will then be placed in a html or pdf template. Here's an example. Option A Option B Option C If Option A, insert _ into the template. If Option B, insert _ into the template. If Option C, insert _ into the template. The reason I used __ is because the user needs to be able to edit, from the GUI, which information is associated with each option, and, subsequently, which information will be placed into the template. However, I am very new to python and I don't how to do this. A friend suggested that I create a python file that would store the user defined information, which would be read by the program before the information is placed into the template. So the user could select the options from the GUI, edit the associated information from a preferences tab, and then initiate the process of placing the info into the templates. My question is, how would you do this and, if I do create a file to store the information, could you please give me some examples of code to get me started? Thanks so much! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Nodes and Queues?
A queue is a data structure, which keeps track of multiple objects. You can add data to a queue or you can remove it. When you remove an object from a queue you get the element which you have added first. Therefore, it is also called FIFO (First In First Out). A basic implementation could look like this: class Queue: def __init__(self): self.items = [] def add(self, obj): self.items.append(obj) def remove(self): self.items.pop(0) Nodes are used in multiple contexts, but usually refer to objects which have child objects. -- Patrick On 2011-05-11 13:44, Clara Mintz wrote: Hi all I am sorry I am a beginner at python and I was reading my book and I came across the terms Nodes and Queue. I am sorry but I don't quite understand how they work. Is there anyone who could possibly explain them in simple terms? Thank you so much. Sincerely, Clara ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python program with multiple answers
* Create a list. * Each time, the user gets an answer add it to the list * At the end of the program: sort the list and print each element of it - Patrick On 2011-05-11 12:49, Johnson Tran wrote: Hi Guys, I've been working on a Python program where I create an 8 ball that will allow you to ask questions and will reply back with 20 possible answers. It will be continuous until the user says quit. My program works fine although I am trying to add something more to it, where when the user quits, it will present all the answers that the user got again and display them in alphabetical order...if anyone could point me in the right direction it'd be really helpful...my program so far is : (which works fine with no errros) import random dice = ("Without a doubt", "It is certain", "It is decidedly so","Yes", "For Sure", "No", "Dont count on it", "Try asking again","Reply hazy, try again", "Confucious says 'No'", "Better not tell you now","Cannot predict now","Concentrate and ask again","My reply is no","Outlook not so good","Very doubtful","Outlook is good","Most likely","As I see it, yes","I do not understand the question") while True: choice = raw_input("Type 'ask' to ask a question. Type 'quit' to quit.\n") if choice == "ask": raw_input("Please enter your question:\n") roll = random.randint(0, 10) print dice[roll] raw_input() elif choice == "quit": True = 0 raw_input() else: print "Error -- Try again\n" Thanks, JT ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor