Re: HELP - uninstall pyton error
give more details OS, Python Version, Method of installation.. etc.. On 10/7/21 17:18, Almadar Plus wrote: Could you please help me uninstall python? see attached screenshots files Regards -- https://mail.python.org/mailman/listinfo/python-list
Create a class at run-time
Hi everyone, I'm trying to dynamically create a class. What I need is to define a class, add methods to it and later instantiate this class. Methods need to be bound to the instance though, and that's my problem. Here is what I have so far: method_template = "def test_foo(self):\ #actual test_foo\ pass" exec method_template TestClass = types.ClassType("MyTestClass", (unittest.TestCase, ), {}) TestClass.__module__ = "test" now what to do next? I looked at types.MethodType but it needs an instance to bind the method and a function object. Should I define __new__ to bind the method during instantiation? Hope this makes sense, Michel. -- http://mail.python.org/mailman/listinfo/python-list
Re: Create a class at run-time
Well, I don't have the reference to the instance. The class is actually instantiated later by a the unittest library. On Mar 25, 6:18 pm, Michiel Overtoom wrote: > On 2010-03-25 23:00, Michel wrote: > > > I'm trying to dynamically create a class. What I need is to define a > > class, add methods to it and later instantiate this class. Methods > > need to be bound to the instance though, and that's my problem. > > Maybe this snippet is of any help? > > import functools > > class Template(object): > pass > > def printmyname(self): > print self.name > > t=Template() > t.name="Pete" > t.printmyname=functools.partial(printmyname,t) > > u=Template() > u.name="Mary" > u.printmyname=functools.partial(printmyname,u) > > t.printmyname() > u.printmyname() > > Greetings, > > -- > "The ability of the OSS process to collect and harness > the collective IQ of thousands of individuals across > the Internet is simply amazing." - Vinod > Valloppillilhttp://www.catb.org/~esr/halloween/halloween4.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Create a class at run-time
I want to add a method to a class such that it can be invoked on specifics instances. You solution works (as well as Patrick's one), thanks ! I still have a question though. If I print the type of the self object I get when my method is called, I get "". I guess this is because the method is defined as a class method. This is ok in my case, but just out of curiosity, what should I do to change this method to an instance method? Thanks for your help, Michel. On Mar 25, 9:53 pm, I V wrote: > On Thu, 25 Mar 2010 15:00:35 -0700, Michel wrote: > > I'm trying to dynamically create a class. What I need is to define a > > class, add methods to it and later instantiate this class. Methods need > > to be bound to the instance though, and that's my problem. Here is what > > I have so far: > > I'm not entirely sure what you mean by binding methods to the instance. > Do you mean you need to dynamically add methods to a specific instance? > Or that you need to add methods to a class, such that they can be invoked > on specific instances? For the latter, just do: > > TestClass.test_foo = test_foo > > For the former, try: > > tc = TestClass() > tc.test_foo = types.MethodType(test_foo, tc) -- http://mail.python.org/mailman/listinfo/python-list
Re: Create a class at run-time
Thanks Peter. I searched a little bit more and wrote the following example: import types class MyClass: def test_toto(self): print type(self) print self.name def test_toto(self): print type(self) print self.name MyDynClass = types.ClassType("MyDynClass", (object, ), {}) MyDynClass.__module__ = "test.complex.hierarchy" MyDynClass.test_toto = test_toto t1 = MyDynClass() t2 = MyDynClass() t1.name = "Marcel" t2.name = "Oscar" t1.test_toto() t2.test_toto() c1 = MyClass() c1.name = "Raoul" c1.test_toto() the output is: Marcel Oscar Raoul I'm wondering why the type of the self parameter is not 'instance' in the calls t1.test_toto() and t2.test_toto() The rest of the behavior is correct though, so I guess it's just internal Python stuff. Thanks for your help, Michel. On Mar 26, 1:29 pm, Peter Otten <__pete...@web.de> wrote: > Michel wrote: > > Hi everyone, > > > I'm trying to dynamically create a class. What I need is to define a > > class, add methods to it and later instantiate this class. Methods > > need to be bound to the instance though, and that's my problem. Here > > is what I have so far: > > > method_template = "def test_foo(self):\ > > #actual test_foo\ > > pass" > > exec method_template > > > TestClass = types.ClassType("MyTestClass", (unittest.TestCase, ), {}) > > TestClass.__module__ = "test" > > > now what to do next? > > Just assign it: > > >>> import unittest > >>> class MyTestClass(unittest.TestCase): pass > ... > >>> def test_foo(self): > > ... self.assertEquals(1, 2) > ...>>> MyTestClass.test_foo = test_foo # < > >>> unittest.main() > > F > == > FAIL: test_foo (__main__.MyTestClass) > -- > Traceback (most recent call last): > File "", line 2, in test_foo > AssertionError: 1 != 2 > > -- > Ran 1 test in 0.000s > > FAILED (failures=1) > > If you don't know the method name beforehand use > > setattr(MyTestClass, method_name, method), e. g: > > >>> import unittest > >>> class MyTestClass(unittest.TestCase): pass > > ... >>> def make_method(n): > > ... def test(self): self.assertEquals(2, n) > ... return test > ...>>> for i in range(3): > > ... setattr(MyTestClass, "test_%d" % i, make_method(i)) > ...>>> unittest.main() > > FF. > == > FAIL: test_0 (__main__.MyTestClass) > -- > Traceback (most recent call last): > File "", line 2, in test > AssertionError: 2 != 0 > > == > FAIL: test_1 (__main__.MyTestClass) > -- > Traceback (most recent call last): > File "", line 2, in test > AssertionError: 2 != 1 > > -- > Ran 3 tests in 0.000s > > FAILED (failures=2) > > Peter -- http://mail.python.org/mailman/listinfo/python-list
Relocatable python install
Hi, I would like to create a binary package of python that we will ship with our product. I need to be able to install the package anywhere in the file system. The interpreter seems to be ok with that, but a few other tools that are installed in the PREFIX/bin directory (pydoc, py2to3, python- config,...) contain hardcoded path to the interpreter. Is there a way around that? Or an configure option to prevent these files to be installed? Regards, Michel. -- http://mail.python.org/mailman/listinfo/python-list
Making `logging.basicConfig` log to *both* `sys.stderr` and `sys.stdout`?
Hi, I use python oftentimes to write automation scripts on Linux servers. And there's a big pattern in my scripts: - I *always* use `logging` instead of `print` statements. - I *always* create two stream handlers. One for `sys.stdout` with level `INFO` and one for `sys.stderr` with level `WARN` Well, the levels may variate occasionally, but that's only the rare exception. The reason I do this is simple: Most automation tasks are run via cron. With this setup, I can redirect `stdout` to `/dev/null` and still receive e-mails if things go wrong. And having two handlers gives me more flexibility in my scripts. In one case, I used a different color for error messages for example as this script is run primarily from the shell and having errors stand out has proven to be a good thing. Unfortunately this setup makes `logging.basicConfig` pretty useless. However, I believe that this is something that more people could benefit from. I also believe, that it just "makes sense" to send warnings (and above) to `stderr`, the rest to `stdout`. So I was thinking: "Why does `logging.basicConfig` not behave that way". Naturally, I was thinking of writing a patch against the python codebase and submit it as a suggestion. But before doing so, I would like to hear your thoughts on this. Does it make sense to you too or am I on the wrong track? Are there any downsides I am missing? -- http://mail.python.org/mailman/listinfo/python-list
Re: Making `logging.basicConfig` log to *both* `sys.stderr` and `sys.stdout`?
On Aug 30, 11:45 am, Peter Otten <__pete...@web.de> wrote: > Michel Albert wrote: > > I use python oftentimes to write automation scripts on Linux servers. > > And there's a big pattern in my scripts: > > > - I *always* use `logging` instead of `print` statements. > > - I *always* create two stream handlers. One for `sys.stdout` with > > level `INFO` and one for `sys.stderr` with level `WARN` > > > Well, the levels may variate occasionally, but that's only the rare > > exception. > > How would a call to basicConfig() look like that produces this setup? I personally see this happen by default (i.e. no additional parameters). And in case the `stream` parameter is set, /then/ you would send all to that stream only. In my point of view, the call to `basicConfig` is either something used in only the most mundane usages of the logging package, or it's mainly used by people that have not yet grokked the logging package (correct me if I'm wrong). In both cases, I find it useful to redirect warnings and errors to `stderr` by default. However, this would also mean that existing code calling this method would result in different behavior. But only /slightly/ different. Meaning, you still see the output on the console as expected. But it gives you the possibility to use standard shell redirection in a way that "makes sense". -- http://mail.python.org/mailman/listinfo/python-list
Re: matplotlib graph white space
u can adjust any side with the other options... (margins) if you don t want to use tight layout... On 21/10/04 11:39AM, Steve wrote: > > Yes, I saw that but it is a change for all sides. > Is there a setting to change just the left and right padding? > > > > > -Original Message- > From: Michel Alwan > Sent: Monday, October 4, 2021 7:56 AM > To: Steve > Cc: python-list@python.org > Subject: Re: matplotlib graph white space > > In the plot window, you can click on the settings (up), and select the > option "tight layout" by pressing that button... I think this is what you > are looking for... > > > On 21/10/04 04:39AM, Steve wrote: > > > > I am using the first bar graph listed at this site: > > https://matplotlib.org/stable/gallery/index.html > > > > The problem I have is that there is too much white space around the graph. > > My data would be better displayed if I could widen the graph into the > > space to the right and left of the chart. > > > > Steve > > > > -- > > https://mail.python.org/mailman/listinfo/python-list > > -- > Michel Alwan > > > ( support Stallman : stallmansupport.org ) > -- Michel Alwan ( support Stallman : stallmansupport.org ) -- https://mail.python.org/mailman/listinfo/python-list
Re: matplotlib graph white space
In the plot window, you can click on the settings (up), and select the option "tight layout" by pressing that button... I think this is what you are looking for... On 21/10/04 04:39AM, Steve wrote: > > I am using the first bar graph listed at this site: > https://matplotlib.org/stable/gallery/index.html > > The problem I have is that there is too much white space around the graph. > My data would be better displayed if I could widen the graph into the space > to the right and left of the chart. > > Steve > > -- > https://mail.python.org/mailman/listinfo/python-list -- Michel Alwan ( support Stallman : stallmansupport.org ) -- https://mail.python.org/mailman/listinfo/python-list
Re: [python-win32] on the way to find pi!
Hi ! Very more simplistic, but easy for to code : def pi(nb): cpi=0 for i in xrange(1,nb,4): cpi=cpi+4./i-4./(i+2.) return(cpi) print pi(99) @-salutations -- Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: wxgrid multiline cell editor
"James" <[EMAIL PROTECTED]> a écrit dans le message de news:[EMAIL PROTECTED] > wxpython 2.5.3 > anyone know how to make a multiline cell editor for wxgrid? Hello, You can do that by a "wxGridCellAutoWrapStringEditor". You can test it by modifying GridSimple.py in the demo by adding (at line 24 in my version): self.SetRowSize(1, 45) self.SetCellEditor(1, 1, wxGridCellAutoWrapStringEditor()) Save it and now, when you launch the gridsimple in the demo (it's in core windows control), you can enter multiple lines in the cell containing "Another cell". It works in 2.4.2.4. I think it should also in 2.5. I join the whole program. Have fun. ++jm #--- from wxPython.wx import * from wxPython.grid import * from wxPython.lib.mixins.grid import wxGridAutoEditMixin #--- class SimpleGrid(wxGrid): ##, wxGridAutoEditMixin): def __init__(self, parent, log): wxGrid.__init__(self, parent, -1) ##wxGridAutoEditMixin.__init__(self) self.log = log self.moveTo = None EVT_IDLE(self, self.OnIdle) self.CreateGrid(25, 25) #, wxGrid.wxGridSelectRows) ##self.EnableEditing(False) # simple cell formatting self.SetColSize(3, 200) self.SetRowSize(4, 45) self.SetCellValue(0, 0, "First cell") self.SetCellValue(1, 1, "Another cell") self.SetRowSize(1, 45) self.SetCellEditor(1, 1, wxGridCellAutoWrapStringEditor()) self.SetCellValue(2, 2, "Yet another cell") self.SetCellValue(3, 3, "This cell is read-only") self.SetCellFont(0, 0, wxFont(12, wxROMAN, wxITALIC, wxNORMAL)) self.SetCellTextColour(1, 1, wxRED) self.SetCellBackgroundColour(2, 2, wxCYAN) self.SetReadOnly(3, 3, True) self.SetCellEditor(5, 0, wxGridCellNumberEditor(1,1000)) self.SetCellValue(5, 0, "123") self.SetCellEditor(6, 0, wxGridCellFloatEditor()) self.SetCellValue(6, 0, "123.34") self.SetCellEditor(7, 0, wxGridCellNumberEditor()) self.SetCellValue(6, 3, "You can veto editing this cell") # attribute objects let you keep a set of formatting values # in one spot, and reuse them if needed attr = wxGridCellAttr() attr.SetTextColour(wxBLACK) attr.SetBackgroundColour(wxRED) attr.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxBOLD)) # you can set cell attributes for the whole row (or column) self.SetRowAttr(5, attr) self.SetColLabelValue(0, "Custom") self.SetColLabelValue(1, "column") self.SetColLabelValue(2, "labels") self.SetColLabelAlignment(wxALIGN_LEFT, wxALIGN_BOTTOM) #self.SetDefaultCellOverflow(False) #r = wxGridCellAutoWrapStringRenderer() #self.SetCellRenderer(9, 1, r) # overflow cells self.SetCellValue( 9, 1, "This default cell will overflow into neighboring cells, but not if you turn overflow off."); self.SetCellSize(11, 1, 3, 3); self.SetCellAlignment(11, 1, wxALIGN_CENTRE, wxALIGN_CENTRE); self.SetCellValue(11, 1, "This cell is set to span 3 rows and 3 columns"); editor = wxGridCellTextEditor() editor.SetParameters('10') self.SetCellEditor(0, 4, editor) self.SetCellValue(0, 4, "Limited text") # test all the events EVT_GRID_CELL_LEFT_CLICK(self, self.OnCellLeftClick) EVT_GRID_CELL_RIGHT_CLICK(self, self.OnCellRightClick) EVT_GRID_CELL_LEFT_DCLICK(self, self.OnCellLeftDClick) EVT_GRID_CELL_RIGHT_DCLICK(self, self.OnCellRightDClick) EVT_GRID_LABEL_LEFT_CLICK(self, self.OnLabelLeftClick) EVT_GRID_LABEL_RIGHT_CLICK(self, self.OnLabelRightClick) EVT_GRID_LABEL_LEFT_DCLICK(self, self.OnLabelLeftDClick) EVT_GRID_LABEL_RIGHT_DCLICK(self, self.OnLabelRightDClick) EVT_GRID_ROW_SIZE(self, self.OnRowSize) EVT_GRID_COL_SIZE(self, self.OnColSize) EVT_GRID_RANGE_SELECT(self, self.OnRangeSelect) EVT_GRID_CELL_CHANGE(self, self.OnCellChange) EVT_GRID_SELECT_CELL(self, self.OnSelectCell) EVT_GRID_EDITOR_SHOWN(self, self.OnEditorShown) EVT_GRID_EDITOR_HIDDEN(self, self.OnEditorHidden) EVT_GRID_EDITOR_CREATED(self, self.OnEditorCreated) def OnCellLeftClick(self, evt): self.log.write("OnCellLeftClick: (%d,%d) %s\n" % (evt.GetRow(), evt.GetCol(), evt.GetPosition())) evt.Skip() def OnCellRightClick(self, evt): self.log.write("OnCellRightClick: (%d,%d) %s\n" % (evt.GetRow(), evt.GetCol(), evt.GetPosition())) evt.Skip() def OnCellLeftDClick(self, evt): self.log.write("OnCellLeftDClick: (%d,%d) %s\n" % (evt.GetRow(), evt.GetCol(), evt.GetPosition())) evt.Skip() def OnCel
Re: python equivalent to access reports
"flupke" <[EMAIL PROTECTED]> a écrit dans le message de news:[EMAIL PROTECTED] > 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. > > Any other ideas? Hello, You can use wxwindows (http://www.wxpython.org/) which have some very nice report classes. If you want to know more, you just have to download and try the demo. ++jm -- http://mail.python.org/mailman/listinfo/python-list
Re: goto, cls, wait commands
"BOOGIEMAN" <[EMAIL PROTECTED]> a écrit dans le message de news:[EMAIL PROTECTED] > I've just finished reading Python turtorial for non-programmers > and I haven't found there anything about some usefull commands I used in > QBasic. First of all, what's Python command equivalent to QBasic's "goto" ? > Secondly, how do I clear screen (cls) from text and other content ? > And last, how do I put program to wait certain amount of seconds ? > If I remeber correctly I used to type "Wait 10" and QBasic waits > 10 seconds before proceeding to next command. Hi all, I saw a lot of comments saying GOTO is not usefull, very bad, and we should'nt use it because we don't need it. I think that's true, but only if you *create* programs. But if the goal is to provide some kind of converter to automatically take an old application written with an old language (using GOTO), and generating python code, it would certainly a great help to have this (unclean) feature in native python. Best regards jm -- http://mail.python.org/mailman/listinfo/python-list
Re: goto, cls, wait commands
"Jeff Shannon" <[EMAIL PROTECTED]> a écrit dans le message de news:[EMAIL PROTECTED] > jean-michel wrote: > > > Hi all, > > I saw a lot of comments saying GOTO is not usefull, very bad, and we > > should'nt use it because we don't need it. > > I think that's true, but only if you *create* programs. > > But if the goal is to provide some kind of converter to automatically take > > an old application written with an old language (using GOTO), and generating > > python code, it would certainly a great help to have this (unclean) feature > > in native python. > > But an automatic translator is certain to be imperfect. One can no > more translate mechanically between computer languages than one can > translate mechanically between human languages -- and we've all seen > the fun that can be had by machine-translating from language A -> > language B -> language A, right? What do you think the effect of that > sort of meaning-drift would be on application code? > > In other words, any translation from one language to another will > require significant human attention, by someone familiar with both > languages, to ensure that the original meaning is preserved as close > as possible. You're going to have to rewrite chunks of code by hand > no matter what you do; it'd be silly to *not* take that opportunity to > purge things like GOTO. > > Jeff Shannon > Technician/Programmer > Credit International > The automated translations are very commonly used actually in computing industry. If you want an overview, you can try "legacy migration" in google for instance (or "as400 automated migration" or anything of that kind). Translate a computer's language is not the same at all than to translate a human language. In the first case, you have a good chance to know all the rules. Even if the work is not perfect, it can offer you a chance to continue to use a 1 programs application without having to rewrite all (several years of work indeed). The last time I did that, I converted arround 6000 cobol programs in a couple of months, which is obviously not possible by hand (thanks to python ;-). And it was not possible to remove GOTO, because that would really need to rewrite manually the programs, that means to entirely redo the application (probably a 20 human years work !). Regards, jm -- http://mail.python.org/mailman/listinfo/python-list
Fw: Message vtkUser
Hello everyone, my student had the following problem with a python program featuring multiple vtkTkRenderWidget calls. See below... Can anyone suggest a workaround? Best regards, Michel Michel Audette, Ph.D., Research Fellow, Surgical Simulation, Surgical Assist Technology Group, AIST, Namiki 1-2, Tsukuba, Japan, 305-8564. "If you think you can do it, you're right. If you think you can't do it, you're still right." - Henry Ford > > I have some problems with management of many vtkTkRenderWidget. > > I am developing GUI for surgical software in Python Language. > Each window of this GUI have one vtkTkRenderWidget to show 3D Objects > (One of them used the vtksliceWidget develop by Atamai). > I succeed to show one objects in one of these windows. > But if I try to open another one I get this error: > > File "/usr/local/lib/python2.2/lib-tk/Tkinter.py", line 1316, in __call__ > return apply(self.func, args) > File "selection.py", line 64, in > command = lambda: > File "functionclass.py", line 550, in entranceTriplan > self.show2(self.triplan) > File "functionclass.py", line 164, in show2 > self.affichageTriplan("exemple.mnc") > File "functionclass.py", line 584, in affichageTriplan > self.viewer1 = vtkSliceWidget.vtkSliceWidget(self.triplan.frame1, > width=256,height=256) > File "/home/athinnes/atamai/examples/vtkSliceWidget.py", line 108, in > __init__ > Tkinter.Widget.__init__(self, master, 'vtkTkRenderWidget', cnf, kw) > File "/usr/local/lib/python2.2/lib-tk/Tkinter.py", line 1780, in > __init__ > self.tk.call( > TclError: invalid command name "vtkTkRenderWidget" > > This following is a simplify version of the software architecture without > using vtkSliceWidget . > Each module corresponding to one part of the interface: > > ## > #testfunc.py > > from Tkinter import * > from vtkTkRenderWidget import * > import triplantest > import bouton > import render > > class Functions: > >def __init__(self, myParent): > print "functions class created" > # If you comment the self.render line. The button will open the > triplantest window > self.render = render.Render(self, myParent) > > self.bouton = bouton.Bouton(self) > self.triplan = triplantest.Triplan(self) > > ## Procedure: show > # this procedure is call to show on the screen the windows winname >def show(self, winname): > winname.deiconify() > self.affichageTriplan() > > ## Procedure: affichageTriplan > # This procedure setup the slice image inside triplan interface > >def affichageTriplan(self): > > self.renderWidget = vtkTkRenderWidget(self.triplan.frame1) > self.renderWidget.pack(expand='true',fill='both') > > > if __name__ == '__main__': > >root = Tk() >function = Functions(root) >function.triplan.withdraw() >root.mainloop() > > ### > #render.py > > from vtkTkRenderWidget import * > from vtkpython import * > from Tkinter import * > > class Render: > >def __init__(self, myFunctions, myParentFunction): > > self.functions = myFunctions > myParentFunction.title("test vtkTkRenderWidget") > > self.viewer = Frame(myParentFunction, borderwidth = 2, relief = > "ridge") > self.renderWidget = vtkTkRenderWidget(self.viewer) > > self.viewer.pack(expand='true',fill='both') > self.renderWidget.pack(expand='true',fill='both') > > # > # > #triplantest.py > > from Tkinter import * > > class Triplan(Tk): >def __init__(self, myFct): > Tk.__init__(self) > > self.functions = myFct > self.title("Frame for vtkSliceWidget") > > self.mainframe = Frame(self) > self.frame1 = Frame(self.mainframe, relief="ridge", borderwidth=2) > > self.frame1.pack(expand='true',fill='both') > self.mainframe.pack(expand='true',fill='both') > > ### > #bouton.py > > from Tkinter import * > class Bouton(Tk): > >def __init__(self, myFunctions): > Tk.__init__(self) > self.functions = myFunctions > self.title(&qu
How to display ReST properly on pypi?
In general, I write my README files using the ReST syntax. But when I do, they don't show up formatted on pypi (see for example https://pypi.python.org/pypi/config_resolver/3.3.0). How do I get it to be formatted properly? Also, is there a way to specify that the "description" field in setup.py is formatted as ReST? -- https://mail.python.org/mailman/listinfo/python-list
Re: How to display ReST properly on pypi?
Ah... I understand. Makes sense. I was confused that it worked properly on github, but not on pypi, so I never even thought about checking it in rst2html. I thought I would need to specify somewhere manually that it was formatted as ReST instead of plain-text. Thanks for the info. On Saturday, 14 September 2013 11:53:12 UTC+2, Chris “Kwpolska” Warrick wrote: > On Sat, Sep 14, 2013 at 11:08 AM, Michel Albert wrote: > > > In general, I write my README files using the ReST syntax. But when I do, > > they don't show up formatted on pypi (see for example > > https://pypi.python.org/pypi/config_resolver/3.3.0). > > > > > > How do I get it to be formatted properly? > > > > > > Also, is there a way to specify that the "description" field in setup.py is > > formatted as ReST? > > > -- > > > https://mail.python.org/mailman/listinfo/python-list > > > > rst2html crashes with your file. Also, `py:class` is Sphinx-only and > > won’t work with the Cheeseshop and produce garbage in the output. > > > > [kwpolska@kwpolska-lin config_resolver-3.3.0]% rst2html README.rst > > README.rst:67: (WARNING/2) Inline emphasis start-string without end-string. > > README.rst:108: (ERROR/3) Unknown interpreted text role "py:class". > > README.rst:115: (ERROR/3) Unknown interpreted text role "py:class". > > README.rst:121: (ERROR/3) Unknown interpreted text role "py:class". > > README.rst:142: (SEVERE/4) Problems with "include" directive path: > > InputError: [Errno 2] No such file or directory: 'CHANGES'. > > Exiting due to level-4 (SEVERE) system message. > > [kwpolska@kwpolska-lin config_resolver-3.3.0]% echo $? > > 1 > > [kwpolska@kwpolska-lin config_resolver-3.3.0]% > > > > -- > > Chris “Kwpolska” Warrick <http://kwpolska.tk> > > PGP: 5EAAEA16 > > stop html mail | always bottom-post | only UTF-8 makes sense -- https://mail.python.org/mailman/listinfo/python-list
DNS query against a specific server.
Hi, ``socket.gethostbyname`` sends the DNS resolution query to the DNS server specified by the OS. Is there an easy way to send a query to a *different* server? I see that twisted.names allows you to do this, but, having all of twisted as dependency to my project when all I need to do is a simple DNS query seems a bit extreme. I also found pydns, but that looks fairly outdated and unmaintained. Is there not an actively maintained lightweight solution? If not, I will go with twisted. Cheers, Mich. -- https://mail.python.org/mailman/listinfo/python-list
Re: DNS query against a specific server.
On Monday, 30 September 2013 14:36:34 UTC+2, William Ray Wing wrote: > On Sep 30, 2013, at 7:42 AM, Michel Albert <***> wrote: > > > > > Hi, > > > > > > ``socket.gethostbyname`` sends the DNS resolution query to the DNS server > > specified by the OS. Is there an easy way to send a query to a *different* > > server? > > > > > > I see that twisted.names allows you to do this, but, having all of twisted > > as dependency to my project when all I need to do is a simple DNS query > > seems a bit extreme. I also found pydns, but that looks fairly outdated and > > unmaintained. > > > > > > Is there not an actively maintained lightweight solution? If not, I will go > > with twisted. > > > > > > > > > Cheers, > > > Mich. > > > -- > > > https://mail.python.org/mailman/listinfo/python-list > > > > It isn't pure python, but you would be pretty much guaranteed a maintained > solution if you use the name server lookup in your OS. Something like: > > > > import subprocess > > nsl_reslt = subprocess.Popen(['nslookup', '' ],stderr > = subprocess.PIPE, stdout = subprocess.PIPE).communicate()[0] > > > > > > Hope this helps, > > Bill Hmm... I had this option in mind, but opening a subprocess for something as small as this seemed a bit error-prone. If something on the system changes, nslookup replaced by dig or nslookup output changes for example your application will bug out. Granted, the chance of this happening is slim, but using a fixed-version dependency in your setup script gives you a much safer solution IMO. I know I may be splitting hairs. Any of the mentioned solutions are fine. But I am curious to see if something like this is not yet implemented in a more standard way. I was surprised to see that ``gethostbyname`` does not take an optional parameter for this task. -- https://mail.python.org/mailman/listinfo/python-list
Re: DNS query against a specific server.
On Monday, 30 September 2013 14:54:41 UTC+2, Ervin Hegedüs wrote: > Hello, > > > > On Mon, Sep 30, 2013 at 04:42:29AM -0700, Michel Albert wrote: > > > Hi, > > > > > > ``socket.gethostbyname`` sends the DNS resolution query to the DNS server > > specified by the OS. Is there an easy way to send a query to a *different* > > server? > > > > > > I see that twisted.names allows you to do this, but, having all of twisted > > as dependency to my project when all I need to do is a simple DNS query > > seems a bit extreme. I also found pydns, but that looks fairly outdated and > > unmaintained. > > > > > > Is there not an actively maintained lightweight solution? If not, I will go > > with twisted. > > > > > > > there is a dns modul for Python (I don't know is it part of > > standard Python library or not), on most Linux distribution you > > can find it, eg. in Debian it's called python-dnspython. > > > > It can handle different nameserver, than OS knows - here is a > > sample code: > > > > > > import dns.resolver > > > > r = dns.resolver.Resolver() > > r.namerservers = ['127.0.0.1'] > > # or any other IP, in my case I'm using PDNS, which have two > > # parts: a recursor and a resolver; recursor allows requests only > > # on localhost > > > > mxservers = r.query("python.org", 'MX').response > > > > > > > > > > hth, > > > > > > a. Indeed, this looks much nicer than both twisted or pydns. I think I'll go with that one. Thanks a lot! -- https://mail.python.org/mailman/listinfo/python-list
Problem to calculate the mean in version 3.4
Good morning, I have downloaded the version 3.4 and I have a problem to calculate the mean. The software does not recognise the function mean(). I am getting the following error. >>> mean([1, 2, 3, 4, 4]) Traceback (most recent call last): File "", line 1, in mean([1, 2, 3, 4, 4]) NameError: name 'mean' is not defined Could you please help. Is it possible to send me the version that calculate statistics. Thanks, Michel 9.7. statistics — Mathematical statistics functions New in version 3.4. Source code: Lib/statistics.py This module provides functions for calculating mathematical statistics of numeric (Real-valued) data. NoteUnless explicitly noted otherwise, these functions support int, float, decimal.Decimal and fractions.Fraction. Behaviour with other types (whether in the numeric tower or not) is currently unsupported. Mixed types are also undefined and implementation-dependent. If your input data consists of mixed types, you may be able to use map() to ensure a consistent result, e.g. map(float,input_data). 9.7.1. Averages and measures of central location These functions calculate an average or typical value from a population or sample. mean() Arithmetic mean (“average”) of data. median()Median (middle value) of data. median_low()Low median of data. median_high() High median of data. median_grouped()Median, or 50th percentile, of grouped data. mode() Mode (most common value) of discrete data. 9.7.2. Measures of spread These functions calculate a measure of how much the population or sample tends to deviate from the typical or average values. pstdev()Population standard deviation of data. pvariance() Population variance of data. stdev() Sample standard deviation of data. variance() Sample variance of data. 9.7.3. Function details Note: The functions do not require the data given to them to be sorted. However, for reading convenience, most of the examples show sorted sequences. statistics.mean(data) Return the sample arithmetic mean of data, a sequence or iterator of real-valued numbers. The arithmetic mean is the sum of the data divided by the number of data points. It is commonly called “the average”, although it is only one of many different mathematical averages. It is a measure of the central location of the data. If data is empty, StatisticsError will be raised. Some examples of use: >>> >>> mean([1, 2, 3, 4, 4]) 2.8 >>> mean([-1.0, 2.5, 3.25, 5.75]) 2.625 -- https://mail.python.org/mailman/listinfo/python-list
Re: Can Python write foreign characters to the console?
Hi! I have a problem, under win-XP, with this code : # -*- coding: cp-1252 -*- import sys print u"Martin v. Löwis" print "€ for Noël" print u"€ for Noël" sys.exit() ==> "Python a provoqué une erreur" Am I the only one to have that? Michel Claveau -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Calling GPL code from a Python application
Hello, One of the greatest feature of Python in my opinion is the way the interpreter can be used to integrate a wide variety of software packages by dynamically linking them. This approach has been extremely successful for us so far but now I run into a license nightmare. Some the libraries we wrapped using SWIG are under GPL but the applications we are distributing are not (mainly because we are asked by funding agencies to keep track of users and hence ask people to download the source from our site). A google search about GPL and dynamic linking came up with an equal number of pages saying that dynamic linking of GPL code into non GPL applications is allowed as it is the end user who cretes the derived work, as pages saying the opposite ! So does anyone know what to do about this ? The second question I would like to get an answer for is whether doing an "os.system('GPLapp')" violates GPL if I ship my Python code that does the os.system call and the GPLapp program ? Thanks for any input. Please reply to [EMAIL PROTECTED] -- --- o /Michel F. Sanner Ph.D.The Scripps Research Institute o Associate Professor Department of Molecular Biology \ 10550 North Torrey Pines Road o Tel. (858) 784-2341 La Jolla, CA 92037 /Fax. (858) 784-2860 o [EMAIL PROTECTED] http://www.scripps.edu/~sanner --- -- http://mail.python.org/mailman/listinfo/python-list
Re: WMI Help
Hi! Win32_PhysicalMedia WMI class is available only on Windows 2003 or XP Then, swap Admin <=> Normal_user -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: WMI Help
Re! This script run on my XP : import win32com.client WMIS = win32com.client.GetObject(r"winmgmts:root\cimv2") objs = WMIS.ExecQuery("select * from Win32_PhysicalMedia") for obj in objs: print obj.SerialNumber print obj.Tag print -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: running windows 'start' cmd using spawnl
Hi! You can use (exemple) : "cmd /cSTART notepad" -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Where is __builtin__
Hi! >> http://www.effbot.org/pyfaq/where-is-the-math-py-socket-py-regex-py-etc-source-file.htm Yeaaahh!!!Finally a genuine URL;o) -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: C# equivalent to range()
Hi! > There are thousands of threads to choose from in this forum. > If they didn't like this question, they could have picked any other one > to discuss. > There's no need to be disagreeable :-) I think the same thing. -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Using PHP in Python
Hi! Only in Windows, I can call PHP (more exactly PHP-script) from Python. I can, also, call, from Python, PHP-defined-functions, like a method of a Python-class. It's a combination of Active-scripting & dynamic method add to a class. -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Bridge: Ruby to Python communication
Hi! For me, like PHP (message of 11h.35) : Only in Windows, I can call Ruby (more exactly Ruby-script) from Python. I can, also, call, from Python, Ruby-defined-functions, like a method of a Python-class. It's a combination of Active-scripting & dynamic method add to a class. It's run OK with : Ruby-script, Perl-script, PHPscript, VBscript, Jscript. -- @-salutations Michel Claveau -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Bridge: Ruby to Python communication
Hi! Sorry for my bad english. Look here : http://www.mvps.org/scripting/languages/ Python, with PyWin32, can use ActiveScripting. But... only windows... -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Life + Python = Golly
Cool ! Thanks ! -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Threads and time.strptime()
Hi all, I have an interesting problem: I have written code, that reads a logfile and parses it for date string (Thu Jun 29 14:01:23 2006). Standalone everthing works fine, all is recognized. But if I let the same code run in a thread, with the same file as input I get the following error: ... File "sensor.py", line 158, in gotData t = time.strptime(s) File "/usr/lib/python2.4/_strptime.py", line 293, in strptime raise ValueError("time data did not match format: data=%s fmt=%s" % ValueError: time data did not match format: data=Thu Jun 29 14:01:23 2006 fmt=%a %b %d %H:%M:%S %Y Has anyone encountered similiar problems? And how did you get around? Thanks, Maximilian -- http://mail.python.org/mailman/listinfo/python-list
Re: Threads and time.strptime()
The parsing thread reads also the file from the disk. placid wrote: > Maximilian Michel wrote: > > Hi all, > > > > I have an interesting problem: > > I have written code, that reads a logfile and parses it for date string > > (Thu Jun 29 14:01:23 2006). > > Standalone everthing works fine, all is recognized. > > > > But if I let the same code run in a thread, with the same file as input > > I get the following error: > > do you read the logfile in the thread too or pass the read that to the > thread? -- http://mail.python.org/mailman/listinfo/python-list
Re: Threads and time.strptime()
Thank you so much! (2) was the reason! Without threads, locale.getlocale() returns (None, None), while calling it in this thread gives back ('de_DE', 'iso-8859-15'). I'm still curious, why this occurs, but anyway it's fixable with setlocale(LC_ALL, 'C'); so normally Python doesn't set locales according to my system environment, but in a separate thread it does... strange (or i just didn't set something correctly?). Thank you so much! max John Machin wrote: > On 3/07/2006 6:57 PM, Maximilian Michel wrote: > > Hi all, > > > > I have an interesting problem: > > I have written code, that reads a logfile and parses it for date string > > (Thu Jun 29 14:01:23 2006). > > Standalone everthing works fine, all is recognized. > > > > But if I let the same code run in a thread, with the same file as input > > I get the following error: > > ... > > File "sensor.py", line 158, in gotData > > t = time.strptime(s) > > File "/usr/lib/python2.4/_strptime.py", line 293, in strptime > > raise ValueError("time data did not match format: data=%s fmt=%s" > > % > > ValueError: time data did not match format: data=Thu Jun 29 14:01:23 > > 2006 fmt=%a %b %d %H:%M:%S %Y > > Possibilities: > > (1) The thread implementation has acquired extra characters (whitespace > or \x00). > > (2) The thread implementation has changed to a locale that doesn't have > "Thu" & "Jun" as day/month name abbreviations. > > Try inserting > print "strptime(%r); locale: %r" % (s, locale.getlocale()) > before your call to strptime() > > HTH, > John -- http://mail.python.org/mailman/listinfo/python-list
Re: Hardlinks on NTFS
Hi! NTFS hardlink exists before others filesystem. Please, send question to other FS... -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Automatic import PEP
Hi! >>> I have also found "autoimp" useful in writing normal Python... +1 -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
"wxmsw26uh_vc.dll not found" when using wxAgg backend
Hello, Copy wxmsw26uh_vc.dll inC:\python24\lib\site-packages\matplotlib\backends.To find wxmsw26uh_vc.dll, you can downloadwxPython2.6-win32-unicode-2.6.3.3-py24.exe,and execute in aspecific directory and extract the file wxmsw26uh_vc.dll(C:\...\wx-2.6-msw-unicode\wx) Regards, Michel -- http://mail.python.org/mailman/listinfo/python-list
Re: converting dict to object
Hi! Yes. But... Try:d = {'a': 1, 'b': 2, 'def': 123} Ok, I go out... -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Plugin for Web Browser
Re ! Je ne sais pas quel est ton objectif, mais il est possible de couplet Python & Javascript, de manière à générer/modifier/piloter le contenu HTML de pages Web depuis Python. Je fais ça tous les jours (avec IE) Pour cela je passe par COM. Malheureusement, à cause de la paranoïa sécuritaire ambiante, il y a de plus en plus de contraintes et d'obtacles. Ainsi, s'il n'y a pas (encore) trop de problèmes tant que l'on est en local (avec les .HTA, par exemple), dès que l'on est distant (Intranet, Extranet, Web), il y a maintenant des confirmations à tout bout de champ, des avertissements peu utiles, mais devenus incontournables, des boîte de dialogues intempestives, etc. Donc, si c'est pour utiliser comme interface pour des applis sur le disque (ou le réseau local), OK ; sinon, ça posera des problèmes. C'en est à tel point que je me demande si l'utilisation de frontaux HTML comme GUI est toujours intéressante. Et le problème ne touche pas que Python. Par exemple, j'ai un client qui utilise un logiciel de gestion de l'assurance qualité, utilisant des navigateurs comme interface. Du coup, ils ont des patchs 2 fois par mois, et les utilisateurs ont toujours plus choses à valider... -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: inquiry about installing Python 2.5
Hi! For Python only, it's possible. But, if you add Pywin32... problem! -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Shared memory
mmap? -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Tail Call Optimization as a Decorator
Neat stuff! I commented on the ActiveState post, but for completeness, I modified your code to support mutual recursions, and used jorend's isTailCall() to make it safe to call an optimized function in a non-tail-call context. http://the-dubois-papers.blogspot.com/2006/03/python-tail-call-decorator.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Win32api, pyHook, possibly win32com, not sure XD, thats why I'm posting
Hi! Rename Pythonw.exe like jtp.exe And... run: jtp.exe yourscript.pyw -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Embed text document in excel application using python
Hi! > to embed object in excel An example come with PyWin32. This example create a toolbar inside Excel. This toolbar is write with Python. -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: which "GUI module" you suggest me to use?
Hi! Only under Win: PLUIE (http://ponx.org/ponx/guie) This GUI is natively HTML. -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
who know?
Hi! This image show IronPython. But... what is it? Link : http://msdn2.microsoft.com/en-us/vstudio/bb510103.vss_IronPython_large.jpg -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
PythonS?
Hi! Python, Iron-Python, Jython, StackLess-Python, Monty-Python, Movable-Python, etc. Shouldn't add a "S" to the end of "Python"? See: http://www.jfwilliam.com/Sites/1473/Python.jpg The fact of adding a "S" could constitute a PEP. for classification, I propose: PEP'S -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem redefining __getitem__ for str subclass
Hi! Same result, with Python 2.5.1 on win-XP; I have compassion with you. -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
SilverLight, a new way for Python?
Hi! SilverLight ("MS flash killer"), is a plug-in for InternetExplorer (Win), FireFox (Win), and Safari (Mac). The release 1.1-Alpha come with JScript & Python (or ironPython?) See : http://www.microsoft.com/silverlight/default.aspx http://www.microsoft.com/silverlight/why-compelling.aspx http://silverlight.net/Default.aspx http://www.microsoft.com/silverlight/install.aspx Perhaps SilverLight is a new substitute for Python-Active-Scripting in IE. Perhaps SilverLight is the begin for new GUI style (vectors + XAML). Perhaps SilverLight is the start for a new IDE (plug-in for VS-2005 or Expression are availables). But, I don't had try SilverLight... Who had try it? -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Microsoft's Dynamic Languages Runtime (DLR)
Hi! DLR is include in SilverLight. See my message of yesterday. For instant, DLR is for IronPython & JScript. Others languages are only promised. You can install SilverLight 1.1, and make your tests. -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Microsoft's Dynamic Languages Runtime (DLR)
Re! During we post messages, then blog of Jim Hugunin is updated: http://blogs.msdn.com/hugunin/ -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 3131: Supporting Non-ASCII Identifiers
Hi ! > - should non-ASCII identifiers be supported? why? > - would you use them if it was possible to do so? in what cases? Yes. And, more: yes yes yes Because: 1) when I connect Python to j(ava)Script, if the pages "connected" contains objects with non-ascii characters, I can't use it ; snif... 2) when I connect Python to databases, if there are fields (columns) with emphatic letters, I can't use class properties for drive these fields. Exemples: "cité" (french translate of "city") "téléphone" (for phone) And, because non-ASCII characters are possible, they are no-obligatory ; consequently guys (snobs?) want stay in pure-ASCII dimension will can. * sorry for my bad english * -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 3131: Supporting Non-ASCII Identifiers
And Il1 O0 ? -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 3131: Supporting Non-ASCII Identifiers
Hi! ;-))) In whitespace-programming-language, only three characters are used : Space - Tab - RC No parasitic characters in listings ; economy of ink ; ecological behavior ; LOL programming... Must, Python, follow this way? -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: os.listdir() doesn't work ??
Hi! > You want the glob module Warning: glob has "unix like behavior"; just a little different with windows's DIR -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 3131: Supporting Non-ASCII Identifiers
Hi! Yes, for legibility. If letters with accents are possible: d=dict(numéro=1234, name='Löwis', prénom='Martin', téléphone='+33123') or p1 = personn() #class p1.numéro = 1234 p1.name='Löwis' p1.prénom='Martin' p1.téléphone='+33123' Imagine the same code, is accents are not possible... Don't forget: we must often be connected to databases who already exists -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: minimum age to learn python (a.k.a graphical vs text languages)
Hi! Personally, I was yet in the belly of my mom, whom I already thought in Python… -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Executing a list of functions
Hi! Your code run OK for me. But, if you want "time-lag" (sorry for my english) execution, you can try this: def a(): print "this is a" def b(): print "this is b" lst = [a, b] [f() for f in lst] -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: pluie documentation in english
Hi! Bonjour ! Thanks very well for translation. Merci beaucoup pour la traduction. I add a link on the index page of the site. J'ai ajouté un lien vers le document, dans la page d'accueil. Site: http://www.ponx.org/ponx/guie.htm But... I hope complete the (french) doc in next days. Mais... J'espère pouvoir compléter la documentation dans les jours qui viennent. -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Kill thread
Hi! If you have the PID of the process (example: 1234), use this command-line : TASKKILL /F /PID 1234 -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: TASK KILL
> Will TASKKILL kills a thread when thread id is given ?? Or does it > kill only a process?? > > How to ensure that a thread is killed? Hi! Sorry, TASKKILL is only for process. For help on TASKKILL :TASKKILL /? Other infos with TASKLIST (TASKLIST /?) If the object who use process is a service (kif-kif daemon), you can use SC (see SC /?) For thread, the concept is fuzzy. Thread can be manage by OS, by software (e.g. by Python, for Python's threads), or by middlewares. There are no universal way. -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: How to initialize a table of months.
Hi! Not best, but another lisibility : mons=dict(Jan=1, Feb=2, Fev=2, Mar=3, Apr=4, Avr=4, May=5, Mai=5, Jun=6, Jui=6, Jul=7, Aug=8, Aou=8, Sep=9, Oct=10, Nov=11, Dec=12) def mon2int(m): return mons[m] def mond2int(**m): return mons[m.keys()[0]] print mons['Mar'] print mon2int('May') print mond2int(Jul=0) > 3 > 5 > 7 (The dict is mixed : French/English) -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: How to initialize a table of months.
Hi (bis) A class way : class cmon(object): Jan=1 Feb=2 Fev=2 Mar=3 Apr=4 Avr=4 May=5 Mai=5 Jun=6 Jui=6 Juin=6 Jul=7 Juil=7 Aug=8 Aou=8 Sep=9 Oct=10 Nov=11 Dec=12 print cmon.Mar print cmon.Sep print cmon.Dec -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Python + Shoutpy + Twisted Locks
On Oct 6, 4:21 am, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote: > En Fri, 05 Oct 2007 04:55:55 -0300, exhuma.twn <[EMAIL PROTECTED]> escribi?: > > > [...] What I found > > is that "libshout" is blocking, which should be fine as the whole > > thing runs in it's separate thread. But the application hangs > > nevertheless while streaming. This effectively blocks out the other > > thread that checks the player status, which then fails to append new > > songs to the queue. So only one song is played when streaming. > > > The other threads in my application run fine and don't block the rest > > of the app. So I guess, that the main problem is that blocking occurs > > "outside" the python world and "inside" the libshout world. > > Only one thread at a time may be executing Python code; the Global > Interpreter Lock (GIL) ensures the mutual exclusion. Extension modules > (written in C) may use the macros > Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS to release/acquire the GIL > before/after an external blocking call. > I don't know libshout, or how you are doing the binding python-libshout, > but if your analysis is correct it means that the code is not releasing > the GIL at the appropiate points. > > -- > Gabriel Genellina Hmmm... ok. I suppose rewriting the whole thing using twisted's deferreds could then solve the problem. Which are basically nothing more than callbacks with a weird name ;) Unfortunately this means that I have to re-think a lot. But in the end I suppose it will pay off. Thanks for taking the time and reading my little essay Gabriel ;) -- http://mail.python.org/mailman/listinfo/python-list
Drawing charts in Qt
I would like to display some charts in a Qt application. But all the docs I find online are rather dusty and talk about Qt3. My application uses Qt4 however. I ran into PyQwt and matplotlib. But the docs of matplotlib are horrid and the example in their wiki covers Qt3, and things look quite cryptic to me. PyQwt looks much more interesting, but I have trouble installing it. On my machine it complains that sipconfig "has no attribute '_pkg_config'". In the end the application should also run on Windows boxes. And I suppose as long as I use the right versions and use the precompiled binaries, I should get it at least installed. But the thing with the version numbers looks like some major lottery game to me. If one of the elements in the chain (be it Qt, or Qwt) release new versions and the available binary distributions get "out of sync", future support for the written application becomes foggy. Has anyone ever successfully used these graphing libraries with PyQt? Or are there other graphing libraries available? In fact, my needs are modest. A Line- and Bar-Chart would solve the majority of problems. -- http://mail.python.org/mailman/listinfo/python-list
Re: Drawing charts in Qt
On Nov 6, 5:08 pm, David Boddie <[EMAIL PROTECTED]> wrote: > On Tue Nov 6 15:46:07 CET 2007, Michel Albert wrote: > > [PyQwt and matplotlib] > > > PyQwt looks much more interesting, but I have trouble installing it. > > On my machine it complains that sipconfig "has no attribute > > '_pkg_config'". > > Is the configuration script finding the sipconfig file for SIP 3 or SIP 4? How can I see if it's finding it or not? It does not give me any helpful output. > > > In the end the application should also run on Windows boxes. And I > > suppose as long as I use the right versions and use the precompiled > > binaries, I should get it at least installed. But the thing with the > > version numbers looks like some major lottery game to me. If one of > > the elements in the chain (be it Qt, or Qwt) release new versions and > > the available binary distributions get "out of sync", future support > > for the written application becomes foggy. > > I'm not sure what you mean. Can you explain? Well, I suppose I can manage this. If there really are some version problems I can always compile everything I need myself. > > > Has anyone ever successfully used these graphing libraries with PyQt? > > Or are there other graphing libraries available? In fact, my needs are > > modest. A Line- and Bar-Chart would solve the majority of problems. > > I've installed PyQwt for PyQt4 and tried the examples, but only out of > curiosity because I wasn't writing an application that needed those > facilities at the time. > > David -- http://mail.python.org/mailman/listinfo/python-list
Using python as primary language
In our company we are looking for one language to be used as default language. So far Python looks like a good choice (slacking behind Java). A few requirements that the language should be able cope with are: * Database access to Sybase. This seems to be available for python, but the windows-binaries for the library are not available. Self-Compiling them proved to be non-trivial (As always on windows). * Easy GUI creation. Solved using PyQt. * Cross Platform (Linux + Windows). Again, PyQt, solves this * Easy deployment. Solved using py2exe + innosetup * Charting (Histograms, Line charts, bar charts, pie charts, ...) I am currently looking into PyQwt, which looks promising. * Report generation with GUI support reportlab + rml? So far, nearly all point seems to be manageable. But I was not yet able to find a solution for the report generation. What we would like to have is a sort of GUI interface to prepare the reports without having to "code" the positioning. I found reportlab, and it looks like it can do all that is needed in terms of output. But you still have to code the report. And this is a no go. In context, I found RML and saw links to graphical RML editors. But I have not yet found a concrete example code, or documentation. What am I missing? Is RML a reportlab creation or is it a recognised open standard? If not, is there an open standard, that is easily to process with python? Any pointers? I would prefer coding Python to coding Java or worse. VB ;) which is another contender in our roundup. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using python as primary language
On Nov 8, 8:55 pm, [EMAIL PROTECTED] wrote: > On Nov 8, 1:52 am, Michel Albert <[EMAIL PROTECTED]> wrote: > > > > > In our company we are looking for one language to be used as default > > language. So far Python looks like a good choice (slacking behind > > Java). A few requirements that the language should be able cope with > > are: > > > * Database access to Sybase. > > This seems to be available for python, but the windows-binaries for > > the library > > are not available. Self-Compiling them proved to be non-trivial (As > > always > > on windows). > > * Easy GUI creation. > > Solved using PyQt. > > * Cross Platform (Linux + Windows). > > Again, PyQt, solves this > > * Easy deployment. > > Solved using py2exe + innosetup > > * Charting (Histograms, Line charts, bar charts, pie charts, ...) > > I am currently looking into PyQwt, which looks promising. > > * Report generation with GUI support > > reportlab + rml? > > > So far, nearly all point seems to be manageable. But I was not yet > > able to find a solution for the report generation. What we would like > > to have is a sort of GUI interface to prepare the reports without > > having to "code" the positioning. I found reportlab, and it looks like > > it can do all that is needed in terms of output. But you still have to > > code the report. And this is a no go. In context, I found RML and saw > > links to graphical RML editors. But I have not yet found a concrete > > example code, or documentation. What am I missing? Is RML a reportlab > > creation or is it a recognised open standard? If not, is there an open > > standard, that is easily to process with python? > > > Any pointers? I would prefer coding Python to coding Java or > > worse. VB ;) which is another contender in our roundup. > > It looks like RML (Reportlab Markup Language) is a type of XML to me. > It also appears to be a ReportLab invention. Lots of code examples can > be found here: > > http://developer.reportlab.com/examples.html > > See also:http://www.reportlab.com/rml_index.html > > I'm not sure what you mean by "editing" a report. I have an > application that allows users to enter data into a GUI and then it > takes their data and inputs it into a ReportLab generated PDF. > > Mike What I meant was that one should be able to "draw" a report template. Basically a graphical user interface for RML in this case. I personally would opt for writing RML or whatever code myself. But it's impossible to convice my boss. The dialog usually goes like this: "So, did you find a click-and-play editor for reports" - "Not yet, but anyway, writing code is more flexible and easier to manage later on" - "Hmmm... but it's code!" - "Sure, but you only write it once for one report, you can easily re-use code-snippets, modifying the code does not require one additional program, you just use your text-editor of choice,..." - "Okay, but it's CODE!" and this goes on forever. My boss seems to be allergic to writing code by hand. Which is very frustrating. I'm happy that Qt has the "designer", although it's very easy to code the GUI's too ;) -- http://mail.python.org/mailman/listinfo/python-list
parallel csv-file processing
Currently I am faced with a large computation tasks, which works on a huge CSV file. As a test I am working on a very small subset which already contains 2E6 records. The task itself allows the file to be split however as each computation only involves one line. The application performing the computation exists already, but it was never meant to run on such a big dataset. One thing that is clear, is that it will take a while to compute all this. So a distributed approach is probably a good idea. There ar a couple of options for this: Scenario A ( file is split manually in smaller parts ): 1) Fire up an openmosix/kerrighed cluster, and run one process for each file part. Scenario B ( file is "split" using the application itself ): 2) Again with an openmosix/kerrighed cluster, but only one instance of the application is run, using parallelpython 3) Using parallelpython without cluster, but using ppserver.py on each node. The second case looks most interesting as it is quite flexible. In this case I would need to address subsets of the CSV file however. And the default csv.reader class does not allow random-access of the file (or jumping to a specific line). What would be the most efficient way to subset a CSV-file. For example: f1 = job_server.submit(calc_scores, datafile[0:1000]) f2 = job_server.submit(calc_scores, datafile[1001:2000]) f3 = job_server.submit(calc_scores, datafile[2001:3000]) ... and so on Obviously this won't work as you cannot access a slice of a csv-file. Would it be possible to subclass the csv.reader class in a way that you can somewhat efficiently access a slice? Jumping backwards is not really necessary, so it's not really random access. The obvious way is to do the following: buffer = [] for line in reader: buffer.append(line) if len(buffer) == 1000: f = job_server.submit(calc_scores, buffer) buffer = [] f = job_server.submit(calc_scores, buffer) buffer = [] but would this not kill my memory if I start loading bigger slices into the "buffer" variable? -- http://mail.python.org/mailman/listinfo/python-list
Re: Binary search tree
On Nov 9, 11:45 pm, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] a écrit : > > > Hi, > > > I have to get list of URLs one by one and to find the URLs that I have > > more than one time(can't be more than twice). > > > I thought to put them into binary search tree, this way they'll be > > sorted and I'll be able to check if the URL already exist. > > What about a set ? > > s = set() > for url in urls: >if url in s: > print "already have ", url >else: > set.add(url) Interesting. For this case I usually used dicts. As in: d = {} for url in urls: if url in d: print "already have ", url else: d[url] = 1 Now, I can see that this method has some superfluous data (the `1` that is assigned to the dict). So I suppose this is less memory efficient. But is this slower then? As both implementations use hashes of the URL to access the data. Just asking out of curiosity ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: [Edu-sig] "do" as a keyword
> they find the "while" logic to be unintuitive I've found that a good way to explain 'while' is to consider it as an 'if' statement that repeats. Kids grasp simple conditionals fairly easily. I would sometimes hear them talk about 'if loops' when they were actually trying to discuss conditional statements, and I would say to them hey look, there's no such THING as an 'if loop'! But then it occurred to me - well, that's what a while statement is! So, let's just take a simple conditional, change the 'if' to 'while', and there you have a loop! Only problem, it will keep repeating forever, so now we have to consider ways to get it to stop. Speaking from my own learning experiences, 'while True' initially seemed awkward, probably for the same reason 'if True' would - why bother? But at this point I actually do like the 'while True' structure. - Michel Paul On Dec 12, 2007 3:01 AM, Brian Blais <[EMAIL PROTECTED]> wrote: > On Dec 11, 2007, at Dec 11:11:11 PM, Terry Reedy wrote: > > > "Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > || > | But loops that run at least once is a basic element of algorithms. > | Perhaps not as common as the zero or more times of the while loop, but > | still fundamental. It is a shame it has to be faked using: > | > | while True: # force the first iteration to always run > |process > |if condition: break > | > | Ugly and misleading. > > I disagree. Nothing is being faked. The generic loop is > > while True: > pre_process > if condition: break > post_process > > > I find that when teaching beginning programmers, they usually think in > "until" terms, and not "while" terms. > > do: > Forward() > until Touched() > > and I have to explain to them that Python doesn't have "until", and that > the logic for while is exactly the opposite: > > while not Touched(): > Forward() > > they find the "while" logic to be unintuitive, and I often find myself > feeling the same way: crafting it with the until logic, and then reversing > it. Perhaps I should do as above, and do: > > while True: > Forward() > if Touched(): break > > but somehow that feels wrong to me, like bypassing the point of the while: > all that power to check for conditions, and you just use it to check True, > and then use a break inside. It's readable, I guess, but not a programming > construct I am immediately drawn to. > > > Brian Blais > > > -- > Brian Blais > [EMAIL PROTECTED] > http://web.bryant.edu/~bblais <http://web.bryant.edu/%7Ebblais> > > > > > ___ > Edu-sig mailing list > [EMAIL PROTECTED] > http://mail.python.org/mailman/listinfo/edu-sig > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyrex installation on windows XP: step-by-step guide
Merci beaucoup ! Thank you very much! -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: python and xulrunner
Hi! My answer is (perhaps a little) hard, but... I read pages and pages, and traversed sites and sites. Conclusion : - XPcom functions, perhaps, on some special configurations. - xulrunner is an idea (vapor?) But, in production, nothing of all that is usable (for the moment?) -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Help with regular expression patterns
Hi: i'm so newbie in python that i don't get the right idea about regular expressions. This is what i want to do: Extract using python some information and them replace this expresion for others, i use as a base the wikitext and this is what i do: paragraphs = """ = Test '''wikitest'''= [[Image:image_link.jpg|rigth|thumbnail|200px|"PREMIER"]] [http://www.google.com.cu] ::''Note: This is just an example to test some regular expressions stuffs.'' The ''wikitext'' is a text format that helps a lot. In concept is a simple [[markup]] [[programming_language|language]]. That helps to make simple create documentations texts. ==Wikitext== Created by Warn as a ... [ this is a normal sign] """.split('\n\n') import re wikipatterns = { 'a_nowiki' : re.compile(r"(.\S+)"), # nowiki 'section' : re.compile(r"\=(.*)\="),# section one tags 'sectiontwo' : re.compile(r"\=\=(.*?)\=\="),# section two tags 'wikilink': re.compile(r"\[\[(.*?)\]\]"), # links tags 'link': re.compile(r"\[(.*?)\]"), # external links tags 'italic': re.compile(r"\'\'(.*?)\'\'"), # italic text tags 'bold' : re.compile(r"\'\'\'(.*?)\'\'\'"), # bold text tags } for pattern in wikipatterns: print "===> processing pattern :", pattern, "<==" for paragraph in paragraphs: print wikipatterns[pattern].findall(paragraph) But When i run it the result is not what i want, it's something like: [EMAIL PROTECTED]:/local/python$python parser.py ===> processing pattern : bold <== ['braille'] [] [] [] [] [] ===> processing pattern : section <== [" Test '''wikitest'''"] [] [] ['=Wikitext='] [] [] ===> processing pattern : sectiontwo <== [] [] [] ['Wikitext'] [] [] ===> processing pattern : link <== ['[Image:image_link.jpg|rigth|thumbnail|200px|"PREMIER"'] ['http://www.google.com.cu'] ['[markup', '[programming_language|language'] [] [] [' this is a normal sign'] ===> processing pattern : italic <== ["'wikitest"] ['Note: This is just an example to test some regular expressions stuffs.'] ['wikitext'] [] [] [] ===> processing pattern : wikilink <== ['Image:image_link.jpg|rigth|thumbnail|200px|"PREMIER"'] [] ['markup', 'programming_language|language'] [] [] [] ===> processing pattern : a_nowiki <== [] [] [] [] [] ['sign]'] In the first case the result it's Ok In the second the first it's Ok, but the second it's not because second result it's a level two section not a level one. In the third result things are Ok The fourth, the first and thrid result are wrong beacuse they are level two links, but the second it's Ok. The fifth it Ok The sixth shows only one result and it should show two. Please help. PS: am really sorry about my technical English. -- Michel Perez )\._.,--,'``. Ulrico Software Group/, _.. \ _\ ;`._ ,. Nihil est tam arduo et difficile human `._.-(,_..'--(,_..'`-.;.' mens vincat. Séneca. = --- Red Telematica de Salud - Cuba CNICM - Infomed -- http://mail.python.org/mailman/listinfo/python-list
about recursive load
Hi, am very newbie in Python, but as part of a project i need to load configuration -a settings.py file in the package dir- of my apps recursively, something like this: settings.load_config("project.test.app") settings.load_config("project.test.*") settings.load_config("project.test") settings.load_config("*") this allows me to load them as: settings.project.CONFIG_PARAMETER_1 # project configuration settings.project.test.CONFIG_PARAMETER_1 # sub project and so on. This it's what i've done, class Settings: def __getattr__( self, attr): return self.__dict__['flags'][attr] def __setattr__(self, attr, value): self.__dict__['flags'][attr]=value def __init__(self, package = None, parent = None): self.__package = package self.__parent = None self.__dict__['flags']={} def get_parent ( self): return self.__parent def create_config_structure( self, pkg, parent = None ): # ... assuming no error and all that if pkg.count(".") > 0: if parent is None: if not self.__dict__['flags'].has_key(pkg[:pkg.find(".")]): father=self.__dict__['flags'][pkg]=Settings( \ pkg[:pkg.find(".")],self) else: father = parent else: if not parent.__dict__['flags'].has_key(pkg[:pkg.find(".")]): father=parent.__dict__['flags'][pkg[:pkg.find(".")]]= \ Settings(pkg[:pkg.find(".")], parent) else: father = parent self.create_config_structure( pkg [pkg.find(".")+1:],father) else: if not parent.__dict__['flags'].has_key: parent.__dict__['flags'][pkg]=Settings(pkg,parent) return parent.__dict__['flags'][pkg] def load_config ( self, pkg= None ): config_module_object = self.create_config_structure( pkg ) # the loading configuration part try: if pkg is not None: mod = __import__( pkg + ".settings", {},{},['']) else: mod = __import__( "settings", {},{},['']) except: raise ImportError("Settings not found") data={} for setting in dir(mod): if setting == setting.upper(): data[setting]=getattr(mod, setting) for key in data: if pkg is not None: setattr( config_module_object.__dict__['flags'], key, data[key]) else: setattr(self.__dict__['flags'], key, data[key]) Any idea it's welcome --- Red Telematica de Salud - Cuba CNICM - Infomed -- http://mail.python.org/mailman/listinfo/python-list
find an object ancestor
HI all: imagine something like this: class father: pass class son( father ): pass I need to know the son ancestor class how can i know this. Thanks --- Red Telematica de Salud - Cuba CNICM - Infomed -- http://mail.python.org/mailman/listinfo/python-list
Re: find an object ancestor
Thanks it works OK On Thu, 2008-11-06 at 13:14 +1000, James Mills wrote: > On Mon, Nov 3, 2008 at 7:16 AM, Michel Perez <[EMAIL PROTECTED]> > wrote: > > HI all: > > > > imagine something like this: > > > > class father: > >pass > > class son( father ): > >pass > > > > I need to know the son ancestor class how can i know this. > > >>> class Father(object): pass > ... > >>> class Son(Father): pass > ... > >>> son = Son() > >>> isinstance(son, Father) > True > >>> isinstance(son, Son) > True > >>> son.__class__.__bases__ > (,) > >>> > > --JamesMills > --- Red Telematica de Salud - Cuba CNICM - Infomed -- http://mail.python.org/mailman/listinfo/python-list
convert to XMLRPC
Que vola a todos: I have an object abstraction layer that allows me to comunicate and interact with my DB server without much problems -am thinking in possibles contributors. In the stdlib xmlrpclib handles this in a common way, but i use a customized GatewayHandler that give me the posibility to serialize my objects and send them to my clients but my real need is to convert this object to XML -or something like it- to send it in a way i can use them in every presentation a suggest like GUI, WEB or anything i like. There's any thing i can do to convert them. Don't worry about the way i handle the result i only need to convert them to XML or else. -- Michel Perez )\._.,--,'``. Ulrico Software Group/, _.. \ _\ ;`._ ,. Nihil est tam arduo et difficile human `._.-(,_..'--(,_..'`-.;.' mens vincat.Séneca. = --- Red Telematica de Salud - Cuba CNICM - Infomed -- http://mail.python.org/mailman/listinfo/python-list
problem with JSON-RPC
Hi everybody: I'm trying to use JSON-RPC to provide my services but produce this exception: Traceback (most recent call last): File "", line 1, in File "jsonrpc/proxy.py", line 43, in __call__ resp = loads(respdata) File "jsonrpc/json.py", line 211, in loads raise JSONDecodeException('Expected []{}," or Number, Null, False or True') jsonrpc.json.JSONDecodeException: Expected []{}," or Number, Null, False or True This is what am doing configuration file for apache Alias /services/ //home/mperez/Desktop/test_jsonrpc/ Options Indexes MultiViews FollowSymLinks Order deny,allow Allow from All AddHandler mod_python .py PythonHandler jsonrpc service for jsonrpc test.py from jsonrpc import ServiceMethod class MyService(object): @ServiceMethod def echo(self, msg): return msg service = MyService() service client #!/usr/bin/env python from jsonrpc import ServiceProxy s = ServiceProxy("http://localhost/services/test.py";) print s.echo("foobar") Regards -- Michel Perez )\._.,--,'``. Ulrico Software Group/, _.. \ _\ ;`._ ,. Nihil est tam arduo et difficile human `._.-(,_..'--(,_..'`-.;.' mens vincat.Séneca. = --- Red Telematica de Salud - Cuba CNICM - Infomed -- http://mail.python.org/mailman/listinfo/python-list
Using a decorator to *remove* parameters from a call
A small foreword: This might look like a cherrypy-oriented post, and should therefore go to the cherrypy group, but if you read to the end, you'll see it's a more basic python problem, with cherrypy only as an example. ;) >From the decorator PEP (318) I get it that you can /add/ parameters to a call. Say you do something like this: @mydeco( foo="bar" ) def myfunc( hello ): print foo, foo However, this is not what I would like to do. I would like to take away one or more attributes using a decorator. My goal is to centralize the logic associated with that parameter. In my particular example, I am writing a cherrypy application (more specifically, turbogears1) and I would like all controller method to accept a "lang" and a "skin" attribute. As a simple, but hands-on example, imagine code like this (http://python.pastebin.com/f25f2429b): class MyController(Controller): @expose() def index(self, skin="default", lang="en"): set_skin( skin ) set_language( lang ) return "Hello skinned world" @expose() def foo(self, skin="default", lang="en"): set_skin( skin ) set_language( lang ) return "bar" This becomes cumbersome however for a large application with many controllers and methods. Always adding the parameters to the methods and function calls into the method bodies looks way to repetitive for my taste. Currently I solve this by using a cherrypy filter which removes those parameters from the HTTP-Request and puts them into the session object. This looked wrong to me though right from the start. Also, the cherrypy docs advise against the use of "filters" for application logic. But this looks pretty much like that to me somewhat. Worse yet, filters are not supported in Turbogears2 any longer. Which makes porting my app not straight-forward, as I have to port my filters and write WSGI middleware instead. I would prefer a syntax like this (http://python.pastebin.com/ f462bc29c) class MyController(Controller): @expose() @skinnable @translatable def index(self): return "Hello skinned world" @expose() @skinnable @translatable def foo(self): return "bar" This, to me has several advantages: The logic is "encapsulated" in the application code itself. I do not need to rely on framework specific features (be it cherrypy or wsgi). This would make the application more self-contained and hence more future proof. But right here lies my problem. If you are not familiar with CherryPy, let me digress for a tiny bit to give you the necessary backgroud: Inside a controller, an "exposed" method is reachable via HTTP requests. It's possible to force request parameters. If that is the case (as in my case it is), then the call will only be successful, if all parameters received a vaule and no unknown parameters have been passed. Assume the following signature: def index(self) This will successfully return an HTTP Response when the client requested the resource on the URL "/index". If the client adds a query string, say "/index?lang=en" the call will *fail* as this parameter is unkown. For this to work the signature must read: def index(self, lang) or def index(self, lang="en") Right end of digression, back to topic: My ultimate question is: Is it possible to write a decorator that removes a parameter from a call and return a function without that parameter? Something along the lines (http://python.pastebin.com/ f257877cd): def translatable(f): "Note that this code is only an example and will not work!" lang = f.__get_parameter_value__("lang") f.__remove_parameter__("lang") do_something_with_lang(lang) return f I am aware, that this depends on *when* the decorator call is executed. If its called whenever the decorated function is called, then there should be some way to handle this. If it's called at "compile-time", then I suppose it's not going to be possible. A usage scenario would be this: # --- definition --- @translatable def index(self): return _("Hello", lang) # --- call -- obj.index( lang="de") obj.index() As you can see, the method definition does not contain the "lang" parameter in the signature, but I want to be able to (optionally) set it during a call. I hope I made my ideas clear enough. I would be very positively surprised if this worked. It would make my application code much easier to read, understand and follow. The filters currently do a lot of magic "behind-the-scenes" and if somebody else needs to jump in and code on that application they will surely ask themselves "where the ** is that * lang variable set?" :) And I'd like to make it as easy as possible for everyone :) Or, maybe you even have a better solution in mind? I'm open for suggestions. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using a decorator to *remove* parameters from a call
On Apr 13, 12:52 pm, Jon Clements wrote: > On 13 Apr, 11:11, Michel Albert wrote: > > > > > A small foreword: This might look like a cherrypy-oriented post, and > > should therefore go to the cherrypy group, but if you read to the end, > > you'll see it's a more basic python problem, with cherrypy only as an > > example. ;) > > > From the decorator PEP (318) I get it that you can /add/ parameters to > > a call. Say you do something like this: > > > @mydeco( foo="bar" ) > > def myfunc( hello ): > > print foo, foo > > > However, this is not what I would like to do. I would like to take > > away one or more attributes using a decorator. My goal is to > > centralize the logic associated with that parameter. In my particular > > example, I am writing a cherrypy application (more specifically, > > turbogears1) and I would like all controller method to accept a "lang" > > and a "skin" attribute. As a simple, but hands-on example, imagine > > code like this (http://python.pastebin.com/f25f2429b): > > > class MyController(Controller): > > > @expose() > > def index(self, skin="default", lang="en"): > > set_skin( skin ) > > set_language( lang ) > > return "Hello skinned world" > > > @expose() > > def foo(self, skin="default", lang="en"): > > set_skin( skin ) > > set_language( lang ) > > return "bar" > > > This becomes cumbersome however for a large application with many > > controllers and methods. Always adding the parameters to the methods > > and function calls into the method bodies looks way to repetitive for > > my taste. > > > Currently I solve this by using a cherrypy filter which removes those > > parameters from the HTTP-Request and puts them into the session > > object. This looked wrong to me though right from the start. Also, the > > cherrypy docs advise against the use of "filters" for application > > logic. But this looks pretty much like that to me somewhat. Worse > > yet, filters are not supported in Turbogears2 any longer. Which makes > > porting my app not straight-forward, as I have to port my filters and > > write WSGI middleware instead. > > > I would prefer a syntax like this (http://python.pastebin.com/ > > f462bc29c) > > > class MyController(Controller): > > > @expose() > > @skinnable > > @translatable > > def index(self): > > return "Hello skinned world" > > > @expose() > > @skinnable > > @translatable > > def foo(self): > > return "bar" > > > This, to me has several advantages: The logic is "encapsulated" in the > > application code itself. I do not need to rely on framework specific > > features (be it cherrypy or wsgi). This would make the application > > more self-contained and hence more future proof. > > > But right here lies my problem. If you are not familiar with CherryPy, > > let me digress for a tiny bit to give you the necessary backgroud: > > > Inside a controller, an "exposed" method is reachable via HTTP > > requests. It's possible to force request parameters. If that is the > > case (as in my case it is), then the call will only be successful, if > > all parameters received a vaule and no unknown parameters have been > > passed. Assume the following signature: > > > def index(self) > > > This will successfully return an HTTP Response when the client > > requested the resource on the URL "/index". If the client adds a query > > string, say "/index?lang=en" the call will *fail* as this parameter is > > unkown. For this to work the signature must read: > > > def index(self, lang) > > > or > > > def index(self, lang="en") > > > Right end of digression, back to topic: > > Haven't finished coffee yet, plus it's a bank holiday! [/excuse] > > Can't that be changed to def index(self, **kwdargs) -- then your > decorators can operate something like set_language(kwdargs.get('lang', > 'en')) and then delete the key Sure. It could work like that. But that, in my case, would mean that anyone could pass any parameters into that method. That should not make any problems, but I prefer enforcing only the parameters I expect (and /only/ those) to be passed into the method. If only for my own sanity ;) > Anyway, back to more coff
Re: Using a decorator to *remove* parameters from a call
On Apr 13, 12:45 pm, Aaron Brady wrote: > On Apr 13, 5:11 am, Michel Albert wrote: > > > A small foreword: This might look like a cherrypy-oriented post, and > > should therefore go to the cherrypy group, but if you read to the end, > > you'll see it's a more basic python problem, with cherrypy only as an > > example. ;) > > > From the decorator PEP (318) I get it that you can /add/ parameters to > > a call. Say you do something like this: > > > @mydeco( foo="bar" ) > > def myfunc( hello ): > > print foo, foo > snip > > I would prefer a syntax like this (http://python.pastebin.com/ > > f462bc29c) > > > class MyController(Controller): > > > @expose() > > @skinnable > > @translatable > > def index(self): > > return "Hello skinned world" > > > @expose() > > @skinnable > > @translatable > > def foo(self): > > return "bar" > > snip > > more future proof. > > snip > > Sure. Just pop the keywords you want from the dictionary, if they > exist. > > def take_ab( fun ): > def newfun( *ar, **kw ): > aval= kw.pop( 'a', None ) > bval= kw.pop( 'b', None ) > print( 'aval %r and bval %r popped'% ( aval, bval ) ) > res= fun( *ar, **kw ) > return res > return newfun > > @take_ab > def f( c= 42, d= 'some' ): > print( 'in f, c= %r, d= %r'% ( c, d ) ) > > f( a= 'paramA', b= 'paramB', c= 'other number' ) > > /Output: > > aval 'paramA' and bval 'paramB' popped > in f, c= 'other number', d= 'some' > > As you can see, 'a', 'b', and 'c' were passed to 'f', but 'f' only > received 'c', as well as its default value for 'd'. So long as you > only need to pass by keyword, not position, it's pretty easy. It's > harder if the parameter you want might have been passed by either, and > you need to remove it from whichever one it was passed by. Thanks. That works like a charm. I tried that last night and it gave me an error. So I must have had a typo in there somewhere. Not enough sleep I guess ;) -- http://mail.python.org/mailman/listinfo/python-list
qrcode in python?
I am planning to write a python-module for python as I haven't found anything on the tubes so far. If anyone has any interesting insight on this topic, replies are welcome! ;) Q: What is QR-Code? A: http://www.denso-wave.com/qrcode/qrstandard-e.html So far (as of May 21st 2008): Google (1 sensible hit): http://mail.python.org/pipermail/python-list/2006-May/385258.html The Cheese shop (nothing): http://pypi.python.org/pypi?%3Aaction=search&term=qrcode&submit=search Sourceforge (1 hit - no files/code): http://sourceforge.net/projects/qrcode/ I was planning to make use of qr-code in a web-application which is written in python. So far I was not yet lucky to find any existing module. I just contacted the project lead of http://sourceforge.net/projects/qrcode/ on this topic as well. Let's see what he replies. So. any pointers/ideas ? -- http://mail.python.org/mailman/listinfo/python-list
Stripping scripts from HTML with regular expressions
Hey everyone, I'm trying to strip all script-blocks from a HTML-file using regex. I tried the following in Python: testfile = open('testfile') testhtml = testfile.read() regex = re.compile(']*>(.*?)', re.DOTALL) result = regex.sub('', blaat) print result This strips far more away then just the script-blocks. Am I missing something from the regex-implementation from Python or am I doing something else wrong? greetz MFB -- http://mail.python.org/mailman/listinfo/python-list
RE: Stripping scripts from HTML with regular expressions
Reedick, Andrew wrote: > > >> -Original Message- >> From: [EMAIL PROTECTED] [mailto:python- >> [EMAIL PROTECTED] On Behalf Of Michel Bouwmans >> Sent: Wednesday, April 09, 2008 3:38 PM >> To: python-list@python.org >> Subject: Stripping scripts from HTML with regular expressions >> >> Hey everyone, >> >> I'm trying to strip all script-blocks from a HTML-file using regex. >> >> I tried the following in Python: >> >> testfile = open('testfile') >> testhtml = testfile.read() >> regex = re.compile(']*>(.*?)', re.DOTALL) > > > Aha! \b is being interpolated as a backspace character: > \b ASCII Backspace (BS) > > Always use a raw string with regexes: > regex = re.compile(r']*>(.*?)', re.DOTALL) > > Your regex should now work. > > > > * > > The information transmitted is intended only for the person or entity to > which it is addressed and may contain confidential, proprietary, and/or > privileged material. Any review, retransmission, dissemination or other > use of, or taking of any action in reliance upon this information by > persons or entities other than the intended recipient is prohibited. If > you received this in error, please contact the sender and delete the > material from all computers. GA622 Thanks! That did the trick. :) I was trying to use HTMLParser but that choked on the script-blocks that didn't contain comment-indicators. Guess I can now move on with this script, thank you. MFB -- http://mail.python.org/mailman/listinfo/python-list
Re: How is GUI programming in Python?
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Paul Rubin wrote: > Chris Stewart <[EMAIL PROTECTED]> writes: >> I've always had an interest in Python and would like to dabble in it >> further. I've worked on a few very small command line programs but >> nothing of any complexity. I'd like to build a really simple GUI app >> that will work across Mac, Windows, and Linux. How painful is that >> going to be? I used to be really familiar with Java Swing a few years >> ago. I imagine it will be similar. >> ... >> Next, what would you say is the best framework I should look into? > > If by "best" you mean "easiest", that is probably tkinter, which > comes with python. It is somewhat rudimentary and the widgets that > come with it don't look so great. But if you just want to put up > GUI's with basic functionality and not much glitz, it is ok for most > such purposes. > out how to use I don't quite agree with you on this. Tkinter may be easy because it is available by standard in Python, but that's about it in my opinion. The API, look and performance hit is horrible. You're much better of with PyQt4 which makes the job really simple. MFB -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.7 (GNU/Linux) iD8DBQFH/kjhDpaqHmOKFdQRAj+kAJ0d3aHqpv/mh7kSqtDqUFXtJsxi1gCfU5UP 2Ygw9ttRIYX+ioMyBVUNsVo= =stR5 -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
RE: Stripping scripts from HTML with regular expressions
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Reedick, Andrew wrote: >> -Original Message- >> From: [EMAIL PROTECTED] [mailto:python- >> [EMAIL PROTECTED] On Behalf Of Michel Bouwmans >> Sent: Wednesday, April 09, 2008 5:44 PM >> To: python-list@python.org >> Subject: RE: Stripping scripts from HTML with regular expressions >> >> >> Thanks! That did the trick. :) I was trying to use HTMLParser but that >> choked on the script-blocks that didn't contain comment-indicators. >> Guess I >> can now move on with this script, thank you. >> > > > S you asked for help with a regex workaround, but didn't ask for > help with the original problem, namely HTMLParser? ;-) > > > > * > > The information transmitted is intended only for the person or entity to > which it is addressed and may contain confidential, proprietary, and/or > privileged material. Any review, retransmission, dissemination or other > use of, or taking of any action in reliance upon this information by > persons or entities other than the intended recipient is prohibited. If > you received this in error, please contact the sender and delete the > material from all computers. GA625 I don't think HTMLParser was doing anything wrong here. I needed to parse a HTML document, but it contained script-blocks with document.write's in them. I only care for the content outside these blocks but HTMLParser will choke on such a block when it isn't encapsulated with HTML-comment markers and it tries to parse the contents of the document.write's. ;) MFB -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.7 (GNU/Linux) iD8DBQFH/kvEDpaqHmOKFdQRAgHgAJ4s2YUN6yynUS+8aunhVUR94rs2yQCgrn94 tAFx/dylzEI0TclRDSTRbJI= =k8SN -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: How is GUI programming in Python?
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Mike Driscoll wrote: > On Apr 10, 12:05 pm, Michel Bouwmans <[EMAIL PROTECTED]> wrote: >> -BEGIN PGP SIGNED MESSAGE- >> Hash: SHA1 >> >> >> >> Paul Rubin wrote: >> > Chris Stewart <[EMAIL PROTECTED]> writes: >> >> I've always had an interest in Python and would like to dabble in it >> >> further. I've worked on a few very small command line programs but >> >> nothing of any complexity. I'd like to build a really simple GUI app >> >> that will work across Mac, Windows, and Linux. How painful is that >> >> going to be? I used to be really familiar with Java Swing a few years >> >> ago. I imagine it will be similar. >> >> ... >> >> Next, what would you say is the best framework I should look into? >> >> > If by "best" you mean "easiest", that is probably tkinter, which >> > comes with python. It is somewhat rudimentary and the widgets that >> > come with it don't look so great. But if you just want to put up >> > GUI's with basic functionality and not much glitz, it is ok for most >> > such purposes. >> > out how to use >> >> I don't quite agree with you on this. Tkinter may be easy because it is >> available by standard in Python, but that's about it in my opinion. The >> API, look and performance hit is horrible. You're much better of with >> PyQt4 which makes the job really simple. >> >> MFB >> -BEGIN PGP SIGNATURE- >> Version: GnuPG v1.4.7 (GNU/Linux) >> >> iD8DBQFH/kjhDpaqHmOKFdQRAj+kAJ0d3aHqpv/mh7kSqtDqUFXtJsxi1gCfU5UP >> 2Ygw9ttRIYX+ioMyBVUNsVo= >> =stR5 >> -END PGP SIGNATURE- > > I see a lot of people recommend using pyQt, but they never mention the > controversy that surrounds its licensing. There have been many posts > on the subject already, but if the OP ever decides to sell anything > they create, I've heard that QT's licensing is kind of squirrelly. > Maybe this has been straightened out? > > I looked at the website and found it fairly confusing. And don't you > need to download QT itself? > > Mike Yeah, the licensing of Qt is either be open-source (under one of the Qt-exception licenses licenses so no exclusivity for the GPL anymore) or pay for the commercial version. So yes, if you would like to sell it as closed-source software you will need to buy the commercial version of Qt and PyQt. In other words: you will have to pay twice. Don't forget that you can also sell open-source software, so you don't have to pay. ;) MFB -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.7 (GNU/Linux) iD8DBQFH/mMBDpaqHmOKFdQRAiAkAJ0XoysACvcaxLWwvYauFlgEEaGLVwCfdz7g XMUDfEPLX6RfLV25viLB9aA= =d2ms -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: How is GUI programming in Python?
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Gabriel Genellina wrote: > Another annoying thing with the Qt license is that you have to choose it > at the very start of the project. You cannot develop something using the > open source license and later decide to switch to the commercial licence > and buy it. > Unless you're a company with a risk of being checked for legal software etc., you can always ignore that allthough not very legal. MFB -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.7 (GNU/Linux) iD8DBQFH/3ZSDpaqHmOKFdQRAsupAKCN292aFK7V+AHXeQu/rzac7WAnnACgq+Al 2LzsfA5No1PTOgIc2wdYjf0= =7JyM -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: How is GUI programming in Python?
Steve Holden wrote: > Michel Bouwmans wrote: >> -BEGIN PGP SIGNED MESSAGE- >> Hash: SHA1 >> >> Mike Driscoll wrote: >> >>> On Apr 10, 12:05 pm, Michel Bouwmans <[EMAIL PROTECTED]> wrote: >>>> -BEGIN PGP SIGNED MESSAGE- >>>> Hash: SHA1 >>>> >>>> >>>> >>>> Paul Rubin wrote: >>>>> Chris Stewart <[EMAIL PROTECTED]> writes: >>>>>> I've always had an interest in Python and would like to dabble in it >>>>>> further. I've worked on a few very small command line programs but >>>>>> nothing of any complexity. I'd like to build a really simple GUI app >>>>>> that will work across Mac, Windows, and Linux. How painful is that >>>>>> going to be? I used to be really familiar with Java Swing a few >>>>>> years >>>>>> ago. I imagine it will be similar. >>>>>> ... >>>>>> Next, what would you say is the best framework I should look into? >>>>> If by "best" you mean "easiest", that is probably tkinter, which >>>>> comes with python. It is somewhat rudimentary and the widgets that >>>>> come with it don't look so great. But if you just want to put up >>>>> GUI's with basic functionality and not much glitz, it is ok for most >>>>> such purposes. >>>>> out how to use >>>> I don't quite agree with you on this. Tkinter may be easy because it is >>>> available by standard in Python, but that's about it in my opinion. The >>>> API, look and performance hit is horrible. You're much better of with >>>> PyQt4 which makes the job really simple. >>>> >>>> MFB >>>> -BEGIN PGP SIGNATURE- >>>> Version: GnuPG v1.4.7 (GNU/Linux) >>>> >>>> iD8DBQFH/kjhDpaqHmOKFdQRAj+kAJ0d3aHqpv/mh7kSqtDqUFXtJsxi1gCfU5UP >>>> 2Ygw9ttRIYX+ioMyBVUNsVo= >>>> =stR5 >>>> -END PGP SIGNATURE- >>> I see a lot of people recommend using pyQt, but they never mention the >>> controversy that surrounds its licensing. There have been many posts >>> on the subject already, but if the OP ever decides to sell anything >>> they create, I've heard that QT's licensing is kind of squirrelly. >>> Maybe this has been straightened out? >>> >>> I looked at the website and found it fairly confusing. And don't you >>> need to download QT itself? >>> >>> Mike >> >> Yeah, the licensing of Qt is either be open-source (under one of the >> Qt-exception licenses licenses so no exclusivity for the GPL anymore) or >> pay for the commercial version. So yes, if you would like to sell it as >> closed-source software you will need to buy the commercial version of Qt >> and PyQt. In other words: you will have to pay twice. Don't forget that >> you can also sell open-source software, so you don't have to pay. ;) >> > I don't think PyQt has any licensing restrictions to speak of, only the > underlying Qt platform (though it's a while since I looked). > > regards > Steve Unfortunately, from the PyQt website's FAQ: Do I need the commercial version of PyQt? The easiest way to answer this is to ask "Am I using the commercial edition of Qt?". If so then you also need the commercial version of PyQt. If you are using the GPL version of Qt, then you only need the GPL version of PyQt. MFB -- http://mail.python.org/mailman/listinfo/python-list
Re: How is GUI programming in Python?
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Rune Strand wrote: > On Apr 10, 3:54 am, Chris Stewart <[EMAIL PROTECTED]> wrote: > ... >> >> Next, what would you say is the best framework I should look into? >> I'm curious to hear opinions on that. > > GUI-programming in Python is a neanderthal experience. What one may > love with console scripts is turned upside-down. Projects like Boa > Constructor seemed to be a remedy, but is not developed. The Iron- > Pythonistas has a very promising RAD GUI-tool in the IronPython - > Studio, http://www.codeplex.com/IronPythonStudio - but if you're non- > Iron, only sorrow is left - unless you fancy creating GUI in a text- > editor. Something I consider waste of life. Qt Designer. And creating the GUI yourself in the text editor isn't that bad, plus you have much better control over it. MFB -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.7 (GNU/Linux) iD8DBQFH/+BIDpaqHmOKFdQRAskNAKCDvMAK2MQCurxJ1zopibYOzhUpNgCgq7sn NxW9nWKU9nDrybd2EoxX51w= =okW6 -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: How is GUI programming in Python?
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Gabriel Genellina wrote: > En Fri, 11 Apr 2008 11:31:42 -0300, Michel Bouwmans > <[EMAIL PROTECTED]> escribió: >> Gabriel Genellina wrote: > >>> Another annoying thing with the Qt license is that you have to choose it >>> at the very start of the project. You cannot develop something using the >>> open source license and later decide to switch to the commercial licence >>> and buy it. >> >> Unless you're a company with a risk of being checked for legal software >> etc., you can always ignore that allthough not very legal. > > I just ignore Qt itself. > Then you're ignorant. What do you prefer than? - - GTK is utter bullshit, creating GUI's functional wise. :r - - WxPython is terribly unstable. (Next to that I dislike it using GTK on *NIX, but that's personal :P) - - Tkinter is ugly and is a memory hog. MFB -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.7 (GNU/Linux) iD8DBQFIAQGjDpaqHmOKFdQRAvbQAKCFwfw2qfMPKzwLny1yaLKBb2xMFACfb/2Z 44qenzoZGgNoP1hd76Rrk6k= =eKjK -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: How is GUI programming in Python?
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Torsten Bronger wrote: > Hallöchen! Und auch ein hallo, aus den Niederlanden! :P > Michel Bouwmans writes: > >> Gabriel Genellina wrote: >> >>> Michel Bouwmans <[EMAIL PROTECTED]> escribió: >>> >>>> Gabriel Genellina wrote: >>>> >>>>> Another annoying thing with the Qt license is that you have to >>>>> choose it at the very start of the project. You cannot develop >>>>> something using the open source license and later decide to >>>>> switch to the commercial licence and buy it. >>>> >>>> Unless you're a company with a risk of being checked for legal >>>> software etc., you can always ignore that allthough not very >>>> legal. >>> >>> I just ignore Qt itself. >> >> Then you're ignorant. What do you prefer than? > > Well ... don't expect answers that you like when you suggest doing > something which is not allowed. > >> [...] >> - WxPython is terribly unstable. > > I can't confirm that. When I chose wxPython after thorough > consideration one year ago, my impression was that reports of > instability were indeed frequent but rather old. Apparently, the > situation had improved. Does your experience rely on recent use? > > Tschö, > Torsten. > About half a year/a year ago. Segfaults is simply not something I like to see when I use an API binding. For me it didn't feel that right when using it so I made the temporary switch to Tkinter. greetz MFB -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.7 (GNU/Linux) iD8DBQFIAc3PDpaqHmOKFdQRAi3PAJ4idF7KLdOQfpfARBjA839wyKBQAQCcDIMA GX41PYj5t+ap8nEwkWRtb4Q= =LTVd -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
urllib2 Basic authentication, what am I doing wrong?
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Hey everybody, I'm having a little problem with urllib2 and Basic HTTP authentication. I have the following code: auth = urllib2.HTTPPasswordMgrWithDefaultRealm() auth.add_password(None, 'https://webmail.osg-erasmus.nl/oneNet/NetStorage/', user, password) authhandler = urllib2.HTTPBasicAuthHandler(auth) opener = urllib2.build_opener(auth) opener.addheaders = [('User-agent', 'Mozilla/5.0 Something/1.0')] try: return self.opener.open('https://webmail.osg-erasmus.nl/oneNet/NetStorage/') except urllib2.HTTPError, e: print e.code print e.headers This however does not allow me to authenticate. I keep getting back a 401: 401 Date: Sun, 13 Apr 2008 18:11:32 GMT Server: Apache/2.0.54 (NETWARE) mod_perl/1.99_12 Perl/v5.8.4 PHP/5.0.5 mod_nsn/1.0_0 mod_jk/1.2.14 Set-Cookie: novellsession1=8KuAO0iLyAEAAA==; path=/ WWW-Authenticate: Basic realm="ERASMUS-TREE" Vary: accept-language,accept-charset Accept-Ranges: bytes Connection: close Transfer-Encoding: chunked Content-Type: text/html; charset=iso-8859-1 Content-Language: en Using this nice class (adapted to urllib2) as a basehandler I see that no Authentication-header is being send out: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440574 What am I doing wrong here? I spend almost my entire free time today on this and couldn't find any problem with my code, anyone else has a thought? Thanks in advance. MFB -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.7 (GNU/Linux) iD8DBQFIAkzaDpaqHmOKFdQRAh8WAJ0XbQD5EEmKxVdjndRWWzjwZzWaAgCgjdhR Esk6VBkZ+bEHsxFhg8h3Sy4= =XWrv -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib2 Basic authentication, what am I doing wrong?
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Max Erickson wrote: > On Apr 13, 2:11 pm, Michel Bouwmans <[EMAIL PROTECTED]> wrote: > >> Using this nice class (adapted to urllib2) as a basehandler I see that no >> Authentication-header is being send >> out:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440574 >> >> What am I doing wrong here? I spend almost my entire free time today on >> this and couldn't find any problem with my code, anyone else has a >> thought? Thanks in advance. >> >> MFB > > I've attempted to use a password manager and auth manager and failed > in the past, so this is only a guess, but presumably, between the > realm and uri that you are providing to the password manager, it isn't > providing a password for the page you want to load. I've had success > just explicitly setting the authorization header, using the method > discussed in the comments on this page: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267197 > > > max Thanks for that tip. I tried that and found out that I was still being rejected eventhough the correct Authorization was being send. I then experimented a bit with liveHTTPheaders and it's replay function in firefox and found out that it needed the cookie to succesfully authenticate. I'll try to fix it with that knowledge. Strange software I'm dealing with here, that's for sure. MFB -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.7 (GNU/Linux) iD8DBQFIAovCDpaqHmOKFdQRAuHXAJ9vGNdR2e8s8iA0Z5zIzxASjES3LgCfbVSU 339iu5iO1rv1Ufh0xNntNeY= =2xbX -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Descriptor leak in python 2.4 subprocess module
Hi, I hit an issue with the following python code: try: get_orient = subprocess.Popen (['jpegexiforient', '-n', pathfull], stdin = subprocess.PIPE, stdout = subprocess.PIPE) orient = get_orient.communicate ()[0] except: orient = None The intent of this was to read the exif orientation of a picture, or just use None if jpegexiforient can not run. The application worked fine on my devel machine but I noticed that on a different host, it crashed due to running out of file descriptors. After investigation I found out that the above code was responsible, leaking two file descriptors per invocation if jpegexiforient is not installed on the host. I don't see any way to fix it in my code either, since get_orient is not defined in the exception path, there is no way I can close its file descriptors myself. I believe this is a bug in the subprocess module, it should make sure to clean up after itself when getting out on the exception path. This is with python 2.4.4 on linux (debian etch distribution). Hope this helps. I would prefer to be copied in any replies as I'm not on the list (I will notice the replies after a while either way, but it'll be faster if you can copy me). Cheers, -- Michel "Walken" Lespinasse A program is never fully debugged until the last user dies. -- http://mail.python.org/mailman/listinfo/python-list
Re: Descriptor leak in python 2.4 subprocess module
On Thu, Aug 28, 2008 at 10:37:48AM +0100, Tim Golden wrote: > Michel Lespinasse wrote: > >I hit an issue with the following python code: > >try: > >get_orient = subprocess.Popen (['jpegexiforient', '-n', pathfull], > > stdin = subprocess.PIPE, > > stdout = subprocess.PIPE) > >orient = get_orient.communicate ()[0] > >except: > >orient = None > > > >The application worked fine on my devel machine but I noticed that on a > >different host, it crashed due to running out of file descriptors. > >After investigation I found out that the above code was responsible, > >leaking two file descriptors per invocation if jpegexiforient is not > >installed on the host. > > This looks like a duplicate of http://bugs.python.org/issue3210. > Can you confirm if this seems likely (and, if so, perhaps add > a note to the bug indicating that the problem is on Linux as well)? The root cause is different (subprocess has separate implementations for windows and posix), but the issues are similar. In the posix case, I only observed the issue when you using subprocess.PIPE The attached patch against subprocess.py (as shipped on debian etch, based on python version 2.4.4) seems to work for me: --- /usr/lib/python2.4/subprocess.py2008-04-16 10:59:00.0 -0700 +++ subprocess.py 2008-08-28 13:09:50.0 -0700 @@ -970,6 +970,12 @@ data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB os.close(errpipe_read) if data != "": +if p2cwrite: +os.close(p2cwrite) +if c2pread and c2pread not in (p2cwrite,): +os.close(c2pread) +if errread and errread not in (p2cwrite, c2pread): +os.close(errread) os.waitpid(self.pid, 0) child_exception = pickle.loads(data) raise child_exception I've not tested it much, only wrote it a few minutes ago after looking at the bug you mentionned made me realize that the subprocess module is actually written in python so I could try and fix it :) Hope this helps, -- Michel "Walken" Lespinasse A program is never fully debugged until the last user dies. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Nautilus script
kaer a écrit : #! /usr/bin/python # -*- coding: utf8 -*- import os, sys #NAUTILUS_SCRIPT_SELECTED_FILE_PATHS : chemins des fichiers sélectionnés séparés par des retours à la ligne (newline) (uniquement pour les fichiers locaux) #NAUTILUS_SCRIPT_SELECTED_URIS : URIs des fichiers sélectionnés séparés par des retours à la ligne (newline) #NAUTILUS_SCRIPT_CURRENT_URI : URI de l'emplacement actuel #NAUTILUS_SCRIPT_WINDOW_GEOMETRY : position et taille de la fenêtre actuelle KEYS=("NAUTILUS_SCRIPT_SELECTED_FILE_PATHS", "NAUTILUS_SCRIPT_SELECTED_URIS", "NAUTILUS_SCRIPT_CURRENT_URI", "NAUTILUS_SCRIPT_WINDOW_GEOMETRY") ft=open("/home/kaer/stupid.txt", "w") for key_value in [(key, os.environ.get(key, 'NOT FOUND')) for key in KEYS]: ft.write("env(%s): %s\n" % key_value) file_names=sys.argv[1:] for index, file_name in enumerate(file_names): ft.write("%s: [%s]\n" % (index, file_name)) if os.path.isfile(file_name): os.rename(file_name, '%03d-%s' % (index+1, file_name)) ft.close() Yes, indeed, it works with your code. Thanks for it. I just have to find out why it doesn't work with mine. The problem is that Nautilus scripts are hard to debug. Thanks for your help, Michel -- Michel Leunen http://linux.leunen.com -- http://mail.python.org/mailman/listinfo/python-list