Understanding Python's interpreter
Hello, I'm studying compilers now on my university and I can't quite understand one thing about the python interpreter. Why is its input a binary file (pyc)? The LOAD_CONST opcode is 100 (dec) and STORE_FAST's is 125 (dec). The translation of the following code: foo.py: x = 10 Could be this: foo.pyc: 100 10 125 0 That way you wouldn't need code such as static void w_long(long x, WFILE *p) { w_byte((char)( x & 0xff), p); w_byte((char)((x>> 8) & 0xff), p); w_byte((char)((x>>16) & 0xff), p); w_byte((char)((x>>24) & 0xff), p); } since you could read it with strtol and write back using a simple printf. So you wouldn't need a buch of casts by simple using ascii input and output. What's the reason for having it in a binary form instead of writting it in ascii? (yeah, I know ascii would be binary also, but I think you get my point.) So I was writting this interpreter for some assembly language defined in class and I did something like python does, so I had a binary file to interpret. After a while I thought it was far harder to program. And when I tried to code an assembler my problems got greater, as I wanted to code it in python (the interpreter was in C++) and I had a hard time trying to figure out how I would print something that's not a ascii or unicode string. As for the benefits, I couldn't figure out any. I hope I'm not too offtopic here, but I thought this was probably the best news to ask this. If someone thinks there's another news that's more appropriate, please tell me. []'s Rafael -- http://mail.python.org/mailman/listinfo/python-list
text extractor
Some one knows some python module for working with pdf files (extract text)? or any kind of document such as PostScript, doc, etc? thanks in advance -- http://mail.python.org/mailman/listinfo/python-list
Re: Extract zip file from email attachment
Basilisk96 wrote: > > > > Could the file like object still be encoded in MIME or something? > > > > Yes it is. You don't need to seek(0). > Try this: > > decoded = email.base64mime.decode(part.get_payload()) > fileObj.write(decoded) Or better: decoded = part.get_payload(decode=True) fileObj.write(decoded) fileObj.seek(0) zip = zipfile.ZipFile(fileObj) zip.printdir() -- http://mail.python.org/mailman/listinfo/python-list
Re: Extract zip file from email attachment
Basilisk96 wrote: > > > > Could the file like object still be encoded in MIME or something? > > > > Yes it is. You don't need to seek(0). > Try this: > > decoded = email.base64mime.decode(part.get_payload()) > fileObj.write(decoded) > > > -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Custom Python Runtime
Jack wrote: > Since the full installation of Python (from either the standard installer or > ActiveState installer) is too big for my intended use, I'd like to build a > custom distribution of Python for Windows platform, omitting some lib files, > such as audio, tk, printing, testing units, etc. > > Is there a way to customize the Windows build? In my case, there is no need > to build an installer. The best way is to have everything in a directory, as > long as I know where to find Python and Python knows where to find the > necessary libs. Any online docs describing this? Thanks! Perhaps the easiest way is start with the standard distribution and just delete whatever you don't want. I think that the Unicode tables are rather big and could be omited if you don't need them. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert xml symbol notation
dumbkiwi wrote: > I'm working on a script to download and parse a web page, and it > includes xml symbol notation, such as ' for the ' character. Does > anyone know of a pre-existing python script/lib to convert the xml > notation back to the actual symbol it represents? Try the htmlentitydefs module. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Mail not setting timestamp
Lorenzo Thurman wrote: > I'm using the Mimewriter and mimetools modules to create html messages. > They work OK, except that when the messages are received, they always > have the timestamp of 12/31/1969. I've looked through both packages and > can't find anything that would allow me to manually set it. Can someone > help me out? The date goes into the message headers, like From, To, Subject... message.add_header("Date", "Thu, 22 Jun 2006 23:18:15 -0300") -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Extract zip file from email attachment
> > Could the file like object still be encoded in MIME or something? > Yes it is. You don't need to seek(0). Try this: decoded = email.base64mime.decode(part.get_payload()) fileObj.write(decoded) -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: block scope?
John Nagle <[EMAIL PROTECTED]> writes: > In a language with few declarations, it's probably best not to > have too many different nested scopes. Python has a reasonable > compromise in this area. Functions and classes have a scope, but > "if" and "for" do not. That works adequately. I think Perl did this pretty good. If you say "my $i" that declares $i to have block scope, and it's considered good practice to do this, but it's not required. You can say "for (my $i=0; $i < 5; $i++) { ... }" and that gives $i the same scope as the for loop. Come to think of it you can do something similar in C++. -- http://mail.python.org/mailman/listinfo/python-list
Re: block scope?
Paul Rubin wrote: > James Stroud <[EMAIL PROTECTED]> writes: > >>Probably, with good code, block scope would be overkill, except that I >>would welcome list comprehensions to have a new scope: > > > Block scope is a win because it gets rid of the uncertainty of whether > the variable is used outside the block or not. In a language with few declarations, it's probably best not to have too many different nested scopes. Python has a reasonable compromise in this area. Functions and classes have a scope, but "if" and "for" do not. That works adequately. Javascript got it wrong. They have declarations, but the default, in the absence of a declaration, is global, not local or an error. Bad design. It's a result of retrofitting declarations to a language, which usually has painful aftereffects. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: block scope?
James Stroud <[EMAIL PROTECTED]> writes: > Probably, with good code, block scope would be overkill, except that I > would welcome list comprehensions to have a new scope: Block scope is a win because it gets rid of the uncertainty of whether the variable is used outside the block or not. The "good code" theory (just manually don't use the variable elsewhere) doesn't always hold up under release deadline pressure and so on and doesn't make sense anyway. What's the point of NOT having block scope if you don't want to allow for creating variables in inner blocks and using them in other blocks? I think it's best to require creating the variable in a mutually enclosing scope if you want to use it that way. -- http://mail.python.org/mailman/listinfo/python-list
Re: block scope?
Neal Becker wrote: > One thing I sometimes miss, which is common in some other languages (c++), > is idea of block scope. It would be useful to have variables that did not > outlive their block, primarily to avoid name clashes. This also leads to > more readable code. I wonder if this has been discussed? > Probably, with good code, block scope would be overkill, except that I would welcome list comprehensions to have a new scope: py> i Traceback (most recent call last): File "", line 1, in : name 'i' is not defined py> [i for i in xrange(4)] [0, 1, 2, 3] py> i # hoping for NameError 3 -- http://mail.python.org/mailman/listinfo/python-list
Re: Database Timestamp conversion error
On Apr 6, 6:20 pm, "John Machin" <[EMAIL PROTECTED]> wrote: > On Apr 7, 6:48 am, [EMAIL PROTECTED] wrote: > > > Hi, > > > I am populating a mySQL database with data from the MS Access > > database. I have successfully figured out how to extract the data from > > Access, and I can insert the data successfully into mySQL with Python. > > My problem is that I keep hitting screwy records with what appears to > > be a malformed dbiDate object when I insert certain records. I get the > > following traceback: > > Ummm ... I didn't start using Python on databases till after DB API > 2.0 came out (1999) so please pardon my ignorance, but isn't dbiDate > something that was in API 1.0 but vanished in API 2.0 [e.g. its > mentioned only briefly in the history section of the current mxODBC > docs]? > > If that's what you are still using: > (a) I can't imagine how printing a dbiDate object would give such a > garbled result -- try: > > print type(obj) > print repr(obj) > for both a "bad" obj and a "good" obj. > > (b) The API 1.0 docs give a clue: > """ > dbiDate(value) > > This function constructs a 'dbiDate' instance that holds a > date value. The value should be specified as an integer > number of seconds since the "epoch" (e.g. time.time()). > """ > and googling brought up a few hits mentioning that not handling dates > earlier that the "epoch" (1970-01-01T00:00:00) was a limitation. > > So: if you are calling dbiDate yourself, you can inspect its input > argument; presumably a date in the year 112 will show up as negative. > > > > > > > Traceback (most recent call last): > > File "\\someServer\Development\collectiveFleet.py", line 68, in - > > toplevel- > > mycursor.execute(sql) > > TypeError: argument 1 must be string without null bytes, not str > > > When I print the timestamp variable, I get this output: > > > (I31 > > (S'OK' > > p1 > > Nttp2 > > . > > > If I look in the MS Access database, I see the timestamp as "5/6/112". > > Obviously some user didn't enter the correct date and the programmer > > before me didn't give Access strict enough rules to block bad dates. > > How do I test for a malformed date object so I can avoid this? > > There > > are thousands of records to transfer. > > > I am using the odbc module for connection purposes with Python 2.4 on > > Windows XP SP2. > > If this is the odbc module that comes in the win32all package: > 1. There are much better options available on Windows e.g. mxODBC. > 2. Doesn't document dbiDate objects AFAICT. > > If your SELECT from the Access db is returning you "seconds since the > epoch" values, proceed as I suggested earlier. > > If it is returning you dbiDate objects directly, find out if the > dbiDate obj has any useful attributes or methods e.g. > > obj.date_as_tuple() -> (2007, 4, 7, ...) > or > obj.year -> 2007 > obj.month -> 4 > etc > > How to find out: insert code like > print dir(obj) > in your script and inspect the output for likely attribute/method > names. > > And if that doesn't help, abandon the odbc module and use e.g. mxODBC > or Python adodb. > > Hope some of this helps, > John I did find a workaround that I implemented right before it was quitting time, but I want to look into both of your guy's answers. I have used the adodb module and I can't recall why I switched to the odbc one. I think one of my co-workers said that the adodb wouldn't work with mySQL on Linux or something. The quick-fix I used included using the datetime module and the time module with the strftime() method. The type that was returned said it was a dbiDate object (which is what I think I get in one of my other programs that does use the adodb module!) John - when I tried printing a dir() on the returned object, I got and empty list. Thanks for the suggestions. I won't get to try them until Monday. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting Stack Trace on segfault
On Apr 6, 8:13 am, James Stroud <[EMAIL PROTECTED]> wrote: > Hello All, > > The built-in mac osx vecLib is segfaulting in some cases--A very fun > fact to find out the hard way over two nights of work. I also spent an > embarrassing amount of time figuring out just where. Although I'm in > quite a self-congratulatory mood right now, in the future, I feel like I > could save a lot of time by coercing the interpreter to spew forth > method calls to stderr. Is this possible? > > I would hope to produce something hauntingly reminiscent of > > [] my_function > [my_function] another_function > [my_function -> another_function] yet_a_deeper_function > > Presentation, of course, is irrelevant. > > I read the docs onpdb, but it did not seem to do what I want--unless, > of course, I missed something. > > James pydb (http://bashdb.sf.net0 has the ability to do noninteractive line tracing. See http://bashdb.sourceforge.net/pydb/pydb/lib/subsubsection-set.html or the showmedo demo. It would be kind of neat to extend this to allow for method/fn tracing. Alas the simple hack I tried, didn't work because of code obscurities. (The code could stand to use a rewrite.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Cant access http://cheeseshop.python.org/ or wiki
John Machin wrote: > On Apr 7, 10:43 am, cyb <[EMAIL PROTECTED]> wrote: >> For some reason I can ping these two sites fine, but when I try to go to >> them I cannot get to them. Normal python.org homepage works just fine. >> This is preventing me from getting setuptools and using pyOpenGL =( >> >> I'm using COmcast in savannah, GA > > FWIW: Same story for me with the cheeseshop; I'm in Australia. > Possibilities: (a) it's become a a Norwegian blue cheeseshop (b) it's > Lent; try fishshop.python.org > > The wiki's been bashed by spiders today. The offending IP addresses have now been filtered out and service should be back to normal. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Using os.popen3() to get binary data
On Apr 6, 6:09 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > On 6 Apr 2007 04:02:52 -0700, "Christoph Krammer" > <[EMAIL PROTECTED]> declaimed the following in comp.lang.python: > > > Hello everybody, > > > I need to get the different frames from a GIF image in my python > > script and want to use the giftopnm program from netpbm to get the > > frames and directly convert them to pnm files. I tried to use the > > following code: > > > for image in images: > > if (image[0:3] == 'GIF'): > > What type of data /is/ "image" that the FIRST three characters > identify the type? If it's the name of the file (I don't know what > giftopnm requires for input) I'd have expected the last three to > identify.. > [snip] FYI, the first 3 bytes of a GIF image are the ASCII characters "GIF". -- http://mail.python.org/mailman/listinfo/python-list
Re: Hide the python-script from user
On Sat, 07 Apr 2007 00:19:20 +0200, hlubenow wrote: > Hi, > > recently there was a thread about hiding the python-script from the user. > The OP could use > > http://freshmeat.net/projects/pyobfuscate/ Wearing my developer hat, I can tell you that there's nothing I love more than getting error reports from my users that look like this: Traceback (most recent call last): File "myapp.py", line 36, in ? print i1I1Iiii ( ) File "myapp.py", line 33, in i1I1Iiii return IiiIII111iI ( ) File "myapp.py", line 24, in IiiIII111iI O0oo0OO0 = IiII + I1i1iiI1 ( iI1Ii1iIi ) + i1i1II [ 2 ] - Oo ( ) File "myapp.py", line 18, in Oo raise iI1 ( "a problem happened" ) __main__.iI1: a problem happened I love a challenge! -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Mail not setting timestamp
I'm using the Mimewriter and mimetools modules to create html messages. They work OK, except that when the messages are received, they always have the timestamp of 12/31/1969. I've looked through both packages and can't find anything that would allow me to manually set it. Can someone help me out? TIA -- http://mail.python.org/mailman/listinfo/python-list
Re: Cant access http://cheeseshop.python.org/ or wiki
On Apr 7, 10:43 am, cyb <[EMAIL PROTECTED]> wrote: > For some reason I can ping these two sites fine, but when I try to go to > them I cannot get to them. Normal python.org homepage works just fine. > This is preventing me from getting setuptools and using pyOpenGL =( > > I'm using COmcast in savannah, GA FWIW: Same story for me with the cheeseshop; I'm in Australia. Possibilities: (a) it's become a a Norwegian blue cheeseshop (b) it's Lent; try fishshop.python.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Indentifying the LAST occurrence of an item in a list
On Apr 7, 9:25 am, "mkPyVS" <[EMAIL PROTECTED]> wrote: > On Apr 5, 6:37 pm, "John Machin" <[EMAIL PROTECTED]> wrote: > > >>> help(list.index) > > Help on method_descriptor: > > > index(...) > > L.index(value, [start, [stop]]) -> integer -- return first index > > of value > > > I look forward to your next version. > > Great point! I was assuming the temp variable space was static but the > pointer to the start of the list was moving-> shame on me (what > language is this now ;)! Indeed. IMHO every function/method that searches a sequence should have start/stop arguments so that the caller can search a slice without actually copying the slice. > > Couldn't resist the temptation to just collect all of the locations as > I traversed > > m = [2,9,1,5,6,3,1,1,9,2] > f = 1#What we're looking for > location = 0 #Start at beginning of list > fIndexs = [] > while 1: >try: > location = m.index(f,location) + 1 > fIndexs.append(location-1) >except ValueError: > break > > print("Last location = %d" % fIndexs[-1]) 1. print is a statement, not a function. 2. fIndexs[-1] will crash and burn if there are no occurrences of f in m. > print("All Items = %s" % fIndexs) FWIW, here's my take on a function that emulates the "missing" rindex method: 8<--- start rindex.py --- def rindex(seq, value, lo=0, hi=None): """If there is an x such that seq[x] == value and lo <= x < hi return the largest such x, else raise ValueError""" seqlen = len(seq) if lo < 0: lo += seqlen if lo < 0: lo = 0 if hi is None: hi = seqlen elif hi < 0: hi += seqlen if hi < 0: hi = 0 lo = seq.index(value, lo, hi) while True: try: lo = seq.index(value, lo + 1, hi) except ValueError: return lo if __name__ == "__main__": import sys av = sys.argv print rindex(av[4:], av[1], int(av[2]), int(av[3])) 8<--- end rindex.py --- Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Cant access http://cheeseshop.python.org/ or wiki
For some reason I can ping these two sites fine, but when I try to go to them I cannot get to them. Normal python.org homepage works just fine. This is preventing me from getting setuptools and using pyOpenGL =( I'm using COmcast in savannah, GA -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems with os.spawnv
On Apr 5, 3:25 pm, "Henrik Lied" <[EMAIL PROTECTED]> wrote: > > > I'd still love to get a working example of my problem using the > > > Subprocess module. :-) > > > The same thing: > > p = subprocess.Popen(["mencoder", "/users/...", "-ofps", ...]) > > That example looked great at first, but on a closer look it didn't > quite end up to be what I wanted. In a real environment the user still > had to wait for the command to finish. Then you are not using it correctly. subprocess.Popen() returns immediately. Notice the order of events here: In [2]: subprocess.Popen('sleep 2; echo foo', shell=True); print 'bar' bar foo -Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: SNMP agent
[EMAIL PROTECTED] (Cameron Laird) wrote: > I understand the sentiment; in principle, it shouldn't be hard > to write a library which supports construction of SNMP agents > in Python. I'm aware of no one who has done so publicly, though. I've used pysnmp (http://pysnmp.sourceforge.net/) in a test environment for a while. Only the manager side, never tried to implement an agent. It's pure python, so it's very portable. In theory, that also means it's not very fast, but for what I've ever wanted it for, it was plenty fast enough. The latest NetSNMP release apparently now includes a python binding (http://www.net-snmp.org/docs/NEWS.html). I have not had a chance to use it, but it sounds good. -- http://mail.python.org/mailman/listinfo/python-list
Custom Python Runtime
Since the full installation of Python (from either the standard installer or ActiveState installer) is too big for my intended use, I'd like to build a custom distribution of Python for Windows platform, omitting some lib files, such as audio, tk, printing, testing units, etc. Is there a way to customize the Windows build? In my case, there is no need to build an installer. The best way is to have everything in a directory, as long as I know where to find Python and Python knows where to find the necessary libs. Any online docs describing this? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Hide the python-script from user
hlubenow wrote: > ts-dev wrote: > >> On Apr 6, 3:19 pm, hlubenow <[EMAIL PROTECTED]> wrote: >>> recently there was a thread about hiding the python-script from the >>> user. The OP could use >> >> Interesting - thanks > > Well, testing it, it doesn't seem to work very well ... > > It seems, Python-code is rather difficult to obfuscate, probably because > of its clear syntax and indentations. Here's yet another approach: > > http://pythonhacker.is-a-geek.net/my_programs/pyfuscate/pyfuscate-0.1.zip/view > > H. That didn't work very well either :(. Ok, but now I can offer a real secure solution: You can have real encryption in Python using this modules: http://www.amk.ca/files/python/crypto/pycrypto-2.0.1.tar.gz and http://sourceforge.net/projects/yawpycrypto Below I post a code-example that I've written some time ago. With it, encrypting text is rather easy. Then you have to program a start-script, that reads in your script and the decryption-key. The decryption-key must be encrypted too. Such a encrypted key can be generated by the modules if you don't pass a password to my function "doEncrypt(). The decryption-key must then be hidden somewhere within the encrypted program-script. That's because, if the user knows where to find the key, he can decrypt the program-script. If your start-script is written, everything should work automatically, one shouldn't nearly notice the decryption-process. Ok, here's my example code, how to encrypt and decrypt some text with the modules: #!/usr/bin/env python import os import sys import base64 from yawPyCrypto.Cipher import DecryptCipher, EncryptCipher from yawPyCrypto.Cipher import ZipDecryptCipher, ZipEncryptCipher from yawPyCrypto.Constants import CIPHER_BLOWFISH, MODE_CBC def doEncrypt(text, passw = None): e = EncryptCipher(passw, CIPHER_BLOWFISH, MODE_CBC) e.feed(text) e.finish() encryptedtext = e.data if passw != None: passwr = passw else: passwr = e.password a = (encryptedtext, passwr) return a def doDecrypt(encryptedtext, passw): d = DecryptCipher(passw) d.feed(encryptedtext) d.finish() decoded = (d.data) return decoded # Calling the encryption routine. # If you just pass the text to encrypt, a password is generated: a = doEncrypt("For your eyes only !", "Melina") # Just trying to clean the screen: if sys.platform == "win32": os.system("cls") else: os.system("clear") print print "Hello !" print print "I just encrypted some text. It looks like this now:" print print base64.b64encode(a[0]) print print 'Please notice, that I just encoded the text once more using "base64.b64encode()" to make it printable.' print print "The password for decryption is: " print print base64.b64encode(a[1]) print print "Let's decrypt again (the original password must be passed without b64encoding):" print print doDecrypt(a[0], a[1]) print See you H. -- http://mail.python.org/mailman/listinfo/python-list
Re: Comments in ConfigParser module
Joel Andres Granados wrote: > Hi list: > Any comment greatly appreciated Very clever. -- http://mail.python.org/mailman/listinfo/python-list
Re: Indentifying the LAST occurrence of an item in a list
On Apr 5, 6:37 pm, "John Machin" <[EMAIL PROTECTED]> wrote: >>> help(list.index) > Help on method_descriptor: > > index(...) > L.index(value, [start, [stop]]) -> integer -- return first index > of value > > I look forward to your next version. Great point! I was assuming the temp variable space was static but the pointer to the start of the list was moving-> shame on me (what language is this now ;)! Couldn't resist the temptation to just collect all of the locations as I traversed m = [2,9,1,5,6,3,1,1,9,2] f = 1#What we're looking for location = 0 #Start at beginning of list fIndexs = [] while 1: try: location = m.index(f,location) + 1 fIndexs.append(location-1) except ValueError: break print("Last location = %d" % fIndexs[-1]) print("All Items = %s" % fIndexs) -- http://mail.python.org/mailman/listinfo/python-list
Re: Database Timestamp conversion error
On Apr 7, 6:48 am, [EMAIL PROTECTED] wrote: > Hi, > > I am populating a mySQL database with data from the MS Access > database. I have successfully figured out how to extract the data from > Access, and I can insert the data successfully into mySQL with Python. > My problem is that I keep hitting screwy records with what appears to > be a malformed dbiDate object when I insert certain records. I get the > following traceback: Ummm ... I didn't start using Python on databases till after DB API 2.0 came out (1999) so please pardon my ignorance, but isn't dbiDate something that was in API 1.0 but vanished in API 2.0 [e.g. its mentioned only briefly in the history section of the current mxODBC docs]? If that's what you are still using: (a) I can't imagine how printing a dbiDate object would give such a garbled result -- try: print type(obj) print repr(obj) for both a "bad" obj and a "good" obj. (b) The API 1.0 docs give a clue: """ dbiDate(value) This function constructs a 'dbiDate' instance that holds a date value. The value should be specified as an integer number of seconds since the "epoch" (e.g. time.time()). """ and googling brought up a few hits mentioning that not handling dates earlier that the "epoch" (1970-01-01T00:00:00) was a limitation. So: if you are calling dbiDate yourself, you can inspect its input argument; presumably a date in the year 112 will show up as negative. > > Traceback (most recent call last): > File "\\someServer\Development\collectiveFleet.py", line 68, in - > toplevel- > mycursor.execute(sql) > TypeError: argument 1 must be string without null bytes, not str > > When I print the timestamp variable, I get this output: > > (I31 > (S'OK' > p1 > Nttp2 > . > > If I look in the MS Access database, I see the timestamp as "5/6/112". > Obviously some user didn't enter the correct date and the programmer > before me didn't give Access strict enough rules to block bad dates. > How do I test for a malformed date object so I can avoid this? > There > are thousands of records to transfer. > > I am using the odbc module for connection purposes with Python 2.4 on > Windows XP SP2. If this is the odbc module that comes in the win32all package: 1. There are much better options available on Windows e.g. mxODBC. 2. Doesn't document dbiDate objects AFAICT. If your SELECT from the Access db is returning you "seconds since the epoch" values, proceed as I suggested earlier. If it is returning you dbiDate objects directly, find out if the dbiDate obj has any useful attributes or methods e.g. obj.date_as_tuple() -> (2007, 4, 7, ...) or obj.year -> 2007 obj.month -> 4 etc How to find out: insert code like print dir(obj) in your script and inspect the output for likely attribute/method names. And if that doesn't help, abandon the odbc module and use e.g. mxODBC or Python adodb. Hope some of this helps, John -- http://mail.python.org/mailman/listinfo/python-list
Re: 08 and 09 in sequence create "invalid token" error?!
Thank you! Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: 08 and 09 in sequence create "invalid token" error?!
IamIan wrote: > I am confused as to why including 08 or 09 in a sequence (list or > tuple) causes this error. All other numbers with a leading zero work. All literals that start with "0" digit are considered as octal numbers, i.e. only digits "0".."7" are allowed. See octinteger lexical definition: http://docs.python.org/ref/integers.html w. -- http://mail.python.org/mailman/listinfo/python-list
08 and 09 in sequence create "invalid token" error?!
Hello all, I am confused as to why including 08 or 09 in a sequence (list or tuple) causes this error. All other numbers with a leading zero work. [01,02,03,04,05,06,07] is fine [01,02,03,04,05,06,07,10] is fine [01,02,03,04,05,06,08] produces "SyntaxError: invalid token", as does: [01,02,03,04,05,06,09] I have tried this both in a script and in the interactive interpreter. Using Python 2.3.4 Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Hide the python-script from user
ts-dev wrote: > On Apr 6, 3:19 pm, hlubenow <[EMAIL PROTECTED]> wrote: >> recently there was a thread about hiding the python-script from the user. >> The OP could use > > Interesting - thanks Well, testing it, it doesn't seem to work very well ... It seems, Python-code is rather difficult to obfuscate, probably because of its clear syntax and indentations. Here's yet another approach: http://pythonhacker.is-a-geek.net/my_programs/pyfuscate/pyfuscate-0.1.zip/view H. -- http://mail.python.org/mailman/listinfo/python-list
Convert xml symbol notation
Hi, I'm working on a script to download and parse a web page, and it includes xml symbol notation, such as ' for the ' character. Does anyone know of a pre-existing python script/lib to convert the xml notation back to the actual symbol it represents? -- http://mail.python.org/mailman/listinfo/python-list
Re: Hide the python-script from user
On Apr 6, 3:19 pm, hlubenow <[EMAIL PROTECTED]> wrote: > recently there was a thread about hiding the python-script from the user. > The OP could use Interesting - thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: printing longs
On Apr 7, 7:54 am, "garyp" <[EMAIL PROTECTED]> wrote: > Python 2.3.4 (#1, Oct 26 2004, 16:42:40) > [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 > > >>> x = int("8000", 16) > >>> x = x | 0x8000 > > :1: FutureWarning: hex/oct constants > sys.maxint will return > positive values in Python 2.4 and up As your subject says, you are working with longs, so don't mix in an int (0x800, which is negative in Python 2.3 and earlier) -- use 0x800L instead. > > >>> print "%x" % ( x ) > -8000 "%x" % x is enough. > > How do I get python to print the usual answer: 800, not -8000 "usual" in what context? Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Hide the python-script from user
Hi, recently there was a thread about hiding the python-script from the user. The OP could use http://freshmeat.net/projects/pyobfuscate/ H. -- http://mail.python.org/mailman/listinfo/python-list
printing longs
Python 2.3.4 (#1, Oct 26 2004, 16:42:40) [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 >>> x = int("8000", 16) >>> x = x | 0x8000 :1: FutureWarning: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up >>> print "%x" % ( x ) -8000 >>> How do I get python to print the usual answer: 800, not -8000 Thanks, Gary -- http://mail.python.org/mailman/listinfo/python-list
Re: Database Timestamp conversion error
On Apr 6, 1:48 pm, [EMAIL PROTECTED] wrote: (snipped) > If I look in the MS Access database, I see the timestamp as "5/6/112". > Obviously some user didn't enter the correct date and the programmer > before me didn't give Access strict enough rules to block bad dates. > How do I test for a malformed date object so I can avoid this? There > are thousands of records to transfer. > time.strptime ? import time for date in ("5/6/2008", "5/6/118"): try: struct_tm = time.strptime(date, "%m/%d/%Y") print "Good date: " + date print struct_tm except ValueError: print "Bad date: " + date -- Hope this helps, Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Debugging multithreaded program using Eclipse/Pydev
On Apr 6, 1:33 pm, Michael Bentley <[EMAIL PROTECTED]> wrote: > On Apr 6, 2007, at 2:32 PM, John Henry wrote: > > > I am back against the wall trying to migrate my multithreaded > > application from Python 2.3 to 2.5. The part of the code that's > > failing has to do with queues (2.3 queues and 2.5 queues are not the > > same). Since WingIDE doesn't support multithread debugging (they've > > been saying that one day they might support that - and that was 2003), > > I am starting to look for alternatives. > > The alpha release of Wing IDE (3.0.0-a1) does in fact, support > multithread debugging. It is an alpha release but so far, I'm quite > satisfied with it. > > hth, > Michael That's nice to know. May be I can get on their alpha list. Thanks, -- http://mail.python.org/mailman/listinfo/python-list
Re: British Marines Were tortured In Iran According to the Washington Conventions Re: Dr Jeff King, A Jewish MIT Engineer is the LEAD SPEAKER on 911 truth, no Islamics involved http://video.google.com
On Apr 6, 1:06 pm, [EMAIL PROTECTED] wrote: > We have just heard the news that the British Marines are ashamed to > admit that they were tortured with Electric Wires to their Genitalia > and two of them have had their penises bitten while a third ones > testicles were eaten by an Iranian dog for the meal. People are now > preferring the AbuGharib and Guantanamo style Washington Conventions > over the Geneva Conventions. stj911: That was indeed a good pun at the BASTARDS of the tribal bastards. Such CONTEMPTIBLE liars. There is no comparison between the bening Iranian treatment and the Bastards give in ABU-GHRAIB, and GUANTANAMO and the SECRET DETENTION CENTERS of the CRIMINAL INTERNATIONAL AGENCY whose chief at one time was the PEDOPHILE Herbert Walter Bush the most even man alive after his son. Even Newt Gingrich, who cheated on both his wives has not that much blood on his both hands. They were injected with LSD, carcinogens, poisons, mind altering drugs by the yank bastards. The zionist press has published these openly with relish and when it became an issue, the pawns were given contemptibly token punishment. > On Apr 6, 9:43 am, [EMAIL PROTECTED] wrote: > > > See the video with your own EYEBALLS, that is if you have some courage > > and shame left: > > >http://video.google.com/videoplay?docid=1822764959599063248 > > > On Apr 6, 9:39 am, [EMAIL PROTECTED] wrote: > > > > On Apr 4, 6:31 pm, "Dr. V I Plankenstein" <[EMAIL PROTECTED]> > > > wrote: > > > > > The anthrax attack was almost certainly carried out by someone who had > > > > access to Gov labs or other secure facilities, but the attack on WTC > > > > was an > > > > act of Islamic fanaticism, and you're an ass to suggest otherwise > > > > without > > > > having some very solid proof to back your ridiculous claims - which you > > > > lack. > > > > You are a LYING SPOOK from the FOOLISH BUREAU OF INCOMPETENCE. > > > > If the ODIOUS George W Bush did not inform the American Public (Who > > > pays his salary) that Anthrax Attack was by a YANK BASTARD, then it > > > must not be so. > > > > On the other hand if the Anthrax Attack was produced on such short > > > notice and such coordination with the whole 911, then 911 was ALL done > > > by yank bastards themselves and George W Bush is a prime suspect with > > > all his underlings. > > > > ABSENSE OF EVIDENCE IS NOT THE EVIDENCE OF ABSENSE. > > > > 911 was a heinous crime done by RACIST and UTTERLY SELFISH yank > > > bastards themselves. -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Serialization - a design decision question
"Gizmo" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] | Hello | I am a relative newcomer to Python, and I am studying it to understand its | design. It intrigues me. | I recently studied Serialization of classes via the pickle/cPickle library, | and I have a question. | | Why is Serialization handled by a separate library (ie, pickle). Is it | possible, by design, to have serialization "internally" implemented via an | implicit ___serialize___ method? Ofcourse, you have to make this method not | overrideable (sp?). For example, the __repr__ method gives us the string | representation of a class... similarly, the __serialize__ method would give | us the "serial norm" representation of the class. Pickle has the factored-out code common to all classes. It uses .__reduce__() for each, which has the class-specific code. | This would allow me to do something like this, | conn.send(serial(myClass)); // or something like that? I believe pickle does more than just that. tjr -- http://mail.python.org/mailman/listinfo/python-list
Database Timestamp conversion error
Hi, I am populating a mySQL database with data from the MS Access database. I have successfully figured out how to extract the data from Access, and I can insert the data successfully into mySQL with Python. My problem is that I keep hitting screwy records with what appears to be a malformed dbiDate object when I insert certain records. I get the following traceback: Traceback (most recent call last): File "\\someServer\Development\collectiveFleet.py", line 68, in - toplevel- mycursor.execute(sql) TypeError: argument 1 must be string without null bytes, not str When I print the timestamp variable, I get this output: (I31 (S'OK' p1 Nttp2 . If I look in the MS Access database, I see the timestamp as "5/6/112". Obviously some user didn't enter the correct date and the programmer before me didn't give Access strict enough rules to block bad dates. How do I test for a malformed date object so I can avoid this? There are thousands of records to transfer. I am using the odbc module for connection purposes with Python 2.4 on Windows XP SP2. Thanks a lot! Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Debugging multithreaded program using Eclipse/Pydev
On Apr 6, 2007, at 2:32 PM, John Henry wrote: > I am back against the wall trying to migrate my multithreaded > application from Python 2.3 to 2.5. The part of the code that's > failing has to do with queues (2.3 queues and 2.5 queues are not the > same). Since WingIDE doesn't support multithread debugging (they've > been saying that one day they might support that - and that was 2003), > I am starting to look for alternatives. The alpha release of Wing IDE (3.0.0-a1) does in fact, support multithread debugging. It is an alpha release but so far, I'm quite satisfied with it. hth, Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: real time updating of popen, bufsize=0 problems
On Apr 6, 3:59 pm, Rob Wolfe <[EMAIL PROTECTED]> wrote: > "ianaré" <[EMAIL PROTECTED]> writes: > > hey all, I'm trying to get real time updates of batch file output. > > [...] > > > So I tried subprocess: > > proc = subprocess.Popen('"C:/path/to/test.bat"', bufsize=0, > > stdout=subprocess.PIPE) > > Instead of that: > > > for line in proc.stdout: > > self.display.WriteText(line) > > try that: > > while True: > line = proc.stdout.readline() > if not line: break > self.display.WriteText(line) > > When a file is used in a for loop it works like an iterator. > You can read details here (description of method > ``next``):http://docs.python.org/lib/bltin-file-objects.html > > -- > HTH, > Rob Rob, you are the man =) thanks! -- http://mail.python.org/mailman/listinfo/python-list
British Marines Were tortured In Iran According to the Washington Conventions Re: Dr Jeff King, A Jewish MIT Engineer is the LEAD SPEAKER on 911 truth, no Islamics involved http://video.google.com/vid
We have just heard the news that the British Marines are ashamed to admit that they were tortured with Electric Wires to their Genitalia and two of them have had their penises bitten while a third ones testicles were eaten by an Iranian dog for the meal. People are now preferring the AbuGharib and Guantanamo style Washington Conventions over the Geneva Conventions. On Apr 6, 9:43 am, [EMAIL PROTECTED] wrote: > See the video with your own EYEBALLS, that is if you have some courage > and shame left: > > http://video.google.com/videoplay?docid=1822764959599063248 > > On Apr 6, 9:39 am, [EMAIL PROTECTED] wrote: > > > On Apr 4, 6:31 pm, "Dr. V I Plankenstein" <[EMAIL PROTECTED]> > > wrote: > > > > The anthrax attack was almost certainly carried out by someone who had > > > access to Gov labs or other secure facilities, but the attack on WTC was > > > an > > > act of Islamic fanaticism, and you're an ass to suggest otherwise without > > > having some very solid proof to back your ridiculous claims - which you > > > lack. > > > You are a LYING SPOOK from the FOOLISH BUREAU OF INCOMPETENCE. > > > If the ODIOUS George W Bush did not inform the American Public (Who > > pays his salary) that Anthrax Attack was by a YANK BASTARD, then it > > must not be so. > > > On the other hand if the Anthrax Attack was produced on such short > > notice and such coordination with the whole 911, then 911 was ALL done > > by yank bastards themselves and George W Bush is a prime suspect with > > all his underlings. > > > ABSENSE OF EVIDENCE IS NOT THE EVIDENCE OF ABSENSE. > > > 911 was a heinous crime done by RACIST and UTTERLY SELFISH yank > > bastards themselves. -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML Parser in python
Beautiful Soup. http://www.crummy.com/software/BeautifulSoup/ Works, well...beautifully. -- http://mail.python.org/mailman/listinfo/python-list
Re: real time updating of popen, bufsize=0 problems
"ianaré" <[EMAIL PROTECTED]> writes: > hey all, I'm trying to get real time updates of batch file output. [...] > So I tried subprocess: > proc = subprocess.Popen('"C:/path/to/test.bat"', bufsize=0, > stdout=subprocess.PIPE) Instead of that: > for line in proc.stdout: > self.display.WriteText(line) try that: while True: line = proc.stdout.readline() if not line: break self.display.WriteText(line) When a file is used in a for loop it works like an iterator. You can read details here (description of method ``next``): http://docs.python.org/lib/bltin-file-objects.html -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Serialization - a design decision question
Gizmo wrote: > Hello > I am a relative newcomer to Python, and I am studying it to understand > its design. It intrigues me. > I recently studied Serialization of classes via the pickle/cPickle > library, and I have a question. > > Why is Serialization handled by a separate library (ie, pickle). Is it > possible, by design, to have serialization "internally" implemented via > an implicit ___serialize___ method? Ofcourse, you have to make this > method not overrideable (sp?). For example, the __repr__ method gives us > the string representation of a class... similarly, the __serialize__ > method would give us the "serial norm" representation of the class. > > This would allow me to do something like this, > conn.send(serial(myClass)); // or something like that? > > Thoughts? > > > It would be quite possible to do this - it just hasn't been done, is all. I'm not quite sure what advantage you see for serial(myClass) over pickle.dumps(myClass) though. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Question about sequence multiplication
Scott wrote: [...] > > Now when suggesting books, keep in mind that, that while I'm new to Python > (and programming in general) I'm able to grasp difficult concepts as long > as I have enough detail as to why it is the way it is. For instance I'm, by > experience and nature, a computer technician and communications specialist. > I've studied, everything from childrens walkie talkie to deep space > satalittes back to how computers talk (which is why I'm here now trying to > learn the language of computers). And all that just because I have a > unquenchable desire to know. SO, with that all said, the more details the > better. If you have a book with 4 chapters on functions..I want to read > it. > > Any help would be greatly appreciated. As I've said, this is something that > I feel I have to know. > "Dive into Python" is probably the best free read about Python for programmers. It takes you in deep much more quickly that the tutorial, but if you can understand it you develop quite a sophisticated understanding of the language in a fairly short time. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: real time updating of popen, bufsize=0 problems
On Apr 6, 3:22 pm, [EMAIL PROTECTED] wrote: > On Apr 6, 1:44 pm, "ianaré" <[EMAIL PROTECTED]> wrote: > > > > > hey all, I'm trying to get real time updates of batch file output. > > > Here is my batch file: > > @echo off > > echo 1 > > @ping 127.0.0.1 -n 2 -w 1500 > nul > > echo 2 > > @ping 127.0.0.1 -n 2 -w 1500 > nul > > echo 3 > > > If I run it in cmd.exe it will print "1", wait 15sec, print "2", wait > > 15sec, print "3". > > > I tried doing it like this: > > > r, w, e = popen2.popen3('"C:/path/to/test.bat"',bufsize=0) > > for line in r: > > self.display.WriteText(line) > > > ... but get: ValueError: popen3() arg 3 must be -1 > > > If I use -1, then it waits for the batch file to complete, and prints > > out all 3 lines at once. > > > So I tried subprocess: > > proc = subprocess.Popen('"C:/path/to/test.bat"', bufsize=0, > > stdout=subprocess.PIPE) > > for line in proc.stdout: > > self.display.WriteText(line) > > > No error message, but no real time printing either. > > > info: > > self.display is a wx.TextCtrl - not that it should matter,as > > 'WriteText()' behaves basically like 'print' > > winXP pro SP2, python 2.5, wxPython 2.6.3.3 > > > You help is appreciated. > > Hi, > > I think this script on another post will help: > > http://groups.google.com/group/comp.lang.python/msg/9fa3a3c287e8e2a3?... > > The 4 line code example (from Daniel) in one of the posts at this link > worked with your batch > file:http://www.velocityreviews.com/forums/t350573-redirect-ossystem-outpu... > > Mike Thanks but it doesn't work. Still prints it out all at once. It is supposed to print, then wait 15sec for the next line to print. -- http://mail.python.org/mailman/listinfo/python-list
Debugging multithreaded program using Eclipse/Pydev
I am back against the wall trying to migrate my multithreaded application from Python 2.3 to 2.5. The part of the code that's failing has to do with queues (2.3 queues and 2.5 queues are not the same). Since WingIDE doesn't support multithread debugging (they've been saying that one day they might support that - and that was 2003), I am starting to look for alternatives. >From what I can gather, it appears the only *real* option I have is to debug under Eclipse/Pydev. I did a google search of this newsgroup and didn't turn up too many hits. Before I invest the time to learn Eclipse/Pydev, I like to hear from somebody that have gone this path. Have you been successful in using Eclipse/Pydev to debug multi- threaded Python applications? Is so, what was the learning curve like to you? Thanks, -- http://mail.python.org/mailman/listinfo/python-list
Re: real time updating of popen, bufsize=0 problems
On Apr 6, 1:44 pm, "ianaré" <[EMAIL PROTECTED]> wrote: > hey all, I'm trying to get real time updates of batch file output. > > Here is my batch file: > @echo off > echo 1 > @ping 127.0.0.1 -n 2 -w 1500 > nul > echo 2 > @ping 127.0.0.1 -n 2 -w 1500 > nul > echo 3 > > If I run it in cmd.exe it will print "1", wait 15sec, print "2", wait > 15sec, print "3". > > I tried doing it like this: > > r, w, e = popen2.popen3('"C:/path/to/test.bat"',bufsize=0) > for line in r: > self.display.WriteText(line) > > ... but get: ValueError: popen3() arg 3 must be -1 > > If I use -1, then it waits for the batch file to complete, and prints > out all 3 lines at once. > > So I tried subprocess: > proc = subprocess.Popen('"C:/path/to/test.bat"', bufsize=0, > stdout=subprocess.PIPE) > for line in proc.stdout: > self.display.WriteText(line) > > No error message, but no real time printing either. > > info: > self.display is a wx.TextCtrl - not that it should matter,as > 'WriteText()' behaves basically like 'print' > winXP pro SP2, python 2.5, wxPython 2.6.3.3 > > You help is appreciated. Hi, I think this script on another post will help: http://groups.google.com/group/comp.lang.python/msg/9fa3a3c287e8e2a3?hl=en&; The 4 line code example (from Daniel) in one of the posts at this link worked with your batch file: http://www.velocityreviews.com/forums/t350573-redirect-ossystem-output.html Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On Fri, 2007-04-06 at 11:33 -0700, 7stud wrote: > On Apr 6, 7:56 am, "Paul Boddie" <[EMAIL PROTECTED]> wrote: > > The problem with 7stud's quote from GvR is that it's out of date: > > I would argue that it shows the very guy who invented the language > stated publicly there was no good reason for tuples not to have an > index method---except for consistency; tuples had no other methods. > Now that tuples have other methods, the only justification he stated > no longer exists. Except that that wasn't the only justification. GvR also said: """ For tuples, I suspect such a function would rarely be used; I think that is most cases where x.index() would be useful, x is generally a list, whose contents varies in time, rather than a tuple (which cannot change easily). """ The lack of convincing use cases is still a pertinent reason today. Note that the original poster on this thread did not present a use case for tuple.index, they were only asking out of curiosity. If you have a use case for tuple.index, please show it to me, and I'll show you what you should be using instead of a tuple. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Serialization - a design decision question
Gizmo wrote: > Hello > I am a relative newcomer to Python, and I am studying it to understand > its design. It intrigues me. > I recently studied Serialization of classes via the pickle/cPickle > library, and I have a question. > > Why is Serialization handled by a separate library (ie, pickle). Is it > possible, by design, to have serialization "internally" implemented via > an implicit ___serialize___ method? Ofcourse, you have to make this > method not overrideable (sp?). For example, the __repr__ method gives us > the string representation of a class... similarly, the __serialize__ > method would give us the "serial norm" representation of the class. > > This would allow me to do something like this, > conn.send(serial(myClass)); // or something like that? Serialization is a complicated task. It needs at least a full module devoted to it just in terms of being able to implement it. Trying to stuff all of it into a builtin is asking for trouble. Of course, you can always do this: from cPickle import dumps ... conn.send(dumps(myClass)) -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Picture resolution and PIL
Johny: > Is it possible to find out a picture resolution by using PIL package By Gian Mario Tagliaretti: import PIL.Image a = PIL.Image.open("foo.jpg") a.info["dpi"] (72, 72) (It may raise an exception if that information isn't available) I don't know if that can be used to read the DPI tag inside a TIFF image. You can also read the pixel size of any image. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
SWIG, Python, C++, and Coca-Cola
Hi Everyone, Recently I have been working on building a module for Python from C++ code, with SWIG, and towards the end of compiling the various sets of code I'm getting an error. [comp:~/swig_project] user% swig -c++ -python example.i [comp:~/swig_project] user% g++ -c example.cpp [comp:~/swig_project] user% g++ -c example_wrap.cxx -I/scisoft/i386/ Packages/Python-2.4.3/Python.framework/Versions/2.4/include/python2.4/ example_wrap.cxx: In function 'PyObject* _wrap_main(PyObject*, PyObject*)': example_wrap.cxx:735: error: 'main' was not declared in this scope The beginning of example.i looks like the following: %module filename %{ #define file_plugin "plugins/file.h" #if foo_OS!=2 #include #endif #include "../Foo.h" using namespace foo_library; %} The error that is being picked up in reference to 'main' is contained in the following excerpt, generated by SWIG (example_wrap.cxx): /*--- @(target):= _filename.so */ #define SWIG_initinit_filename #define SWIG_name"_filename" #define cimg_plugin "plugins/file.h" #if foo_OS!=2 #include #endif #include "../Foo.h" using namespace foo_library; #ifdef __cplusplus extern "C" { #endif static PyObject *_wrap_main(PyObject *self, PyObject *args) { PyObject *resultobj; int arg1 ; char **arg2 = (char **) 0 ; int result; PyObject * obj1 = 0 ; if(!PyArg_ParseTuple(args,(char *)"iO:main",&arg1,&obj1)) goto fail; if ((SWIG_ConvertPtr(obj1,(void **) &arg2, SWIGTYPE_p_p_char,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail; result = (int)main(arg1,arg2); resultobj = PyInt_FromLong((long)result); return resultobj; fail: return NULL; } Any clues as to what is happening here or what to do next? If you know, your help would greatly help. Thanks in advance! -- http://mail.python.org/mailman/listinfo/python-list
Re:
C.L. wrote: > James Stroud mbi.ucla.edu> writes: >> C.L. wrote: >>> I was looking for a function or method that would return the index to the >>> first matching element in a list. ... >>> ... __please don't be overly defensive__ ... >> The amount of typing wasted to defend design decisions such as this can >> boggle one's mind. Just use lists unless you have on overwhelming reason >> to do otherwise. >> >> James > > > Read the quote. I *am* using a list. > > That doesn't change the fact that this is unfriendly design. It's an ugly > inconsistent chunk of a Python's past in which built-in types didn't behave > like > objects. It sticks out like a sore thumb, maybe just not very often. > > Oh, and thanks for the insulting tone of your anticipated response. Have you > anything better to do with your time than wasting bytes writing empty > responses > to what you already deem a waste of typing? > > *sighs* just what I expected: another idle troll defending something just for > the sake of defending it. On the other hand, thanks 7stud, for the truly > helpful > response. > I think you misinterpreted my post, I agree with you. Please read it again. You have touched on a very old topic. Many people have fought tooth and nail to defend arbitrary design decisions such as a tuple not having an index. It boils down to the fact that tuples are useless as a result unless you know you really need them--and you never really NEED them. James -- http://mail.python.org/mailman/listinfo/python-list
Re: zip files as nested modules?
Importing modules from zip files was proposed in PEP-273 [1] Here is how the spec of PEP-273 begins: ''' Currently, sys.path is a list of directory names as strings. If this PEP is implemented, an item of sys.path can be a string naming a zip file archive. ''' My interpretation of the above is that, to be importable, a zip file must be explicitly named in sys.path. So the mere fact that a zip file lies somewhere in a directory which is part of the sys.path does not make it importable. Cheers, Luciano [1] http://www.python.org/dev/peps/pep-0273/ -- http://mail.python.org/mailman/listinfo/python-list
real time updating of popen, bufsize=0 problems
hey all, I'm trying to get real time updates of batch file output. Here is my batch file: @echo off echo 1 @ping 127.0.0.1 -n 2 -w 1500 > nul echo 2 @ping 127.0.0.1 -n 2 -w 1500 > nul echo 3 If I run it in cmd.exe it will print "1", wait 15sec, print "2", wait 15sec, print "3". I tried doing it like this: r, w, e = popen2.popen3('"C:/path/to/test.bat"',bufsize=0) for line in r: self.display.WriteText(line) ... but get: ValueError: popen3() arg 3 must be -1 If I use -1, then it waits for the batch file to complete, and prints out all 3 lines at once. So I tried subprocess: proc = subprocess.Popen('"C:/path/to/test.bat"', bufsize=0, stdout=subprocess.PIPE) for line in proc.stdout: self.display.WriteText(line) No error message, but no real time printing either. info: self.display is a wx.TextCtrl - not that it should matter,as 'WriteText()' behaves basically like 'print' winXP pro SP2, python 2.5, wxPython 2.6.3.3 You help is appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
On Apr 6, 7:56 am, "Paul Boddie" <[EMAIL PROTECTED]> wrote: > The problem with 7stud's quote from GvR is that it's out of date: I would argue that it shows the very guy who invented the language stated publicly there was no good reason for tuples not to have an index method---except for consistency; tuples had no other methods. Now that tuples have other methods, the only justification he stated no longer exists. -- http://mail.python.org/mailman/listinfo/python-list
Re: Picture resolution and PIL
On Apr 6, 1:16 pm, "Johny" <[EMAIL PROTECTED]> wrote: > Is it possible to find out a picture resolution by using PIL package? > Thanks for help > L. Dunno. But I found some ways to read metadata that should give you the info in most cases: http://snippets.dzone.com/posts/show/768 http://hachoir.org/wiki/hachoir-metadata Hope that helps, Mike -- http://mail.python.org/mailman/listinfo/python-list
Picture resolution and PIL
Is it possible to find out a picture resolution by using PIL package? Thanks for help L. -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML Parser in python
On Apr 6, 1:05 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > Hi, > > Is there a HTML parser (not xml) in python? > I need a html parser which has the ability to handle mal-format html > pages. > > Thank you. Yeah...it's called Beautiful Soup. http://www.crummy.com/software/BeautifulSoup/ Mike -- http://mail.python.org/mailman/listinfo/python-list
HTML Parser in python
Hi, Is there a HTML parser (not xml) in python? I need a html parser which has the ability to handle mal-format html pages. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Prevent Modification of Script?
On Wednesday, Apr 4th 2007 at 18:04 -0700, quoth ts-dev: =>Is it possible to prevent modification of a python file once its been =>deployed? File permissions of the OS could be used..but that doesn't =>seem very secure. => =>The root of my question is verifying the integrity of the application =>and the scripts being run. Is this possible, if so, how? I'm going to take a stab at this one even though I'm a really junior pythonian. I know others have already responded, but I'd like to offer a couple of suggestions that have nothing to do with python. (BTW, I do applaud the previous answers that suggest that this is really a non-problem in the first place.) 1. *IF* you are on a linux target platform then it's likely that you have a package management system in use, either rpm or deb. In either case, you have the ability to verify by checksum, every file of any package. In the case of rpm, just use the -V option. 2. You also have the ability to set the immutable flag on ext2/ext3 filesystems. See lsattr/chattr commands. Of course, if you can get root access then you can shut off immutability, but you can also replace your package management tools as well. AAAUUUGGGHHH!!! -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net -- http://mail.python.org/mailman/listinfo/python-list
Re: BaseHTTPRequestHandler reading .html with python code
On 6 avr, 11:52, [EMAIL PROTECTED] wrote: > H! > > I was wondering how I can do something like this. Use a template engine like : Genshi Django/Jinja Cheetah Kid template For more engine look at http://www.turbogears.org/cogbin/ And maybe what you are looking fore is a complete framework like : turbogears pylon django Hope this help > > file.html > - > hello world > > print 'hello world' > #or display str(time.localtime()[7]) > > > webserver.py > - > def do_GET(self): > try: > if self.path.endswith(".html"): > f = open(curdir + sep + self.path) #self.path has / > test.html > self.send_response(200) > self.send_header('Content-type','text/html') > self.end_headers() > # now display the hello world and run the python code. > self.wfile.write(f.read()) > f.close() > return > > I saw the mod python for apache and some PSP but I really want to know > how they do this. > Is there are special module for doing this ? > > Or is there something like this: > --- > 1. a running python program > 2. include with write(f.read()) a extra python code inside the already > running python program. > > How they handle this ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Welch essential for learning Tkinter well?
In article <[EMAIL PROTECTED]>, Kevin Walzer <[EMAIL PROTECTED]> wrote: > James Stroud wrote: > >This begs the > > question, is anyone truly an expert in Tkinter? > > Frederick Lundh is, if anyone is. > > http://www.pythonware.com/library/tkinter/introduction/index.htm (outdated) > http://effbot.org/tkinterbook/ (new but incomplete) I agree that this is an excellent resource. I find Welch's book and the on-line tcl/tk help very helpful for Tkinter programming--especially some of the more obscure details. But to use either of these resources comfortably you must learn the basics of Tkinter first (including understanding the simple mapping between Tkinter and Tcl/Tk). For learning the basics of Tkinter I suggest the links that Kevin listed above and/or Alex Martelli's "Python in a Nutshell" (an excellent reference in any case). Grayson's book is another reasonable alternative (and includes enough reference material to keep you from having to refer to the tcl/tk documentation very often). -- Russell -- http://mail.python.org/mailman/listinfo/python-list
Re: block scope?
"Neal Becker" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] | One thing I sometimes miss, which is common in some other languages (c++), | is idea of block scope. It would be useful to have variables that did not | outlive their block, primarily to avoid name clashes. This also leads to | more readable code. I wonder if this has been discussed? Yes, but Guido (and others) prefer to keep things simple. There is also the question of how to indicate a limited scope. In C++, you put the declaration in the scope. But Python has no such declarations. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter canvas
gigs wrote: > I have made drawing area and few butons. > How can I make when i click my fill button that later when i click on > oval oval gets filled with chousen color? when later click on my oval that is drawn in to change oval color, or to fill color in oval if click in oval with mouse -- http://mail.python.org/mailman/listinfo/python-list
Re: Why NOT only one class per file?
On 4/6/07, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > For one liners, wouldn't > > ECHO the text line >the.file > > be more appropriate? # dd if=/dev/tty of=/dev/hda1 -- Greg Donald http://destiney.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on MIPS
Thomas Krüger ha scritto: > Lorenzo Mainardi schrieb: >> I bought a very small embedded card, with a MIPS processor, running >> Linux. So, I would to use Python on that; I checked on python.org, but I >> did'nt find any release for this architecture. Could you help me? > > How about compiling it from source? > > Thomas I did'nt try...I will do that :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Question about sequence multiplication
Thanks to everyone that respondedI would never have figured that out. 7stud, Your suggestion is being considered lol, as there are a lot more bits of code in that book that I can't get running correctly. Any other books you'd, or anyone for that matter, would recommend as required reading? Free would be very very (read very) good, as you've already said the one I have isn't very viable and it cost me $50. Basically, what I'm saying is that if I go and spend another $50+ my wife is going to make it very hard to learn Python; after all, how much can I learn with a size 5 down my throat? lol Now when suggesting books, keep in mind that, that while I'm new to Python (and programming in general) I'm able to grasp difficult concepts as long as I have enough detail as to why it is the way it is. For instance I'm, by experience and nature, a computer technician and communications specialist. I've studied, everything from childrens walkie talkie to deep space satalittes back to how computers talk (which is why I'm here now trying to learn the language of computers). And all that just because I have a unquenchable desire to know. SO, with that all said, the more details the better. If you have a book with 4 chapters on functions..I want to read it. Any help would be greatly appreciated. As I've said, this is something that I feel I have to know. "7stud" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > On Apr 4, 4:48 pm, "John Machin" > I suggest you get another book. I am currently reading that book, and > unless you are an experienced programmer that can detect all the > mistakes, and you have another book like "Python in a Nutshell" to > fill in all the gaps, I don't think you can learn python from that > book. > > I recently looked at Learning Python in the bookstore, and it seems a > lot better. Unfortunately, it doesn't reflect the major changes in > python over the last couple of years, but I would still recommend it > over Beginning Python: From Novice to Professional. > > > -- http://mail.python.org/mailman/listinfo/python-list
Dr Jeff King, A Jewish MIT Engineer is the LEAD SPEAKER on 911 truth, no Islamics involved http://video.google.com/videoplay?docid=1822764959599063248
See the video with your own EYEBALLS, that is if you have some courage and shame left: http://video.google.com/videoplay?docid=1822764959599063248 On Apr 6, 9:39 am, [EMAIL PROTECTED] wrote: > On Apr 4, 6:31 pm, "Dr. V I Plankenstein" <[EMAIL PROTECTED]> > wrote: > > > The anthrax attack was almost certainly carried out by someone who had > > access to Gov labs or other secure facilities, but the attack on WTC was an > > act of Islamic fanaticism, and you're an ass to suggest otherwise without > > having some very solid proof to back your ridiculous claims - which you > > lack. > > You are a LYING SPOOK from the FOOLISH BUREAU OF INCOMPETENCE. > > If the ODIOUS George W Bush did not inform the American Public (Who > pays his salary) that Anthrax Attack was by a YANK BASTARD, then it > must not be so. > > On the other hand if the Anthrax Attack was produced on such short > notice and such coordination with the whole 911, then 911 was ALL done > by yank bastards themselves and George W Bush is a prime suspect with > all his underlings. > > ABSENSE OF EVIDENCE IS NOT THE EVIDENCE OF ABSENSE. > > 911 was a heinous crime done by RACIST and UTTERLY SELFISH yank > bastards themselves. -- http://mail.python.org/mailman/listinfo/python-list
Re: block scope?
On 4/6/07, Neal Becker <[EMAIL PROTECTED]> wrote: > One thing I sometimes miss, which is common in some other languages (c++), > is idea of block scope. It would be useful to have variables that did not > outlive their block, primarily to avoid name clashes. This also leads to > more readable code. I wonder if this has been discussed? > Block scope as a way to prevent name clashes is usually solved by refactoring (in C++, too) - if you can't disambiguate locals in a function it's usually a sign that your function does to much and needs to be broken up. Block scope as a way to control object lifetimes (automatic variables, or RAII) is addressed (in 2.5) by context managers or (pre-2.5) try/finally blocks. -- http://mail.python.org/mailman/listinfo/python-list
Basic Serialization - a design decision question
Hello I am a relative newcomer to Python, and I am studying it to understand its design. It intrigues me. I recently studied Serialization of classes via the pickle/cPickle library, and I have a question. Why is Serialization handled by a separate library (ie, pickle). Is it possible, by design, to have serialization "internally" implemented via an implicit ___serialize___ method? Ofcourse, you have to make this method not overrideable (sp?). For example, the __repr__ method gives us the string representation of a class... similarly, the __serialize__ method would give us the "serial norm" representation of the class. This would allow me to do something like this, conn.send(serial(myClass)); // or something like that? Thoughts? -- http://mail.python.org/mailman/listinfo/python-list
Re: Over a billion people believe Allah will provide 72 virgins to some Muslims.
On Apr 4, 6:31 pm, "Dr. V I Plankenstein" <[EMAIL PROTECTED]> wrote: > The anthrax attack was almost certainly carried out by someone who had > access to Gov labs or other secure facilities, but the attack on WTC was an > act of Islamic fanaticism, and you're an ass to suggest otherwise without > having some very solid proof to back your ridiculous claims - which you > lack. You are a LYING SPOOK from the FOOLISH BUREAU OF INCOMPETENCE. If the ODIOUS George W Bush did not inform the American Public (Who pays his salary) that Anthrax Attack was by a YANK BASTARD, then it must not be so. On the other hand if the Anthrax Attack was produced on such short notice and such coordination with the whole 911, then 911 was ALL done by yank bastards themselves and George W Bush is a prime suspect with all his underlings. ABSENSE OF EVIDENCE IS NOT THE EVIDENCE OF ABSENSE. 911 was a heinous crime done by RACIST and UTTERLY SELFISH yank bastards themselves. -- http://mail.python.org/mailman/listinfo/python-list
Re: block scope?
Neal Becker wrote: > One thing I sometimes miss, which is common in some other languages (c++), > is idea of block scope. It would be useful to have variables that did not > outlive their block, primarily to avoid name clashes. This also leads to > more readable code. I wonder if this has been discussed? > Nested scopes were put into the language for function definitions, at least. Back in around 2.0, I believe, though that's lost in the mists of time for me as it's not a feature I use. I suspect, in fact, that those nested scopes have caused more trouble that they're worth, and continue to do so. Be that as it may, I don't think there's ever been any attempt to introduce scoping blocks into the language. Any ideas how you'd like it done? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Java
Ed Jensen wrote: > Steve Holden <[EMAIL PROTECTED]> wrote: >> Ed Jensen wrote: >>> Steve Holden <[EMAIL PROTECTED]> wrote: Jython is an implementation of Python that compiles to Java bytecode, but at the moment there's some version lag so it won't handle the mos recent language enhancements. Probably worth a look, though. http://www.jython.org/ >>> Does Jython compile to Java bytecode, or is Jython a Java >>> implementation of a Python interpreter? >> Please read what I wrote again. > > I read it and understood it just fine. My question was meant more > along the lines of, "Are you SURE it compiles to Java bytecode, and > isn't a Python interpreter written in Java?" I guess I didn't make > that clear. > > Anyway, I checked the Jython home page, and sure enough, Jython > compiles Python code to Java bytecode, as stated in the FAQ which can > be found at the following URL (in case anyone else reading this > message is following along and is interested): > > http://www.jython.com/Project/userfaq.html#what-is-jython > > In particular: > > 1.1 What is Jython? > > Jython implements the Python programming language on the Java(tm) > Platform. It consists of a compiler to compile Python source code down > to Java bytecodes which can run directly on a JVM, a set of support > libraries which are used by the compiled Java bytecodes, and extra > support to make it trivial to use Java packages from within Jython. > > Sorry if I bothered/annoyed you, Steve. No real problem, I just thought I had already answered the question you asked. Of course the web reference was, as you'd expect, definitive, and your quoting it in this group will probably help those weho follow along. Glad it sounds like Jython might suit you - it's a great integration job! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
block scope?
One thing I sometimes miss, which is common in some other languages (c++), is idea of block scope. It would be useful to have variables that did not outlive their block, primarily to avoid name clashes. This also leads to more readable code. I wonder if this has been discussed? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to access multiple group matches?
Christoph Krammer wrote: > Hello, > > I want to use the re module to split a data stream that consists of > several blocks of data. I use the following code: > > iter = re.finditer('^(HEADER\n.*)+$', data) > > The data variable contains binary data that has the word HEADER in it > in some places and binary data after this word till the next > appearance of header or the end of the file. But if I iterate over > iter, I only get one match and this match only contains one group. How > to access the other matches? Data may contain tens of them. > > Thanks in advance, > Christoph > > Use .*? instead of .* in your regular expression. From the manual page: *|*?|, |+?|, |??|* The "*", "+", and "?" qualifiers are all /greedy/; they match as much text as possible. Sometimes this behaviour isn't desired; if the RE <.*> is matched against |'title'|, it will match the entire string, and not just |''|. Adding "?" after the qualifier makes it perform the match in /non-greedy/ or /minimal/ fashion; as /few/ characters as possible will be matched. Using .*? in the previous expression will match only |''|. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: [optparse] Problem with getting an option value
Peter Otten wrote: > Lucas Malor wrote: > >> Hello all. I'm trying to do a little script. Simply I want to make a list >> of all options with them default values. If the option is not specified in >> the command line, the script must try to read it in a config.ini file. If >> it's not present also there, it must set the default value. >> >> The problem is I maked a simple list for this: >> >> optname = [ >> [ "delete", False ], >> [ "file", "file" ], >> [ "dir","" ], >> >> But I must check that the option was specified in command line: >> >> (options, args) = parser.parse_args() >> for opt in optname : >> if not options.opt[0] : >> # read the options from config.ini >> >> The problem is options is an instance, so options."delete", for example, >> is wrong; I should pass options.delete . How can I do? > > Use getattr(): > > for name, default_value in optname: > if getattr(options, name) == default_value: > value = ... # read value from config file > setattr(options, name, value) > > Personally, I would always read the config file, use the values found there > to set up the parser and avoid such post-proc But then, if the command-line value == the default_value the program will try to get a value from the config file. If the config file overrides the defaults, then the command line can't re-override. Stuck with this, I usually initialize with None, then after all the option sources have been done, set anything that's still None to the default. It's not tidy. If even None could be a valid value, then a new None: class LikeNothingElse: '''Not a reasonable option value for anything''' # ... various code option_a = LikeNothingElse option_b = LikeNothingElse # ... process all the option sources if option_a == LikeNothingElse: option_a = None Mel. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Java
Steve Holden <[EMAIL PROTECTED]> wrote: > Ed Jensen wrote: >> Steve Holden <[EMAIL PROTECTED]> wrote: >>> Jython is an implementation of Python that compiles to Java bytecode, >>> but at the moment there's some version lag so it won't handle the mos >>> recent language enhancements. Probably worth a look, though. >>> >>>http://www.jython.org/ >> >> Does Jython compile to Java bytecode, or is Jython a Java >> implementation of a Python interpreter? > > Please read what I wrote again. I read it and understood it just fine. My question was meant more along the lines of, "Are you SURE it compiles to Java bytecode, and isn't a Python interpreter written in Java?" I guess I didn't make that clear. Anyway, I checked the Jython home page, and sure enough, Jython compiles Python code to Java bytecode, as stated in the FAQ which can be found at the following URL (in case anyone else reading this message is following along and is interested): http://www.jython.com/Project/userfaq.html#what-is-jython In particular: 1.1 What is Jython? Jython implements the Python programming language on the Java(tm) Platform. It consists of a compiler to compile Python source code down to Java bytecodes which can run directly on a JVM, a set of support libraries which are used by the compiled Java bytecodes, and extra support to make it trivial to use Java packages from within Jython. Sorry if I bothered/annoyed you, Steve. -- http://mail.python.org/mailman/listinfo/python-list
Re: SNMP agent
In article <[EMAIL PROTECTED]>, alain <[EMAIL PROTECTED]> wrote: . . . >I still find it strange that, in all these years of existence, no one >felt the need for a SNMP agent in Python. > >Do Pythoneers only write test tools and not real apps? . . . No, but I understand the question. Python has had considerable success with test tools, by the way. On the other hand, SNMP has become such a minor niche that its technologic implementations depend heavily on historical accident. The right combination of expertise-resources-need-... simply hasn't occurred for Python- based SNMP. I'll repeat: Tcl is the basis of Scotty, which, while largely unsupported now, remains quite usable. Perl is in a somewhat more primitive condition. I don't know of any other high-level language which can effectively boast of the ability to write SNMP agents. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why NOT only one class per file?
Steven D'Aprano wrote: > On Wed, 04 Apr 2007 14:23:19 -0700, Chris Lasher wrote: > >> A friend of mine with a programming background in Java and Perl places >> each class in its own separate file in . I informed him that keeping >> all related classes together in a single file is more in the Python >> idiom than one file per class. He asked why, and frankly, his valid >> question has me flummoxed. > > > Hah! Writing one class per file is for wimps! When I program, I write one > *method* per file, then import them and build the class at runtime. > > I have a friend who writes one *line* per file, then pulls them all > together with exec(), but that's just being stupid. > > > I guess you're one of those sissies who uses EDLIN as an editor. REAL programmers use COPY CON: ... :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting Stack Trace on segfault
On Apr 6, 7:13 am, James Stroud <[EMAIL PROTECTED]> wrote: > Hello All, > > The built-in mac osx vecLib is segfaulting in some cases--A very fun > fact to find out the hard way over two nights of work. I also spent an > embarrassing amount of time figuring out just where. Although I'm in > quite a self-congratulatory mood right now, in the future, I feel like I > could save a lot of time by coercing the interpreter to spew forth > method calls to stderr. Is this possible? > > I would hope to produce something hauntingly reminiscent of > > [] my_function > [my_function] another_function > [my_function -> another_function] yet_a_deeper_function > > Presentation, of course, is irrelevant. > > I read the docs on pdb, but it did not seem to do what I want--unless, > of course, I missed something. > > James Hi, I've never done that before, but I found a recipe that claims to do it with meta-classes. Check it out: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/198078 I hope this gives you some ideas. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple mx.ODBC prob seeks simple answer
Thanks Steve, Once again your advice solved the problem Greg Steve Holden wrote: > > Greg Corradini wrote: >> Hello all, >> I'm having trouble inserting an SQL selection into a new MS Access table. >> I >> get a parameter error on my insert statement when I try this (see below >> for >> code and error msg). I'm not sure if 'insert' or 'update' is the route I >> should be taking. >> >> CODE: >> #Import Pythond Standard Library Modules >> import win32com.client, sys, os, string, copy, glob >> import mx.ODBC.Windows as odbc >> >> # Create the Geoprocessor Object >> gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") >> gp.overwriteoutput = 1 >> >> # Variables >> tempspace = "C:\Documents and Settings\corr1gre\Desktop\Workspace\DBFs & >> Shapefiles\TEST.mdb" >> workspace = string.replace(tempspace,"\\","/") >> worksheet1 = "Mower_I" >> worksheet2 = "Mower_II" >> >> #Conection to Access >> driv = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+workspace >> conn = odbc.DriverConnect(driv) >> curse = conn.cursor() >> >> #Drop Tables if they already exist >> try: >> curse.execute('Drop table Table_I') >> curse.execute('Drop table Table_II') >> curse.execute('Drop table Checker') >> except: >> pass >> #Create a New Tables >> curse.execute('Create table Table_I (TISCODE TEXT(12), EXISTSIN >> TEXT(4),STATUS TEXT(3),NOTES TEXT(50))') >> curse.execute('Create table Table_II(TISCODE TEXT(12), EXISTSIN >> TEXT(4))') >> curse.execute('Create table Checker (TISCODE TEXT(12), EXISTSIN >> TEXT(4),STATUS TEXT(3),NOTES TEXT(50))') >> conn.commit() >> >> #Upload DBF 1 as a List of Tuples: Returns tuple as ('102150','BMP') >> sql = 'SELECT TISCODE,EXISTSIN from '+worksheet2 >> curse.execute(sql) >> x = curse.fetchall() >> >> #Put the fetched Data into Table_II >> for i in x: >> curse.execute('Insert into Table_II (TISCODE,EXISTSIN) values >> (%s,%s)'%(i[0],i[1])) >> conn.commit() >> conn.close() >> >> TRACEBACK ERROR MSG: >> Traceback (most recent call last): >> File "C:/Documents and >> Settings/corr1gre/Desktop/Workspace/Python/ArcGIS >> Python/ExistenceChecker and Update/Access Double Checker/Access_SQL.py", >> line 40, in ? >> curse.execute('Insert into Table_II (TISCODE,EXISTSIN) values >> (%s,%s)'%(i[0],i[1])) >> ProgrammingError: ('07001', -3010, '[Microsoft][ODBC Microsoft Access >> Driver] Too few parameters. Expected 1.', 4612) > > That error usually occurs when you use a name that isn't defined int he > database (typically I mistype a column name) - the JET engine then > thinks it's missing a value for some parameter. > > In your case it's because you aren't surrounding the string literal > value for TISCODE in your statement with the appropriate '' single > quotes. The engine thus parses it as a name, hence the assumption that a > parameter is missing. > > It's actually good that you have made this error, because it allows me > to expound yet again on the dangers of constructing your own SQL > statements instead of using parameterised statements. In the case of > mxODBC the correct parameter mark to use is a question mark. You should > then supply the data to be substituted for the parameter marks as a > tuple argument to the cursor's execute() method. > > So what you really need is: > > #Put the fetched Data into Table_II > for i in x: > curse.execute("""Insert into Table_II (TISCODE,EXISTSIN) > values (?, ?)""", i) > conn.commit() > conn.close() > > A couple of other points: > > 1. It would actually be better to put the commit() call outside the > loop. This is not only more efficient but it defines the whole set of > changes as a transaction. > > 2. It would be even more efficient not to use a loop at all but to use > the cursor's executemany() method to perform all inserts with a single > call as follows: > > #Put the fetched Data into Table_II > curse.executemany("""Insert into Table_II (TISCODE,EXISTSIN) > values (?, ?)""", x) > conn.commit() > conn.close() > > For more on using the DBI API, including something about the risks of > SQL injection vulnerabilities, take a look at the notes from my PyCon > tutorial at > >http://www.holdenweb.com/PyConTX2007/dbapi.tgz > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > Recent Ramblings http://holdenweb.blogspot.com > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Simple-mx.ODBC-prob-seeks-simple-answer-tf3536661.html#a9873176 Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
How to access multiple group matches?
Hello, I want to use the re module to split a data stream that consists of several blocks of data. I use the following code: iter = re.finditer('^(HEADER\n.*)+$', data) The data variable contains binary data that has the word HEADER in it in some places and binary data after this word till the next appearance of header or the end of the file. But if I iterate over iter, I only get one match and this match only contains one group. How to access the other matches? Data may contain tens of them. Thanks in advance, Christoph -- http://mail.python.org/mailman/listinfo/python-list
Re: Extract zip file from email attachment
On Apr 6, 12:51 am, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote: > erikcw wrote: > > resp = p.retr(msg_num) > > if resp[0].startswith('+OK'): > > You don't have to check this; errors are transformed into exceptions. > > > fileObj = StringIO.StringIO() > > cStringIO is faster > > > fileObj.write( part.get_payload() ) > > You have to reset the file pointer to the beginning: fileObj.seek(0), > else ZipFile will not be able to read the contents. > > -- > Gabriel Genellina Hi Gabriel, I added fileObj.seek(0) on the line directly after fileObj.write( part.get_payload() ) and I'm still getting the following error. Traceback (most recent call last): File "wa.py", line 209, in attachment = zipfile.ZipFile(fileObj) File "/usr/lib/python2.5/zipfile.py", line 346, in __init__ self._GetContents() File "/usr/lib/python2.5/zipfile.py", line 366, in _GetContents self._RealGetContents() File "/usr/lib/python2.5/zipfile.py", line 378, in _RealGetContents raise BadZipfile, "File is not a zip file" zipfile.BadZipfile: File is not a zip file Could the file like object still be encoded in MIME or something? Thanks! Erik -- http://mail.python.org/mailman/listinfo/python-list
Re: low level networking in python
On 4/4/07, Irmen de Jong <[EMAIL PROTECTED]> wrote: > Maxim Veksler wrote: > > > I'm trying to bind a non-blocking socket, here is my code: > > """ > > #!/usr/bin/env python > > > > import socket, select > > from time import sleep > > > > s_nb1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > s_nb1.setblocking(0) > > > > s_nb1.bind(('192.168.2.106', 10002)) > > s_nb1.listen(5) > > > > while 1: > > conn, addr = s_nb1.accept() > > ready_to_read, ready_to_write, in_error = select.select([conn], [], > > [], 0) > > print (ready_to_read, ready_to_write, in_error) > > sleep(100) > > > > s_nb1.close() > > """ > > > > And this is the exception I'm getting: > > """ > > python non_blocking_socket.py > > Traceback (most recent call last): > > File "non_blocking_socket.py", line 13, in ? > >conn, addr = s_nb1.accept() > > File "/usr/lib/python2.4/socket.py", line 161, in accept > >sock, addr = self._sock.accept() > > socket.error: (11, 'Resource temporarily unavailable') > > """ > > > > What am I doing wrong here? > > Nothing. > Any operation on a non-blocking socket that is usually blocking > (this includes accept(), bind(), connect(), recv with MSG_WAITALL) > can possibly return a socket.error with errno set to EAGAIN. > ('resource temporarily unavailable'). > If this happens you should use a select() on the socket to > wait until it's done with the requested operation. > Hello everyone, I would like to thank you all for the helping tips so far, with your help I managed to improve the previous code to not give the error, I believe it's now working. The non blocking echo socket code: """ #!/usr/bin/env python import socket, select s_nb1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s_nb1.setblocking(0) s_nb1.bind(('0.0.0.0', 10002)) s_nb1.listen(5) while 1: ready_to_read, ready_to_write, in_error = select.select([s_nb1], [], [], 0) if s_nb1 in ready_to_read: conn, addr = s_nb1.accept() while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() s_nb1.close() """ > --Irmen > Maxim. -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Using os.popen3() to get binary data
Just got the solution... After sending the image data with "si.write(image)", I have to close the pipe to tell the program to convert the image with "si.close()". Now everything works fine. Christoph -- http://mail.python.org/mailman/listinfo/python-list
Re: Why NOT only one class per file?
On Wed, 04 Apr 2007 14:23:19 -0700, Chris Lasher wrote: > A friend of mine with a programming background in Java and Perl places > each class in its own separate file in . I informed him that keeping > all related classes together in a single file is more in the Python > idiom than one file per class. He asked why, and frankly, his valid > question has me flummoxed. Hah! Writing one class per file is for wimps! When I program, I write one *method* per file, then import them and build the class at runtime. I have a friend who writes one *line* per file, then pulls them all together with exec(), but that's just being stupid. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: "Plugin" architecture - how to do?
On Apr 5, 10:57 am, [EMAIL PROTECTED] wrote: > I'm making a program that consists of a main engine + plugins. Both > are in Python. My question is, how do I go about importing arbitrary > code and have it be able to use the engine's functions, classes, etc? For a true plugin architecture, you don't have the main engine calling methods on the plugin. What you do is have an API on your engine with methods the plugin can call and events it can hook into. The events are how the engine communicates state to any plugins, without having to know who they are or what they do. Your engine has a configuration that tells it what plugins to load (which the plugins presumably modified when they installed themselves) or otherwise has some standard way that the engine can figure out what plugins need to be loaded. Now granted, I don't specifically know how to do this via python.. but, maybe what I've said will send you in the right direction. -Nate -- http://mail.python.org/mailman/listinfo/python-list
Re: tuples, index method, Python's design
C.L. wrote: > > That doesn't change the fact that this is unfriendly design. It's an ugly > inconsistent chunk of a Python's past in which built-in types didn't behave > like > objects. It sticks out like a sore thumb, maybe just not very often. When this topic last appeared on my radar, I ended up writing a long message about it: http://groups.google.com/group/comp.lang.python/msg/30e89128bdeb59c0 [...] > *sighs* just what I expected: another idle troll defending something just for > the sake of defending it. On the other hand, thanks 7stud, for the truly > helpful > response. The problem with 7stud's quote from GvR is that it's out of date: tuples do have methods now, as you've noticed, but just not the index method. Previously, I've missed that method, and it wouldn't be hard to add it to the tuple class (in CPython's own source code), but one has to wonder whether it's really necessary, or at least as necessary as for other classes. Certainly, there's a trade-off between essential functionality and having, say, 100 methods which are all useful to someone but which make interactive introspection a rather tedious and confusing business. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: how to remove multiple occurrences of a string within a list?
On Wed, 04 Apr 2007 15:56:34 +0200, Hendrik van Rooyen wrote: > Now how would one do it and preserve the original order? > This apparently simple problem is surprisingly FOS... > But list comprehension to the rescue : > [x for x in duplist if duplist.count(x) == 1] > ['haha', 5, 6] > > *shakes head* duh... why does it take so long? Because you are using Shlemiel the painter's algorithm: http://www.joelonsoftware.com/articles/fog000319.html Each time you call duplist.count(), you go back to the beginning of the list and walk the entire list. You end up walking the list over and over and over again. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple mx.ODBC prob seeks simple answer
Greg Corradini wrote: > Hello all, > I'm having trouble inserting an SQL selection into a new MS Access table. I > get a parameter error on my insert statement when I try this (see below for > code and error msg). I'm not sure if 'insert' or 'update' is the route I > should be taking. > > CODE: > #Import Pythond Standard Library Modules > import win32com.client, sys, os, string, copy, glob > import mx.ODBC.Windows as odbc > > # Create the Geoprocessor Object > gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") > gp.overwriteoutput = 1 > > # Variables > tempspace = "C:\Documents and Settings\corr1gre\Desktop\Workspace\DBFs & > Shapefiles\TEST.mdb" > workspace = string.replace(tempspace,"\\","/") > worksheet1 = "Mower_I" > worksheet2 = "Mower_II" > > #Conection to Access > driv = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+workspace > conn = odbc.DriverConnect(driv) > curse = conn.cursor() > > #Drop Tables if they already exist > try: > curse.execute('Drop table Table_I') > curse.execute('Drop table Table_II') > curse.execute('Drop table Checker') > except: > pass > #Create a New Tables > curse.execute('Create table Table_I (TISCODE TEXT(12), EXISTSIN > TEXT(4),STATUS TEXT(3),NOTES TEXT(50))') > curse.execute('Create table Table_II(TISCODE TEXT(12), EXISTSIN TEXT(4))') > curse.execute('Create table Checker (TISCODE TEXT(12), EXISTSIN > TEXT(4),STATUS TEXT(3),NOTES TEXT(50))') > conn.commit() > > #Upload DBF 1 as a List of Tuples: Returns tuple as ('102150','BMP') > sql = 'SELECT TISCODE,EXISTSIN from '+worksheet2 > curse.execute(sql) > x = curse.fetchall() > > #Put the fetched Data into Table_II > for i in x: > curse.execute('Insert into Table_II (TISCODE,EXISTSIN) values > (%s,%s)'%(i[0],i[1])) > conn.commit() > conn.close() > > TRACEBACK ERROR MSG: > Traceback (most recent call last): > File "C:/Documents and Settings/corr1gre/Desktop/Workspace/Python/ArcGIS > Python/ExistenceChecker and Update/Access Double Checker/Access_SQL.py", > line 40, in ? > curse.execute('Insert into Table_II (TISCODE,EXISTSIN) values > (%s,%s)'%(i[0],i[1])) > ProgrammingError: ('07001', -3010, '[Microsoft][ODBC Microsoft Access > Driver] Too few parameters. Expected 1.', 4612) That error usually occurs when you use a name that isn't defined int he database (typically I mistype a column name) - the JET engine then thinks it's missing a value for some parameter. In your case it's because you aren't surrounding the string literal value for TISCODE in your statement with the appropriate '' single quotes. The engine thus parses it as a name, hence the assumption that a parameter is missing. It's actually good that you have made this error, because it allows me to expound yet again on the dangers of constructing your own SQL statements instead of using parameterised statements. In the case of mxODBC the correct parameter mark to use is a question mark. You should then supply the data to be substituted for the parameter marks as a tuple argument to the cursor's execute() method. So what you really need is: #Put the fetched Data into Table_II for i in x: curse.execute("""Insert into Table_II (TISCODE,EXISTSIN) values (?, ?)""", i) conn.commit() conn.close() A couple of other points: 1. It would actually be better to put the commit() call outside the loop. This is not only more efficient but it defines the whole set of changes as a transaction. 2. It would be even more efficient not to use a loop at all but to use the cursor's executemany() method to perform all inserts with a single call as follows: #Put the fetched Data into Table_II curse.executemany("""Insert into Table_II (TISCODE,EXISTSIN) values (?, ?)""", x) conn.commit() conn.close() For more on using the DBI API, including something about the risks of SQL injection vulnerabilities, take a look at the notes from my PyCon tutorial at http://www.holdenweb.com/PyConTX2007/dbapi.tgz regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: elementary tuple question. (sorry)
On Apr 6, 5:31 am, "7stud" <[EMAIL PROTECTED]> wrote: > On Apr 5, 3:08 pm, "Steven W. Orr" <[EMAIL PROTECTED]> wrote: > > > I have a tuple that I got from struct.unpack. Now I want to pass the data > > from the returned tuple to struct.pack > > > >>> fmt > > > 'l 10l 11i h 4h c 47c 0l'>>>struct.pack(fmt, tup) > > > Traceback (most recent call last): > >File "", line 1, in ? > > struct.error: required argument is not an integer > > > What's the idiom to pass the data in tup? > > > TIA > > import struct > > fmt = "l l" > result = struct.pack(fmt, 12, 4) > > t = (12, 4) > result = struct.pack(fmt, *t) > - > > The * unpacks the tuple. there's an unpack(). >>> struct.unpack(fmt,result) -- http://mail.python.org/mailman/listinfo/python-list
Simple mx.ODBC prob seeks simple answer
Hello all, I'm having trouble inserting an SQL selection into a new MS Access table. I get a parameter error on my insert statement when I try this (see below for code and error msg). I'm not sure if 'insert' or 'update' is the route I should be taking. CODE: #Import Pythond Standard Library Modules import win32com.client, sys, os, string, copy, glob import mx.ODBC.Windows as odbc # Create the Geoprocessor Object gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") gp.overwriteoutput = 1 # Variables tempspace = "C:\Documents and Settings\corr1gre\Desktop\Workspace\DBFs & Shapefiles\TEST.mdb" workspace = string.replace(tempspace,"\\","/") worksheet1 = "Mower_I" worksheet2 = "Mower_II" #Conection to Access driv = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+workspace conn = odbc.DriverConnect(driv) curse = conn.cursor() #Drop Tables if they already exist try: curse.execute('Drop table Table_I') curse.execute('Drop table Table_II') curse.execute('Drop table Checker') except: pass #Create a New Tables curse.execute('Create table Table_I (TISCODE TEXT(12), EXISTSIN TEXT(4),STATUS TEXT(3),NOTES TEXT(50))') curse.execute('Create table Table_II(TISCODE TEXT(12), EXISTSIN TEXT(4))') curse.execute('Create table Checker (TISCODE TEXT(12), EXISTSIN TEXT(4),STATUS TEXT(3),NOTES TEXT(50))') conn.commit() #Upload DBF 1 as a List of Tuples: Returns tuple as ('102150','BMP') sql = 'SELECT TISCODE,EXISTSIN from '+worksheet2 curse.execute(sql) x = curse.fetchall() #Put the fetched Data into Table_II for i in x: curse.execute('Insert into Table_II (TISCODE,EXISTSIN) values (%s,%s)'%(i[0],i[1])) conn.commit() conn.close() TRACEBACK ERROR MSG: Traceback (most recent call last): File "C:/Documents and Settings/corr1gre/Desktop/Workspace/Python/ArcGIS Python/ExistenceChecker and Update/Access Double Checker/Access_SQL.py", line 40, in ? curse.execute('Insert into Table_II (TISCODE,EXISTSIN) values (%s,%s)'%(i[0],i[1])) ProgrammingError: ('07001', -3010, '[Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.', 4612) -- View this message in context: http://www.nabble.com/Simple-mx.ODBC-prob-seeks-simple-answer-tf3536661.html#a9871804 Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Getting Stack Trace on segfault
Hello All, The built-in mac osx vecLib is segfaulting in some cases--A very fun fact to find out the hard way over two nights of work. I also spent an embarrassing amount of time figuring out just where. Although I'm in quite a self-congratulatory mood right now, in the future, I feel like I could save a lot of time by coercing the interpreter to spew forth method calls to stderr. Is this possible? I would hope to produce something hauntingly reminiscent of [] my_function [my_function] another_function [my_function -> another_function] yet_a_deeper_function Presentation, of course, is irrelevant. I read the docs on pdb, but it did not seem to do what I want--unless, of course, I missed something. James -- http://mail.python.org/mailman/listinfo/python-list
Re: Using os.popen3() to get binary data
Christoph Krammer schrieb: > for image in images: > if (image[0:3] == 'GIF'): > (si, so, se) = os.popen3('giftopnm -image=all', 'b') > si.write(image) > frame = so.readlines() > > But with this code the script just hangs. When I interrupt the script, > I get the following error message: > Traceback (most recent call last): > File "/home/tiger/stock-spam/scripts/all_in_one.py", line 46, in ? > frames = so.readlines() > KeyboardInterrupt > close failed: [Errno 32] Broken pipe Just a try: use read() instead of readlines()! Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: About python Sybase module and the database manipulation!
boyeestudio wrote: > I write a python program which can insert one record into the Sybase > databae at a time using the function "fetchone()",But I find it runs slowly. > So I want speed it up,But I don't know how to manipulate the database > more efficiently! Thread or any other methods can do it?? > Since fetchone() is for *retrieval* of data from a database and since you don't show us your code it's difficult to know what to suggest. If you let us have an example it will be easier to tell you why your code doesn't run fast enough. You may wish to look at executemany() if you have lots of insertions to make. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list