How to decompile an exe file compiled by py2exe?
Dear All, I lost my source code because of my incaution. so anyone can tell me how to decompile the exe file compiled by py2exe? Thanks. -- Best Regards, Leo Jay -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem subclassing (Newbie)
>Then I have an instance of class Button called obj. My probelm is that >the test isinstance(obj, Widget) resturns False! > You must have a typo somewhere. Please try this little test program. >>> class Widget(object): ... pass ... >>> class Button(Widget): ... pass ... >>> b = Button() >>> isinstance(b,Widget) True >>> isinstance(b,Button) True >>> issubclass(Widget,Button) False >>> issubclass(Button,Widget) True >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: Config parser module
Thanks a lot for Dale and Larry, I have not tried the OOP way yet like you mentioned, I will try to create a parser soon, maybe I will post it in the net after that, it may be useful to others too, Thanks again -Jiro -- http://mail.python.org/mailman/listinfo/python-list
Problem subclassing (Newbie)
Hi, I'm new to Python, so forgive me if I'm missing something obvious here. All what I am trying to do is create a hirarachy of objects (i.e. one that inherits from another). But for somereason my subclasses are not recognizing their superclass! I have the following: class Widget(object): def __init__(self, app, name, loc, width=30, height=50): #some initialization class Button(Widget): def __init__(self, app, label, loc, callback, width=30, height=50): Widget.__init__(self, app, label, loc, width, height) #some initialozation Then I have an instance of class Button called obj. My probelm is that the test isinstance(obj, Widget) resturns False! What is really strange is that even the test issubclass(Button, Widget) returns False!! Obviously I did not achieve the hirarchy I wanted. Any ideas what I could be missing? Thanks a lot! -Shahla -- http://mail.python.org/mailman/listinfo/python-list
Re: Single type for __builtins__ in Py3.0
On 9/23/05, Peter Hansen <[EMAIL PROTECTED]> wrote: > My point, which might not have been clear, is that users are *already* > told that they shouldn't ever touch __anything__ without understanding > what it is, which is more general advice than and therefore encompasses > the __builtins__ issue. For this reason I believe the existing advice > is sufficient for everyone except those who would probably also end up > ignoring your above suggestions anyway. I'm not proposing a new rule on the level of "learn about __foo__ before you mess with it"; the delegation structure of that rule is sufficient. I do however want the docs for __builtins__ to explicitly mention a) that you should do your mucking with __builtin__ instead, and b) that __builtins__ is a module when in __main__ and a dict everywhere else; the current documentation makes no mention of either. Come morning I'll submit a patch for the reference manual. > > Maybe > > __builtins__ could be removed entirely from Py3.0, thus bringing > > reality in to sync with policy. > > That's a possibility, though given that it's an implementation detail > there could easily be other implementation details which you would then > be asking to be removed as well because they might confuse someone. If > you really want to avoid having implementation details exposed like > this, you should probably be participating closely in the development > process. ;-) I'm relatively new to the python-dev world, but I intend to do what I can to eliminate blemishes like __builtins__. Collin Winter -- http://mail.python.org/mailman/listinfo/python-list
RE: Re: A World Beyond Capitalism 2005, An Annual International Multiracial Alliance Building Peace Conference Is Accepting Proposals...
You consider it spam because you don't agree with the political message or the idea of people working for a better world. However, if it had been a subject which was "acceptable" to your standards as a self-made moderator, then everything would have been wonderful in Kansas. Click your heels please, you're not in Kansas. People are going to work for a better world whether you like it or not. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can I compile Python for the web?
On Friday 23 September 2005 07:53 pm, Peter Hansen wrote: > What you appear to be asking is if it's possible to create *native > machine code* from Python source in order to achieve a significant > increase in performance. The short answer is "no, not really", and > longer answers include "yes, sort of, using something like Psyco", and > "who cares because it wouldn't give you much better performance for a > web-based application where you're probably either I/O-bound or limited > by the speed of the non-Python database solution you are using in the > first place?". All pretty true of course, but I think I did read about some tests of running Zope with psyco. Zope uses a pretty massive amount of Python code on each access, so there's probably a lot to optimize. Unfortunately I don't remember what the results were. But I'd recommend search the zope-user mailing list archives or just google for "psyco site:zope.org" Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing class variable at class creation time
Carlos wrote: > Hi! > > class A: > X = 2 > def F(): > print A.X > F() > > The above fails because the name A is not > yet at global scope when the reference A.X > is reached. Is there any way to refer to A.X > without making explicit use of the name 'A'? How about this: >>> class A: ... X = 2 ... print X ... 2 -- Benji York -- http://mail.python.org/mailman/listinfo/python-list
Re: Bluetooth
Okei I've been doing some research since my first post and now I'm really confused. I'm programming in xp, and found some c++ code out of this world that supposidly should list all available services to a given bluetooth device. This code however where only working with certain bluetooth-devices supported by the Microsoft Bluetooth Stack. If someone out there has any advice/ experience on bluetooth-programming on laptops (preferably in windows) I would appreciate it. Maybe there is some easy-to-grasp tutorials out there using the windows API for bluetooth-programing??? regards tores "Paul Boddie" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] Tor Erik Sønvisen wrote: > I'm making a server-side solution in Python and need to be able to > communicate through bluetooth. Is there any bluetooth-packages out there > for > python? At the lowest level, you should be able to create sockets for Bluetooth communications (see the socket module's documentation and the source code in Modules/socketmodule.c); for example: from socket import * s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM) On Linux, upon binding a device file to the Bluetooth device, you can use things like pySerial to manage the communications; this works with software like t616hack: http://www.nelson.monkey.org/~nelson/weblog/tech/phone/ http://pyserial.sourceforge.net/ Various other tools exist which understand Bluetooth communications, notably the OpenOBEX tools: http://triq.net/obex/ I prefer to work with tools at the higher levels (obexftp to access files, pySerial/t616hack to access messages), but provided your Python distribution is set up correctly, you should be able to work at the lowest levels too. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Productivity and economics at software development
Paul Rubin wrote: > Peter Hansen <[EMAIL PROTECTED]> writes: >>If you focus on IDEs, your research will have pre-selected only >>certain kinds of programmers and teams, and will not necessarily >>include the best ones. > > It wouldn't have occurred to me to say that Ken Iverson (APL), Peter > Deutsch (PARC Smalltalk), or Dave Moon (MIT Lisp machine) were any of > them slouches. Some of the best programming ever done has gone into > IDE's. It would be great if Python had anything of the caliber of > those old systems. Then we're on the same page, Paul, since I would never say that any of those people, nor many others who use or create IDEs, were slouches. If you thought I said that, I believe you're parsing my statement incorrectly, or using incorrect logic. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Can I compile Python for the web?
Charles wrote: > I'm doing some investigations on the Python language. > I'd like to know if it is possible to compile Python code made for the > web (an online database for instance), and to run it using mod_python. > How is it possible? I think it would be very fast to execute the code > if it were compiled. Python code is already compiled, specifically to .pyc files, though this is clearly not what you meant by the above. (The .pyc files contain "bytecode" which is executed by the Python virtual machine, much like a CPU executes its native opcodes, or like Java executes its own bytecode instructions.) What you appear to be asking is if it's possible to create *native machine code* from Python source in order to achieve a significant increase in performance. The short answer is "no, not really", and longer answers include "yes, sort of, using something like Psyco", and "who cares because it wouldn't give you much better performance for a web-based application where you're probably either I/O-bound or limited by the speed of the non-Python database solution you are using in the first place?". -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Single type for __builtins__ in Py3.0
Collin Winter wrote: > The difference between __builtins__ and the other __*__ names is that > while the others shouldn't be used without understanding their > purpose, the consensus on __builtins__ seems to be that it shouldn't > be used at all. > > ... at the very > least, users should be explicitly told -- up front, in the official > documentation -- that they shouldn't ever touch __builtins__. (...all of which I understood you to be saying in your previous post on the matter.) My point, which might not have been clear, is that users are *already* told that they shouldn't ever touch __anything__ without understanding what it is, which is more general advice than and therefore encompasses the __builtins__ issue. For this reason I believe the existing advice is sufficient for everyone except those who would probably also end up ignoring your above suggestions anyway. > Maybe > __builtins__ could be removed entirely from Py3.0, thus bringing > reality in to sync with policy. That's a possibility, though given that it's an implementation detail there could easily be other implementation details which you would then be asking to be removed as well because they might confuse someone. If you really want to avoid having implementation details exposed like this, you should probably be participating closely in the development process. ;-) (I'm also someone who believes we have way too many laws and that a few core ones already cover the majority of interesting situations for which the politicians are endlessly dreaming up more and more specific laws. So far this thread seems to me a parallel sort of situation...) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Productivity and economics at software development
Peter Hansen <[EMAIL PROTECTED]> writes: > If you focus on IDEs, your research will have pre-selected only > certain kinds of programmers and teams, and will not necessarily > include the best ones. It wouldn't have occurred to me to say that Ken Iverson (APL), Peter Deutsch (PARC Smalltalk), or Dave Moon (MIT Lisp machine) were any of them slouches. Some of the best programming ever done has gone into IDE's. It would be great if Python had anything of the caliber of those old systems. -- http://mail.python.org/mailman/listinfo/python-list
Can I compile Python for the web?
Dear sirs, I'm doing some investigations on the Python language. I'd like to know if it is possible to compile Python code made for the web (an online database for instance), and to run it using mod_python. How is it possible? I think it would be very fast to execute the code if it were compiled. Thanks, -- Charles. Desenvolvimento e criação de sites: www.auriance.com Hospedagem de sites e servidores dedicados: www.auriance.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Wrapping classes
Jeremy Sanders wrote: > Colin J. Williams wrote: > > >>Could you not have functions a and b each of which returns a NumArray >>instance? >> >>Your expression would then be something like a(..)+2*b(..). > > > The user enters the expression (yes - I'm aware of the possible security > issues), as it is a scientific application. I don't think they'd like to > put () after each variable name. > > I could always munge the expression after the user enters it, of course. > > Jeremy > Alternatively, you could build your own expression calculator, and initialize the objects if necessary as they are evaluated. If you are happy with Python syntax for your expressiones then the stdlib compiler package is helpful. The example below is not tested beyond what you see. It's a bit verbose, but most of the code is boilerplate. >>> a = 3 >>> b = 4 >>> calc('a * b') using a using b 12 >>> calc('a * b ** (b - a) * "a"') using a using b using b using a '' >>> calc("0 and a or b") using b 4 >>> calc("1 and a or b") using a 3 >>> calc("1 and a or c") using a 3 >>> calc("0 and a or c") Undefined symbol: c >>> HTH, Michael - import compiler class CalcError(Exception): def __init__(self,error,descr = None,node = None): self.error = error self.descr = descr self.node = node def __repr__(self): return "%s: %s" % (self.error, self.descr) __str__ = __repr__ class LazyCalc(object): def __init__(self, namespace): self._cache = {} # dispatch table self.context = namespace def visit(self, node,**kw): cls = node.__class__ meth = self._cache.setdefault(cls, getattr(self,'visit'+cls.__name__,self.default)) return meth(node, **kw) def visitExpression(self, node, **kw): return self.visit(node.node) # Binary Ops def visitAdd(self,node,**kw): return self.visit(node.left) + self.visit(node.right) def visitDiv(self,node,**kw): return self.visit(node.left) / self.visit(node.right) def visitFloorDiv(self,node,**kw): return self.visit(node.left) // self.visit(node.right) def visitLeftShift(self,node,**kw): return self.visit(node.left) << self.visit(node.right) def visitMod(self,node,**kw): return self.visit(node.left) % self.visit(node.right) def visitMul(self,node,**kw): return self.visit(node.left) * self.visit(node.right) def visitPower(self,node,**kw): return self.visit(node.left) ** self.visit(node.right) def visitRightShift(self,node,**kw): return self.visit(node.left) >> self.visit(node.right) def visitSub(self,node,**kw): return self.visit(node.left) - self.visit(node.right) # Unary ops def visitNot(self,node,*kw): return not self.visit(node.expr) def visitUnarySub(self,node,*kw): return -self.visit(node.expr) def visitInvert(self,node,*kw): return ~self.visit(node.expr) def visitUnaryAdd(self,node,*kw): return +self.visit(node.expr) # Flow Control def visitAnd(self,node,**kw): for arg in node.nodes: val = self.visit(arg) if not val: return val return val def visitOr(self,node,**kw): for arg in node.nodes: val = self.visit(arg) if val: return val return val # Logical Ops def visitBitand(self,node,**kw): return reduce(lambda a,b: a & b,[self.visit(arg) for arg in node.nodes]) def visitBitor(self,node,**kw): return reduce(lambda a,b: a | b,[self.visit(arg) for arg in node.nodes]) def visitBitxor(self,node,**kw): return reduce(lambda a,b: a ^ b,[self.visit(arg) for arg in node.nodes]) def visitCompare(self,node,**kw): comparisons = { "<": operator.lt, # strictly less than "<=": operator.le,# less than or equal ">": operator.gt, # strictly greater than ">=": operator.ge, # greater than or equal "==": operator.eq, # equal "!=": operator.ne, # not equal "<>": operator.ne, # not equal "is": operator.is_, # object identity "is not": operator.is_not # negated object identity } obj = self.visit(node.expr) for op, compnode in node.ops: compobj = self.visit(compnode) if not comparisons[op](obj, compobj): return False obj = compobj return True # Values def visitCallFunc(self,node,**kw): raise CalcError("Functions not supported", node.node) def visitName(self, node, **kw): """LazyEvaluation""" name = node.name try: val = eval(name, self.context) except
Re: parsing a date
Kalle Anke wrote: >I want to parse a date string, for example '2005-09-23', and since I haven't >done this before I would like to ask what is the best way to do it. > >I've looked around and the dateutil seems to be what most people use, but >unfortunately I only get an empty file when I try to download it. I also >tried the standard modules and ended up with this > >import datetime >from time import strptime > >d = '2005-09-23' >w = strptime(d,'%Y-%m-%d') >print datetime.date( w[0], w[1], w[2] ) > Well, thats not _to_ bad. >But I suspect there is a better way to do it?? > > > There is... I would check out "strftime" With strftime you could do something like this... # -- print strftime("%Y-%m-%d") # - or if you wanted to get the time in the past or future you could do something like # -- tm = time.localtime(time.time() + ((60 * 60) * 24)) print strftime("%Y-%m-%d", tm) # - Which gets the date of tommarow. HTH, Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Help installing Python 2.3 on Win2K
On 23/09/05, D.S. Hein <[EMAIL PROTECTED]> wrote: > I have tried various ways to set PYTHONPATH with the various directories > where I have python programs (i.e. xx.py) but no matter how I set > PYTHONPATH I keep getting a message that python can't open the python > file. If I try to specify the full pathname by typing: python > c:\Documents and Settings\-rest of path- I get an error message that > python can't open c:\Documents. > add these directories to a text file called python.pth in your python23 directory in the format d:\dir1\dir2 HTH :) -- Tim Williams -- http://mail.python.org/mailman/listinfo/python-list
Re: Single type for __builtins__ in Py3.0
On 9/23/05, Peter Hansen <[EMAIL PROTECTED]> wrote: > User are clearly told in various places that names with leading and > trailing double underscores are *special*, and at least by implication > they are not to be used without a good understanding of what they are. > You certainly shouldn't have found any docs telling you to use > __builtins__ that way. > > http://www.google.ca/search?q=site%3Apython.org+__builtin__ is a pretty > quick way of finding the above docs, and while doing the same search > with __builtins__ admittedly finds lots of mailing list archives where > people have the same misconception as you did, it doesn't take one past > the second page of results before you'll be right back at a post by > Fredrik pointing out the same mistake. :-) The difference between __builtins__ and the other __*__ names is that while the others shouldn't be used without understanding their purpose, the consensus on __builtins__ seems to be that it shouldn't be used at all. Since you mention Fredrik's posts on the subject, I'll quote one for you: http://mail.python.org/pipermail/python-list/2002-June/109090.html """ forget about __builtins__; it's an implementation detail. if you need to explicitly refer to stuff in the built-in namespace, *always* import the __builtin__ module. never use __builtins__ in your code. """ Other posts echo this. To my mind this indicates that, at the very least, users should be explicitly told -- up front, in the official documentation -- that they shouldn't ever touch __builtins__. Maybe __builtins__ could be removed entirely from Py3.0, thus bringing reality in to sync with policy. Collin Winter -- http://mail.python.org/mailman/listinfo/python-list
Re: Help installing Python 2.3 on Win2K
D.S. Hein wrote: > I have installed python 2.3 on my Windows 2K laptop and I can run python > from the command prompt. > > I have tried various ways to set PYTHONPATH with the various directories > where I have python programs (i.e. xx.py) but no matter how I set > PYTHONPATH I keep getting a message that python can't open the python > file. If I try to specify the full pathname by typing: python > c:\Documents and Settings\-rest of path- I get an error message that > python can't open c:\Documents. Put the path inside quotation marks just as you would any other command. C:\>dir C:\documents and settings\a* The system cannot find the file specified. C:\>dir "C:\documents and settings\a*" Volume in drive C is PXXABA Volume Serial Number is 90C0-740E Directory of C:\documents and settings 07/16/2001 08:40aAdministrator 07/29/2005 08:20aAll Users 0 File(s) 0 bytes 2 Dir(s) 772,973,568 bytes free > > The ways I have set PYTHONPATH are by directly changing the registry > entry for Python 2.3, by setting the environment variable by > right-clicking on My Computer and by adding set PYTHONPATH=-various > pathnames-. > > I'd be grateful for any guidance on how to organize my system. -- http://mail.python.org/mailman/listinfo/python-list
Re: CRC16
Tuvas wrote: > Anyone know a module that does CRC16 for Python? I have an aplication > that I need to run it, and am not having alot of sucess. I have a > program in C that uses a CRC16 according to CCITT standards, but need > to get a program that tests it with python as well. Thanks! > Try this one http://crcmod.sourceforge.net/ It will do what you want as long as you know what polynomial to use and what type of algorithm. I think you want the CCITT polynomial with a bit-reverse algorithm. If that is the case, the following will generate the Python function you want (assumes you want to seed the CRC calculation with the starting value of 0x). import crcmod crc16 = crcmod.mkCrcFun(0x11021, 0x, True) Now compute the crc of a data string as crc = crc16(data) -- http://mail.python.org/mailman/listinfo/python-list
Help installing Python 2.3 on Win2K
I have installed python 2.3 on my Windows 2K laptop and I can run python from the command prompt. I have tried various ways to set PYTHONPATH with the various directories where I have python programs (i.e. xx.py) but no matter how I set PYTHONPATH I keep getting a message that python can't open the python file. If I try to specify the full pathname by typing: python c:\Documents and Settings\-rest of path- I get an error message that python can't open c:\Documents. The ways I have set PYTHONPATH are by directly changing the registry entry for Python 2.3, by setting the environment variable by right-clicking on My Computer and by adding set PYTHONPATH=-various pathnames-. I'd be grateful for any guidance on how to organize my system. -- http://mail.python.org/mailman/listinfo/python-list
Re: Single type for __builtins__ in Py3.0
Collin Winter wrote: > On 9/23/05, Fredrik Lundh <[EMAIL PROTECTED]> wrote: >>__builtins__ is a CPython implementation detail. why not just let it >>be an implementation detail, and refrain from using it? it's not that >>hard, really. > Given, but I fail to see why it can't be a consistent implementation > detail. After my own encounter with __builtins__, I now know that I > should use __builtin__ instead. However, the docs never mention this. http://docs.python.org/lib/module-builtin.html > The only way you'd know that __builtin__ is preferred is by searching > the list archives, something you're not likely to do unless you're > already having a problem. > > If it's decided to leave things they way they are, at the very least > the docs should be amended to indicate that users shouldn't be > touching __builtins__. If anyone has a suggestion as to where this > kind of thing might best fit (tutorial, library reference, language > reference?), I'd be happy to write a patch for the docs. User are clearly told in various places that names with leading and trailing double underscores are *special*, and at least by implication they are not to be used without a good understanding of what they are. You certainly shouldn't have found any docs telling you to use __builtins__ that way. http://www.google.ca/search?q=site%3Apython.org+__builtin__ is a pretty quick way of finding the above docs, and while doing the same search with __builtins__ admittedly finds lots of mailing list archives where people have the same misconception as you did, it doesn't take one past the second page of results before you'll be right back at a post by Fredrik pointing out the same mistake. :-) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Dialogs
James Stroud wrote: > from tkMessageBox import showerror > showerror('Problem','Program Crashed before Starting') Thanks. That works great when interpreted (though a blank window seems to open as well). Unfortunately it still takes 40 seconds to execute after it has been 'compiled' with py2exe (I've only got a P3). This probably has something to do with the fact that the resulting files for this two-liner weigh in at just under 8MB. Sounds like I'll need to write a one-line msgbox.exe in Visual Whatever or Euphoria and execute that from Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: Productivity and economics at software development
Adriano Monteiro wrote: > I'm making a little research project about programming languages e > their respective IDEs. The goal is to trace each language silhouettes, > where it fits better, their goods/bads and the costs of developing in > this language. You say this as though each language has and needs an IDE! We do all our development using a simple text editor (often Scite) and a console window (or three), plus assorted other tools developed or discovered, as required. It's not "integrated" like an IDE, but we find it a much more effective approach, especially as we are doing test-driven development. An IDE just gets in our way. If you focus on IDEs, your research will have pre-selected only certain kinds of programmers and teams, and will not necessarily include the best ones. (Looking at the VB world, one might even say something more extreme than that.) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing class variable at class creation time
It might be that I'm complicating something easy here, but I immediately thought of import sys class A: X = 2 def F(): f = sys._getframe().f_back print f.f_locals["X"] F() -- http://mail.python.org/mailman/listinfo/python-list
Re: Bluetooth
Tor Erik Sønvisen wrote: > I'm making a server-side solution in Python and need to be able to > communicate through bluetooth. Is there any bluetooth-packages out there for > python? At the lowest level, you should be able to create sockets for Bluetooth communications (see the socket module's documentation and the source code in Modules/socketmodule.c); for example: from socket import * s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM) On Linux, upon binding a device file to the Bluetooth device, you can use things like pySerial to manage the communications; this works with software like t616hack: http://www.nelson.monkey.org/~nelson/weblog/tech/phone/ http://pyserial.sourceforge.net/ Various other tools exist which understand Bluetooth communications, notably the OpenOBEX tools: http://triq.net/obex/ I prefer to work with tools at the higher levels (obexftp to access files, pySerial/t616hack to access messages), but provided your Python distribution is set up correctly, you should be able to work at the lowest levels too. Paul -- http://mail.python.org/mailman/listinfo/python-list
RE: distutils and decorators
Benji York wrote: > Robert Brewer wrote: > > Actually, in this case we most definitely want to test > > 2.4's "@" syntax. The decorator in question is an aliaser, > > and therefore is one of the few > > decorators which must be implemented differently for the 2.3-style > > decoration and the 2.4-style. See the "expose" function at: > > http://www.cherrypy.org/file/trunk/cherrypy/__init__.py?rev=654 > > I extracted "expose" from the above URL and wrote this test > script (mind the wrapping): > ... > What am I missing? Nothing, apparently. Looks like I outfoxed myself with my own poor comments. Thanks for the correction! Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing class variable at class creation time
You could use self.__class__.X HTH, Ole 23 Sep 2005 14:01:21 -0700, Carlos <[EMAIL PROTECTED]>: > Hi! > > class A: > X = 2 > def F(): > print A.X > F() > > The above fails because the name A is not > yet at global scope when the reference A.X > is reached. Is there any way to refer to A.X > without making explicit use of the name 'A'? > Admittedly the code looks pretty unusual, > but I'm defining configuration "minilanguages" > to configure different parts of an application, > each inside a configuration class (like A), > and I find this very convenient except for > the above problem. > > Thank you in advance > Regards, > Carlos > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: batch mkdir using a file list
Awesome! That worked! Much thanks to Peter and all of you who took the time to answer my question. R.D. -- http://mail.python.org/mailman/listinfo/python-list
Re: CRC16
Tuvas wrote: > Anyone know a module that does CRC16 for Python? I have an aplication > that I need to run it, and am not having alot of sucess. I have a > program in C that uses a CRC16 according to CCITT standards, but need > to get a program that tests it with python as well. Thanks! I'll include one below. There's a tricky bit in that most standards assume a serial bit stream, not byte data, leading to the relection issue discussed in the reference in the doc. Let me know if gets the same answers as your C version. -- --Bryan === #!/usr/bin/env python # crc16.py by Bryan G. Olson, 2005 # This module is free software and may be used and # distributed under the same terms as Python itself. """ CRC-16 in Python, as standard as possible. This is the 'reflected' version, which is usually what people want. See Ross N. Williams' /A Painless Guide to CRC error detection algorithms/. """ from array import array def crc16(string, value=0): """ Single-function interface, like gzip module's crc32 """ for ch in string: value = table[ord(ch) ^ (value & 0xff)] ^ (value >> 8) return value class CRC16(object): """ Class interface, like the Python library's cryptographic hash functions (which CRC's are definitely not.) """ def __init__(self, string=''): self.val = 0 if string: self.update(string) def update(self, string): self.val = crc16(string, self.val) def checksum(self): return chr(self.val >> 8) + chr(self.val & 0xff) def hexchecksum(self): return '%04x' % self.val def copy(self): clone = CRC16() clone.val = self.val return clone # CRC-16 poly: p(x) = x**16 + x**15 + x**2 + 1 # top bit implicit, reflected poly = 0xa001 table = array('H') for byte in range(256): crc = 0 for bit in range(8): if (byte ^ crc) & 1: crc = (crc >> 1) ^ poly else: crc >>= 1 byte >>= 1 table.append(crc) crc = CRC16() crc.update("123456789") assert crc.checksum() == '\xbb\x3d' -- http://mail.python.org/mailman/listinfo/python-list
Re: Wrapping classes
I agree this is a case for using metaclasses. What about an implementation like this ? Seems like checking if init was already called will slow down all attribute access significantly, but, I don't like this approach of changing the __init__ method. class LazyInit(type): def __new__(self, name, bases, dict): def __getattribute__(self, attr): attrs = object.__getattribute__(self, "__dict__") init = attrs["_init"] if not init: args = attrs["_args"] kwds = attrs["_kwds"] __init__ = object.__getattribute__(self, "__init__") __init__(*args, **kwds) attrs["_init"] = True return object.__getattribute__(self, attr) dict['__getattribute__'] = __getattribute__ return type.__new__(self, name, bases, dict) def __call__(cls, *args, **kwds): o = object.__new__(cls, *args, **kwds) o._args = args o._kwds = kwds o._init = False return o And some simple testing: >>> class Foo: ... __metaclass__ = LazyInit ... def __init__(self, x, y): ... print "init was called", x, y ... self.x = x ... self.y = y ... >>> o = Foo(1, None) >>> o <__main__.Foo object at 0x402cc96c> >>> o.x init was called 1 None 1 >>> o.y >>> Regards, Pedro On Fri, 23 Sep 2005 10:28:42 +0200 Paolino <[EMAIL PROTECTED]> wrote: > Jeremy Sanders wrote: > > Is it possible to implement some sort of "lazy" creation of objects > > only when the object is used, but behaving in the same way as the > > object? > > > A generic approach would override __getattribute__ to let it perform > the > __init__ method on not initialized objects.This is a case for using > metaclasses as even __init__ method must be overridden ad hoc to > register the arguments for the lazy initialization. > Probably you want to fine-tune the triggering (specifing which > attribute should make it happen ),as every look up would trigger. > > class NotInitializedObjects(type): >def __init__(cls,*_): > realInit=cls.__init__ > def __newInit__(self,*pos,**key): >def _init(): > realInit(self,*pos,**key) >self._init=_init > cls.__init__=__newInit__ > def __getattribute__(self,attr): >def getter(attr): > return object.__getattribute__(self,attr) >if '_init' in getter('__dict__'): > getter('_init')() > del self._init >return getter(attr) > cls.__getattribute__=__getattribute__ > > > if __name__=='__main__': >class Class: > __metaclass__=NotInitializedObjects > def __init__(self,*pos,**key): >self.initialized=True >print 'initializing with',pos,key >a=Class('arg',key='key') # a fake initialization > >try: > object.__getattribute__(a,'initialized') >except AttributeError: # should raise > print 'not initialized' >else: > raise >try: > a.initialized #every look up would do ,even a print >except AttributeError: > raise >else: > print 'initialized' > > > Have fun Paolino > > > > > > ___ > Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB > http://mail.yahoo.it > -- > http://mail.python.org/mailman/listinfo/python-list -- Pedro Werneck -- http://mail.python.org/mailman/listinfo/python-list
Re: parsing a date
Better than a single line of code? What is it that you are looking for? If you dates are consistent you can do: year, month, day=map(int, d.split('-')) but I'm not sure it is "better". I guess it depends on what you want to do with them after parsing. -Larry Bates Kalle Anke wrote: > I want to parse a date string, for example '2005-09-23', and since I haven't > done this before I would like to ask what is the best way to do it. > > I've looked around and the dateutil seems to be what most people use, but > unfortunately I only get an empty file when I try to download it. I also > tried the standard modules and ended up with this > > import datetime > from time import strptime > > d = '2005-09-23' > w = strptime(d,'%Y-%m-%d') > print datetime.date( w[0], w[1], w[2] ) > > But I suspect there is a better way to do it?? > -- http://mail.python.org/mailman/listinfo/python-list
Accessing class variable at class creation time
Hi! class A: X = 2 def F(): print A.X F() The above fails because the name A is not yet at global scope when the reference A.X is reached. Is there any way to refer to A.X without making explicit use of the name 'A'? Admittedly the code looks pretty unusual, but I'm defining configuration "minilanguages" to configure different parts of an application, each inside a configuration class (like A), and I find this very convenient except for the above problem. Thank you in advance Regards, Carlos -- http://mail.python.org/mailman/listinfo/python-list
HTML to LaTeX RE pattern and sub
Hi, trying to make a small script which would translate wiki file into LaTeX and when trying to translate possible HTML elements into LaTeX I did this: def latexEnvironments(matchobj): print >>sys.stderr,str(matchobj.groups()) inStr = matchobj.group(1) translDict = {'dl': ('\\begin{description}','\\end{description}'), 'ol': ('\\begin{enumerate}','\\end{enumerate}'), 'ul': ('\\begin{itemize}','\\end{itemize}'), 'blockquote': ('\\begin{quote}','\\end{quote}'), 'center': ('\\begin{center}','\\end{center}'), 'li': ('\\item',''), 'pre': ('\\begin{ttfamily}','\\end{ttfamily}')} if translDict.has_key(inStr): retTuple = translDict[inStr] else: retTuple = ('','') if matchobj.group(0) == '/': return retTuple[1] else: return retTuple[0] def latexHeadings(matchobj): print >>sys.stderr,str(matchobj.groups()) inStr = matchobj.groups[1] translDict = {'h1': '\\section{}', 'h2': '\\subsection{}', 'h3': '\\subsubsection{}', 'h4': '\\subsubsubsection{}', 'h5': '\\paragraph{}'} if translDict.has_key(inStr) and (matchobj.groups[0] != '/'): return translDict[inStr] else: return '' def latexEmptyElements(matchobj): retString = "" print >>sys.stderr,str(matchobj.groups()) inStr = matchobj.group(0) translDict = {'br//': '', 'hr': '\\par{}\\hrulefill{}\\par{}'} if translDict.has_key(inStr): return translDict[inStr] else: return '' [... snip ...] # Remove superfluous HTML elements reEnvironments = re.compile(r'<(/?)(dl|ol|ul|address|blockquote|center|del\ |ins|div|isindex|noscript|p|pre)>',re.IGNORE) reHeadings = re.compile(r'<(/?)(h1|h2|h3|h4|h5|h6)>',re.IGNORE) reEmpty = re.compile(r'<(hr|br)\s*/?>',re.IGNORE) body = reEnvironments.sub(latexEnvironments,body) body = reHeadings.sub(latexHeadings,body) body = reEmpty.sub(latexEmptyElements,body) The problem is that apparently RE never matches (and no function is thus called). Can anybody tell me what's wrong with my REs, please? Thanks for any help, Matej -- http://mail.python.org/mailman/listinfo/python-list
Re: batch mkdir using a file list
DataSmash wrote: > I am using bash shell on windows and I'm getting the error: > TypeError: loop over non-sequence Use open(filename).readlines() instead of open(filename) or switch to a current Python version. > OR...if python can't handle this type of text file, > what do I need to do to remove the "\n" from the file? line.strip() removes all leading and trailing whitespace (not just "\n") from the line string. import os for line in open("list.txt").readlines(): directory = line.strip() os.mkdir(directory) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling Access module functions from python
> "kayakerjess" == kayakerjess <[EMAIL PROTECTED]> writes: kayakerjess> Hi, I have an Access Data Project (.adp) that I am kayakerjess> trying to open and execute from Python. I am using kayakerjess> the win32com.client, and I have successfully opened kayakerjess> the application, but I'm getting an exception when I kayakerjess> try to execute the function (actually a "Sub" that kayakerjess> returns void, but that shouldn't matter). Here's kayakerjess> what I have so far: kayakerjess> conn=win32com.client.Dispatch('Access.Application') kayakerjess> conn.OpenAccessProject("C:/path/to/file/filename.adp") kayakerjess> conn.Visible = 1 # works so far kayakerjess> conn.Run("test_interface") kayakerjess> # Exception is thrown here. # com_error: kayakerjess> (-2147352567, 'Exception occurred.', (0, None, None, kayakerjess> None, 0, -2147352562), None) kayakerjess> The 'test_interface' function takes no arguments, but kayakerjess> I've tried the same thing with another function that kayakerjess> does take arguments and gotten the same result. kayakerjess> Any help would be appreciated. kayakerjess> Thanks, kayakerjess Assuming you have a copy of Access, no? I would recommend lighting off Access, and exploring the Modules collection. Possibly start a new file, and see if you can prototype your python code in Visceral Baysuck for crApplications, (which is actually a better tool than my sophomoric comment implies). The modules collection may let you invoke a Sub in one of them. Google might also yield something. HTH, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Open PDF
"Martin Miller" <[EMAIL PROTECTED]> writes: > IMHO, the fact that there is no way to wait for the application to > finish is major deficiency with os.startfile() -- and why I often > cannot use it instead of other techniques [such as the much more > involved but limited os.spawnv() function]. > > I don't if if this is just a limitation of the implementation in the > Python os module or one with the underlying OS (Windoze) -- I suspect > the latter. os.startfile calls ShellExecute. AFAIK, if ShellExecuteEx were used, this could retrieve a process handle which you could wait for os so. With ctypes you can easily experiment with this kind of stuff. Another interesting feature, imo, is the 'verb' that you can pass to these functions. With this, you could for example specify 'print' to print the file instead of just opening it. Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Source Code for a HTTP Proxy
llothar wrote: >Hello, > >i'm looking for a simple http proxy in python. >Does anybody know about something like this ? > > > Here's a list, maintained by Alan Kennedy, of about 20 proxys written in Python: http://xhaus.com/alan/python/proxies.html Enjoy, Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting tired with py2exe
Any luck on finding anyone to take over py2exe development Thomas? It's a GREAT project and would be a shame to see it fall into obsolescence. Thomas Heller wrote: [snip] > > Is anyone interested in taking over the maintainance, documentation, and > further development? > [snip] -- http://mail.python.org/mailman/listinfo/python-list
Re: Run VPython on FC3
In the darkest hour on Fri, 16 Sep 2005 15:45:33 -0700, York <[EMAIL PROTECTED]> screamed: >>>/usr/local/lib/libgtkgl.so.4.0.0 >>>/usr/local/lib/libgtkgl.so.4 >>> >>>Does anybody know a solution for this problem? >>> >> >> You need libgtk-(open)gl package (i don't know the exact name in FC). >> > Actually the gtkgl was installed, I can find it at /usr/local/lib: > /usr/local/lib/libgtkgl.so.4.0.0 > /usr/local/lib/libgtkgl.so.4 > Check for presence of /usr/local/lib in /etc/ld.so.conf Append it if necessary. Don't forget to run ldconfig afterwards. -- [ Artur M. Piwko : Pipen : AMP29-RIPE : RLU:100918 : From == Trap! : SIG:228B ] [ 21:38:09 user up 10743 days, 9:33, 1 user, load average: 0.06, 0.06, 0.06 ] I considered atheism but there weren't enough holidays. -- http://mail.python.org/mailman/listinfo/python-list
parsing a date
I want to parse a date string, for example '2005-09-23', and since I haven't done this before I would like to ask what is the best way to do it. I've looked around and the dateutil seems to be what most people use, but unfortunately I only get an empty file when I try to download it. I also tried the standard modules and ended up with this import datetime from time import strptime d = '2005-09-23' w = strptime(d,'%Y-%m-%d') print datetime.date( w[0], w[1], w[2] ) But I suspect there is a better way to do it?? -- http://mail.python.org/mailman/listinfo/python-list
Re: batch mkdir using a file list
OR...if python can't handle this type of text file, what do I need to do to remove the "\n" from the file? -- http://mail.python.org/mailman/listinfo/python-list
Re: Single type for __builtins__ in Py3.0
On 9/23/05, Christopher Subich <[EMAIL PROTECTED]> wrote: > How would this change, if made in a minimal way, impact the "provide > alternate globals() and locals() to eval and exec" feature? Altering > __builtins__ is a half-assed way of providing some sort of security, but > it's probably useful in preventing user-supplied code from shooting > itself in the foot without aiming first. In all cases (eval, exec, execfile), the globals parameter must be a dict and the locals can be any mapping object, so the value of the __builtins__ key would just need to be a module (could be created with the "new" module). This is about the same breakage as with any other code using __builtins__. One possibility would be to deprecate the dict-form. This could be done as Tom Anderson suggests, by supporting both __getattr__ and __getitem__, with the latter issuing a deprecation warning for a while. My tests indicate that this is possible, with both module.attr and module['item'] forms available. Collin Winter -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Dialogs
py> from tkMessageBox import askquestion, showerror py> from tkSimpleDialog import askfloa py> a = askfloat('Census Data', 'Enter Salary') py> print a 12500.51 py> a = askquestion('Opinion', 'Do you think windoze sucks?') py> print a yes py> a = showerror('Problem','Program Crashed before Starting') py> print a ok On Friday 23 September 2005 11:33, [EMAIL PROTECTED] wrote: > I'm looking for a lightweight dialog boxes from Python. > JavaScript uses: alert(), confirm() and prompt() > VB uses: MsgBox() and InputBox() > EasyGui seemed perfect, but a "Hello World" application takes nearly a > minute to execute after the program has been compiled by py2exe. > > There appear to be dozens of windowing toolkits avilable for Python, > could someone point me in the direction of something lightweight? > > Thanks. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Python Source Code for a HTTP Proxy
Hello, i'm looking for a simple http proxy in python. Does anybody know about something like this ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Anyone else getting posts back as email undeliverable bounces?
On Fri, 23 Sep 2005 11:49:51 +0100, Steve Holden <[EMAIL PROTECTED]> wrote: >I've even tried communicating with postmaster at all relevant domains, >but such messages are either bounced or ignored, so I've just filtered >that domain out. > Yeah, but I thought maybe there could be a way to detect this kind of situation from the python.org or xs4all.nl side and not feed a thing that vomits indiscriminately, so to speak. Sorry about the metaphor ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: batch mkdir using a file list
I am using bash shell on windows and I'm getting the error: TypeError: loop over non-sequence Is there any way around not messing with the text file. I want to batch generate the text lists as well. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: batch mkdir using a file list
Jeremy Jones wrote: > DataSmash wrote: > > >Hello, > >I think I've tried everything now and can't figure out how to do it. > >I want to read in a text list from the current directory, > >and for each line in the list, make a system directory for that name. > > > >My text file would look something like this: > >1144 > >1145 > >1146 > >1147 > > > >I simply want to create these 4 directories. > >It seems like something like the following > >code should work, but it doesn't. > > > >import os > > > >file = open("list.txt", "r") > >read = file.read() > >print "Creating directory " + str(read) > >os.mkdir(str(read)) > > > >Appreciate any help you can give! > >R.D. Harles > > > > > > > Untested code: > > import os > for line in open("list.txt", "r"): > os.mkdir(line) That won't work (in Windows at least) because you have to remove the "\n" from the line before you pass it to os.mkdir. > > > - JMJ -- http://mail.python.org/mailman/listinfo/python-list
Re: Single type for __builtins__ in Py3.0
On 9/23/05, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > Collin Winter wrote: > > > As it currently stands, the type of the global __builtins__ differs > > depending on whether you're in the __main__ namespace (__builtins__ is > > a module) or not (its a dict). I was recently tripped up by this > > discrepancy, and googling the issue brings up half-a-dozen or so c.l.p > > threads where others have been bitten by this, too. > > __builtins__ is a CPython implementation detail. why not just let it > be an implementation detail, and refrain from using it? it's not that > hard, really. Given, but I fail to see why it can't be a consistent implementation detail. After my own encounter with __builtins__, I now know that I should use __builtin__ instead. However, the docs never mention this. The only way you'd know that __builtin__ is preferred is by searching the list archives, something you're not likely to do unless you're already having a problem. If it's decided to leave things they way they are, at the very least the docs should be amended to indicate that users shouldn't be touching __builtins__. If anyone has a suggestion as to where this kind of thing might best fit (tutorial, library reference, language reference?), I'd be happy to write a patch for the docs. Collin Winter -- http://mail.python.org/mailman/listinfo/python-list
Re: Single type for __builtins__ in Py3.0
Collin Winter wrote: > Hallo all, > I'd like to propose that in Py3.0 (if not earlier), __builtins__ will > be the same type regardless of which namespace you're in. Tim Peters > has said [1] that the reason __builtins__ in __main__ is a module so > that "the curious don't get flooded with output when doing vars() at > the prompt". Based on this, I propose that __builtins__ be a module > (really, an alias for the __builtin__ module as it is now) in all > namespaces. > > If possible, I'd like to see this go in before 3.0. The reference > manual currently states [2] that __builtins__ can be either a dict or > a module, so changing it to always be a module would still be in > keeping with this. However, I realise that there's probably code out > there that hasn't been written to deal with both types, so this would > result in some minor breakage (though it would be easily fixable). > > If this gets a good response, I'll kick it up to python-dev. A few questions: How would this change, if made in a minimal way, impact the "provide alternate globals() and locals() to eval and exec" feature? Altering __builtins__ is a half-assed way of providing some sort of security, but it's probably useful in preventing user-supplied code from shooting itself in the foot without aiming first. Secondly, wouldn't this also be a good time to implement modules as actual objects, so (e.g) modules could provide a __getattribute__ for references of the form modname.thing? If the change can't be made without breaking the altering of __builtins__ for exec/eval, then I'm -0.5. Otherwise, +1, and the second bit is probably good for further debate. -- http://mail.python.org/mailman/listinfo/python-list
Re: Open PDF
IMHO, the fact that there is no way to wait for the application to finish is major deficiency with os.startfile() -- and why I often cannot use it instead of other techniques [such as the much more involved but limited os.spawnv() function]. I don't if if this is just a limitation of the implementation in the Python os module or one with the underlying OS (Windoze) -- I suspect the latter. Regards, -Martin Dennis Lee Bieber wrote: > On Thu, 22 Sep 2005 15:16:09 +0100, Dan <[EMAIL PROTECTED]> declaimed > the following in comp.lang.python: > > > > I would like to know how to open a PDF document from a python script > > > > You mean open it and display it to the user? Under Windows you may be > > able to get away with just "executing" the file (as though it were an > > executable): > > > > import os > > os.system("c:/path/to/file.pdf") > > For Windows, os.startfile() may be better... > > >>> help(os.startfile) > Help on built-in function startfile: > > startfile(...) > startfile(filepath) - Start a file with its associated application. > > This acts like double-clicking the file in Explorer, or giving the > file > name as an argument to the DOS "start" command: the file is opened > with whatever application (if any) its extension is associated. > > startfile returns as soon as the associated application is launched. > There is no option to wait for the application to close, and no way > to retrieve the application's exit status. > > The filepath is relative to the current directory. If you want to > use > an absolute path, make sure the first character is not a slash > ("/"); > the underlying Win32 ShellExecute function doesn't work if it is. > > >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: What is "self"?
Ron Adam wrote: > Erik Max Francis wrote: > >>Ron Adam wrote: >> >> >>>When you call a method of an instance, Python translates it to... >>> >>> leader.set_name(leader, "John") >> >> >>It actually translates it to >> >>Person.set_name(leader, "John") >> > > > I thought that I might have missed something there. > > Is there a paper on how python accesses and stores instance data and > methods? I googled but couldn't find anything that addressed this > particular question. > > >>> class a(object): > ...def x(self): > ... print 'x' > ... > >>> b = a() > >>> b > <__main__.a object at 0x009D1890> > >>> b.x > > > > So what exactly is a bound method object? Does it possibly translates > to something like the following? > > def x(*args, **kwds): > self = ? > return __class__.self(self, *args, **kwds) > > Cheers, > Ron > > > > > All is explained at: http://users.rcn.com/python/download/Descriptor.htm#functions-and-methods and further at: http://www.python.org/pycon/2005/papers/36/pyc05_bla_dp.pdf "For objects, the machinery is in object.__getattribute__ which transforms b.x into type(b).__dict__['x'].__get__(b, type(b))." What follows is my interpretation - hope it's correct: # what exactly is a bound method object? # Illustrate b.f => type(b).__dict__['x'].__get__(b, type(b)) >>> class B(object): ... def f(self, x): ... return x or 42 ... >>> b = B() >>> type(b).__dict__['f'] # a plain old function >>> _.__get__(b, type(b)) # invoke the descriptor protocol # to make a bound method > >>> You don't have to use object.__getattribute__ to get a bound method. Nor does the function have to be in the class dictionary. You can just call any function descriptor yourself: >>> def g(self, y): ... return self.f(y) ... >>> boundg = g.__get__(b) # bind to B instance >>> boundg > >>> boundg(0) 42 >>> Looked at this way, function.__get__ just does partial function application (aka currying). >>> def f(x, y): ... return x+y ... >>> add42 = f.__get__(42) >>> add42 >>> add42(1) 43 Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: batch mkdir using a file list
DataSmash wrote: >Hello, >I think I've tried everything now and can't figure out how to do it. >I want to read in a text list from the current directory, >and for each line in the list, make a system directory for that name. > >My text file would look something like this: >1144 >1145 >1146 >1147 > >I simply want to create these 4 directories. >It seems like something like the following >code should work, but it doesn't. > >import os > >file = open("list.txt", "r") >read = file.read() >print "Creating directory " + str(read) >os.mkdir(str(read)) > >Appreciate any help you can give! >R.D. Harles > > > Untested code: import os for line in open("list.txt", "r"): os.mkdir(line) - JMJ -- http://mail.python.org/mailman/listinfo/python-list
Re: batch mkdir using a file list
DataSmash <[EMAIL PROTECTED]> wrote > I think I've tried everything now and can't figure out how to do it. > I want to read in a text list from the current directory, > and for each line in the list, make a system directory for that name. > > My text file would look something like this: > 1144 > 1145 > 1146 > 1147 > > I simply want to create these 4 directories. > It seems like something like the following > code should work, but it doesn't. > > import os > > file = open("list.txt", "r") > read = file.read() > print "Creating directory " + str(read) > os.mkdir(str(read)) read() returns *all* text in the file as a single string, but you really want to process each line for itself. try this: for name in open("list.txt"): name = name.strip() # get rid of extra whitespace os.mkdir(name) -- http://mail.python.org/mailman/listinfo/python-list
Simple Dialogs
I'm looking for a lightweight dialog boxes from Python. JavaScript uses: alert(), confirm() and prompt() VB uses: MsgBox() and InputBox() EasyGui seemed perfect, but a "Hello World" application takes nearly a minute to execute after the program has been compiled by py2exe. There appear to be dozens of windowing toolkits avilable for Python, could someone point me in the direction of something lightweight? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
batch mkdir using a file list
Hello, I think I've tried everything now and can't figure out how to do it. I want to read in a text list from the current directory, and for each line in the list, make a system directory for that name. My text file would look something like this: 1144 1145 1146 1147 I simply want to create these 4 directories. It seems like something like the following code should work, but it doesn't. import os file = open("list.txt", "r") read = file.read() print "Creating directory " + str(read) os.mkdir(str(read)) Appreciate any help you can give! R.D. Harles -- http://mail.python.org/mailman/listinfo/python-list
Re: CRC16
The first URL back from Google is: http://www.onembedding.com/tools/python/code/crc16.htm Site is Russian, but crc16.py that is listed there has English comments. Maybe you can use some/all of it. -Larry Bates Tuvas wrote: > Anyone know a module that does CRC16 for Python? I have an aplication > that I need to run it, and am not having alot of sucess. I have a > program in C that uses a CRC16 according to CCITT standards, but need > to get a program that tests it with python as well. Thanks! > -- http://mail.python.org/mailman/listinfo/python-list
tk_focusNext() revisited
Hello, I am trying to move focus between Tkinter (and other) widgets. A solution similar with my approach was suggested by Eric Brunel at http://mail.python.org/pipermail/python-list/2004-July/229971.html It will generate an error: Exception in Tkinter callback Traceback (most recent call last): File "/usr/local/lib/python2.4/lib-tk/Tkinter.py", line 1345, in __call__ return self.func(*args) File "ab.py", line 20, in t.bind('', lambda e, t=t: focusNext(t)) File "ab.py", line 12, in focusNext widget.tk_focusNext().focus_set() File "/usr/local/lib/python2.4/lib-tk/Tkinter.py", line 435, in tk_focusNext return self._nametowidget(name) File "/usr/local/lib/python2.4/lib-tk/Tkinter.py", line 1006, in nametowidget if name[0] == '.': TypeError: unsubscriptable object I tried to trace the error in Tkinter.py and found that name is a cmdName and it is indeed an unsubscriptable object. It has a string method, and name.string will print a Tk-style widget name, like ".-1121901300". This one can be used to find the next widget to jump to, but later the conversion _nametowidget fails. What are my options? Platform: Gentoo, KDE, Tcl/Tk 8.4, Python 2.4.1 Sorin __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Single type for __builtins__ in Py3.0
Collin Winter wrote: > As it currently stands, the type of the global __builtins__ differs > depending on whether you're in the __main__ namespace (__builtins__ is > a module) or not (its a dict). I was recently tripped up by this > discrepancy, and googling the issue brings up half-a-dozen or so c.l.p > threads where others have been bitten by this, too. __builtins__ is a CPython implementation detail. why not just let it be an implementation detail, and refrain from using it? it's not that hard, really. -- http://mail.python.org/mailman/listinfo/python-list
Re: Productivity and economics at software development
On Fri, 23 Sep 2005, Scott David Daniels wrote: > Adriano Monteiro wrote: > >> I'm making a little research project about programming languages e >> their respective IDEs. The goal is to trace each language silhouettes, >> where it fits better, their goods/bads and the costs of developing in >> this language. > > What do you consider the IDE for Assembly code or Microcode? emacs, of course - just as it is for every other language. tom -- If you think it's expensive to hire a professional to do the job, wait until you hire an amateur. -- Red Adair -- http://mail.python.org/mailman/listinfo/python-list
Re: Single type for __builtins__ in Py3.0
On Fri, 23 Sep 2005, Collin Winter wrote: > If possible, I'd like to see this go in before 3.0. The reference manual > currently states [2] that __builtins__ can be either a dict or a module, > so changing it to always be a module would still be in keeping with > this. However, I realise that there's probably code out there that > hasn't been written to deal with both types, so this would result in > some minor breakage (though it would be easily fixable). Perhaps __builtins__ should be a magic module which could be accessed using subscripting as well as proper names (__builtins__["int"] as well as __builtins__.int), to avoid breakage. AFAICT, there's no easy way to do this at the moment: defining __getitem__ in a module doesn't give you a working [] operator on it. Have i screwed that up? If not, might it be possible to change this, so modules are treated the same as any other object in terms of handling []? I admit that this is the only use case for it, and it's a pretty weak one, but it would be good to be consistent, i think. > If this gets a good response, I'll kick it up to python-dev. +1 tom -- Gatsos are a stealth tax on motorists in the same way that city centre video cameras are a stealth tax on muggers and DNA testing is a stealth tax on rapists. -- Guy Chapman -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Logic In Python
Steven D'Aprano wrote: > Or wait, I have thought of one usage case: if you are returning a value > that you know will be used only as a flag, you should convert it into a > bool. Are there any other uses for bool()? We could, of course, get along without it. One use for canonical true and false values is to give 'not' something sensible to return. -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding where to store application data portably
Steven D'Aprano wrote: > On Thu, 22 Sep 2005 19:09:28 +0400, en.karpachov wrote: > > >>There is an other way around: look at your home dir as if it is your >>"settings" dir and don't clutter it with files other than application >>config dot-files. Just make ~/files/, ~/bin/ ~/lib/ etc. for it. > > > Do you put everything into /etc (/etc/bin, /etc/var, /etc/usr, /etc/mnt, > and so forth)? If your home directory is for settings, why would you store > files and binaries inside your settings directory? > > I understand the historical reasons for why ~/ is treated as a > structureless grab-bag of everything and anything. That made sense back in > the distant past when users used dumb terminals and they had perhaps half > a dozen dot files. But at the point your home directory has three times as > many dot files as regular files, the time has come to stop doing things > just because that's the way they have always been done. Yes, it's all pretty much historical isn't it. Someones needs to start form scratch I think as far as file storage systems go. Personally I'd love a cross platform intelligent file storage device that managed security and user accounts independent of the operating system. (With it's own internal CPU and firmware.) A few thoughts ... It should be built on concepts of 'Responsibility', 'Authority', and 'Delegation', So you could call it.. RADOS or RAD for short, or just use my initials. RA.. (just kidding) ;-) Also note that an application is just another user by proxy. And it all comes down to private and shared user data. In other words, organize all files by who's "Responsible" for them. You would "Delegate Authority" by using file links with private keys in them. Giving a file link to someone else wouldn't work since it would need to be ran from your user account to be valid. These file links is how you would access other files in other users file space. Anyway... such a system would mean that when an application accesses the Internet, (has Authority), to update it's own files, (Responsibility), it does so in it's own user space and can't access any other users (or applications) files. Virus's would find this very limiting. Every user account would be a complete unit which can be backed up and restored independently of the OS. If something went wrong you could always find out which user (or application developer) was responsible. Anyway... just wishful thinking. I'm sure there are a lot of problems that would need to be worked out. ;-) Cheers, Ron Adam -- http://mail.python.org/mailman/listinfo/python-list
CRC16
Anyone know a module that does CRC16 for Python? I have an aplication that I need to run it, and am not having alot of sucess. I have a program in C that uses a CRC16 according to CCITT standards, but need to get a program that tests it with python as well. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Bluetooth
Hi I'm making a server-side solution in Python and need to be able to communicate through bluetooth. Is there any bluetooth-packages out there for python? regards tores -- http://mail.python.org/mailman/listinfo/python-list
Re: File processing
Peter Hansen wrote: > Gopal wrote: >> [...] I'm >> thinking of going with this format by having "Param Name - value". Note >> that the value is a string/number; something like this: >> >> PROJECT_ID = "E4208506" >> SW_VERSION = "18d" >> HW_VERSION = "2" >> >> In my script, I need to parse this config file and extract the Values >> of the parameters. > Luckily, you're already done! Just make sure the above file has a .py > extension, say maybe "config.py", and then in code where you need to > "parse" it and extract the values you can just do this: > > import config > print 'Project Id is', config.PROJECT_ID In many cases that's fine, but at least be aware that the party supplying the config data also gets the ability to change the behavior of the process in ways of his choosing. -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list
Re: replacments for stdio?
[EMAIL PROTECTED] wrote: >i was wondering if anyone have written a GUI module that can > function as a replacment for stdin/stdout? ie. has a file like > interface, by which one could just assaign it to sys.stdout or > sys.stdin and have all your prints and raw_inputs and other such things > shown in a GUI window? Xterm? -- http://mail.python.org/mailman/listinfo/python-list
Re: Small python24.dll / how to strip off asian codecs to separate package(s) ?
Robert wrote: > Or how to build one? Just download the source, and follow the instructions in PCBuild/readme.txt. Then, edit the pythoncore project to remove the files you don't want to include, and edit config.c to remove the dangling references. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: C#3.0 and lambdas
Fredrik Lundh wrote: > Reinhold Birkenfeld wrote: > >>> And I think the discussion that followed proved your point perfectly >>> Fredrik. Big discussion over fairly minor things, but no "big picture". >>> Where are the initiatives on the "big stuff" (common documentation >>> format, improved build system, improved web modules, reworking the >>> standard library to mention a few) Hey, even Ruby is passing us here. >> >> This is Open Source. If you want an initiative, start one. > > you know, this "you have opinions? fuck off!" attitude isn't really helping. If I had wanted to say "you have opinions? fuck off!", I would have said "you have opinions? fuck off!". All I wanted to say is that if you want a common documentation format, and you want it badly, you should show up on python-dev and offer help. Unfortunately, there are not as many Python core developers as Perl core developers, and things move at a slower pace. That's mostly not their fault, and not anyone's fault. It's a consequence of the amount of time that is spent on Python-the-core itself. And why? Well, because it's more fun to program in Python than to program Python. Reinhold -- http://mail.python.org/mailman/listinfo/python-list
desktop module (was Re: Open PDF)
Dennis Lee Bieber skrev: > On Thu, 22 Sep 2005 15:16:09 +0100, Dan <[EMAIL PROTECTED]> declaimed > the following in comp.lang.python: > > > > I would like to know how to open a PDF document from a python script > > > > You mean open it and display it to the user? Under Windows you may be > > able to get away with just "executing" the file (as though it were an > > executable): > > For Windows, os.startfile() may be better... I've just uploaded a patch/suggestion/module (#1301512) to SourceForge which seeks to provide the equivalent of os.startfile for KDE and GNOME (as well as Windows) as part of a generic desktop module: http://sourceforge.net/tracker/index.php?func=detail&aid=1301512&group_id=5470&atid=305470 Rather than submit yet another PEP and argue about insignificant details whilst the webbrowser module sits comfortably in the standard library, failing to address general file-opening issues directly and doing the wrong thing under various modern desktop environments, I advocate people submitting suggestions, criticism and amendments to the uploaded attachment until we have something like os.startfile for all major desktop environments. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: What is "self"?
Erik Max Francis wrote: > Ron Adam wrote: > >> When you call a method of an instance, Python translates it to... >> >> leader.set_name(leader, "John") > > > It actually translates it to > > Person.set_name(leader, "John") > I thought that I might have missed something there. Is there a paper on how python accesses and stores instance data and methods? I googled but couldn't find anything that addressed this particular question. >>> class a(object): ...def x(self): ... print 'x' ... >>> b = a() >>> b <__main__.a object at 0x009D1890> >>> b.x > So what exactly is a bound method object? Does it possibly translates to something like the following? def x(*args, **kwds): self = ? return __class__.self(self, *args, **kwds) Cheers, Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: xml2schema
""" Er, do you mean to generate a Relax NG (or possibly a DTD in fact) from some XML file?? If you do mean this then just think of that how you could generate grammar from some paragraphs of English text... Sorta non-trivial, if possible at all, isn't it? :-) """ Very well put. However, for RELAX NG there is a tool that might work for the OP: Examplotron. See: http://www-128.ibm.com/developerworks/xml/library/x-xmptron/ As I show in that article, you can use Examplotron from any XSLT processor, including one invoked through Python API. -- Uche http://copia.ogbuji.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Config parser module
ConfigParser is for parsing configuration files of the format: [section1] option1= option2= . . . optionN= [section2] option1= option2= . . . optionN= Your data doesn't fit that format. Looks to me like you should write a small class object for each different type of record that can be found in the file that knows how to parse that record and put the information from that record in to class attributes for easy access. Something like: class gridclass: def __init__(self, recordToParse): elements=recordToParse.split(' ') self.type=elements[0] self.pointId=int(elements[1]) self.coordinateSysNo=float(elements[2]) self.x=float(elements[3]) self.y=float(elements[4]) self.z=int(elements[5]) Then read the lines, determine the line type and create a class instance for each one. -larry [EMAIL PROTECTED] wrote: > Hi all > I am a newbie and I just saw a ongoing thread on Fileprocessing which > talks abt config parser. > I have writen many pyhton program to parse many kind of text files by > using string module and regex. But after reading that config parser > thread I feel stunned. > > Can somebody tell me some intro info how to parse huge data (most of > them are input data to application softwares like nastran, abaqus etc) > > Recently I saw a great work by John on Nastran file parser (i am still > trying to understand the program, > http://jrfonseca.dyndns.org/svn/phd/python/Data/Nastran/ > > An example of dat may be like this, (part of) > (say point id coordinateSysNo x,y,z ...) > GRID 1 12478.0 0.0 256.75 1 > GRID 2 12357.25 0.0 256.75 1 > GRID 3 12357.25 0.0 199.0 1 > (say Elementtype id property point1 point 2 point3 point4 etc) > CQUAD4 7231 2156915700570156920.0 > > CQUAD4 7232 2156925701570256930.0 > > CQUAD4 7233 2156935702570356940.0 > > the data file is very complex if i consider all complexities) > > Is is possible to use config parser module insome way for this. I also > have few perl parser (for some part for some particular tasks) and now > changing them to python. (I feel perl regex combination is very easy to > learn and very powerfull) > > Any information will be appreciated. > > -jiro > -- http://mail.python.org/mailman/listinfo/python-list
Re: What is "self"?
On Friday 23 September 2005 10:41 am, Rick Wotnaz wrote: > Oh, 'ix' would be fine. Single-letter loop counters are also semi- > fine if that is in fact their only use. It too-frequently happens > that at some point the handy 'i' identifier is used outside the > loop (for another placeholder), and its value is tromped by an > intervening loop. Not terribly difficult to discover, but then > what? When you're maintaining code, even a two-character index is a > *lot* easier to find in source code and replace as needed. Sorry, but if you have to grep for it, your loop is TOO DARNED LARGE, USE A FUNCTION CALL! -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: What is "self"?
On Friday 23 September 2005 10:42 am, Peter wrote: > Terry Hancock wrote: > >How exactly is that? Anybody who uses "i" as a variable name for > >anything other than an innermost loop index is a sick and twisted > >code sadist. > > > Agreed, though to say "code sadist" is a little hard don't ya think? ;) I don't know, I thought it quite poetic. ;-) > >You'd prefer what? "count" or "kount" or > >"i_am_an_innermost_loop_index_counter". > >I mean "explicit is better than implicit", right? > > > >Maybe Fortran warped my brain, but I just don't see the benefit here. > > > Me ither. > > I am no english professor, but isn't the word "i" usualy pointed at > something you will, have, can, or can't do in english? > "me" or "self" or "this" or "my" or "cls" or "inst" are refering to just > the object, nothing more, nothing less (except for "my" which is like > referring to "something i own") and are much more human-comprehendable. > IMHO. Whoa, you totally lost me there, dude. ;-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: NaN Vs None
[Peck, Jon] > In choosing a way to represent a value of "no information" for a > float, would it be better to use NaN or None? None has the advantage > of standard behavior across platforms, but NaN seems to propagate more > easily – at least on Windows. [...] What I do for these things is creating a Missing type which behaves like a number, that is, it has all __FUNCTION__ magic required by numbers. I then create either a single missing constant or very few such missing constants, in which case each one representing a particular way or flavor of a missing number (unknown, not applicable, uncomputable, etc.) The magic functions for Missing should know how to combine the few missing constants with numbers, and with other missing constants, for returning the "proper" one. It's easier with only one missing constant. You also need to take care of comparisons and logical operators on missing values. My usual convention is that missing values propagate within booleans and behave like False when tested. Sometimes, I also need "missing" strings. That's more difficult to implement, because of the numerous string methods and ramifications. -- François Pinard http://pinard.progiciels-bpi.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: optimizing a program that just shuffles data, a bit like cat...
On Fri, 23 Sep 2005 10:18:47 -0500, Oracle wrote: > On Fri, 23 Sep 2005 01:16:46 +, Dan Stromberg wrote: > >> [quoted text muted] > > Try using psyco and see if that helps. Also, sometimes smaller blocks are > better than large blocks. Try using smaller block sizes and see if that > helps. I like the psyco idea, but I'm on an AIX system with a powerpc CPU, rather than an x86 CPU. > If you're worried about the time required to calculate the length of > your block, try calculating it once and pass the length around. Is that > doable? AFAIK, that's what I've been doing... Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Single type for __builtins__ in Py3.0
Collin Winter wrote: > If possible, I'd like to see this go in before 3.0. +1 -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Config parser module
The Config Parser module is for extracting data from and writing to a specific format of file, generally known as a config file. As explained in the documentation, a config file is in the same format as .ini files frequently found on windows - especially used by older software. It is a very handy file format for all sorts of jobs, more so on Linux these days than Windows, probably. However, it isn't much use for your particular need as described here. [EMAIL PROTECTED] wrote: > Hi all > I am a newbie and I just saw a ongoing thread on Fileprocessing which > talks abt config parser. > I have writen many pyhton program to parse many kind of text files by > using string module and regex. But after reading that config parser > thread I feel stunned. > > Can somebody tell me some intro info how to parse huge data (most of > them are input data to application softwares like nastran, abaqus etc) > > Recently I saw a great work by John on Nastran file parser (i am still > trying to understand the program, > http://jrfonseca.dyndns.org/svn/phd/python/Data/Nastran/ > > An example of dat may be like this, (part of) > (say point id coordinateSysNo x,y,z ...) > GRID 1 12478.0 0.0 256.75 1 > GRID 2 12357.25 0.0 256.75 1 > GRID 3 12357.25 0.0 199.0 1 > (say Elementtype id property point1 point 2 point3 point4 etc) > CQUAD4 7231 2156915700570156920.0 > > CQUAD4 7232 2156925701570256930.0 > > CQUAD4 7233 2156935702570356940.0 > > the data file is very complex if i consider all complexities) > > Is is possible to use config parser module insome way for this. I also > have few perl parser (for some part for some particular tasks) and now > changing them to python. (I feel perl regex combination is very easy to > learn and very powerfull) > > Any information will be appreciated. > > -jiro -- Dale Strickland-Clark Riverhall Systems www.riverhall.co.uk We're recruiting Python programmers. See web site. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is "self"?
Terry Hancock <[EMAIL PROTECTED]> wrote in news:[EMAIL PROTECTED]: > On Friday 23 September 2005 07:11 am, Rick Wotnaz wrote: >> I've long thought that Guido missed an opportunity by not >> choosing to use 'i' as the instance identifier, and making it a >> reserved word. For one thing, it would resonate with the >> personal pronoun 'I', and so carry essentially the same meaning >> as 'self'. It could also be understood as an initialism for >> 'instance'. And, because it is shorter, the number of >> objections to its existence *might* have been smaller than >> seems to be the case with 'self' as the convention. >> >> And as a side benefit, it would make it impossible to use as a >> loop index a language feature that would be a huge selling >> point among a lot of experienced programmers. > > How exactly is that? Anybody who uses "i" as a variable name > for anything other than an innermost loop index is a sick and > twisted code sadist. > > You'd prefer what? "count" or "kount" or > "i_am_an_innermost_loop_index_counter". I mean "explicit is > better than implicit", right? > > Maybe Fortran warped my brain, but I just don't see the benefit > here. -- Oh, 'ix' would be fine. Single-letter loop counters are also semi- fine if that is in fact their only use. It too-frequently happens that at some point the handy 'i' identifier is used outside the loop (for another placeholder), and its value is tromped by an intervening loop. Not terribly difficult to discover, but then what? When you're maintaining code, even a two-character index is a *lot* easier to find in source code and replace as needed. -- rzed -- http://mail.python.org/mailman/listinfo/python-list
Re: What is "self"?
Terry Hancock wrote: >On Friday 23 September 2005 07:11 am, Rick Wotnaz wrote: > > >>I've long thought that Guido missed an opportunity by not choosing >>to use 'i' as the instance identifier, and making it a reserved >>word. For one thing, it would resonate with the personal pronoun >>'I', and so carry essentially the same meaning as 'self'. >> Not realy. >> It could >>also be understood as an initialism for 'instance'. >> MUCH better then trying to make it refer to "i" as in "me", but still. >>And, because it >>is shorter, the number of objections to its existence *might* have >>been smaller than seems to be the case with 'self' as the >>convention. >> >> Humm... maybe. But would reap the fact that i does not have the same exact meaning of self. With the word self, it is possable to change a feature of yourSELF, but try saying you changed a feature of "yourI", some internal logic in the programmers brain is going to go off, and if the programmer is tired and trying to finish something up but has that kind of internal confusion, as suttle as it may be, he will get burnt out and have to wait intill the next day. >>And as a side benefit, it would make it impossible to use as a loop >>index a language feature that would be a huge selling point among a >>lot of experienced programmers. >> >> > > > You think thats a good thing? o.0. I agree that sometimes you need to name your loop variables well, but sometimes you only need a simple, temp loop variable. I would expect such an aprouch to be more likely to be found in intercal (http://www.catb.org/~esr/intercal/), rather then in Python. >How exactly is that? Anybody who uses "i" as a variable name for >anything other than an innermost loop index is a sick and twisted >code sadist. > > > Agreed, though to say "code sadist" is a little hard don't ya think? ;) >You'd prefer what? "count" or "kount" or >"i_am_an_innermost_loop_index_counter". >I mean "explicit is better than implicit", right? > > >Maybe Fortran warped my brain, but I just don't see the benefit here. > Me ither. I am no english professor, but isn't the word "i" usualy pointed at something you will, have, can, or can't do in english? "me" or "self" or "this" or "my" or "cls" or "inst" are refering to just the object, nothing more, nothing less (except for "my" which is like referring to "something i own") and are much more human-comprehendable. IMHO. >-- >Terry Hancock ( hancock at anansispaceworks.com ) >Anansi Spaceworks http://www.anansispaceworks.com > > > Peter -- http://mail.python.org/mailman/listinfo/python-list
Config parser module
Hi all I am a newbie and I just saw a ongoing thread on Fileprocessing which talks abt config parser. I have writen many pyhton program to parse many kind of text files by using string module and regex. But after reading that config parser thread I feel stunned. Can somebody tell me some intro info how to parse huge data (most of them are input data to application softwares like nastran, abaqus etc) Recently I saw a great work by John on Nastran file parser (i am still trying to understand the program, http://jrfonseca.dyndns.org/svn/phd/python/Data/Nastran/ An example of dat may be like this, (part of) (say point id coordinateSysNo x,y,z ...) GRID 1 12478.0 0.0 256.75 1 GRID 2 12357.25 0.0 256.75 1 GRID 3 12357.25 0.0 199.0 1 (say Elementtype id property point1 point 2 point3 point4 etc) CQUAD4 7231 2156915700570156920.0 CQUAD4 7232 2156925701570256930.0 CQUAD4 7233 2156935702570356940.0 the data file is very complex if i consider all complexities) Is is possible to use config parser module insome way for this. I also have few perl parser (for some part for some particular tasks) and now changing them to python. (I feel perl regex combination is very easy to learn and very powerfull) Any information will be appreciated. -jiro -- http://mail.python.org/mailman/listinfo/python-list
Re: optimizing a program that just shuffles data, a bit like cat...
On Fri, 23 Sep 2005 01:16:46 +, Dan Stromberg wrote: > > ...but with much bigger blocksizes, and with a netcat-like ability to use > sockets. > Try using psyco and see if that helps. Also, sometimes smaller blocks are better than large blocks. Try using smaller block sizes and see if that helps. If you're worried about the time required to calculate the length of your block, try calculating it once and pass the length around. Is that doable? -- http://mail.python.org/mailman/listinfo/python-list
NaN Vs None
In choosing a way to represent a value of "no information" for a float, would it be better to use NaN or None? None has the advantage of standard behavior across platforms, but NaN seems to propagate more easily – at least on Windows. For example, NaN+1 = NaN but None+1 raises an exception. Thanks in advance for any advice. Jon K Peck (Kim) [EMAIL PROTECTED] 312-651-3435 233 S Wacker Dr Chicago, IL 60606 -- http://mail.python.org/mailman/listinfo/python-list
Re: time challenge
sorry about that, i got a message in my inbox that said that the post was rejected so i tried it from my email client. wont happen again. shawn -- http://mail.python.org/mailman/listinfo/python-list
Re: Sniffing Text Files
Thanks Mike this is really great! Regards, David On Friday, September 23, 2005, at 11:55 AM, Mike Meyer wrote: > David Pratt <[EMAIL PROTECTED]> writes: >> Thanks Mike for your reply. I am not aware of libmagic and will look >> to see what it provides. > > and ... > > Skip Montanaro <[EMAIL PROTECTED]> writes: >> You can also run the file(1) command and see what it says. I seem >> to recall someone asking about the equivalent to file(1) implemented >> in >> Python awhile back. > > libmagic is the smarts of the file command. As I said before, people > have done Python wrappers for it. It uses a text database describing > how to recognize a files type - see the magic(5) man page for details > on that. If you use libmagic, you'll probably want to provide your own > version of the databse, excerpted to include just the file types you > want to recognize. > > You can check on whether or not this will work for you by seeing what > the file command says about your sample data. > > -- > Mike Meyer <[EMAIL PROTECTED]> > http://www.mired.org/home/mwm/ > Independent WWW/Perforce/FreeBSD/Unix consultant, email for more > information. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Sniffing Text Files
Hi Skip. Thank you for your reply. This is helpful and I am glad I put this to the list. There are some really good ideas that will help me come up with something good to use. Regards, David On Friday, September 23, 2005, at 11:14 AM, [EMAIL PROTECTED] wrote: > > David> I realize CSV module has a sniffer but it is something that > is > David> limited more or less to delimited files. > > Sure. How about: > > def sniff(fname): > if open(fname).read(4) == " return "xml" > else: > # assume csv - use its sniffer to generate a dialect > return d > > Of course, as the number of file formats grows, you'll need to expand > the > logic. You can also run the file(1) command and see what it says. I > seem > to recall someone asking about the equivalent to file(1) implemented in > Python awhile back. > > -- > Skip Montanaro > Katrina Benefit Concerts: http://www.musi-cal.com/katrina > [EMAIL PROTECTED] > -- http://mail.python.org/mailman/listinfo/python-list
Re: Sniffing Text Files
David Pratt <[EMAIL PROTECTED]> writes: > Thanks Mike for your reply. I am not aware of libmagic and will look > to see what it provides. and ... Skip Montanaro <[EMAIL PROTECTED]> writes: > You can also run the file(1) command and see what it says. I seem > to recall someone asking about the equivalent to file(1) implemented in > Python awhile back. libmagic is the smarts of the file command. As I said before, people have done Python wrappers for it. It uses a text database describing how to recognize a files type - see the magic(5) man page for details on that. If you use libmagic, you'll probably want to provide your own version of the databse, excerpted to include just the file types you want to recognize. You can check on whether or not this will work for you by seeing what the file command says about your sample data. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Single type for __builtins__ in Py3.0
Hallo all, As it currently stands, the type of the global __builtins__ differs depending on whether you're in the __main__ namespace (__builtins__ is a module) or not (its a dict). I was recently tripped up by this discrepancy, and googling the issue brings up half-a-dozen or so c.l.p threads where others have been bitten by this, too. I'd like to propose that in Py3.0 (if not earlier), __builtins__ will be the same type regardless of which namespace you're in. Tim Peters has said [1] that the reason __builtins__ in __main__ is a module so that "the curious don't get flooded with output when doing vars() at the prompt". Based on this, I propose that __builtins__ be a module (really, an alias for the __builtin__ module as it is now) in all namespaces. If possible, I'd like to see this go in before 3.0. The reference manual currently states [2] that __builtins__ can be either a dict or a module, so changing it to always be a module would still be in keeping with this. However, I realise that there's probably code out there that hasn't been written to deal with both types, so this would result in some minor breakage (though it would be easily fixable). If this gets a good response, I'll kick it up to python-dev. Thanks, Collin Winter [1] http://mail.python.org/pipermail/python-list/2002-May/103613.html [2] http://www.python.org/doc/2.4.1/ref/naming.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Productivity and economics at software development
Adriano Monteiro wrote: > Hi folks, > I'm making a little research project about programming languages e > their respective IDEs. The goal is to trace each language silhouettes, > where it fits better, their goods/bads and the costs of developing in > this language. What do you consider the IDE for Assembly code or Microcode? --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: What is "self"?
On Friday 23 September 2005 07:11 am, Rick Wotnaz wrote: > I've long thought that Guido missed an opportunity by not choosing > to use 'i' as the instance identifier, and making it a reserved > word. For one thing, it would resonate with the personal pronoun > 'I', and so carry essentially the same meaning as 'self'. It could > also be understood as an initialism for 'instance'. And, because it > is shorter, the number of objections to its existence *might* have > been smaller than seems to be the case with 'self' as the > convention. > > And as a side benefit, it would make it impossible to use as a loop > index a language feature that would be a huge selling point among a > lot of experienced programmers. How exactly is that? Anybody who uses "i" as a variable name for anything other than an innermost loop index is a sick and twisted code sadist. You'd prefer what? "count" or "kount" or "i_am_an_innermost_loop_index_counter". I mean "explicit is better than implicit", right? Maybe Fortran warped my brain, but I just don't see the benefit here. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Productivity and economics at software development
I get this: Mod_python error: "PythonHandler mod_python.publisher" Traceback (most recent call last): File "/usr/lib/python2.3/site-packages/mod_python/apache.py", line 299, in HandlerDispatch result = object(req) File "/usr/lib/python2.3/site-packages/mod_python/publisher.py", line 136, in handler result = util.apply_fs_data(object, req.form, req=req) File "/usr/lib/python2.3/site-packages/mod_python/util.py", line 361, in apply_fs_data return object(**args) File "/var/www/html/quest/index.py", line 156, in gravar cursor.execute(sql) File "/usr/lib/python2.3/site-packages/pgdb.py", line 163, in execute self.executemany(operation, (params,)) File "/usr/lib/python2.3/site-packages/pgdb.py", line 185, in executemany raise DatabaseError, "error '%s' in '%s'" % ( msg, sql ) DatabaseError: error 'ERROR: value too long for type character varying(2) ' in 'INSERT INTO questionario ( linguagem, rad, preco_rad, linux, macosx, palmos, solaris, windows, windowsce, outras_plataformas, treinamento, desktop, modo_texto, paginas_web, celular, palm, outras_aplicacoes, dificuldade, tempo, dependencia, duracao, novo_programador, comentario, moeda) VALUES ('false', 'false', 0.0, true, true, false, false, true, false, false, 0.0, true, true, true, false, false, false, 1, 4, 2, 0.5, 1000.0, 'false', 'false')' -- http://mail.python.org/mailman/listinfo/python-list
Re: What is "self"?
Rick Wotnaz <[EMAIL PROTECTED]> wrote: >I've long thought that Guido missed an opportunity by not choosing >to use 'i' as the instance identifier, and making it a reserved >word. For one thing, it would resonate with the personal pronoun >'I', and so carry essentially the same meaning as 'self'. It could >also be understood as an initialism for 'instance'. And, because it >is shorter, the number of objections to its existence *might* have >been smaller than seems to be the case with 'self' as the >convention. My first serious forays into Python, where no-one else was expected to be maintaining the code, used 'I' instead of 'self' -- it's shorter, stands out better, and 'I.do_something()' reads more like English than 'self.do_something()' (unless, I suppose, you're thinking in terms of message passing). Then I started working on code which other people might need to look at, and got an editor whose Python syntax highlighting pretended that 'self' was a reserved word, and now all my old code looks odd. (But still perfectly readable -- this is Python after all.) -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ |-- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: Using distutils 2.4 for python 2.3
Fredrik Lundh wrote: > > you can enable new metadata fields in older versions by assigning to > the DistributionMetadata structure: > > try: > from distutils.dist import DistributionMetadata > DistributionMetadata.package_data = None > except: > pass > > setup( > ... > package_data=... > ) > > I tried this, but it made python2.4 behave like python2.3, and not install the package_data files. Did I do something wrong? -- http://mail.python.org/mailman/listinfo/python-list
Re: C#3.0 and lambdas
Erik Wilsher wrote: > And I think the discussion that followed proved your point perfectly > Fredrik. Big discussion over fairly minor things, but no "big > picture". Where are the initiatives on the "big stuff" (common > documentation format, improved build system, improved web modules, > reworking the standard library to mention a few) Hey, even Ruby is > passing us here. Reinhold Birkenfeld wrote: > This is Open Source. If you want an initiative, start one. Fredrik Lundh wrote: > you know, this "you have opinions? fuck off!" attitude isn't really helping. While I should know better than replying to , ;) I have to say that I don't think "you have opinions? fuck off!" was the intent at all. I don't know many people who'd argue that we don't need: * more complete and better organized documentation * a simpler build/install system * etc. But they'll never get done if no one volunteers to work on them. Recently, I saw a volunteer on python-dev looking to help make the docs more complete, and he was redirected to the docs SIG to help out. This is good. I know that there's been a bunch of work on setuptools[1] that's supposed to be a real improvement on distutils. This is also goood. But there're only so many man-hours available to work on these projects. If you see a problem, and you want it fixed, the right thing to do is to donate some of your time to a project that needs it. This, I believe, is the essence of Reinhold Birkenfeld's comment. STeVe [1]http://peak.telecommunity.com/DevCenter/setuptools -- http://mail.python.org/mailman/listinfo/python-list
Productivity and economics at software development
Hi folks, I'm making a little research project about programming languages e their respective IDEs. The goal is to trace each language silhouettes, where it fits better, their goods/bads and the costs of developing in this language. It's easy to find projects that doesn't worked as expected because they were develop with the wrong toolkit, or people that now dislike a given language because didn't know where the language is better used. To provide a good quality research, with results that near reality, I need the help of the community to answer my survey. This survey doesn't ask any information that identifies the person who answer the questions and is super fast to be answered. The average time to fill out the survey is 50 seconds. The survey: http://www.globalred.com.br/quest The results and the research will be released as soons as they get ready. Thank you for your cooperation! Cheers! --- Adriano Monteiro Marques http://umit.sourceforge.net http://www.globalred.com.br -- http://mail.python.org/mailman/listinfo/python-list
Re: C#3.0 and lambdas
> A M Kuchling <[EMAIL PROTECTED]> writes: > The group of committers is a diverse group of people, and not every one of > them uses a relational database; that effort would be better done on the > DB-SIG mailing list, because the people there presumably do all use an > RDBMS. (Now, if you wanted to include SQLite in core Python, that *would* > be a python-dev topic, and ISTR it's been brought up in the past.) I would definitely love to see SQLite included in core python. I am a Unix systems/networking programmer myself. Just like the fact that everything looks like a database programmers to most database, I've observed that the reverse is true for non database programmers. In other words, most non RDMS normally don't think of a database even the solution screams for a database. I think SQLite does an amazing job in bridging this gap. > Agreed; python-dev has gotten pretty boring with all the endless discussions > over some minor point. Of course, it's much easier and lower-effort to > propose a syntax or nitpick a small point issue than to tackle a big > complicated issue like static typing. You have a point there :-). > Similar things happen on the catalog SIG: people suggest, or even > implement, an automatic package management system, But bring up the > question of whether it should be called PyPI or Cheeseshop or the Catalog, > and *everyone* can make a suggestion. My memory may not be perfect but I remember reading that Python 2.5's focus is libraries and no language changes. If that's correct, I can understand why core python folks are more interested in discussing language features for Python 3000 ;-). Speaking of libraries, I haven't seen many discussions on libraries in python-dev. Is there some other list with more discussions on libraries? Ganesan -- Ganesan Rajagopal (rganesan at debian.org) | GPG Key: 1024D/5D8C12EA Web: http://employees.org/~rganesan| http://rganesan.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Sniffing Text Files
David> I realize CSV module has a sniffer but it is something that is David> limited more or less to delimited files. Sure. How about: def sniff(fname): if open(fname).read(4) == "http://www.musi-cal.com/katrina [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Sniffing Text Files
Thanks Mike for your reply. I am not aware of libmagic and will look to see what it provides. As far as your first suggestion, this is what I have been looking at - probably a combination regex and readlines or similar but trying to get a better sense of best sort of approach more or less. I can't rely on file extensions in this case so believing the content will be what the file extension indicates would not be so good. Mime types can be helpful but don't always give you the full story either - so the need to sniff in the first place so I can apply the right process to the file. As it stands I am filtering mime types to the importing process to attempt to limit the possibilities. Regards, David On Friday, September 23, 2005, at 02:01 AM, Mike Meyer wrote: > David Pratt <[EMAIL PROTECTED]> writes: > >> Hi. I have files that I will be importing in at least four different >> plain text formats, one of them being tab delimited format, a couple >> being token based uses pipes (but not delimited with pipes), another >> being xml. There will likely be others as well but the data needs to >> be extracted and rewritten to a single format. The files can be fairly >> large (several MB) so I do not want to read the whole file into >> memory. What approach would be recommended for sniffing the files for >> the different text formats. I realize CSV module has a sniffer but it >> is something that is limited more or less to delimited files. I have >> a couple of ideas on what I could do but I am interested in hearing >> from others on how they might handle something like this so I can >> determine the best approach to take. Many thanks. > > With GB memory machines being common, I wouldn't think twice about > slurping a couple of meg into RAM to examine. But if that's to much, > how about simply reading in the first bytes, and checking that > for the characters you want? should be large enough to reveal > what you need, but small enogh that your'e comfortable reading it > in. I'm not sure that there aren't funny interactions between read and > readline, so do be careful with that. > > Another approach to consider is libmagic. Google turns up a number of > links to Python wrappers for it. > >-- > Mike Meyer <[EMAIL PROTECTED]> > http://www.mired.org/home/mwm/ > Independent WWW/Perforce/FreeBSD/Unix consultant, email for more > information. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: how to pickle unpicklable objects
Guy Lateur schrieb: > Hi all, > > I've been writing an application containing a lot of settings which can be > changed by the user. I'm using wx.Config to read/write these settings (to > the windows registry). This means I can only store strings, ints and floats. > > However, it would be very convenient if I could also store more general > objects. It seems to work for wx.Colour, but not for wx.Font. It raises a > "TypeError: can't pickle PySwigObject objects". The object is wrapped by SWIG. So, python can not know anything about it and the object can not be pickled. As far as I see, there are two possibilities - define __getstate__ and __setstate__ in the c/c++-source or the .i file (used by swig). This is only possible if the source is available - use copy_reg (http://docs.python.org/lib/module-copyreg.html) to register a 'reduce' function (I never used that). I use the first option in the .i-File for a wrapped c++-class like this: %extend UMDMResult { %insert("python") %{ def __getstate__(self): return (self.v,self.u,self.l,self.unit,self.Z0,self.Eta0,self.t) def __setstate__(self,tup): self.this = _umddevice.new_UMDMResult(tup[0],tup[1],tup[2],tup[3]) self.thisown=1 (self.Z0,self.Eta0,self.t)=[i for i in tup[4:]] %} } regards Hans Georg Krauthaeuser -- http://mail.python.org/mailman/listinfo/python-list