Module import via sys.path and py2exe
Hi, i have a program with is built like this: startup.py dir1/__init__.py dir1/file1.py dir2/__init__.py dir2/file2.py dir3/__init__.py dir3/file3.py The program works but now i want to add the functionality into an existing program 2. This is program 2: program2.py program2dir1/__init__.py program2dir1/file4.py When i copy the directories over i get this situation: program2.py program2dir1/__init__.py program2dir1/file4.py program1/__init__.py program1/dir1/__init__.py program1/dir1/file1.py program1/dir2/__init__.py program1/dir2/file2.py program1/dir3/__init__.py program1/dir3/file3.py However, i need to specify this in program2.py or i can't use the files 1-3: import sys sys.path.append('program1') import program1.dir1.file1 as f1 Then i can use the functionality of the first program in the second. Now for my questions: 1. Is this the correct way or is there an easier/more logical sollution. Now all __init__.py file are empty 2. As said this works but when i make a standalone of program2 it doesn't find any of the program1 files: Traceback (most recent call last): File "start.py", line 20, in ? File "windows\windowmain.pyo", line 59, in ? File "program1\__init__.pyo", line 2, in ? File "program1\dir1\__init__.pyo", line 1, in ? File "program1\dir1\file1.pyo", line 28, in ? ImportError: No module named dir2.file2 dir2.file2 is imported in file1.py as import dir2.file2. So something in my setup script is wrong. How can i make sure all file of program1 are also added? Excerpt of setup.py ... py_modules=['start'], packages=['database','dialogs','export','graphics','localutils','windows'], ... If i specify program1 as module or as package or program1.dir1 and so on doesn't seem to help. Any ideas? Thanks Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: Module import via sys.path and py2exe
flupke wrote: > Hi, > > i have a program with is built like this: > startup.py > dir1/__init__.py > dir1/file1.py > dir2/__init__.py > dir2/file2.py > dir3/__init__.py > dir3/file3.py > > The program works but now i want to add the functionality into an > existing program 2. This is program 2: > > program2.py > program2dir1/__init__.py > program2dir1/file4.py > > When i copy the directories over i get this situation: > > program2.py > program2dir1/__init__.py > program2dir1/file4.py > program1/__init__.py > program1/dir1/__init__.py > program1/dir1/file1.py > program1/dir2/__init__.py > program1/dir2/file2.py > program1/dir3/__init__.py > program1/dir3/file3.py > > However, i need to specify this in program2.py or i can't use the files > 1-3: > import sys > sys.path.append('program1') > import program1.dir1.file1 as f1 > > Then i can use the functionality of the first program in the second. > > Now for my questions: > > 1. Is this the correct way or is there an easier/more logical sollution. > Now all __init__.py file are empty > > 2. As said this works but when i make a standalone of program2 it > doesn't find any of the program1 files: > Traceback (most recent call last): > File "start.py", line 20, in ? > File "windows\windowmain.pyo", line 59, in ? > File "program1\__init__.pyo", line 2, in ? > File "program1\dir1\__init__.pyo", line 1, in ? > File "program1\dir1\file1.pyo", line 28, in ? > ImportError: No module named dir2.file2 > > dir2.file2 is imported in file1.py as import dir2.file2. > So something in my setup script is wrong. How can i make sure all file > of program1 are also added? > > Excerpt of setup.py > ... > py_modules=['start'], > packages=['database','dialogs','export','graphics','localutils','windows'], > ... > If i specify program1 as module or as package or program1.dir1 and so on > doesn't seem to help. > > Any ideas? > > Thanks > Benedict I forgot to add that if i check the shared.lib py2exe creates, the program1 dir and subdirs/files are there so they are included in the package. Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: Module import via sys.path and py2exe
flupke wrote: > I forgot to add that if i check the shared.lib py2exe creates, the > program1 dir and subdirs/files are there so they are included in the > package. > > Benedict Hi, i solved it by adding the same import statement to the py2exe setup.py script as in my code: import sys sys.path.append('program1') I'm still not sure though that the way i'm adding the module in the first place is correct but it seems to work okay. Regards, Benedict -- http://mail.python.org/mailman/listinfo/python-list
time conversion
Is there an easy to convert following hour notation hh:mm to decimals? For instance 2 hours and 30 minutes as 2:30 to 2,50 I don't really know where to search for this kind of conversion. Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: time conversion
flupke wrote: > Is there an easy to convert following hour notation hh:mm > to decimals? > For instance 2 hours and 30 minutes as 2:30 to 2,50 > I don't really know where to search for this kind of conversion. > > Thanks, > Benedict I found a way. Not sure if it's the best: time = "2:3" factor = 100.0/60.0 time_parts = time.split(":") minutes = int(float(time_parts[1]) * factor) if ( len(str(minutes)) == 1 ): minutes *= 10 # to get 50 instead of 5 time_new = "%s,%.02s" % (time_parts[0],minutes) print "%s -> %s " % (time,time_new) -- http://mail.python.org/mailman/listinfo/python-list
Re: time conversion
Fredrik Lundh wrote: > "flupke" wrote: > > >>Is there an easy to convert following hour notation hh:mm >>to decimals? >>For instance 2 hours and 30 minutes as 2:30 to 2,50 >>I don't really know where to search for this kind of conversion. > > > you mean like > > >>> timestamp = "2:30" > >>> hour, minute = timestamp.split(":") > >>> print int(hour) + int(minute) / 60.0 > 2.5 > > ? > > > > > yep, your sollution is shorter so i'll use that :) Thanks Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: logging from severl classes
Vinay Sajip wrote: It works for me: #file3.py import file1 import file2 a = file1.A() b = file2.B() b.otherfunction() gives 2004-12-28 00:18:34,805 DEBUG file2 6 creating class B 2004-12-28 00:18:34,805 DEBUG file2 9 in otherfunction yeah, the classes where a simplification of the classes i'm using and used these to just show what i wanted to do without testing them. they indeed work. strange. Thanks for your answer benedict -- http://mail.python.org/mailman/listinfo/python-list
2 versions of python on 1 machine
I searched with Google and on this newsgroups and i didn't find any info regarding this. If there is more info, please redirect me to that info. I have version 2.3.4 and 2.4 installed on windows and i thought that by switching the PYTHONPATH parameter to the dir of the 2.4 version that that would make python 2.4 active. However when i envoke python from the commandline, it still runs 2.3.4 Is it possible to have 2 versions installed and switching versions when you need to? How can i do that? Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: 2 versions of python on 1 machine
Peter Hansen wrote: On my machine, I have a folder called c:\bin where I put useful batch files. I have a python23.bat and a python24.bat file, which basically just call c:\python23\python.exe or c:\python24\python.exe as required. For various reasons which may or may not apply to you as well, I also have each of them set the PYTHONHOME variable to point to the right folder as well. The content of each batch file is like this: @echo off c:\python23\python.exe %1 %2 %3 %4 %5 %6 %7 %8 %9 -Peter I used the 2 batch files technique and removed c:\python23 from my path var and all is fine now. Where did you find more info on PYTHONHOME and PYTHONPATH because the docs don't seem to contain a whole lot of info. Thanks Benedict -- http://mail.python.org/mailman/listinfo/python-list
2 versions of python on 1 machine
Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit Lines: 15 Message-ID: <[EMAIL PROTECTED]> Date: Thu, 06 Jan 2005 15:13:42 GMT NNTP-Posting-Host: 212.123.8.34 X-Complaints-To: [EMAIL PROTECTED] X-Trace: phobos.telenet-ops.be 1105024422 212.123.8.34 (Thu, 06 Jan 2005 16:13:42 MET) NNTP-Posting-Date: Thu, 06 Jan 2005 16:13:42 MET Organization: Telenet Internet Path: cernne01.cern.ch!news-zh.switch.ch!switch.ch!news.mailgate.org!newsfeed.stueberl.de!newsgate.cistron.nl!skynet.be!skynet.be!ossa.telenet-ops.be!phobos.telenet-ops.be.POSTED!not-for-mail Xref: cernne01.cern.ch comp.lang.python:6747 I searched with Google and on this newsgroups and i didn't find any info regarding this. If there is more info, please redirect me to that info. I have version 2.3.4 and 2.4 installed on windows and i thought that by switching the PYTHONPATH parameter to the dir of the 2.4 version that that would make python 2.4 active. However when i envoke python from the commandline, it still runs 2.3.4 Is it possible to have 2 versions installed and switching versions when you need to? How can i do that? Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
seperating GUI from other code + reports
Hi, i need to develop an app here which will be used to produce stats. I'm going to go with twisted pb for the client server communication. And wxPython for the GUI. Now i would want to split the GUI code from the pb code to make debugging easier amongst other things but i'm not sure how i would best implement the communication of between the GUI and the client. Do i also use pb for it? But then i would end up with the problems that some users have reported here that wxPython and pb have. This would look like this, where GUI and CLIENT are off course on the same machine. GUI pb CLIENT pb SERVER <---> <---> 1) Any thoughts about this or other methods of doing this or reason why i should not bother with this setup? 2) I will display the results of the query in a list of grid on the client. But then the users are going to want to print the results. Are there any tools that provide a way of printing queries or that provide a mechanism to build reports based on tables? The easiest way i can do it now is to make a html of the results and then opening a browser with that html page using popen. Any other ideas? Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
importing a package
Hi, I developed a package with a structure like this src/ tesfile.py dir1/ __init__.py file1.py dir2/ __init__.py file2.py The testfile is meant to try the code out that is specified in file1.py and file2.py Now i have another project where i want to use the code from that package. The structure of that project: src/ file3.py dir3/ __init__.py file4.py To use it, i copied the package in the root of the project: src/ file3.py dir3/ __init__.py file4.py package/ __init__.py dir1/ __init__.py file1.py dir2/ __init__.py file2.py In my code (file3.py) i then do an "import package.dir1.file1 as myobj" and access a class like this: myobj.LMyClass() (where myobj and LMyClass are decent names. Used these as example) That works but i get an error in the package files. I then get an error in package/dir1/file1.py on an import statement specified in that file1.py that says import dir2.file2 How come this works as standalone project and not when i try to use it as in situation 2 it doesn't seem to find module file2.py ? How can i solve that? Thanks Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: importing a package
Damjan wrote: >>I developed a package with a structure like this >>src/ >>tesfile.py >>dir1/ >>__init__.py >>file1.py >>dir2/ >>__init__.py >>file2.py > > > Importing dir2/file2 from dir1/file1.py works here, because when yuo started > the testfile script the src/ directory was added to the sys.path list. > > If you relocate dir1/ and dir2/ in a "package" directory here it will not > work. > > Indeed, when i do this, then it works import sys sys.path.append('package') However, why is it that package isn't added automatically to the pad? Regards, Benedict -- http://mail.python.org/mailman/listinfo/python-list
webserver application (via Twisted?)
I need to program and setup serveral webservices. If i were still using jsp, i would use Tomcat to make the several applications available on a given port. How can i accomplish this in Python? I was thinking about Twisted but it's not clear to me what parts i need to make a webserver listen on a certain port and having it serve different application based on the url that i received. Any advice on this? Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: Web Framework Reviews
Dave Cook wrote: > On 2005-07-19, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > > >>On the other hand I even in its current form I don't see how I would to >>the simple things that I need every day. Create a session, set a >>cookie, redirect to another url, perform HTTP autentication, create >>filter, use another templating language? This is also integral part of >>the functionality that I expect from an web framework. Web specific >>things exposed in some python ic way. > > > Take a look at the Nevow FAQ and examples. Also, Nevow sits on top of > Twisted, so you have all of Twisted's features available. > > http://divmod.org/users/wiki.twistd/nevow/moin.cgi/FrequentlyAskedQuestions > > Dave Cook One could use twisted.web2 also without the nevow part. The docs @ http://twistedmatrix.com/projects/web2/documentation/ are very clear and it contains a good example at the end. Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: OO design
Robert Kern wrote: > chris wrote: > >> When I think about what I should do I end up with a class XY that has a >> method for everything I want to do eg. >> >> class XY: >> def read_file >> def scale_data >> def plot_data >> def shelve_data >> >> But somehow that doesn't feel right, especially when I expect the >> number of >> methods will grow and grow, which would make the class very unwieldy. > In short slogans: Just Do It. Make It Work, Then Make It Right. Refactor > Mercilessly. Do the Simplest Thing That Could Possibly Work. +1 QOTW Very good advice IMO. I would like to add that for the simpler classes, thinking of how you want to use data can be a great starting point. I recently programmed an interface to a firebird database and said, how do i want to be able to use the software? I thought of this: table = fb.Table("datafile.fdb","customers") vals = {} vals["name"]="customer1" vals["city"]="mytown" table.insert(vals) It looked like a great way to access and use it and it hides all the sql details. Well, that's how i started and i had to refactor along the way too :) Regards, Benedict -- http://mail.python.org/mailman/listinfo/python-list
getting the class name of a subclass
I have the following test code setup, trying to get the class name of a subclass in the super class. (Reason why i want this is described below) file class_name_start.py import class_name as cn obj = cn.B() obj.printclass() file class_name.py class A(object): def __init__(self): print "I'm A" def printclass(self): print "Name ",__name__ print "Class ",A.__name__ class B(A): def __init__(self): super(B,self).__init__() print "I'm B" Output: I'm A I'm B Name class_name Class A I would want the last line to be Class B The reason i want this is since i have a number of dialogs all deriving from the same super class. In the superclass i have a save function and i thought it would be easy to get the classname and write the properties in a filename with the classes name as the filename. However it turns out i get the class name of the superclass for all. All the different dialogs are in seperate files. Is there a way to get the name of the subclass. If not i could always pass a param to the init function but in my real life code i already have several params shipped to the init so i wanted to solve it slightly more elegant. Regards, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: getting the class name of a subclass
George Sakkis wrote: > Make printclass a class method: > > class A(object): > def __init__(self): > print "I'm A" > > # for python 2.4 > @classmethod > def printclass(cls): > print "Module", cls.__module__ > print "Class", cls.__name__ > # for 2.3 or older > printclass = classmethod(printclass) > > > Regards, > George George, it works like a charm. Thanks! Benedict -- http://mail.python.org/mailman/listinfo/python-list
finding out the calling function
Hi, i have a property in a class that gets changed and i would want to know who changes it. Is there a way i can find out the calling function of a property? Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: finding out the calling function
flupke wrote: > Hi, > > i have a property in a class that gets changed > and i would want to know who changes it. > Is there a way i can find out the calling function of a property? > > Thanks, > Benedict I solved it by using import traceback, sys traceback.print_stack() in the property However, i'm not sure this is the best way. I also tried to use the print_tb funtion from the traceback function traceback.print_tb(sys.last_traceback) This produces an error AttributeError: 'module' object has no attribute 'last_traceback' So how can i pass a valid "traceback" object to the print_tb function and where do i find one? Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
py2exe uses __init__ for class names when logging
Hi, when i run my program and use the logging component, i see this: 2005-09-02 17:07:48,193 INFO windowmain 97 Main window created 2005-09-02 17:07:49,020 DEBUG windowmain 103 Frame 2005-09-02 17:07:49,145 INFO firebird 195 Starting up the database However when i run py2exe on my app and run it then i don't see the file name anymore. Instead it says __init__: 2005-09-06 16:01:17,098 INFO __init__ 1032 Main window created 2005-09-06 16:01:17,615 DEBUG __init__ 1032 Frame 2005-09-06 16:01:17,677 INFO __init__ 1032 Starting up the database Any ideas on how to solve this? Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: py2exe uses __init__ for class names when logging
Thomas Heller wrote: > This has been discussed on the py2exe-users lists, and a fix was found > by David Hess. Fortunately he added it to the wiki: > > http://starship.python.net/crew/theller/moin.cgi/LoggingModule > > Thomas Cool, thanks Thomas, i'll give that a whirl Benedict -- http://mail.python.org/mailman/listinfo/python-list
python equivalent to access reports
Hi, a lot of applications here a made with access. Tables, forms, reports and the like. Now i rather use Python to do this but i'm not sure how to proceed. I can use wxPython for a gui via wxGlade for rapid testing and design (forms), MySQL as db (tables) but the report part is what's bothering me. The only semi easy way that i see is by making html files with the results in and then opening a browser to display the result. But this would lack nice printing as there is no way to cleanly start a new page. Any other ideas? Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: python equivalent to access reports
flupke wrote: Hi, a lot of applications here a made with access. Tables, forms, reports and the like. Now i rather use Python to do this but i'm not sure how to proceed. I can use wxPython for a gui via wxGlade for rapid testing and design (forms), MySQL as db (tables) but the report part is what's bothering me. The only semi easy way that i see is by making html files with the results in and then opening a browser to display the result. But this would lack nice printing as there is no way to cleanly start a new page. Any other ideas? Thanks, Benedict I just saw a reference too http://www.reportlab.org/ This might do what i want. Benedict -- http://mail.python.org/mailman/listinfo/python-list
site indexer and search script
Hi, for an old intranet that is still used here, i would like to add a search function. I think there migth already be an indexer/search script available in python. I've googled and come across a few scripts but i'm not sure which one is really easy and good at the task. Any good scripts (and easy to configure) around? I would like to use python to generate the corresponding results page, what would i use for that, again bearing in mind that it needs to be done quite quickly so i cannot afford to waste to much time ? Is mod_python usable for such a simple page generation or would i better focus on Twisted or CherryPie? Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
reading timestamp from vid file (avi)
Hi, i capture a movie from mividv to an avi containing the dv video. I found a program that reads the timestamp from the avi so you know the exact date and time the video was shot. However, the source of that program is not available and it doesn't allow to batch process a directory of video files which is a pain if you import the video using "split scenes". Is there a script/program in python that reads the header or where do i start to write something like that? Any info is appreciated. Regards, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: reading timestamp from vid file (avi)
Lucas Raab wrote: flupke wrote: Hi, i capture a movie from mividv to an avi containing the dv video. I found a program that reads the timestamp from the avi so you know the exact date and time the video was shot. However, the source of that program is not available and it doesn't allow to batch process a directory of video files which is a pain if you import the video using "split scenes". Is there a script/program in python that reads the header or where do i start to write something like that? Any info is appreciated. Regards, Benedict Take a look at pymedia at http://pymedia.org. Thanks, i'll see if i can do something with it. It looks promising but not as simple so i might ask this question on their list. Thanks Benedict -- http://mail.python.org/mailman/listinfo/python-list
wxPython and loading multiple panels (code included)
Hi, i need to develop a gui which will load several "windows" depending on what the users selects in the menu and i thought i could accomplish this with panels. What i'm trying to do to test this is load an initial panel and then when the user hits a button load a second panel. This doesn't seem to work. 1. what's the appropriate way of switching panels? 2. the loadNewPanel function seem wrong. I always get loading panel two". Thanks, Benedict multi.py === import wx from multi_panel import * active_frame = 1 class MyFrame(wx.Frame): def __init__(self, *args, **kwds): kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.panel = PanelOne(self) self.__set_properties() self.__do_layout() def __set_properties(self): self.SetTitle("frame_1") def __do_layout(self): self.sizer_1 = wx.BoxSizer(wx.VERTICAL) self.sizer_1.Add(self.panel, 1, wx.EXPAND, 0) self.SetAutoLayout(True) self.SetSizer(self.sizer_1) self.sizer_1.Fit(self) self.sizer_1.SetSizeHints(self) self.Layout() def loadNewPanel(self,invoker): if isinstance(invoker,PanelOne): print "loading panel two" self.panel = PanelTwo(self) else: print "loading panel one" self.panel = PanelOne(self) self.sizer_1.Fit(self) self.sizer_1.SetSizeHints(self) class MyApp(wx.App): def OnInit(self): wx.InitAllImageHandlers() frame = MyFrame(None, -1, "This is a wx.Frame",pos=(0,0),size=(640,480),style = wx.DEFAULT_FRAME_STYLE) self.SetTopWindow(frame) frame.Show() return 1 if __name__ == "__main__": app = MyApp(0) app.MainLoop() multi.py === and panels.py === import wx class PanelOne(wx.Panel): def __init__(self,parent): wx.Panel.__init__(self, parent, -1) self.parent = parent self.label = wx.StaticText(self, -1, "panel one") self.switch_panel = wx.Button(self, -1, "Switch to panel two", (50,50)) self.Bind(wx.EVT_BUTTON, self.__OnButton, self.switch_panel) self.__do_layout() def __do_layout(self): self.grid_sizer = wx.GridSizer(5, 5, 4, 4) self.grid_sizer.Add(self.label, 0, wx.FIXED_MINSIZE, 0) self.grid_sizer.Add(self.switch_panel, 0, wx.FIXED_MINSIZE, 0) self.SetAutoLayout(True) self.SetSizer(self.grid_sizer) self.grid_sizer.Fit(self) self.grid_sizer.SetSizeHints(self) def __OnButton(self,event): print "OnButton" self.parent.loadNewPanel(self) class PanelTwo(wx.Panel): def __init__(self,parent): wx.Panel.__init__(self, parent, -1) self.label = wx.StaticText(self, -1, "panel two") self.switch_panel = wx.Button(self, -1, "Switch to panel one", (50,50)) self.Bind(wx.EVT_BUTTON, self.__OnButton, self.switch_panel) self.__do_layout() def __do_layout(self): self.grid_sizer = wx.GridSizer(5, 5, 4, 4) self.grid_sizer.Add(self.label, 0, wx.FIXED_MINSIZE, 0) self.grid_sizer.Add(self.switch_panel, 0, wx.FIXED_MINSIZE, 0) self.SetAutoLayout(True) self.SetSizer(self.grid_sizer) self.grid_sizer.Fit(self) self.grid_sizer.SetSizeHints(self) def __OnButton(self,event): print "OnButton" self.parent.loadNewPanel(self) panels.py === -- http://mail.python.org/mailman/listinfo/python-list
xmlrpclib or twisted?
Hi, previously i made an application that used sockets to do some network based processing. My next app is again going to be a client/server app and i wanted to see if i can't find an easier way to make the networking going. I bumped into xmlrpclib and also twisted (pb). I'm not sure which on of these would suit my needs better. I am planning to build a web GUI for the client so if i use twisted, i would already have the components in there to do so, so this could be a plus for twisted. The client will connect to the server to receive data. The data is the result of one of several queries and these raw results would then be displayed in the client via a webgui or wxPython. (leaning towards webgui) Any other ideas? Thanks Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: xmlrpclib or twisted?
flupke wrote: Thanks for the info. Benedict -- http://mail.python.org/mailman/listinfo/python-list
logging from severl classes
Hi, i'm trying to log to the same file (using logging module) from different classes but i can't seem to get it to work. File 1 is the main file which sets up the logger and then i want to also use the same logger in another class This is what i have file1 = import logging class A: def __init__(self): self.logger = logging.getLogger("app_logfile") ### stdout handler ### self.logger.setLevel(logging.DEBUG) stream_hld = logging.StreamHandler() stream_hld.setLevel(logging.DEBUG) stream_formatter = logging.Formatter('%(asctime)s %(levelname)s %(module)s %(lineno)d %(message)s ') stream_hld.setFormatter(stream_formatter) self.logger.addHandler(stream_hld)") = file2 = import logging class B: def __init__(self): self.logger = logging.getLogger("app_logfile") self.logger.debug("creating class B") def otherfunction(self): self.logger.debug("in otherfunction") = But i get an error: AttributeError: B instance has no attribute 'logger' I was hoping that by requesting a logger with the same name (app_logfile) i would get the setup also and could use the logger straight away. Funny thing is that the use of the logger in the __init__ function of class B works but the call to the logger in otherfunction doesn't work and results in the error above. Class B is created after class A so the logger object exists already. Any ideas of what i'm doing wrong and how i can achieve setting up the logger object only once? Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
odbc for solid
Hi, at work we use a solid database and i need to develop an application that accesses it. Problem is the drivers: i only have some dll's lying around and jar. On winsdows i could get by by using ODBC and the dll's to access the solid database but i want to eventually run it on a linux server. Solid doesn't seem to have a driver specifically for Linux so i'm stuck here. Is there any way i can still use Linux and have access to solid? Maybe i need to revert to jython so i can use the jar? Thanks for any info Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: odbc for solid
> Steve Holden wrote: This might be of interest (and also possibly of relevance to an earlier query about accessing MS SQL Server from Unix in the "Python, unix and mssql" thread): http://sourceforge.net/projects/pyodb """PyODB is an ODBC Python module to provide an quick an easy way to work with databases. It provides a small set of simplified bindings to the unixODBC API and has been developed using SWIG." regards Steve Thanks Steve, i'll check the link Benedict -- http://mail.python.org/mailman/listinfo/python-list
workaround for generating gui tools
Hi, i create my GUIs mainly via wxGlade. However when you start of to program and want to do some rearranging to the gui, wxglade overwrites your file and you've got to put your own code back in. I think i can work around that (at least a bit) by making a second file that imports the gui generated by wxglade and make classes that extend the original ones. For instance i could have a class MainForm that extends the wxFrame class that wxGlade produces. Are there other clever ways to work around this problem? Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: workaround for generating gui tools
Reinhold Birkenfeld wrote: Have to disagree strongly. It's evil anyway (for more complex applications) to put GUI construction in your code. GUI should be described appropriately in data files. Glade does this very good, and with pygtk it's no problem to use the XML files. Reinhold So the GUI should be seperate from the code. Is the way i described valid then? Extending from the gui class and putting event handlers in the derived classes? Or is there a better way to seperate the GUI from the code? Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: workaround for generating gui tools
Jeremy Bowers wrote: Domain-specific abstractions do that *faster* than GUI designers, not slower. And better, too, since every iteration tends to be fully functional and not just a "let's see what this looks like" prototype. Heck, switch 'em out dynamically based on what day of the week it is and how the user feels today. Let's see your GUI-designer do that. And if you're not used to doing it that way, you'll be *stunned* at how much stuff tends to factor out and get easily re-used. An approach that has more data to work with (some idea of what things are doing and what they are for) will beat an approach with less data ("thing at row 4, col 2" or, worst case, "thing at 233,144") any day. GUI designers are like the regexs in the famous jwz quote: "Some people, when confronted with a problem, think 'I know, I'll use a GUI designer'. Now they have two problems." Both have a niche in the "quick fix" department, both are typically over-used, but overall regexs are the more useful of the two; at least there are cases where they are the undisputed right answer (like defining tokens in a language parser). Generally, over the first couple of weeks of a project, the domain-specific language writer may seem to be behind the GUI designer cranking out screen after screen of templated GUI widgets, but after a couple of weeks the domain-specific language user will pull into the lead and never give it up, and will be a lot happier to boot. First time i hear about domain-specific abstractions. Do you mean that instead of using a GUI designer, you make some sort of engine that constructs a gui for you? One thing i find repetitive to do is designing gui's that are just simple views on a database tables where one can create,edit and delete records. If one could construct a gui dynamically for these types of things, that would be great. Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: workaround for generating gui tools
Dave Cook wrote: On 2005-04-09, flupke <[EMAIL PROTECTED]> wrote: i create my GUIs mainly via wxGlade. However when you start of to program and want to do some rearranging to the gui, wxglade overwrites your file and you've got to put your own code back in. How about generating XRC files instead of Python? I admit I've never tried it with wxGlade, so I don't know how well it works, but with the original Glade one only uses XML, you can't generate Python at all. Dave Cook That sounds like a good idea. I'm going to check how i can load stuff from the resource file. Thanks for the tip Regards, Benedict Verheyen -- http://mail.python.org/mailman/listinfo/python-list
Re: Glade for Windows and Python
Richard Lyons wrote: Has anyone been successful in using Glade for Windows with Python? Yeah, i'm using it right now. See the previous email for the links Benedict -- http://mail.python.org/mailman/listinfo/python-list
__del__ and reference count problem
Hi, i'm starting work and a simple database layer and wanted to use the __del__ to open and close a connection. However, i get an erro when executing this script: class Table: refcount = 0 def __init__(self, name): self.name = name print "table %s " % repr(self) Table.refcount += 1 print "refcount = %s" % str(Table.refcount) def __del__(self): Table.refcount -= 1 if (Table.refcount == 0): print "Last table standing" else: print "There is/are still %d table(s) left." % Table.refcount def __getitem__(self,item): return "not implemented" def howMany(self): if (Table.refcount == 1): print "Only 1 table" else: print "There are %d tables active." % Table.refcount if __name__ == '__main__': suppliera = Table("suppliers") supplierb = Table("suppliers") print "Supplier returned from a %s: %s" % (1, suppliera[1]) print "Supplier returned from b %s: %s" % (2, supplierb[2]) suppliera.howMany() supplierb.howMany() This produces the following output and error: table <__main__.Table instance at 0x008D5C10> refcount = 1 table <__main__.Table instance at 0x008D5C38> refcount = 2 Supplier returned from a 1: not implemented Supplier returned from b 2: not implemented There are 2 tables active. There are 2 tables active. Exception exceptions.AttributeError: "'NoneType' object has no attribute 'refcount'" in > ignored Exception exceptions.AttributeError: "'NoneType' object has no attribute 'refcount'" in > ignored What am i doing wrong? Thanks Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: __del__ and reference count problem
[EMAIL PROTECTED] wrote: look at this discussion: http://www.dbforums.com/archive/index.php/t-1100372.html it looks like we have to use other way, hold the data we want to preseve in an object, because it is possible the class is removed before the instance cleaned, and we can not expect __del__ 100% in handling finalizing process. Pujo That forum helped. I changed this in my code and it worked def __del__(self): self.__class__.refcount -= 1 if (self.__class__.refcount == 0): print "Last table standing" else: print "There is/are still %d table(s) left." % self.__class__.refcount Output: table <__main__.Table instance at 0x009D5B98> refcount = 1 table <__main__.Table instance at 0x009D5BC0> refcount = 2 Supplier returned from a 1: not implemented Supplier returned from b 2: not implemented There are 2 tables active. There are 2 tables active. There is/are still 1 table(s) left. Last table standing Seems to work allright ! Thanks ! :) Benedict -- http://mail.python.org/mailman/listinfo/python-list
__del__ and logging
Hi, i have a class and a class attribute log which is a logger object. In the __del__() function i want to log a message but it fails even if i use self.__class__.log. The error i get is this: Traceback (most recent call last): File "C:\Python24\lib\logging\__init__.py", line 712, in emit self.stream.write(fs % msg) ValueError: I/O operation on closed file So is there no way to use the logger object in a __del__ I wanted to use the message to clearly indicate in the logger file that the instance had closed ok. Regards, Benedict -- http://mail.python.org/mailman/listinfo/python-list
logging error with RotatingFileHandler
Hi, i'm getting errors with the log module concerning RotatingFileHandler. I'm using Python 2.4.3 on Windows XP SP2. This used to work in previous python versions but since i upgraded to 2.4.3 i get these errors: Traceback (most recent call last): File "C:\Python24\lib\logging\handlers.py", line 71, in emit if self.shouldRollover(record): File "C:\Python24\lib\logging\handlers.py", line 150, in shouldRollover self.stream.seek(0, 2) #due to non-posix-compliant Windows feature ValueError: I/O operation on closed file 2006-06-25 10:35:07,171 INFO firebird 210 Starting up the database Traceback (most recent call last): File "C:\Python24\lib\logging\handlers.py", line 72, in emit self.doRollover() File "C:\Python24\lib\logging\handlers.py", line 134, in doRollover self.handleError(record) NameError: global name 'record' is not defined I use the logging module by loading a config file: import logging import logging.config LOGFILE = r"logconf.ini" Then in the init function of the class # load logger logging.config.fileConfig(LOGFILE) self.log = logging.getLogger('stats') If i have a main class and a class deriving from it, i let the main class instantiate the class by issueing the commands like above and then get automatically get access to it in the deriving classes. If i remove the logfile, it all works until it has to rollover. My config.ini file contains this info: [loggers] keys=root,stats,database [handlers] keys=hand01,hand02 [formatters] keys=form01,form02 [logger_root] level=NOTSET handlers=hand01 qualname=(root) # note - this is used in non-root loggers propagate=1 # note - this is used in non-root loggers channel= parent= [logger_stats] level=DEBUG propagate=0 qualname=stats handlers=hand01,hand02 channel=log02 parent=(root) [logger_database] level=DEBUG propagate=0 qualname=database handlers=hand01,hand02 channel=log03 parent=(root2 [handler_hand01] class=StreamHandler level=DEBUG formatter=form01 args=(sys.stdout,) stream=sys.stdout [handler_hand02] class=handlers.RotatingFileHandler level=NOTSET formatter=form01 filename=stats.log mode=a maxsize=50 backcount=9 args=('stats.log', 'a', 90, 5) [formatter_form01] format=%(asctime)s %(levelname)s %(module)s %(lineno)d %(message)s datefmt= [formatter_form02] format=%(asctime)s %(levelname)s %(module)s %(lineno)d %(message)s datefmt= Any idea on why this suddenly doesn't work anymore? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: logging error with RotatingFileHandler
Vinay Sajip wrote: > flupke wrote: > > >> File "C:\Python24\lib\logging\handlers.py", line 134, in doRollover >>self.handleError(record) >>NameError: global name 'record' is not defined > > > There's a bug in doRollover's exception handling, which is masking the > true error - which is most probably an exception being thrown in > os.rename. > > I'll look at fixing this bug asap. Most likely, it'll be done by let > the exception propagate up from doRollover to its caller. > > Regards, > > Vinay Sajip > OK Vinjay, thanks for the info. If this bug is fixed, where will i find a fixed version and how do i install it? Also, more important to me, what am i doing wrong to get this error message in the first place? I could reproduce the error with this program: import logging import logging.config LOGFILE = r"logconf.ini" logging.config.fileConfig(LOGFILE) class TypeA(object): def __init__(self): #logging.config.fileConfig(LOGFILE) self.log = logging.getLogger('logfile') self.dolog("Starting the program") def dolog(self,text): self.log.debug(text) class TypeB(TypeA): def __init__(self): super(TypeB,self).__init__() # put this line in comment to prevent the error logging.config.fileConfig(LOGFILE) #self.log = logging.getLogger('logfile') self.log.debug("Starting class B") for nr_of_lognr in range(0,2000): b = TypeB() b.dolog("This is a test to see if logging works and more specifically the RotatingFileHandler functionallity") It seemed as if the "logging.config.fileConfig(LOGFILE)" line in Type B is to blame. I changed the code of my big program to reflect this change yet i still get this error. I didn't get this with an earlier version of python. Regards, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: logging error with RotatingFileHandler
Vinay Sajip schreef: > flupke wrote: > >> If this bug is fixed, where will i find a fixed version and how do i >> install it? >> Also, more important to me, what am i doing wrong to get this error >> message in the first place? > > You're not doing anything particularly wrong, though it's not exactly > good practice to call fileConfig lots of times. (It's really meant for > one-off configuration, not incremental configuration.) > > I get an error with just the following script typed in at the > interactive prompt: > > import logging.config > logging.config.fileConfig("logconf.ini") > logging.config.fileConfig("logconf.ini") > > So, I will investigate, and when I check in a fix to the Python > Subversion repository, I will post a message to this thread. > > Regards, > > Vinay Sajip > Hi Vinay, thanks for the info. I tried to change the handlers.py file. First, i changed some code in doRollover. if os.path.exists(dfn): os.remove(dfn) try: #os.rename(self.baseFilename, dfn) -> The rename fails for some reason. I tried with the move function of shutil shutil.move(self.baseFilename, dfn) This partially works: the file is now rotated but i still get an error: The error that i get is this: Error [Errno 13] Permission denied: 'E:\\python\\proj1\\src\\proj1.log' Traceback (most recent call last): File "C:\Python24\lib\logging\handlers.py", line 72, in emit self.doRollover() File "C:\Python24\lib\logging\handlers.py", line 141, in doRollover self.handleError(record) NameError: global name 'record' is not defined The last part of the error shows that the part where the exception is caugth is also not working correctly as the "record" isn't know. When i close my program, i get this error as well: Error in atexit._run_exitfuncs: Traceback (most recent call last): File "C:\Python24\lib\atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "C:\Python24\lib\logging\__init__.py", line 1333, in shutdown h.close() File "C:\Python24\lib\logging\__init__.py", line 772, in close StreamHandler.close(self) File "C:\Python24\lib\logging\__init__.py", line 674, in close del _handlers[self] KeyError: Error in sys.exitfunc: Traceback (most recent call last): File "C:\Python24\lib\atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "C:\Python24\lib\logging\__init__.py", line 1333, in shutdown h.close() File "C:\Python24\lib\logging\__init__.py", line 772, in close StreamHandler.close(self) File "C:\Python24\lib\logging\__init__.py", line 674, in close del _handlers[self] KeyError: Regards Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: logging error with RotatingFileHandler
flupke schreef: > Hi Vinay, > > thanks for the info. > > I tried to change the handlers.py file. > First, i changed some code in doRollover. > > if os.path.exists(dfn): > os.remove(dfn) > try: > #os.rename(self.baseFilename, dfn) > > -> The rename fails for some reason. > > I tried with the move function of shutil > shutil.move(self.baseFilename, dfn) > > This partially works: the file is now rotated but i still get an error: > The error that i get is this: > Error [Errno 13] Permission denied: 'E:\\python\\proj1\\src\\proj1.log' > Traceback (most recent call last): > File "C:\Python24\lib\logging\handlers.py", line 72, in emit > self.doRollover() > File "C:\Python24\lib\logging\handlers.py", line 141, in doRollover > self.handleError(record) > NameError: global name 'record' is not defined > > The last part of the error shows that the part where the exception is > caugth is also not working correctly as the "record" isn't know. > > When i close my program, i get this error as well: > > Error in atexit._run_exitfuncs: > Traceback (most recent call last): > File "C:\Python24\lib\atexit.py", line 24, in _run_exitfuncs > func(*targs, **kargs) > File "C:\Python24\lib\logging\__init__.py", line 1333, in shutdown > h.close() > File "C:\Python24\lib\logging\__init__.py", line 772, in close > StreamHandler.close(self) > File "C:\Python24\lib\logging\__init__.py", line 674, in close > del _handlers[self] > KeyError: > Error in sys.exitfunc: > Traceback (most recent call last): > File "C:\Python24\lib\atexit.py", line 24, in _run_exitfuncs > func(*targs, **kargs) > File "C:\Python24\lib\logging\__init__.py", line 1333, in shutdown > h.close() > File "C:\Python24\lib\logging\__init__.py", line 772, in close > StreamHandler.close(self) > File "C:\Python24\lib\logging\__init__.py", line 674, in close > del _handlers[self] > KeyError: > > Regards > Benedict I was able to solve the errors (i think): 1. in the function doRollover of the class RotatingFileHandler if os.path.exists(dfn): os.remove(dfn) try: os.rename(self.baseFilename, dfn) I added this instead of the rename function: import shutil shutil.copy(self.baseFilename, dfn) If this code works ok, then the "import shutil" should be placed at the top of the file for performance reasons. The logic of the copy is that a few statements later, the self.stream var is set to a new file again so it doesn't need to be deleted. At least it seems to work here. I will need to test further. Weird thing is, the stream is closed and yet you get this error when you use rename: [Errno 13] Permission denied 2. in the same function, when an error occurred, the record var wasn't found. This can be solved by changing the code of emit in BaseRotatingHandler. Change this: if self.shouldRollover(record): self.doRollover() by: if self.shouldRollover(record): self.doRollover(record) 3. The last error (error when closing the program) can be solved by editing the __init__.py, close(self) function. Change this: _acquireLock() try:#unlikely to raise an exception, but you never know... del _handlers[self] _handlerList.remove(self) finally: _releaseLock() by: _acquireLock() try:#unlikely to raise an exception, but you never know... #del _handlers[self] if ( _handlers.has_key(self) ): del _handlers[self] #if ( self in _handlerList ): _handlerList.remove(self) _handlerList.remove(self) finally: _releaseLock() It might even be better to change the _handlerList.remove(self) statement by this statement: if ( self in _handlerList ): _handlerList.remove(self) Regards, Benedict Verheyen -- http://mail.python.org/mailman/listinfo/python-list
Re: about daemons and IPC
[EMAIL PROTECTED] schreef: > Hey people! > For the first time I'm doing a client/server application, and I'm > really confused with IPC stuff. > > I read the fastest method is shared memory, but I tryed mmap and found > it tedious for the amount of data I'm handling (which is 30K at most, > but mmap seems to get tedious for anything bigger than a boolean... am > I missing something?) > > Then I found many solutions for forked processes (like posh), but > that's not what I need right now. > > Any suggestions? > You can also use RPC or even use a framework to do that for you like Twisted. I like both approaches because they simplify communications. For Twisted you have the initial investement in getting to know it but it's also a lot more versatile -- http://mail.python.org/mailman/listinfo/python-list
odbc DbiDate date conversion
I'm using a solid DB and i'm accessing it via the odbc module (activepython). I get a DbiDate object returned but i don't find a way to decently print it or get a format like %d/%m%/%y. I found a few posts but the code doesn't work. >>> birthd = results[0][4] #info from db >>> birthd >>> str(birthd) 'e\x00\x00d\x00\x00\x19d\x01\x00\x19Z\x01\x00d\x02\x00S\x00[4]\n\x00' >>> t = time.strftime('%d %B %Y', birthd) Traceback (most recent call last): File "", line 1, in ? TypeError: argument must be 9-item sequence, not DbiDate How can i convert this DbiDate to a string formated like '%d %B %Y' I look at the DB API 2.0 but couldn't find the relevant info. Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: odbc DbiDate date conversion
Frank Millman schreef: > flupke wrote: >> I'm using a solid DB and i'm accessing it via the odbc module >> (activepython). >> I get a DbiDate object returned but i don't find a way to decently print >> it or get a format like %d/%m%/%y. >> > > I convert it to a datetime() instance, like this - > > mydate = datetime.datetime.fromtimestamp(int(dbidate)) > > Then I can use all the functionality of the datetime module. > > HTH > > Frank Millman > Hi Frank, i tried it and i end up with this: >>> mydate = datetime.datetime.fromtimestamp(int(birthd)) Traceback (most recent call last): File "", line 1, in ? ValueError: timestamp out of range for platform localtime()/gmtime() function Regards, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: odbc DbiDate date conversion
Frank Millman schreef: > Well waddyaknow - I get exactly the same, for dates earlier than > 1970-01-02. Thanks for finding a bug that would have bitten me sooner > or later. > > I will do some investigation. If I find an answer I will post it here, > unless some kind soul saves me the trouble and beats me to it. > > Frank > Thanks for investigating it so far Frank. Is there a workaround to parse that date and get the date info that i want? Regards, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: odbc DbiDate date conversion
flupke schreef: When i do the same sql from a client, i get this: 1961-02-15 Seems ok. If i check the catalog, the native field type is listed as 10 positions and of type date. Yet when i print it after i got the values i get this which looks very weird (print "value ",str(i)," type ",type(i)): value "main_kamer"."nummer" m" type The type is ok but the result of str(i) looks wrong. Or is it due to conversion by str? Regards, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: odbc DbiDate date conversion
Frank Millman schreef: > Not that I know of. The results of my investigations so far seem to > indicate that we have a problem :-( > > Here is a link to an article dated 1998 - > https://svn.python.org/www/trunk/pydotorg/windows/OdbcHints.html > > Among other interesting stuff, it states - > > "Notice that result values are converted to Python objects. Dates in > particular are returned as dbiDate objects. This can be a serious > limitation, because dbiDate can not represent dates prior to the UNIX > epoch (1 Jan 1970 00:00:00 GMT). If you try to retrieve earlier dates, > you'll get garbage and may even provoke a crash." > > I contacted Mark Hammond, author of the win32 extensions, to ask if > there was a solution and particularly to suggest a modification to > return a datetime.datetime object. This was his reply - > > "I'd be happy with an option to use the datetime module - maybe it > could even be on the cursor? However, I wont have time to do this in > the short term. > You could consider using ADO via win32com too..." > > It looks as if we will have to use ADO for now. There is an 'adodbapi' > module available which is DB-API 2.0 compliant - > adodbapi.sourceforge.net. I will give it a try. > > Frank Frank, thanks for your effort. Looks indeed like it's not going to be solved in the short term. I will give adodbapi a whirl then. Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: Difference between two dates in seconds
Fredrik Lundh schreef: > def get_seconds(td): > ... return td.days * (24*60*60) + td.seconds > ... import dis dis.dis(get_seconds) > 2 0 LOAD_FAST0 (td) > 3 LOAD_ATTR0 (days) > 6 LOAD_CONST 4 (86400) > 9 BINARY_MULTIPLY > 10 LOAD_FAST0 (td) > 13 LOAD_ATTR1 (seconds) > 16 BINARY_ADD > 17 RETURN_VALUE > > Ha, i didn't know about the dis module. Looks fun. I get these results: >>> def get_seconds(td): ... return td.days * (24*60*60) + td.seconds ... >>> dis.dis(get_seconds) 2 0 LOAD_FAST0 (td) 3 LOAD_ATTR1 (days) 6 LOAD_CONST 1 (24) 9 LOAD_CONST 2 (60) 12 BINARY_MULTIPLY 13 LOAD_CONST 2 (60) 16 BINARY_MULTIPLY 17 BINARY_MULTIPLY 18 LOAD_FAST0 (td) 21 LOAD_ATTR2 (seconds) 24 BINARY_ADD 25 RETURN_VALUE >>> def get_seconds2(td): ... return td.days * 86400 + td.seconds >>> dis.dis(get_seconds2) 2 0 LOAD_FAST0 (td) 3 LOAD_ATTR1 (days) 6 LOAD_CONST 1 (86400) 9 BINARY_MULTIPLY 10 LOAD_FAST0 (td) 13 LOAD_ATTR2 (seconds) 16 BINARY_ADD 17 RETURN_VALUE Using 86400 instead of (24*60*60) is faster Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: Can string formatting be used to convert an integer to its binary form ?
[EMAIL PROTECTED] schreef: > Hi, > > String formatting can be used to converting an integer to its octal or > hexadecimal form: a = 199 "%o" % a > '307' "%x" % a > 'c7' > > But, can string formatting be used to convert an integer to its binary > form ? > > > Thanks in advance. > > xiaojf I don't actually know how to do it with string formatting but you can create a simple function to do it. Here's an example: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/219300 Regards, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: Difference between two dates in seconds
Duncan Booth schreef: > flupke <[EMAIL PROTECTED]> wrote: > >> Using 86400 instead of (24*60*60) is faster > > s/is/was/ > > upgrade to Python 2.5 Indeed, i'm still on 2.4. I thought 2.5 might give a different result :) Thanks for the info Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: __del__ and logging
Vinay Sajip wrote: > flupke nonexistingdomain.com> writes: > > >>Hi, >> >>i have a class and a class attribute log which is a logger object. In >>the __del__() function i want to log a message but it fails even if i >>use self.__class__.log. >> >>The error i get is this: >>Traceback (most recent call last): >> File "C:\Python24\lib\logging\__init__.py", line 712, in emit >> self.stream.write(fs % msg) >>ValueError: I/O operation on closed file >> >>So is there no way to use the logger object in a __del__ >>I wanted to use the message to clearly indicate in the logger file that >>the instance had closed ok. >> > > > It all depends. If your __del__ is being called via atexit() for application > cleanup, for example, logging may not be available to you because it has been > cleaned up beforehand. > > The logging module registers an atexit() handler to flush and close handlers > before script termination. > > Vinay Sajip > > Thanks i was able to solve it using a function registered in both the classes i used in that project. Why would one use __del__ instead of atexit then especially if the calls you make in __del__ are so unrelieable? Regards, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: Advice needed on __del__
phil wrote: > A class instance based language doesn't have to BE C++ to have a > destructor method. > > All I wanted to know is: is the apparent treatment of __del__ > which SEEMS to work fine for me in 2.3.4 deprecated or mangled > in some later release or future plans. > If someone doesn't know the answer to this question or if noone > knows the answer to this question, I will still love and > respect the Python Community. In large part cause it ain't C++> I like to use destructors to and find the way __del__ works a bit strange. For instance if you want to use a class variable in the __del__ function it's possible that it's not reachable via . and then you have to call it via self.__class__.. I find this non intuitive. I heard the explanations why but that doens't make it more intuitive. Then i got a tip that you can register a function that needs to be called when the object is going to be deleted. For instance to register a function __exit, you do this: import atexit ... class Bla: def __init__(self) ... atexit.register(self.__exit) ... def __exit(self): It still doesn't feel right to me as i would rather use __del__ but since the behaviour can't be predicted, using atext is the next best thing Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: Destructor Woes, was Advice needed on __del__
phil wrote: > >> Then i got a tip that you can register a function that needs to be >> called when the object is going to be deleted. >> For instance to register a function __exit, you do this: >> > > > Here is the complete line class with your suggestion: > > Below is the output. > > Nice idea, maybe I did something wrong? > > class line: > def __init__(s,glob,argl,color=''): > atexit.register(s.__exit) > s.glob = glob > s.type = 'line' > s.color = color > if not s.color: s.color = glob.color > if len(argl) == 2: > wobj = glob.objs[ argl[0] ][0] > s.x0 = a0 = wobj.x > s.y0 = b0 = wobj.y > wobj = glob.objs[ argl[1] ][0] > s.x1 = a1 = wobj.x > s.y1 = b1 = wobj.y > > elif len(argl) == 4: > s.x0 = a0 = float( argl[0] ) > s.y0 = b0 = float( argl[1] ) > s.x1 = a1 = float( argl[2] ) > s.y1 = b1 = float( argl[3] ) > else: return > s.midx = (s.x0 + s.x1) / 2 > s.midy = (s.y0 + s.y1) / 2 > s.len = sqrt( (s.x1 -s.x0)**2 + (s.y1 -s.y0)**2 ) > if (s.y1 -s.y0) == 0: s.slope = 0 > elif (s.x1 -s.x0) == 0: s.slope = 99 > else: s.slope = ( (s.y1 -s.y0) / (s.x1 -s.x0) ) > > # center point of graph is 400,300 > # scale is no of pixels per unit of measure > x0 = a0 * s.glob.scale + 400 > y0 = 300 - b0 * s.glob.scale > x1 = a1 * s.glob.scale + 400 > y1 = 300 - b1 * s.glob.scale > s.obj = glob.can.create_line(x0,y0,x1,y1, > width=glob.width,fill=s.color) > def __exit(s): > print 'exit' > s.glob.can.delete(s.obj) > > # def __del__(s): > # s.glob.can.delete(s.obj) > > > exit > > Error in sys.exitfunc: > Traceback (most recent call last): > File "/usr/local/lib/python2.3/atexit.py", line 20, in _run_exitfuncs > func(*targs, **kargs) > File "./graph.py", line 972, in __exit > s.glob.can.delete(s.obj) > File "/usr/local/lib/python2.3/lib-tk/Tkinter.py", line 2085, in delete > self.tk.call((self._w, 'delete') + args) > _tkinter.TclError: invalid command name ".1076354284" > I don't know what's wrong in your example. Here it works (doesn't help you of course). I would first try with an easy example an try to test the atexit functionality like that. It seems that the problem you are having isn't related to the atexit part. Sorry i couldn't be of more help Benedict -- http://mail.python.org/mailman/listinfo/python-list
subclass dialog or put in the resource files?
I'm using wxPython and design the gui via wxglade. One of the gui components is a simple dialog class that gets displayed when a user exits the program. I want to use the same dialog but with a different text for closing certain dialogs in the program. (it's a pure "do you want to exit " dialog) What would i better use, knowing the rest of the gui is in a resource (xrc) file: 1. Find some way to put a standard exit dialog in the resource file and then somehow try to set the message to the correct one. 2. Make a simple dialog class that accepts the message to be displayed. I could even use glade to generate the python code for a start. What would be the better/cleaner/logical way to do this? Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: Destructor Woes, was Advice needed on __del__
Fredrik Lundh wrote: > "flupke" wrote: > > >>>Then i got a tip that you can register a function that needs to be >>>called when the object is going to be deleted. >>>For instance to register a function __exit, you do this: > > >>>class line: >>>def __init__(s,glob,argl,color=''): >>>atexit.register(s.__exit) > > >>I don't know what's wrong in your example. Here it works (doesn't help >>you of course). I would first try with an easy example an try to test >>the atexit functionality like that. It seems that the problem you are >>having isn't related to the atexit part. > > > do you (or whoever gave you the tip) have the slightest idea what atexit does? > > As i said, it works for me. I use it to log the closure of my main program. Maybe my first message wasn't clear on the use of atexit. Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: subclass dialog or put in the resource files?
flupke wrote: > > I'm using wxPython and design the gui via wxglade. One of the gui > components is a simple dialog class that gets displayed when a user > exits the program. > I want to use the same dialog but with a different text for closing > certain dialogs in the program. (it's a pure "do you want to exit > " dialog) > > What would i better use, knowing the rest of the gui is in a resource > (xrc) file: > > 1. Find some way to put a standard exit dialog in the resource file and > then somehow try to set the message to the correct one. > > 2. Make a simple dialog class that accepts the message to be displayed. > I could even use glade to generate the python code for a start. > > What would be the better/cleaner/logical way to do this? > > Thanks, > Benedict I found what i was looking for. I first load the dialog from the resource files and then i change the text like this: children = self.d_exit.GetChildren() for control in children: if ( type(control) is wx.StaticText ): control.SetLabel("") Benedict -- http://mail.python.org/mailman/listinfo/python-list
cddb and mci produce an ImportError
Hi, i am in search of a cddb module for Python on windows. I stumbled upon http://sourceforge.net/projects/cddb-py but couldn't use it since the mci.dll is compiled against Python2.0. So i'm trying to rebuild it using Dev-C++. I've succeeded in building a dll but when i try a test program it get this error: http://sourceforge.net/projects/cddb-py Traceback (most recent call last): File "cddtest.py", line 1, in ? import CDDB, DiscID File "C:\Python24\lib\DiscID.py", line 15, in ? import cdrom, sys File "C:\Python24\lib\cdrom.py", line 8, in ? import mci ImportError: dynamic module does not define init function (initmci) I had already some problems with the CDDB.py program since it used os.geteuid() and python gave an error for that too. These are the files i'm using and i'm not sure the content is correct. I used a dll project and copied and pasted the content of the original files from the cddb project in there in the hopes of getting it to work. mci.h #ifndef _DLL_H_ #define _DLL_H_ #if BUILDING_DLL # define DLLIMPORT __declspec (dllexport) #else /* Not BUILDING_DLL */ # define DLLIMPORT __declspec (dllimport) #endif /* Not BUILDING_DLL */ DLLIMPORT void initmci(void); class DLLIMPORT DllClass { public: DllClass(); virtual ~DllClass(void); private: }; #endif /* _DLL_H_ */ mci.cpp /* Replace "dll.h" with the name of your header */ #include "mci.h" #include #include #include DllClass::DllClass() { } DllClass::~DllClass () { } static PyObject *mci_error; #define MCI_STRING_LEN 1000 static PyObject *mci_mciSendString(PyObject *self, PyObject *args) { char resultStr[MCI_STRING_LEN+1]; PyObject *pyStr = 0; if (!PyArg_ParseTuple(args, "O!", &PyString_Type, &pyStr)) return NULL; // windows mciSendString see cdrom.py for Samples (or MSDN for complete doc) mciSendString( PyString_AsString(pyStr), resultStr,MCI_STRING_LEN,0); return Py_BuildValue("s", resultStr); } static PyMethodDef mci_methods[] = { { "mciSendString", mci_mciSendString, METH_VARARGS }, { NULL, NULL } }; void initmci(void) { PyObject *module, *dict; module = Py_InitModule("mci", mci_methods); dict = PyModule_GetDict(module); mci_error = PyErr_NewException("mci.error", NULL, NULL); PyDict_SetItemString(dict, "error", mci_error); } BOOL APIENTRY DllMain (HINSTANCE hInst /* Library instance handle. */ , DWORD reason/* Reason this function is being called. */ , LPVOID reserved /* Not used. */ ) { switch (reason) { case DLL_PROCESS_ATTACH: break; case DLL_PROCESS_DETACH: break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; } /* Returns TRUE on success, FALSE on failure */ return TRUE; } test program import CDDB, DiscID cdrom = DiscID.open() disc_id = DiscID.disc_id(cdrom) (query_status, query_info) = CDDB.query(disc_id) (read_status, read_info) = CDDB.read(query_info['category'], query_info['disc_id']) for i in range(disc_id[1]): print "Track %.02d: %s" % (i, read_info['TTITLE' + `i`]) I've included these libraries (linker options): --no-export-all-symbols --add-stdcall-alias C:/Dev-Cpp/lib/libwinmm.a C:/Python24/libs/python24.lib C:/Python24/libs/libpython24.a It compiles fine and makes a mci.dll but as i said, i get the ImportError when i run it. Any ideas? Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: cddb and mci produce an ImportError
flupke wrote: I finally succeeded in making a proper mci.dll that works. I will document what i did in the coming days and place it here. I developed the dll with DevC++. Anyway, it all works :) Benedict -- http://mail.python.org/mailman/listinfo/python-list
firebird and unicode
Hi, i'm developing an app that uses wxPython and Firebird via kinterbasdb on Win XP SP2. On insert of a record i get this error: (kinterbasdb.InterfaceError) (0, "Type mismatch: Input parameter for field named [name n ot known at this stage of query execution] must be a string, rather than a .") Python, wxPython are all unicode enabled. The firebird database is created with the UNICODE_FSS charset and opened as such in kinterbasdb's connect function (charset=UNICODE). The GUI's charset is made with wxGlade and there i specified UTF-8 for the encoding. I'm out of ideas as to why i get this error message. Any ideas? Thanks Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: firebird and unicode
flupke wrote: > Hi, > > i'm developing an app that uses wxPython and Firebird via kinterbasdb on > Win XP SP2. On insert of a record i get this error: > (kinterbasdb.InterfaceError) > (0, "Type mismatch: Input parameter for field named [name n > ot known at this stage of query execution] must be a string, rather than > a .") > > Python, wxPython are all unicode enabled. The firebird database is > created with the UNICODE_FSS charset and opened as such in kinterbasdb's > connect function (charset=UNICODE). The GUI's charset is made with > wxGlade and there i specified UTF-8 for the encoding. > > I'm out of ideas as to why i get this error message. > > Any ideas? > > Thanks > Benedict If looked around a bit and it seems i have to do a kinterbasdb.init(type_conv=100). But this gives another error: File "C:\Python24\lib\site-packages\kinterbasdb\__init__.py", line 343, in init fakeFunc.func_code = realFunc.func_code ValueError: Date() requires a code object with 0 free vars, not 1 I installd the mx Data time module and the fixedpoint module but that doesn't help. I still get the same error. Does anybody know what's wrong? Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: firebird and unicode
flupke wrote: I solved it by getting the latest py files from CVS and overwriting the existing ones. It gave an Attribute error but that was gone after commenting this line: #isc_info_isc_version = _k.isc_info_isc_version I'm not sure if this is a safe way of working. It's like jumping over a fence with barb wire. You know your balls might be in danger but sometimes you got to take a risk :) I hope i don't end up singing with a funny voice ;) Thanks, Benedict Verheyen -- http://mail.python.org/mailman/listinfo/python-list
Re: Terminating a thread from the parent
DE wrote: > Hello, > > I have an app with embedded Python. Python scripts create their own > threads and I need to terminate these threads at the point where the > user wants to leave the application. I use threading.Thread as base > classes. > > I have tried to use call the join method of the python thread objects > from C++. But although the call succeeds, the threads don't exit. > > What is the proper way of doing this ? (e.g. how does the python shell > do this ? ) > > Thanks in advance, > > Devrim. > I found this example somewhere. It shows how you terminate a thread. As Peter said, it's the thread that terminates itself. #!/usr/bin/env python """ testthread.py An example of an idiom for controling threads Doug Fort http://www.dougfort.net """ import threading class TestThread(threading.Thread): """ A sample thread class """ def __init__(self): """ Constructor, setting initial variables """ self._stopevent = threading.Event() self._sleepperiod = 1.0 threading.Thread.__init__(self, name="TestThread") def run(self): """ overload of threading.thread.run() main control loop """ print "%s starts" % (self.getName(),) count = 0 while not self._stopevent.isSet(): count += 1 print "loop %d" % (count,) self._stopevent.wait(self._sleepperiod) print "%s ends" % (self.getName(),) def join(self,timeout=None): """ Stop the thread """ self._stopevent.set() threading.Thread.join(self, timeout) if __name__ == "__main__": testthread = TestThread() testthread.start() import time time.sleep(10.0) testthread.join() Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking for a full house
Paul Rubin wrote: > "Raymond Hettinger" <[EMAIL PROTECTED]> writes: > >>Your use case for gathering roll statistics probably needs a more >>general solution: >> >>hands = { >>(1,1,1,1,1): 'nothing', >>(1,1,1,2): 'one pair', >>(1,2,2): 'two pair', >>(1,1,3): 'three of a kind', >>(2,3): 'full house', >>(1,4): 'four of a kind', >>(5): 'flush (five of a kind)' >>} >> >>def eval_hand(hand): >>counts = tuple(sorted(hand.count(card) for card in set(hand))) >>return hands.get(counts, 'misdeal') > > > 1. "Flush" means 5 cards of the same suit (i.e. all hearts), not 5 of >a kind. > > 2. That code doesn't detect flushes or straights. It would be interesting to see how complicated it would get to write code to detect the correct hands in poker with wildcards included. I tried that a year or 2 ago when i wanted to write a pokergame in java but i failed miserably in doing so. I have a gut feeling that with python this is easier. I might give it another go. Is there any of such code available somewhere? The reason i wanted to do so is that there isn't a game that allows a player to specify it's own games. I wanted to make a simple network enabled game with simple graphics and scriptable poker games via a wizard. But as i said, i first wanted to construct my "card" code to deal, evaluate a hand and compare 2 or more hands, and to find the highest hand in a number of hands. And all this with wildcards, cards in the hands varying from 5 to 7 and high low. I toyed with on several occasions but never could seem to find an easy way to do it. Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking for a full house
Raymond Hettinger wrote: > [Benedict] > >>>It would be interesting to see how complicated it would get to write >>>code to detect the correct hands in poker with wildcards included. > > > There is an interesting SF project with code written in C: > http://pokersource.sourceforge.net/ > > In contrast, Python makes short work of these kind of problems. Here > are some primitives to get you started (just add a representation for > suits, flush detection, and controlling logic for ranking hands): > > def is_straight(hand, numwildcards=0): > """Checks for a five card straight > > Inputs: list of non-wildcards plus wildcard count > 2,3,4, ... 10, 11 for Jack, 12 for Queen, > 13 for King, 14 for Ace > Hand can be any length (i.e. it works for seven card games). > > Outputs: highest card in a five card straight > or 0 if not a straight. > Original list is not mutated. > Ace can also be a low card (i.e. A2345). > > >>> is_straight([14,2,3,4,5]) > 5 > >>> is_straight([14,2,3,4,6]) > 0 > >>> is_straight([10,11,12,13,14]) > 14 > >>> is_straight([2,3,5], 2) > 6 > >>> is_straight([], 5) > 14 > >>> is_straight([2,4,6,8,10], 3) > 12 > >>> is_straight([2,4,4,5,5], 2) > 6 > """ > > hand = set(hand) > if 14 in hand: > hand.add(1) > for low in (10,9,8,7,6,5,4,3,2,1): > needed = set(range(low, low+5)) > if len(needed & hand) + numwildcards >= 5: > return low+4 > return 0 > > > > def groups(hand, numwildcards=0): > """Checks for pairs, threes-of-kind, fours-of-a-kind, >and fives-of-a-kind > > Inputs: list of non-wildcards plus wildcard count > 2,3,4, ... 10, 11 for Jack, 12 for Queen, > 13 for King, 14 for Ace > Hand can be any length (i.e. it works for seven card games) > Output: tuple with counts for each value (high cards first) > for example (3, 14), (2, 11) full-house Aces over Jacks > for example (2, 9), (2, 7)two-pair Nines and Sevens > Maximum count is limited to five (there is no seven of a kind). > Original list is not mutated. > > >>> groups([11,14,11,14,14]) > [(3, 14), (2, 11)] > >>> groups([7, 9, 10, 9, 7]) > [(2, 9), (2, 7)] > >>> groups([11,14,11,14], 1) > [(3, 14), (2, 11)] > >>> groups([9,9,9,9,8], 2) > [(5, 9), (2, 8)] > >>> groups([], 7) > [(5, 14), (2, 13)] > """ > > result = [] > counts = [(hand.count(v), v) for v in range(2,15)] > for c, v in sorted(counts, reverse=True): > newcount = min(5, c + numwildcards) # Add wildcards upto five > numwildcards -= newcount - c# Wildcards remaining > if newcount > 1: > result.append((newcount, v)) > return result > > > > import doctest > print doctest.testmod() > Wow Raymond that's amazing ! Makes we feel stupid, happy and in awe of python at the same time. I only felt this weird before when i got married :) I will have a good look at your code. Excellent :) Regards, Benedict Verheyen -- http://mail.python.org/mailman/listinfo/python-list
using timeit for a function in a class
Hi, i tried to use timeit on a function in a class but it doesn't do what i think it should do ie. time :) In stead it starts printing line after line of hello time test! What am i doing wrong in order to time the f function? class TimeTest(object): def f(self): print "hello time test!" if __name__ == '__main__': from timeit import Timer s = """ test = TimeTest() test.f() """ t = Timer(s,"from __main__ import TimeTest") print t.timeit() Regards, Benedict Verheyen -- http://mail.python.org/mailman/listinfo/python-list
Re: using timeit for a function in a class
Fredrik Lundh wrote: > "flupke" wrote: > > >>i tried to use timeit on a function in a class but it doesn't do what i >>think it should do ie. time :) >>In stead it starts printing line after line of hello time test! >>What am i doing wrong in order to time the f function? > > > how do you expect timeit to figure out how long it takes to run your > function without calling the function? > > >>class TimeTest(object): >>def f(self): >>print "hello time test!" > > > > > > ? i think you missed some of the code ... s = """ test = TimeTest() test.f() """ ... So the function is being called (as i said, it prints the hello message). Regards, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: using timeit for a function in a class
Kent Johnson wrote: > flupke wrote: > >> >> Hi, >> >> i tried to use timeit on a function in a class but it doesn't do what >> i think it should do ie. time :) >> In stead it starts printing line after line of hello time test! >> What am i doing wrong in order to time the f function? > > > Hmm, by default Timer.timeit() calls the function being timed 100 > times. That's a lot of "hello time test" =:-) > > Kent Hehe, thanks Kent. Need to drink more coffee and train the eyes more, a new goal in life :) print t.timeit(1) did the trick. Regards, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: How to restrict lenght of entry widget to certain number of character
Michael Onfrek wrote: > Hi! > I'm playing with entry again and trying to restrict length of entry > widget to certain number of character, so users cannot enter more > character into it. Any ideas? > Reg. Michael Onfrek > What widget set are you talking about, wxPython pygtk, tkinter? In wxPython: .SetMaxLength(length) Benedict -- http://mail.python.org/mailman/listinfo/python-list
(OT) lincense protection generator
I'm going to be distributing a program based on wxPython & python in a few weeks time. The code will run on windows machines. Because i don't want the users to move the folders around or mess with the program or taking copies home to fiddle with it, i was thinking of a way to check when the program starts that it's still on the same directory and same computer. That way i at least avoid unnecessary phone calls asking me for help when they messed the program up. I'm thinking of a function that will generate such a code and put it in a file. Then when the program starts it checks this file and checks the code in there with a code that it generates at that time again based for instance on the current directory and other components unique to that computer. It could be a long string (but what info?) and then take a hash from it and store the hash value. How could i construct such a code without being a total pain? For instance i don't want to check for anything hardware related because then my program would fail to work once the people change their hardware. Anyway, it doesn't need to be waterproof. (not possible anyway) Any ideas? Regards, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: (OT) lincense protection generator
Jarek Zgoda wrote: > flupke napisaĆ(a): > >> I'm thinking of a function that will generate such a code and put it >> in a file. Then when the program starts it checks this file and checks >> the code in there with a code that it generates at that time again >> based for instance on the current directory and other components >> unique to that computer. It could be a long string (but what info?) >> and then take a hash from it and store the hash value. > > > Better, generate sha1 sum of general machine configuration (i.e. what > "set" command returns) and store it on random internet node. You can be > sure nobody would get it. > > Anyway, it's bad idea. Restrict program usage in license) or any other > contract), but don't do such a mess to people who pay your bills. > Well as i said it's more to see when they tampered with the config or the program. It's not a commercial application but it's for inhouse use in the hospital where i work. These people are, to put it mildly, not the most computer savant people around. It could be handy to avoid me searching for a solution to a problem that arises because of messing with the setup rather than a bug in the code. Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: (OT) lincense protection generator
flupke wrote: Thanks for the good ideas people. Regards, Benedict -- http://mail.python.org/mailman/listinfo/python-list
poker card game revisited (code included)
Hi, i've included the code so interested people can take a look. I've tried to expand on the thread of 26/05/2005 on "Checking for a full house". Code is suboptimal as I coded it rather quickly. I've added the "normal" classes one would expect from a cardgame: card, deck, hand etc. 1. I can detect most things except a straightflush. The problem with the code now is that it only returns 1 straight which is enough for mere "straight" detection but won't suffice for hand comparison and especially detecting straight flushes. For use in straight flush detection, the function would need to return all possible straights and then these would need to be checked to see if they are flushes. For instance a list [4,4,5,5,6,7,8] yields 4 different straights. A hand like [4,4,5,5,6,7,8,9] gets even worse. I can't see how i can do this using sets, i'll need to come up with another method since the suit is important. 2. Hand comparison. For this to succeed the getrank function would need to return the exact 5 cards that represent the highest hand. This could be less than 5 cards if one uses wildcards. Then you not only have the correct rank but also the highest hand so you can compare in case there are ties. 3. x wild. For games like "deuces wild", what would be the best way to manage those? I tought about removing them from a hand before shipping it of to the getrank function? Any ideas? Regards, Benedict Verheyen = CODE = """ Attempt for a poker cardgame representation Benedict Verheyen Code additions from web (http://www.ibiblio.org/obp/thinkCSpy/) and newsgroup comp.lang.python esp. Raymond Hettinger """ import random class Card(object): """ Represents a single card 2,3,4, ... 10, 11 for Jack, 12 for Queen, 13 for King, 14 for Ace """ suitList = ["Clubs", "Diamonds", "Hearts", "Spades"] rankList = [ "narf", "narf", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"] def __init__(self, suit=0, rank=0): """ Initialise a card @type suit: int @param suit: suit of the card (see suitList) @type rank: int @param rank: rank of the card (see rankList) """ self.suit = suit self.rank = rank def __str__(self): """ Pretty print a card """ return self.rankList[self.rank] + " of " + self.suitList[self.suit] def __cmp__(self, other): """ Compare 2 cards @type other: card @param other: the card to compare with """ # check the suits if self.suit > other.suit: return 1 if self.suit < other.suit: return -1 # suits are the same... check ranks if self.rank > other.rank: return 1 if self.rank < other.rank: return -1 # ranks are the same... it's a tie return 0 class Deck(object): """ Represents a deck of cards. We can have different decks of cards """ DECK_NORMAL = 1 # 52 cards def __init__(self,decktype=DECK_NORMAL): """ Makes a deck of cards @type decktype: type of deck @param decktype: what type of deck is it? (DECK_NORMAL,...) """ self.cards = [] for suit in range(4): for rank in range(2, 15): self.cards.append(Card(suit, rank)) def printdeck(self): """ Pretty print the deck """ for card in self.cards: print card def __str__(self): """ Pretty print the deck """ s = "" for i in range(len(self.cards)): s = s + " "*i + str(self.cards[i]) + "\n" return s def sort(self,rank=True,suit=False): """ Sort the deck """ def sortonrank(x,y): if x.rank > y.rank: return 1 if x.rank < y.rank: return -1 return 0 def sortonsuit(x,y): if x.suit > y.suit: return 1 if x.suit < y.suit: return -1 return 0 def sortonboth(x,y): return cmp(x,y) if ( rank == True and suit == False): self.cards.sort(sortonrank) elif ( suit == True and rank == False ): self.cards.sort(sortonsuit) else: self.cards.sort(sortonboth) # roept sort van card op def shuffle(self,nshuffle=1): """ Shuffle the deck of cards. This happens by swapping cards @type nshuffle: int @param nshuffle: how many times do we shuffle """ import random nCards = len(self.cards) # swap cards on place i and j for shuffle in range(nshuffle): print " shuffle %s " % shuffle for i in range(nCards): j = random.randrange(i, nCards) [sel
poker card game revisited (code included)
Hi, i've included the code so interested people can take a look. I've tried to expand on the thread of 26/05/2005 on "Checking for a full house". Code is suboptimal as I coded it rather quickly. I've added the "normal" classes one would expect from a cardgame: card, deck, hand etc. 1. I can detect most things except a straightflush. The problem with the code now is that it only returns 1 straight which is enough for mere "straight" detection but won't suffice for hand comparison and especially detecting straight flushes. For use in straight flush detection, the function would need to return all possible straights and then these would need to be checked to see if they are flushes. For instance a list [4,4,5,5,6,7,8] yields 4 different straights. A hand like [4,4,5,5,6,7,8,9] gets even worse. I can't see how i can do this using sets, i'll need to come up with another method since the suit is important. 2. Hand comparison. For this to succeed the getrank function would need to return the exact 5 cards that represent the highest hand. This could be less than 5 cards if one uses wildcards. Then you not only have the correct rank but also the highest hand so you can compare in case there are ties. 3. x wild. For games like "deuces wild", what would be the best way to manage those? I tought about removing them from a hand before shipping it of to the getrank function? Any ideas? Regards, Benedict Verheyen = CODE = """ Attempt for a poker cardgame representation Benedict Verheyen Code additions from web (http://www.ibiblio.org/obp/thinkCSpy/) and newsgroup comp.lang.python esp. Raymond Hettinger """ import random class Card(object): """ Represents a single card 2,3,4, ... 10, 11 for Jack, 12 for Queen, 13 for King, 14 for Ace """ suitList = ["Clubs", "Diamonds", "Hearts", "Spades"] rankList = [ "narf", "narf", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"] def __init__(self, suit=0, rank=0): """ Initialise a card @type suit: int @param suit: suit of the card (see suitList) @type rank: int @param rank: rank of the card (see rankList) """ self.suit = suit self.rank = rank def __str__(self): """ Pretty print a card """ return self.rankList[self.rank] + " of " + self.suitList[self.suit] def __cmp__(self, other): """ Compare 2 cards @type other: card @param other: the card to compare with """ # check the suits if self.suit > other.suit: return 1 if self.suit < other.suit: return -1 # suits are the same... check ranks if self.rank > other.rank: return 1 if self.rank < other.rank: return -1 # ranks are the same... it's a tie return 0 class Deck(object): """ Represents a deck of cards. We can have different decks of cards """ DECK_NORMAL = 1 # 52 cards def __init__(self,decktype=DECK_NORMAL): """ Makes a deck of cards @type decktype: type of deck @param decktype: what type of deck is it? (DECK_NORMAL,...) """ self.cards = [] for suit in range(4): for rank in range(2, 15): self.cards.append(Card(suit, rank)) def printdeck(self): """ Pretty print the deck """ for card in self.cards: print card def __str__(self): """ Pretty print the deck """ s = "" for i in range(len(self.cards)): s = s + " "*i + str(self.cards[i]) + "\n" return s def sort(self,rank=True,suit=False): """ Sort the deck """ def sortonrank(x,y): if x.rank > y.rank: return 1 if x.rank < y.rank: return -1 return 0 def sortonsuit(x,y): if x.suit > y.suit: return 1 if x.suit < y.suit: return -1 return 0 def sortonboth(x,y): return cmp(x,y) if ( rank == True and suit == False): self.cards.sort(sortonrank) elif ( suit == True and rank == False ): self.cards.sort(sortonsuit) else: self.cards.sort(sortonboth) # roept sort van card op def shuffle(self,nshuffle=1): """ Shuffle the deck of cards. This happens by swapping cards @type nshuffle: int @param nshuffle: how many times do we shuffle """ import random nCards = len(self.cards) # swap cards on place i and j for shuffle in range(nshuffle): print " shuffle %s " % shuffle for i in r
poker card game revisited (code included)
Hi, i've included the code so people can take a look. I've tried to expand on the thread of 26/05/2005 on "Checking for a full house". Code is suboptimal as I coded it rather quickly. I've added the "normal" classes one would expect from a cardgame: card, deck, hand etc. 1. I can detect most things except a straightflush. The problem with the code now is that it only returns 1 straight which is enough for mere "straight" detection but won't suffice for hand comparison and especially detecting straight flushes. For use in straight flush detection, the function would need to return all possible straights and then these would need to be checked to see if they are flushes. For instance a list [4,4,5,5,6,7,8] yields 4 different straights. A hand like [4,4,5,5,6,7,8,9] gets even worse. I can't see how i can do this using sets, i'll need to come up with another method since the suit is important. 2. Hand comparison. For this to succeed the getrank function would need to return the exact 5 cards that represent the highest hand. This could be less than 5 cards if one uses wildcards. Then you not only have the correct rank but also the highest hand so you can compare in case there are ties. 3. x wild. For games like "deuces wild", what would be the best way to manage those? I tought about removing them from a hand before shipping it of to the getrank function? Any ideas? Regards, Benedict Verheyen = CODE = """ Attempt for a poker cardgame representation Benedict Verheyen Code additions from web (http://www.ibiblio.org/obp/thinkCSpy/) and newsgroup comp.lang.python esp. Raymond Hettinger """ import random class Card(object): """ Represents a single card 2,3,4, ... 10, 11 for Jack, 12 for Queen, 13 for King, 14 for Ace """ suitList = ["Clubs", "Diamonds", "Hearts", "Spades"] rankList = [ "narf", "narf", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"] def __init__(self, suit=0, rank=0): """ Initialise a card @type suit: int @param suit: suit of the card (see suitList) @type rank: int @param rank: rank of the card (see rankList) """ self.suit = suit self.rank = rank def __str__(self): """ Pretty print a card """ return self.rankList[self.rank] + " of " + self.suitList[self.suit] def __cmp__(self, other): """ Compare 2 cards @type other: card @param other: the card to compare with """ # check the suits if self.suit > other.suit: return 1 if self.suit < other.suit: return -1 # suits are the same... check ranks if self.rank > other.rank: return 1 if self.rank < other.rank: return -1 # ranks are the same... it's a tie return 0 class Deck(object): """ Represents a deck of cards. We can have different decks of cards """ DECK_NORMAL = 1 # 52 cards def __init__(self,decktype=DECK_NORMAL): """ Makes a deck of cards @type decktype: type of deck @param decktype: what type of deck is it? (DECK_NORMAL,...) """ self.cards = [] for suit in range(4): for rank in range(2, 15): self.cards.append(Card(suit, rank)) def printdeck(self): """ Pretty print the deck """ for card in self.cards: print card def __str__(self): """ Pretty print the deck """ s = "" for i in range(len(self.cards)): s = s + " "*i + str(self.cards[i]) + "\n" return s def sort(self,rank=True,suit=False): """ Sort the deck """ def sortonrank(x,y): if x.rank > y.rank: return 1 if x.rank < y.rank: return -1 return 0 def sortonsuit(x,y): if x.suit > y.suit: return 1 if x.suit < y.suit: return -1 return 0 def sortonboth(x,y): return cmp(x,y) if ( rank == True and suit == False): self.cards.sort(sortonrank) elif ( suit == True and rank == False ): self.cards.sort(sortonsuit) else: self.cards.sort(sortonboth) # roept sort van card op def shuffle(self,nshuffle=1): """ Shuffle the deck of cards. This happens by swapping cards @type nshuffle: int @param nshuffle: how many times do we shuffle """ import random nCards = len(self.cards) # swap cards on place i and j for shuffle in range(nshuffle): print " shuffle %s " % shuffle for i in range(nCards
Re: poker card game revisited (code included)
Erik Max Francis wrote: > flupke wrote: > First of all, my apologies for the double posts. I can only see this reply and can't see my original messages. I posted the message from home and work and they didn't show up. We use the same isp at home and at work so it's probably a problem on their end. > It looks like you're not approaching this in a systematic manner. > Algorithms for determining poker hands are already pretty well-known; > there are several open source projects that do it efficiently which you > could learn from. Which projects are you talking about? I only found a library in c to evaluat ranks but i didn't find the code to be very understandable. > When you're evaluating poker hands, you're looking for three basic types > of card groups: matches, straights, and flushes. The most efficient > way to look for matches is with a histogram based on the card rank. Bin > the cards up by rank, and then build a second "histogram" of the counts > of those ranks indexing into a list of the ranks which had those cards > (sorted by rank, so you can pull off the highest ones). Now determining > all the rank-based hands is easy: quads have a hit with four matches, a > boat has a hit with two three matches (there's no "two trips" so this is > a boat at best) or both three and two matches, two pair has two hits > with two matches, etc. With histogram do you mean something like this: Card hand: 2 clubs, 3 diamonds, 10 of diamonds, 4 of hearts, 3 of hearts Histogram 1: list [2,3,4,10] 2 - 14 Histogram 2: list [1,2,1,0,0,0,0,0,1,0,0,0,0] or list [1,2,1,1] so index 0 is count of rank at index 0 of Histogram 1 index 1 is count of rank at index 1 of Histogram 1 > Searching for straights and flushes is much better done by masks. > Arrange all the possible cards in a huge masks based on both cards and > ranks (easy to do in Python with the long type) and then build up rank > masks that build up all possible straight combinations (sorted by the > highest rank so you can search them in order), and then build up card > mask ranks for each suit. For straights, just iterate through the > straight rank masks and see if you find one that's fully occupied; if > you do, that's a straight. For flushes, just iterate through the card > suit masks and see if you find one that has more five or more unique > cards in it. You need to iterate through all four and find the one with > the highest value (for games with lots of cards, you could have two > flushes; you want to count the highest one). Finally, to look for > straight flushes, first apply the suit masks and then turn it into ranks > and apply the straight masks. As for straights, if i understand correctly, you make all possible straights of the cards in the hand and then see if one matches? > Then will all this information you can easily arrange the code to select > the best existing hand. Note that these all use well-established > techniques and reveal nothing secret. Well, it's all new to me :) Regards, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: poker card game revisited (code included)
Erik Max Francis wrote: > flupke wrote: > >> Which projects are you talking about? I only found a library in c to >> evaluat ranks but i didn't find the code to be very understandable. > > > pokersource is the main was I was thinking about, yes. > >> With histogram do you mean something like this: >> Card hand: 2 clubs, 3 diamonds, 10 of diamonds, 4 of hearts, 3 of hearts >> >> Histogram 1: list [2,3,4,10] >> 2 - 14 >> Histogram 2: list [1,2,1,0,0,0,0,0,1,0,0,0,0] >> or >> list [1,2,1,1] >> so index 0 is count of rank at index 0 of Histogram 1 >> index 1 is count of rank at index 1 of Histogram 1 > > > Histograms usually involve putting things in bins and counting the > number by bin. Here the bins are just the ranks of the cards, and so > you're counting the frequency of the ranks. Once that's done, you want > to arrange the frequencies into a mapping of its own, which points to > the list of ranks that have that frequency. That way you can easily > pick things off: If there is a hit in the four bin, you have quads. If > there's a hit in the three bin and either another in the three or one in > the two bin, you have a boat. If there's a hit in the three bin but > _not_ another in three or two, then it's trips. And so on. > >> As for straights, if i understand correctly, you make all possible >> straights of the cards in the hand and then see if one matches? > > > Not quite. You break down the cards by what matters -- ranks and suits > -- and then make sets based on these. Then, standing by, you have the > sets of valid straights (by rank), and then to test for straights, you > iterate through the straight sets and make intersections with the rank > set for the hand in question. If the intersection is the same as the > straight set, then it's a straight. (Do this by reverse order of the > relative values of the straights, and stop when you find the first one, > to get the highest straight.) The most efficient way to do this is with > a bitmask, so that's how it's usually done. > Thanks for the info. I succeeded in doing a straight flush check yesterday but not using the method described. My code works now but using bitmasks might actually be faster to use for hand detection and comparison. I'm not sure that it will be easier to read and understand the code though. I'll play a bit with bitmasks and see what gives. Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: poker card game revisited (code included)
John Hazen wrote: > [Erik Max Francis] > >>>>Searching for straights and flushes is much better done by masks. > > > Interesting. I've been thinking about playing with this stuff too, but > hadn't considered masks. So each card has a representation: > > n bits for rank, then m bits for suit. > > 10 0001 = 2 clubs > 01 1000 = K spades > ... > > [flupke] > >>>As for straights, if i understand correctly, you make all possible >>>straights of the cards in the hand and then see if one matches? > > > Yeah, I originally thought that's what you meant, too. But if you take > the scheme above, and sort the cards before you merge them into the > hand-bits aggregate, then you can just have *one* mask for straights, > and shift it down by a bit each time you check. So the best straight > mask (A high) would be (ignoring suit bits): > > 10 01 001000 000100 10 > > Then this could be shifted right for a K-high straight: > > 01 001000 000100 10 01 > > I guess that means that an Ace has to have the following representation, > since it can be both at the high and low end of a straight: > > 11 0100 = A hearts > > But this may mess with bit-counting shortcuts for other calculations... > > This is interesting to think about. Thanks for the pointer. I'm also > going to look at pokersource, though I may put that off until I at least > partially re-invent the wheel for learning purposes. > > -John I haven't had to much time to play around with it either and i agree it's fascinating. However my code now detects high hands properly (need to do low hands too and check the wildcards some more. I really need to build a test suit) and i find it quite readable code. Why would you want to start messing with bits in python? It feels like a pure c++ approach. Check the way the straight is checked in the code posted here. It's very readable and i doubt you can make it as readable using bitmasks. I do think that bitmasks are going to be faster but i could program the hand checking stuff fairly quick something that would require a lot more work when doing the same with bitmasks. Anyway, i'm still interested in that approach and i will try it whenever i've got the time. Haven't seen a lot of python code that uses bitmasks though. Maybe the pokersource C/C++ code can be wrapped in python? :) Regards, Benedict -- http://mail.python.org/mailman/listinfo/python-list
postgres backup script and popen2
Hi, i made a backup script to backup my postgres database. Problem is that it prompts for a password. It thought i could solve this by using popen2. I tested popen2 with dir (i'm on windows 2000, python 2.4.3) and it works. However when i try popen2 and my pg_dump command, it prompts for a password and I was under the impression that i was going to be able to dynamically communicate with the process. sin, sout = popen2(backup_command) sin.readline() # the password prompt sout.write("password") sin.readlines() How can i catch the password prompt and feed the password from my code? Thanks, Benedict -- http://mail.python.org/mailman/listinfo/python-list
Re: postgres backup script and popen2
flupke schreef: Thanks for all the info. I'm sure i will get it right this time :) Benedict -- http://mail.python.org/mailman/listinfo/python-list