[Tutor] Using the TIME module to extract a semi-random number
- Original Message - Message: 1 Date: Wed, 16 Sep 2009 23:19:39 -0400 From: Kent Johnson To: Laurii Cc: tutor@python.org Subject: Re: [Tutor] Using the time module to extract a semi-random number Message-ID: <1c2a2c590909162019l364b516cifcd2e0befe2ad...@mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1 On Wed, Sep 16, 2009 at 6:43 PM, Laurii wrote: 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". time.localtime().tm_sec will give you the number of seconds as an integer without any conversions. Kent -- Message: 2 Date: Thu, 17 Sep 2009 10:50:11 +0200 From: Patrick Sabin To: Tutor@python.org Subject: Re: [Tutor] Using the time module to extract a semi-random number Message-ID: <4ab1f843.1060...@gmail.com> Content-Type: text/plain; charset=ISO-8859-1; format=flowed 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. Thank you everyone for your help. Even just the examples you have posted have been easier to understand than the python documentation. One last question on the TIME module: Is there one version of these examples that is not portable to other systems? I read something about some functions not working on other systems and I would like to ensure that the programs that I write are completely portable. Thanks again, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Calling a dictionary entry inside of a function
Corey Richardson wrote: I am trying to use a parameter of a function to call a word inside a dictionary. Here is my code wordList = { 'Apple' : ["A delicious snack"], 'Word' : ["This code is not working..."], } def define(word): print wordList['Word'] You put quotess around word which means Pythn uses the literal string 'word' as te kwey. You want to use thevalue of the variable word so you should just use word without quotes. Understanding the difference between literal values and symbolic values(variables) is very important. here is a slightly differemt example: d = {1:'first', 2:'second'} one=0 two=2 print d[1] # ok print d[one] # not ok, looking for d[0] print d[2] # ok print d[two] # ok lokking for d[2] print d['two' # not ok, looking for d['two'] HTH, Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Calling a dictionary entry inside of a function
On Sat, Sep 19, 2009 at 9:27 AM, Corey Richardson wrote: > I am trying to use a parameter of a function to call a word inside a > dictionary. > Here is my code > wordList = { > 'Apple' : ["A delicious snack"], > 'Word' : ["This code is not working..."], > } > def define(word): > print wordList['Word'] > > > When I use define('Apple') it returns ['This code is not working...']. That's what you asked it to do, but I think you meant print wordList[word] instead HTH, benno ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Calling a dictionary entry inside of a function
I am trying to use a parameter of a function to call a word inside a dictionary. Here is my code wordList = { 'Apple' : ["A delicious snack"], 'Word' : ["This code is not working..."], } def define(word): print wordList['Word'] When I use define('Apple') it returns ['This code is not working...']. I tried defining word with a raw_input, but that didn't work, and I wouldn't know how to have them define another word. <>___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python decorator to ensure that kwargs are correct
Should probably clean up my code properly before submitting, to hide some of the noobish errors like forgetting to put quotes round strings... >>> class Demo(object): ... def __init__(self, name="", surname="", age=0): ... print name, surname, age ... >>> Demo(name='Rich', surname='Lovely', age=24) Rich Lovely 24 <__main__.Demo object at 0x00F75230> >>> Demo(notAName='foo') Traceback (most recent call last): File "", line 1, in TypeError: __init__() got an unexpected keyword argument 'notAName' -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python decorator to ensure that kwargs are correct
2009/9/18 Manuel de la Pena : > Hello, > > > I have done a decorator that I used to ensure that the keyword arguments > passed to a constructor are the correct/expected ones. The code is the > following: > > from functools import wraps > > def keyargs_check(keywords): > """ > This decorator ensures that the keys passed in kwargs are the onces that > are specified in the passed tuple. When applied this decorate will > check the keywords and will throw an exception if the developer used > one that is not recognized. > > @type keywords: tuple > @param keywords: A tuple with all the keywords recognized by the function. > """ > > def wrap(f): > �...@wraps(f) > def newFunction(*args, **kw): > # we are going to add an extra check in kw > for current_key in kw.keys(): > if not current_key in keywords: > raise ValueError( > "The key {0} is a not recognized parameters by > {1}.".format( > current_key, f.__name__)) > return f(*args, **kw) > return newFunction > return wrap > > An example use of this decorator would be the following: > > class Person(object): > > @keyargs_check(("name", "surname", "age")) > def __init__(self, **kwargs): > # perform init according to args > > Using the above code if the developer passes a key args like "blah" it > will throw an exception. Unfortunately my implementation has a major > problem with inheritance, if I define the following: > > class PersonTest(Person): > > @keyargs_check(("test")) > def __init__(self, **kwargs): > Person.__init__(self,**kwargs) > > Because I'm passing kwargs to the super class init method, I'm going to > get an exception because "test" is not in the tuple passed to the > decorator of the super class. Is there a way to let the decorator used > in the super class to know about the extra keywords? or event better, is > there a standard way to achieve what I want? > > > Thanks in advance for any help or input, > > kr, > > Manuel > > > > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Is there any specific reason you need to use **kwargs? If you omit it from function definitions, you can use normal argument format: >>> class Demo(object): ... def __init__(self, name="", surname="", age=0): ... print name, surname, age ... >>> Demo(name='Rich', surname=Lovely, age=24) Traceback (most recent call last): File "", line 1, in NameError: name 'Lovely' is not defined >>> Demo(name='Rich', surname='Lovely', age=24) Rich Lovely 24 <__main__.Demo object at 0x00F75230> >>> Demo(notAValidParam='foo') Traceback (most recent call last): File "", line 1, in TypeError: __init__() got an unexpected keyword argument 'notAValidParam' >>> It does of course break if you use positional arguments, but part of the theory behind python is that we're all consenting adults, and should know better than to do things that break existing code. It is for this reason that you can overwrite builtins like range or list without the interpretter moaning. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 67, Issue 62
I'm going to be making a simple program, that is a few books like "A is for...", "B is for...", but it will be many built into one, Sorry, I don't understand? *By that, I mean it will be like a childrens book, teaching the letters. You've read them. example "A is for apple, a yummy treat. B is for Box'es, they hold things". * isn't, and ignore it. Also, Alan, your tutorial is the bomb! Some of the simpler things I've seen done better, but you do an amazing job with it. Thanks for the kind words. If you can offer ideas for improvement I'm always happy to hear. Thats how it improves! And since I;m still working on the latest update for v3 its a good time for suggestions! * Ok, I'll go over it more carefully and see if I can suggest anything.* <>___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Import vs #include
On Fri, Sep 18, 2009 at 4:15 PM, Warren Marshall wrote: > > Excellent, OK, this is becoming clearer ... > > So if I wanted a common library of code that several Python apps would be > using, best practices would say I should put that into a directory that the > projects can see and import it as a package.module. Cool... Yes, and if you want to share it with all python programs, put your dir into Lib/site-packages - that dir is always on the python search path. Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Determine Filetype
On Fri, Sep 18, 2009 at 4:10 PM, ad...@gg-lab.net wrote: > Ok, so magic is not installed on GAE. I've then uploaded it and it > loaded succesfully. New error: > > No module named _ctypes > > And, reading the full debug i got this: > > File "/base/python_dist/lib/python2.5/ctypes/__init__.py", line 10, in > > from _ctypes import Union, Structure, Array > > So, the __init__.py file of the GAE evinronment's ctypes library is > broken, as it's importing from a package that doesn't exist. Right? Probably ctypes is not supported in GAE, that would be a pretty big security hole. Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] order data
2009/9/18 Rayon : I will assume array == python list. > I have a array with this data in it How are you reading the data? Do you convert all the numbers to floats? If so you will need to think about precision of the floats. If you want to preserve the precision look into the decimal module. > 0.0046,0.095,0.0904,521456,['MCI 521456 0.0904'],['ATT 521 0.0919'],['IDT > 521 0.095'],['None'] > 0.0083,0.0192,0.0109,39023821,['MCI 39023821 0.0109'],['ATT 39 0.012'],['IDT > 39 0.0192'],['SPR 39 0.0135'] > 0.0421,0.0681,0.026,73462,['MCI 73462 0.0260'],['ATT 7 0.026'],['IDT 73462 > 0.028'],['SPR 7 0.0681'] > 0.0176,0.1035,0.0859,126872,['MCI 126872 0.0859'],['ATT 1268 0.0919'],['IDT > 126872 0.1035'],['None'] > 0.0215,0.1614,0.1399,5032130,['MCI 5032130 0.1614'],['ATT 5032130 > 0.1399'],['IDT 503 0.152'],['None'] > 0.0206,0.0385,0.0179,1868,['MCI 1868 0.0179'],['ATT 1868 0.0385'],['IDT 1868 > 0.036'],['None'] > 0.0325,0.087,0.0545,5027889,['MCI 5027889 0.0602'],['ATT 5027889 > 0.0545'],['IDT 502 0.087'],['None'] > 0.0325,0.087,0.0545,5027888,['MCI 5027888 0.0602'],['ATT 5027888 > 0.0545'],['IDT 502 0.087'],['None'] > 0.0046,0.095,0.0904,521455,['MCI 521455 0.0904'],['ATT 521 0.0919'],['IDT > 521 0.095'],['None'] > 0.1292,0.1762,0.047,5989,['MCI 5989 0.1762'],['ATT 598 0.05'],['IDT 5989 > 0.173'],['SPR 598 0.047'] > 0.0706,0.2011,0.1305,1284499,['MCI 1284499 0.2011'],['ATT 1284499 > 0.1932'],['IDT 1284499 0.1305'],['None'] > > and I want to order the display of that data by the second row. You probably meant the second column here.If not please explain a bit more. > can I do it in this array from or do I have to break it down more. If the data is in a list of lists you can use itemgetter from the operator module. Example below. >>> import operator >>> a = \ [[0.0046,0.095,0.0904,521456,['MCI 521456 0.0904'],['ATT 521 0.0919'],['IDT 521 0.095'],['None']], [0.0083,0.0192,0.0109,39023821,['MCI 39023821 0.0109'],['ATT 39 0.012'],['IDT 39 0.0192'],['SPR 39 0.0135']], [0.0421,0.0681,0.026,73462,['MCI 73462 0.0260'],['ATT 7 0.026'],['IDT 73462 0.028'],['SPR 7 0.0681']], [0.0176,0.1035,0.0859,126872,['MCI 126872 0.0859'],['ATT 1268 0.0919'],['IDT 126872 0.1035'],['None']], [0.0215,0.1614,0.1399,5032130,['MCI 5032130 0.1614'],['ATT 5032130 0.1399'],['IDT 503 0.152'],['None']], [0.0206,0.0385,0.0179,1868,['MCI 1868 0.0179'],['ATT 1868 0.0385'],['IDT 1868 0.036'],['None']], [0.0325,0.087,0.0545,5027889,['MCI 5027889 0.0602'],['ATT 5027889 0.0545'],['IDT 502 0.087'],['None']], [0.0325,0.087,0.0545,5027888,['MCI 5027888 0.0602'],['ATT 5027888 0.0545'],['IDT 502 0.087'],['None']], [0.0046,0.095,0.0904,521455,['MCI 521455 0.0904'],['ATT 521 0.0919'],['IDT 521 0.095'],['None']], [0.1292,0.1762,0.047,5989,['MCI 5989 0.1762'],['ATT 598 0.05'],['IDT 5989 0.173'],['SPR 598 0.047']], [0.0706,0.2011,0.1305,1284499,['MCI 1284499 0.2011'],['ATT 1284499 0.1932'],['IDT 1284499 0.1305'],['None']]] >>> a.sort(key=operator.itemgetter(1)) >>> for l in a: print l [0.0083001, 0.019198, 0.0109, 39023821, ['MCI 39023821 0.0109'], ['ATT 39 0.012'], ['IDT 39 0.0192'], ['SPR 39 0.0135']] [0.0206, 0.0385, 0.017899, 1868, ['MCI 1868 0.0179'], ['ATT 1868 0.0385'], ['IDT 1868 0.036'], ['None']] [0.042099, 0.068094, 0.025999, 73462, ['MCI 73462 0.0260'], ['ATT 7 0.026'], ['IDT 73462 0.028'], ['SPR 7 0.0681']] [0.032501, 0.086994, 0.0545, 5027889, ['MCI 5027889 0.0602'], ['ATT 5027889 0.0545'], ['IDT 502 0.087'], ['None']] [0.032501, 0.086994, 0.0545, 5027888, ['MCI 5027888 0.0602'], ['ATT 5027888 0.0545'], ['IDT 502 0.087'], ['None']] [0.0045999, 0.095001, 0.090394, 521456, ['MCI 521456 0.0904'], ['ATT 521 0.0919'], ['IDT 521 0.095'], ['None']] [0.0045999, 0.095001, 0.090394, 521455, ['MCI 521455 0.0904'], ['ATT 521 0.0919'], ['IDT 521 0.095'], ['None']] [0.017601, 0.10349, 0.085904, 126872, ['MCI 126872 0.0859'], ['ATT 1268 0.0919'], ['IDT 126872 0.1035'], ['None']] [0.021498, 0.16139, 0.1399, 5032130, ['MCI 5032130 0.1614'], ['ATT 5032130 0.1399'], ['IDT 503 0.152'], ['None']] [0.12921, 0.1762, 0.047, 5989, ['MCI 5989 0.1762'], ['ATT 598 0.05'], ['IDT 5989 0.173'], ['SPR 598 0.047']] [0.070596, 0.2011, 0.1305, 1284499, ['MCI 1284499 0.2011'], ['ATT 1284499 0.1932'], ['IDT 1284499 0.1305'], ['None']] >>> As you can see the numbers are converted to floats in my example and 0.0192 changed to 0.019198. Greets Sander ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Import vs #include
Excellent, OK, this is becoming clearer ... So if I wanted a common library of code that several Python apps would be using, best practices would say I should put that into a directory that the projects can see and import it as a package.module. Cool... - Warren (epic...@gmail.com) On Sep 18, 2009, at 3:25 PM, Kent Johnson wrote: On Fri, Sep 18, 2009 at 2:14 PM, Warren Marshall wrote: I'm trying to get my head around the organization of a larger Python project. 1. Am I right in thinking that in Python, you don't have the concept of something like a precompiled header and that every file that wants to use, say "vector.py" needs to import that module? Yes. 2. How are Python projects typically organized in terms of having many files. Are sub-directories for different kinds of files (rendering files go here, file management files go here, etc), or does that not play nicely with the import command? It's fine. The directories are called packages and must contain a (possibly empty) file named __init__.py. Then you can do things like from package.module import SomeClass See the std lib for examples, for example the email and logging packages. 3. As you can tell, I've done a lot of C/C++/C# and I'm trying to shake loose the analog that I've built up in my head that import is Python's answer to #include. It isn't, is it? Not really, it is more like a using declaration in C# except it doesn't bring the contents of the module into scope, just the module itself. using System; // C# is like from sys import * # Python though the latter form is discouraged in favor of just import sys or importing the specific items you need: from sys import modules 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] Determine Filetype
Ok, a good news for me: i've modified my script, adding a: import magic line at the top of it. But I got this error: No module named magic Ok, so magic is not installed on GAE. I've then uploaded it and it loaded succesfully. New error: No module named _ctypes And, reading the full debug i got this: File "/base/python_dist/lib/python2.5/ctypes/__init__.py", line 10, in from _ctypes import Union, Structure, Array So, the __init__.py file of the GAE evinronment's ctypes library is broken, as it's importing from a package that doesn't exist. Right? Maybe i'm doing something wrong. Thankyou 2009/9/18 ad...@gg-lab.net : > Oh, i'm sorry. > > I've read the README, but haven't noticed that > > m.from_buffer(open("testdata/test.pdf").read(1024)) > > was exactly what i was looking for. > > Ok, i'll try it and let you know :D > > 2009/9/18 Kent Johnson : >> On Fri, Sep 18, 2009 at 2:21 PM, ad...@gg-lab.net wrote: >>> Hi Emile, >>> >>> that functions requires a filename/path. >> >> Did you even look at the link? There is a from_buffer() method also. >> >> Kent >> >>> 2009/9/18 Emile van Sebille : >> I'd take a look at python-magic at http://hupp.org/adam/hg/python-magic/file/d3cd83e5a773 where the example shows that you can do: # For MIME types >>> mime = magic.Magic(mime=True) >>> mime.from_file("testdata/test.pdf") 'application/pdf' >> > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python decorator to ensure that kwargs are correct
Hello, I have done a decorator that I used to ensure that the keyword arguments passed to a constructor are the correct/expected ones. The code is the following: from functools import wraps def keyargs_check(keywords): """ This decorator ensures that the keys passed in kwargs are the onces that are specified in the passed tuple. When applied this decorate will check the keywords and will throw an exception if the developer used one that is not recognized. @type keywords: tuple @param keywords: A tuple with all the keywords recognized by the function. """ def wrap(f): @wraps(f) def newFunction(*args, **kw): # we are going to add an extra check in kw for current_key in kw.keys(): if not current_key in keywords: raise ValueError( "The key {0} is a not recognized parameters by {1}.".format( current_key, f.__name__)) return f(*args, **kw) return newFunction return wrap An example use of this decorator would be the following: class Person(object): @keyargs_check(("name", "surname", "age")) def __init__(self, **kwargs): # perform init according to args Using the above code if the developer passes a key args like "blah" it will throw an exception. Unfortunately my implementation has a major problem with inheritance, if I define the following: class PersonTest(Person): @keyargs_check(("test")) def __init__(self, **kwargs): Person.__init__(self,**kwargs) Because I'm passing kwargs to the super class init method, I'm going to get an exception because "test" is not in the tuple passed to the decorator of the super class. Is there a way to let the decorator used in the super class to know about the extra keywords? or event better, is there a standard way to achieve what I want? Thanks in advance for any help or input, kr, Manuel ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] order data
I have a array with this data in it 0.0046,0.095,0.0904,521456,['MCI 521456 0.0904'],['ATT 521 0.0919'],['IDT 521 0.095'],['None'] 0.0083,0.0192,0.0109,39023821,['MCI 39023821 0.0109'],['ATT 39 0.012'],['IDT 39 0.0192'],['SPR 39 0.0135'] 0.0421,0.0681,0.026,73462,['MCI 73462 0.0260'],['ATT 7 0.026'],['IDT 73462 0.028'],['SPR 7 0.0681'] 0.0176,0.1035,0.0859,126872,['MCI 126872 0.0859'],['ATT 1268 0.0919'],['IDT 126872 0.1035'],['None'] 0.0215,0.1614,0.1399,5032130,['MCI 5032130 0.1614'],['ATT 5032130 0.1399'],['IDT 503 0.152'],['None'] 0.0206,0.0385,0.0179,1868,['MCI 1868 0.0179'],['ATT 1868 0.0385'],['IDT 1868 0.036'],['None'] 0.0325,0.087,0.0545,5027889,['MCI 5027889 0.0602'],['ATT 5027889 0.0545'],['IDT 502 0.087'],['None'] 0.0325,0.087,0.0545,5027888,['MCI 5027888 0.0602'],['ATT 5027888 0.0545'],['IDT 502 0.087'],['None'] 0.0046,0.095,0.0904,521455,['MCI 521455 0.0904'],['ATT 521 0.0919'],['IDT 521 0.095'],['None'] 0.1292,0.1762,0.047,5989,['MCI 5989 0.1762'],['ATT 598 0.05'],['IDT 5989 0.173'],['SPR 598 0.047'] 0.0706,0.2011,0.1305,1284499,['MCI 1284499 0.2011'],['ATT 1284499 0.1932'],['IDT 1284499 0.1305'],['None'] and I want to order the display of that data by the second row. can I do it in this array from or do I have to break it down more. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ODBC SQL Server Question
Thanks for the clarification Kent! Kent Johnson wrote: On Fri, Sep 18, 2009 at 2:14 PM, Jeff Johnson wrote: Kent: How about this: self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME = '%s'" % (name, )) No, that has the same result as your original. For example, In [3]: name = "Kent'; drop table Stories;--" In [4]: "SELECT CUSTID FROM Stories WHERE NAME = '%s'" % (name, ) Out[4]: "SELECT CUSTID FROM Stories WHERE NAME = 'Kent'; drop table Stories;--'" Oops. Question, does execute know to substitute the question mark with name? self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name, )) Yes, and it will correctly quote name according to the conventions of the database in use. (Note that not all DB-API implementations use ? as the placeholder; check the docs for the db you are using.) Kent -- Jeff Jeff Johnson j...@dcsoftware.com Phoenix Python User Group - sunpigg...@googlegroups.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Determine Filetype
Oh, i'm sorry. I've read the README, but haven't noticed that m.from_buffer(open("testdata/test.pdf").read(1024)) was exactly what i was looking for. Ok, i'll try it and let you know :D 2009/9/18 Kent Johnson : > On Fri, Sep 18, 2009 at 2:21 PM, ad...@gg-lab.net wrote: >> Hi Emile, >> >> that functions requires a filename/path. > > Did you even look at the link? There is a from_buffer() method also. > > Kent > >> 2009/9/18 Emile van Sebille : > >>> I'd take a look at python-magic at >>> http://hupp.org/adam/hg/python-magic/file/d3cd83e5a773 where the example >>> shows that you can do: >>> >>> # For MIME types >> mime = magic.Magic(mime=True) >> mime.from_file("testdata/test.pdf") >>> 'application/pdf' > ___ 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)
Patrick Sabin wrote: > > 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 > My experiences with ImageMagick (IM) are limited, but what experiences I have had have been good. The functionality of IM is superb, and that is the impetus for wanting to use it over other softwares/libraries. Ultimately, I want to use IM/Python to replicate something I did in GD/PHP. Using GD/PHP I was able to create thumbnails on-demand that I could output directly to the browser, rather than creating & saving thumbnails to the disk. Is this possible with IM/Python? -- View this message in context: http://www.nabble.com/Image-manipluation-%28On-the-fly-thumbnail-creation%29-tp25456792p25514113.html Sent from the Python - tutor mailing list archive at Nabble.com. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Determine Filetype
On Fri, Sep 18, 2009 at 2:21 PM, ad...@gg-lab.net wrote: > Hi Emile, > > that functions requires a filename/path. Did you even look at the link? There is a from_buffer() method also. Kent > 2009/9/18 Emile van Sebille : >> I'd take a look at python-magic at >> http://hupp.org/adam/hg/python-magic/file/d3cd83e5a773 where the example >> shows that you can do: >> >> # For MIME types > mime = magic.Magic(mime=True) > mime.from_file("testdata/test.pdf") >> 'application/pdf' ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Import vs #include
On Fri, Sep 18, 2009 at 2:14 PM, Warren Marshall wrote: > > I'm trying to get my head around the organization of a larger Python > project. > > 1. Am I right in thinking that in Python, you don't have the concept of > something like a precompiled header and that every file that wants to use, > say "vector.py" needs to import that module? Yes. > 2. How are Python projects typically organized in terms of having many > files. Are sub-directories for different kinds of files (rendering files go > here, file management files go here, etc), or does that not play nicely with > the import command? It's fine. The directories are called packages and must contain a (possibly empty) file named __init__.py. Then you can do things like from package.module import SomeClass See the std lib for examples, for example the email and logging packages. > 3. As you can tell, I've done a lot of C/C++/C# and I'm trying to shake > loose the analog that I've built up in my head that import is Python's > answer to #include. It isn't, is it? Not really, it is more like a using declaration in C# except it doesn't bring the contents of the module into scope, just the module itself. using System; // C# is like from sys import * # Python though the latter form is discouraged in favor of just import sys or importing the specific items you need: from sys import modules Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ODBC SQL Server Question
On Fri, Sep 18, 2009 at 2:14 PM, Jeff Johnson wrote: > Kent: > > How about this: > self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME = '%s'" % (name, > )) No, that has the same result as your original. For example, In [3]: name = "Kent'; drop table Stories;--" In [4]: "SELECT CUSTID FROM Stories WHERE NAME = '%s'" % (name, ) Out[4]: "SELECT CUSTID FROM Stories WHERE NAME = 'Kent'; drop table Stories;--'" Oops. > Question, does execute know to substitute the question mark with name? > self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name, )) Yes, and it will correctly quote name according to the conventions of the database in use. (Note that not all DB-API implementations use ? as the placeholder; check the docs for the db you are using.) Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Import vs #include
I'm trying to get my head around the organization of a larger Python project. 1. Am I right in thinking that in Python, you don't have the concept of something like a precompiled header and that every file that wants to use, say "vector.py" needs to import that module? 2. How are Python projects typically organized in terms of having many files. Are sub-directories for different kinds of files (rendering files go here, file management files go here, etc), or does that not play nicely with the import command? 3. As you can tell, I've done a lot of C/C++/C# and I'm trying to shake loose the analog that I've built up in my head that import is Python's answer to #include. It isn't, is it? - Warren (epic...@gmail.com) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Determine Filetype
Hi Emile, that functions requires a filename/path. Just like this one (for images) http://docs.python.org/library/imghdr.html Ok, i don't have a filename. I get the file from a BLOB in a db. Any idea? Thankyou for your precious help. 2009/9/18 Emile van Sebille : > On 9/18/2009 10:05 AM ad...@gg-lab.net said... >> >> Hi, >> >> i'm putting file in a DB as BLOB entries. To serve them, i need to >> take Content-Type headers. >> >> So, i'm looking for a function that returnes the filetype, given a data >> str. >> >> I've found many other topics like this in python mail-archive, but any >> of them contains the solution. >> >> Can you help me, please? > > I'd take a look at python-magic at > http://hupp.org/adam/hg/python-magic/file/d3cd83e5a773 where the example > shows that you can do: > > # For MIME types mime = magic.Magic(mime=True) mime.from_file("testdata/test.pdf") > 'application/pdf' > > > HTH, > > Emile > > > > > >> >> Thankyou! >> ___ >> Tutor maillist - tu...@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > ___ > Tutor maillist - tu...@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] Calling VB.NET code with Python .. VB.net - Python integration ..
Otonicar Ales wrote: The idea is that Python calls VB.net program. VB.Net program gets data and than forward data back to Python for further processing.. One way to do this is by compiling vb.net program to exe. And than call exe by Python code. Data exchange goes via Access Data Base (Python write in MC Access, vb get data and than write it to MC access, Python reads final data from MC access). In this case I will need Python command to run exe which is enable Python waiting until exe is not finished.. In case anybody out-there has better idea how directly communicate with vb.net program (exchanging data with variables - code integration) please send code sample with a bit of explanation .. You should set up the vb.net program to be a com server. Don't ask me how to do that. Then get Python for Windows: http://sourceforge.net/projects/pywin32/files/pywin32/Build%20214/pywin32-214.win32-py2.6.exe/download import wincom32.client com = wincom32.client.Dispatch( application name or classid of the vb.net app) # now you have a com object with which you can send commands to the vb.net app and receive data back. -- Bob Gailer Chapel Hill NC 919-636-4239 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ODBC SQL Server Question
Kent: How about this: self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME = '%s'" % (name, )) Question, does execute know to substitute the question mark with name? self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name, )) TIA Kent Johnson wrote: On Fri, Sep 18, 2009 at 11:49 AM, Jeff Johnson wrote: Kristina: I would format it as follows: self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME = '%s'" % name) No, that is a recipe for SQL injection attacks such as this: http://xkcd.com/327/ self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name)) I think that should have a comma to create a tuple: self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name,)) I don't know if that could cause your problem. Kent -- Jeff Jeff Johnson j...@dcsoftware.com Phoenix Python User Group - sunpigg...@googlegroups.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Determine Filetype
On 9/18/2009 10:05 AM ad...@gg-lab.net said... Hi, i'm putting file in a DB as BLOB entries. To serve them, i need to take Content-Type headers. So, i'm looking for a function that returnes the filetype, given a data str. I've found many other topics like this in python mail-archive, but any of them contains the solution. Can you help me, please? I'd take a look at python-magic at http://hupp.org/adam/hg/python-magic/file/d3cd83e5a773 where the example shows that you can do: # For MIME types >>> mime = magic.Magic(mime=True) >>> mime.from_file("testdata/test.pdf") 'application/pdf' HTH, Emile Thankyou! ___ 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
[Tutor] Determine Filetype
Hi, i'm putting file in a DB as BLOB entries. To serve them, i need to take Content-Type headers. So, i'm looking for a function that returnes the filetype, given a data str. I've found many other topics like this in python mail-archive, but any of them contains the solution. Can you help me, please? Thankyou! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ODBC SQL Server Question
On Fri, Sep 18, 2009 at 11:49 AM, Jeff Johnson wrote: > Kristina: > > I would format it as follows: > > self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME = '%s'" % name) No, that is a recipe for SQL injection attacks such as this: http://xkcd.com/327/ >> self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name)) I think that should have a comma to create a tuple: self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name,)) I don't know if that could cause your problem. Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ODBC SQL Server Question
Kristina: I would format it as follows: self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME = '%s'" % name) Kristina Ambert wrote: Hi, Is anyone familiar with this error: dbi.internal-error: [Microsoft][SQL Server Driver]Invalid cursor state in EXEC This error is triggered by the first sql statement call in an accessor module which purpose is only to get data from a source module and feed it into a database: self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name)) I can't figure out what's causing it. I searched for the invalid cursor state error online but most of it occurs on the fetchall statement not the execute statement. Any ideas? Thanks! -- Cheers, Krissy --- Testing the waters is always fun... -- Jeff Jeff Johnson j...@dcsoftware.com Phoenix Python User Group - sunpigg...@googlegroups.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] ODBC SQL Server Question
Hi, Is anyone familiar with this error: dbi.internal-error: [Microsoft][SQL Server Driver]Invalid cursor state in EXEC This error is triggered by the first sql statement call in an accessor module which purpose is only to get data from a source module and feed it into a database: self.cursor.execute("SELECT CUSTID FROM Stories WHERE NAME= ?", (name)) I can't figure out what's causing it. I searched for the invalid cursor state error online but most of it occurs on the fetchall statement not the execute statement. Any ideas? Thanks! -- Cheers, Krissy --- Testing the waters is always fun... ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Executing a command from a specific directory
Hello, On Sep 18, 2009, at 5:16 AM, Ansuman Dash wrote: I have written it like that. It is like press 1 and it ll download file1 and press 2 it ll download file2 etc But my question was I am using "time.sleep()" to make my script to wait for the file download and then validate it in log file, so is there any other way I can synchronize my code with the download. I am asking this because some files are very huge (120MB) and download also depends on N/W bandwidth so sometimes it ll be done in 30mins and some times it takes 60 mins. So I can't rely on "time.sleep()" I had a similar problem. I used pyinotify on a linux box. inotify is a kernel hook that you can use to trigger actions on events... like when a file write is completed. Note: I'm a total hack at this. I'm sure there's a more elegant way to do what I'm dong, but I needed a fix fast, and this worked for me. I'd appreciate any tips anyone has to offer to make this cleaner and/or more pythonic. :-) I'll be glad to try to answer any questions about this hackery. Best, Kurt Here's a slightly cut-down version of my code: http://pastebin.com/f239b0413 inotify_published_file_handler.py # #!/usr/bin/env python # -*- coding: utf-8 -*- # encoding: utf-8 """ inotify_published_file_handler.py rev. 20090706-01 Created by Kurt Bendl. Usage - sudo su - www-data -c 'cd /web/log/; \ nohup /web/scripts/inotify_published_file_handler.py > \ /web/log/inotify-errors.txt 2>&1 &' Purpose - Monitor the $WEBROOT/aapracing/import/publish directory. Once a file is closed, act on it: 1. Copy the PDF and XML files from source_dir to web_filebin_dir 2. If the file is an.XML, copy it to the xml_ftp_dir 3. Make the dummy file for PHP publishing process 4. Remove the source file Requirements * Linux kernel 2.6.13 + * pyinotify 2.8.6 + Installation -- To install pyinotify on ubuntu/debian: `sudo easy_install pyinotify` Docs - Docs on pyinotify can be found here: http://trac.dbzteam.org/pyinotify/wiki """ import os import re import shutil import pyinotify import datetime ### production config info source_dir = "/web/site/aapracing/publish/data/publish/" web_filebin_dir = "/web/site/filebin/downloads/" reference_path = '/web/site/aapracing/publish/data/published/' xml_ftp_dir = "/home/ftp/private/xml/" filez = '(PDF|pdf|XML|xml|txt)' logfile_path = "/web/log/inotify.log" event_mask = pyinotify.IN_CLOSE_WRITE wm = pyinotify.WatchManager() def getNow(): """Just return the current time for timestamping logs""" return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") def makeReferenceFile(tfile): open(tfile, 'w').close() class SourceMonitor(pyinotify.ProcessEvent): """ Watches the source dir for IN_CLOSE_WRITE event""" def process_IN_CLOSE_WRITE(self, event): """when an IN_CLOSE_WRITE happens, do something""" if re.search('(.*\.'+filez+'$)', event.pathname): # We have a match, put a copy into the filebin dir shutil.copy2(event.pathname, web_filebin_dir) logfile = open(logfile_path, "a") logfile.write("%s: %s moved to %s. \n" % (getNow(), event.pathname, web_filebin_dir)) if re.search('(.*\.(XML|xml)$)', event.pathname): # If it's and XML, put a copy in the FTP dir shutil.copy2(event.pathname, xml_ftp_dir) logfile.write("%s: %s moved to %s. \n" % (getNow(), event.pathname, xml_ftp_dir)) # Make the dummy file marker to enable PHP # to know the file is really published fhandle = os.path.basename(event.pathname) open(reference_path + fhandle, 'w').close() # Now, whack the source file since we're done with it. os.remove(event.pathname) p = SourceMonitor() notifier = pyinotify.Notifier(wm, p) wdd = wm.add_watch(source_dir, event_mask) print "This should have been started with:\n\n" print " sudo su - www-data -c 'cd /web/log/; nohup /web/scripts/ inotify_published_file_handler.py > /web/log/inotify-errors.txt 2>&1 &' \n\n" notifier.loop() -- Kurt Bendl, Consultant Internet Tool & Die http://tool.net/ 502-759-7104 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Calling VB.NET code with Python .. VB.net - Python integration ..
The idea is that Python calls VB.net program. VB.Net program gets data and than forward data back to Python for further processing.. One way to do this is by compiling vb.net program to exe. And than call exe by Python code. Data exchange goes via Access Data Base (Python write in MC Access, vb get data a n d than write it to MC access, Python reads final data from MC access). In this case I will need Python command to run exe which is enable Python waiting until exe is not finished.. In case anybody out-there has better idea how directly communicate with vb.net program (exchanging data with v ariables - code integration) please send code sample with a bit of explanation .. VB.Net program is very long as it communicate with external provider API. I will change the program on load part of the code (using Visual Studio 2008). Change will make program working hidden - not visable, using data in MC Access. Currently program works as on Screen program with forms and buttons. This part is easy. Best connection with Python is still open debate .. Cheers, Ales ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fw: utf locale sorting
Excellent, the thing works! Thanx a lot! - Original Message - From: Kent Johnson To: Igor Mavrović - ma...@irb Cc: Rich Lovely ; tutor@python.org Sent: Wednesday, September 16, 2009 7:06 PM Subject: Re: [Tutor] Fw: utf locale sorting How about this (assuming both arguments need to be transformed)? key=lambda x:(locale.strxfrm(x[0][1]["sn"]), locale.strxfrm(x[0][1]["givenName"])) Kent __ Information from ESET Smart Security, version of virus signature database 4429 (20090916) __ The message was checked by ESET Smart Security. http://www.eset.com ___ 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
On Thu, Sep 17, 2009 at 4:59 PM, Katt wrote: > > - Original Message - From: "Kent Johnson" >> time.localtime().tm_sec will give you the number of >seconds as an >> integer without any conversions. > > Thank you for your quick response. I didn't expect to get a response for a > couple of days. > > As you know from the others that responded there are a couple of ways that > it could be done. I am curious as to which one is more efficient. > > Your solution was: > number = time.localtime().tm_sec > > The other solutions were > number = int(time.strftime("%S") > number = int(time.strftime("%S"(time.localtime())) > > Is it that the program could access yours faster than the others? Or is it > that there are many ways to accomplish things in python and no one is better > than the other? They will all be fast enough that it doesn't matter. My guess is that if you timed them (with the timeit module) my solution would be faster because it doesn't require converting the time to a string and back to an integer, but that is just a guess. The second two are equivalent because strftime() uses localtime() as the time if it is not provided. You should use whichever one you feel is more readable and expressive. Kent PS Please Reply All to reply to the list. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Executing a command from a specific directory
On Fri, 2009-09-18 at 14:46 +0530, Ansuman Dash wrote: > I have written it like that. It is like press 1 and it ll download > file1 and > press 2 it ll download file2 etc But without providing people how you accomplish this there is no way to help. > But my question was I am using "time.sleep()" to make my script to > wait for > the file download and then validate it in log file, so is there any > other > way I can synchronize my code with the download. This depends on how you are doing this. But *assuming* you are using subprocess you can check the returncode from the Popen object. When the return code is None the command is still running. Greets Sander A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? A: Top-posting. Q: What is the most annoying thing in e-mail? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Executing a command from a specific directory
Ansuman Dash wrote: Hi, I have written it like that. It is like press 1 and it ll download file1 and press 2 it ll download file2 etc What is "like that"? We are not psychic that could read your mind... Describe the way you downloaded the file. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] html color coding: where to start
On Thu, Sep 17, 2009 at 7:24 PM, Kent Johnson wrote: > 2009/9/17 Emad Nawfal (عماد نوفل) : > > Hi Tutors, > > I want to color-code the different parts of the word in a morphologically > > complex natural language. The file I have looks like this, where the > fisrt > > column is the word, and the second is the composite part of speech tag. > For > > example, Al is a DETERMINER, wlAy is a NOUN and At is a PLURAL NOUN > SUFFIX > > > > Al+wlAy+AtDET+NOUN+NSUFF_FEM_PL > > Al+mtHd+pDET+ADJ+NSUFF_FEM_SG > > > > The output I want is one on which the word has no plus signs, and each > > segment is color-coded with a grammatical category. For example, the noun > is > > red, the det is green, and the suffix is orange. Like on this page here: > > http://docs.google.com/View?id=df7jv9p9_3582pt63cc4 > > Here is an example that duplicates your google doc and generates > fairly clean, idiomatic HTML. It requires the HTML generation package > from > http://pypi.python.org/pypi/html/1.4 > > from html import HTML > > lines = ''' > Al+wlAy+AtDET+NOUN+NSUFF_FEM_PL > Al+mtHd+pDET+ADJ+NSUFF_FEM_SG > '''.splitlines() > > # Define colors in a CSS stylesheet > styles = ''' > .NOUN > {color: red } > > .ADJ > {color: brown } > > .DET > {color: green} > > .NSUFF_FEM_PL, .NSUFF_FEM_SG > {color: blue} > ''' > > h = HTML() > > with h.html: >with h.head: >h.title("Example") >h.style(styles) > >with h.body(newlines=True): >for line in lines: > line = line.split() >if len(line) != 2: continue >word = line[0] >pos = line[1] >zipped = zip(word.split("+"), pos.split("+")) > > for part, kind in zipped: >h.span(part, klass=kind) >h.br > > print h > > > Kent > Thank you Kent, and all, for the wonderful advice and contribution. -- لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.محمد الغزالي "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Executing a command from a specific directory
Hi, I have written it like that. It is like press 1 and it ll download file1 and press 2 it ll download file2 etc But my question was I am using "time.sleep()" to make my script to wait for the file download and then validate it in log file, so is there any other way I can synchronize my code with the download. I am asking this because some files are very huge (120MB) and download also depends on N/W bandwidth so sometimes it ll be done in 30mins and some times it takes 60 mins. So I can't rely on "time.sleep()" Thanks, Ansu On Fri, Sep 18, 2009 at 12:21 PM, Lie Ryan wrote: > Ansuman Dash wrote: > >> I am downloading files using various command (because files are different) >> meant for a executable. >> > > What is "various commands"? Are you using wget/curl or similar command-line > downloader programs? Or are you using a python-based script (that uses > urllib)? Or are you using a GUI-based downloader? > > Then how do you invoke those "various commands"? Are you using a separate > python and subprocess/popen to invoke them? Or are you using shell script? > Or do you start them manually? > > So I have created event driven program to download these files one by one. >> But some files are very huge so I want to know how can I synchronize it with >> my code. >> > > Can you modify this "event driven program" so it would call your script > when the files finished downloading? > > That means I want to make my code wait for the complete download of that >> file and then I ll read the log file and validate that download is >> successful. >> > > ___ > 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