title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
pyGame within a pyGTK application
25,661
<p>What is the best way to use PyGame (SDL) within a PyGTK application?</p> <p>I'm searching for a method that allows me to have a drawing area in the GTK window and at the same time being able to manage both GTK and SDL events.</p>
7
2008-08-25T04:36:48Z
88,457
<p>I tried doing this myself a while ago, and I never got it to work perfectly. Actually I never got it to work at all under Windows, as it kept crashing the entire OS and I ran out of patience. I continued to use it though as it was only important it ran on Linux, and was only a small project. I'd strongly recommend you investigate alternatives. It always felt like a nasty hack, and made me feel dirty.</p>
0
2008-09-17T22:45:49Z
[ "python", "gtk", "pygtk", "sdl", "pygame" ]
pyGame within a pyGTK application
25,661
<p>What is the best way to use PyGame (SDL) within a PyGTK application?</p> <p>I'm searching for a method that allows me to have a drawing area in the GTK window and at the same time being able to manage both GTK and SDL events.</p>
7
2008-08-25T04:36:48Z
199,288
<p>There's a simple solution that might work for you. </p> <p>Write the PyGTK stuff and PyGame stuff as separate applications. Then from the PyGTK application call the PyGame application, using os.system to call the PyGame application. If you need to share data between the two then either use a database, pipes or IPC.</p>
0
2008-10-13T22:38:59Z
[ "python", "gtk", "pygtk", "sdl", "pygame" ]
pyGame within a pyGTK application
25,661
<p>What is the best way to use PyGame (SDL) within a PyGTK application?</p> <p>I'm searching for a method that allows me to have a drawing area in the GTK window and at the same time being able to manage both GTK and SDL events.</p>
7
2008-08-25T04:36:48Z
341,525
<p><a href="http://faq.pygtk.org/index.py?file=faq23.042.htp&amp;req=show" rel="nofollow">http://faq.pygtk.org/index.py?file=faq23.042.htp&amp;req=show</a> mentions it all:</p> <p>You need to create a drawing area and set the environment variable SDL_WINDOWID after it's realized:</p> <pre> import os import gobject import gtk import pygame WINX = 400 WINY = 200 window = gtk.Window() window.connect('delete-event', gtk.main_quit) window.set_resizable(False) area = gtk.DrawingArea() area.set_app_paintable(True) area.set_size_request(WINX, WINY) window.add(area) area.realize() # Force SDL to write on our drawing area os.putenv('SDL_WINDOWID', str(area.window.xid)) # We need to flush the XLib event loop otherwise we can't # access the XWindow which set_mode() requires gtk.gdk.flush() pygame.init() pygame.display.set_mode((WINX, WINY), 0, 0) screen = pygame.display.get_surface() image_surface = pygame.image.load('foo.png') screen.blit(image_surface, (0, 0)) gobject.idle_add(pygame.display.update) window.show_all() while gtk.event_pending(): # pygame/SDL event processing goes here gtk.main_iteration(False) </pre>
1
2008-12-04T17:52:13Z
[ "python", "gtk", "pygtk", "sdl", "pygame" ]
pyGame within a pyGTK application
25,661
<p>What is the best way to use PyGame (SDL) within a PyGTK application?</p> <p>I'm searching for a method that allows me to have a drawing area in the GTK window and at the same time being able to manage both GTK and SDL events.</p>
7
2008-08-25T04:36:48Z
19,860,670
<p>The Sugar project has several Activities built with PyGTK and PyGame.</p> <p>They wrote a support lib to achieve this, called <a href="http://wiki.sugarlabs.org/go/Development_Team/Sugargame" rel="nofollow">Sugargame</a>. You should be able to modify it for regular PyGTK apps instead of Sugar.</p> <p>Here's a <a href="http://georgejhunt.com/olpc/pydebug/ActivityBook/ActivitiesGuideSugar__ActivitiesUsingPyGame.html" rel="nofollow">chapter in Sugar's development book</a> about how to use it.</p> <p>The lib allows for communicating events between GTK and PyGame.</p> <p>Enjoy!</p>
0
2013-11-08T13:51:30Z
[ "python", "gtk", "pygtk", "sdl", "pygame" ]
Python super class reflection
25,807
<p>If I have Python code</p> <pre><code>class A(): pass class B(): pass class C(A, B): pass </code></pre> <p>and I have class <code>C</code>, is there a way to iterate through it's super classed (<code>A</code> and <code>B</code>)? Something like pseudocode:</p> <pre><code>&gt;&gt;&gt; magicGetSuperClasses(C) (&lt;type 'A'&gt;, &lt;type 'B'&gt;) </code></pre> <p>One solution seems to be <a href="http://docs.python.org/lib/module-inspect.html">inspect module</a> and <code>getclasstree</code> function.</p> <pre><code>def magicGetSuperClasses(cls): return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type] </code></pre> <p>but is this a "Pythonian" way to achieve the goal?</p>
30
2008-08-25T09:06:16Z
25,815
<p><code>C.__bases__</code> is an array of the super classes, so you could implement your hypothetical function like so:</p> <pre><code>def magicGetSuperClasses(cls): return cls.__bases__ </code></pre> <p>But I imagine it would be easier to just reference <code>cls.__bases__</code> directly in most cases.</p>
36
2008-08-25T09:22:22Z
[ "python", "reflection" ]
Python super class reflection
25,807
<p>If I have Python code</p> <pre><code>class A(): pass class B(): pass class C(A, B): pass </code></pre> <p>and I have class <code>C</code>, is there a way to iterate through it's super classed (<code>A</code> and <code>B</code>)? Something like pseudocode:</p> <pre><code>&gt;&gt;&gt; magicGetSuperClasses(C) (&lt;type 'A'&gt;, &lt;type 'B'&gt;) </code></pre> <p>One solution seems to be <a href="http://docs.python.org/lib/module-inspect.html">inspect module</a> and <code>getclasstree</code> function.</p> <pre><code>def magicGetSuperClasses(cls): return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type] </code></pre> <p>but is this a "Pythonian" way to achieve the goal?</p>
30
2008-08-25T09:06:16Z
35,111
<p>@John: Your snippet doesn't work -- you are returning the <em>class</em> of the base classes (which are also known as metaclasses). You really just want <code>cls.__bases__</code>:</p> <pre><code>class A: pass class B: pass class C(A, B): pass c = C() # Instance assert C.__bases__ == (A, B) # Works assert c.__class__.__bases__ == (A, B) # Works def magicGetSuperClasses(clz): return tuple([base.__class__ for base in clz.__bases__]) assert magicGetSuperClasses(C) == (A, B) # Fails </code></pre> <p>Also, if you're using Python 2.4+ you can use <a href="http://www.python.org/dev/peps/pep-0289/">generator expressions</a> instead of creating a list (via []), then turning it into a tuple (via <code>tuple</code>). For example:</p> <pre><code>def get_base_metaclasses(cls): """Returns the metaclass of all the base classes of cls.""" return tuple(base.__class__ for base in clz.__bases__) </code></pre> <p>That's a somewhat confusing example, but genexps are generally easy and cool. :)</p>
11
2008-08-29T19:30:31Z
[ "python", "reflection" ]
Python super class reflection
25,807
<p>If I have Python code</p> <pre><code>class A(): pass class B(): pass class C(A, B): pass </code></pre> <p>and I have class <code>C</code>, is there a way to iterate through it's super classed (<code>A</code> and <code>B</code>)? Something like pseudocode:</p> <pre><code>&gt;&gt;&gt; magicGetSuperClasses(C) (&lt;type 'A'&gt;, &lt;type 'B'&gt;) </code></pre> <p>One solution seems to be <a href="http://docs.python.org/lib/module-inspect.html">inspect module</a> and <code>getclasstree</code> function.</p> <pre><code>def magicGetSuperClasses(cls): return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type] </code></pre> <p>but is this a "Pythonian" way to achieve the goal?</p>
30
2008-08-25T09:06:16Z
552,862
<p>The inspect module was a good start, use the <a href="http://docs.python.org/library/inspect.html#inspect.getmro" rel="nofollow">getmro</a> function:</p> <blockquote> <p>Return a tuple of class cls’s base classes, including cls, in method resolution order. No class appears more than once in this tuple. ...</p> </blockquote> <pre><code>&gt;&gt;&gt; class A: pass &gt;&gt;&gt; class B: pass &gt;&gt;&gt; class C(A, B): pass &gt;&gt;&gt; import inspect &gt;&gt;&gt; inspect.getmro(C)[1:] (&lt;class __main__.A at 0x8c59f2c&gt;, &lt;class __main__.B at 0x8c59f5c&gt;) </code></pre> <p>The first element of the returned tuple is <code>C</code>, you can just disregard it.</p>
4
2009-02-16T10:27:09Z
[ "python", "reflection" ]
Python super class reflection
25,807
<p>If I have Python code</p> <pre><code>class A(): pass class B(): pass class C(A, B): pass </code></pre> <p>and I have class <code>C</code>, is there a way to iterate through it's super classed (<code>A</code> and <code>B</code>)? Something like pseudocode:</p> <pre><code>&gt;&gt;&gt; magicGetSuperClasses(C) (&lt;type 'A'&gt;, &lt;type 'B'&gt;) </code></pre> <p>One solution seems to be <a href="http://docs.python.org/lib/module-inspect.html">inspect module</a> and <code>getclasstree</code> function.</p> <pre><code>def magicGetSuperClasses(cls): return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type] </code></pre> <p>but is this a "Pythonian" way to achieve the goal?</p>
30
2008-08-25T09:06:16Z
553,927
<p>if you need to know to order in which super() would call the classes you can use <code>C.__mro__</code> and don't need <code>inspect</code> therefore.</p>
2
2009-02-16T16:38:14Z
[ "python", "reflection" ]
Is there any difference between "foo is None" and "foo == None"?
26,595
<p>Is there any difference between:</p> <pre><code>if foo is None: pass </code></pre> <p>and</p> <pre><code>if foo == None: pass </code></pre> <p>The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?</p>
193
2008-08-25T18:27:16Z
26,611
<p><code>is</code> always returns <code>True</code> if it compares the same object instance</p> <p>Whereas <code>==</code> is ultimately determined by the <code>__eq__()</code> method</p> <p>i.e.</p> <pre><code> >>> class foo(object): def __eq__(self, other): return True >>> f = foo() >>> f == None True >>> f is None False </code></pre>
223
2008-08-25T18:38:10Z
[ "python" ]
Is there any difference between "foo is None" and "foo == None"?
26,595
<p>Is there any difference between:</p> <pre><code>if foo is None: pass </code></pre> <p>and</p> <pre><code>if foo == None: pass </code></pre> <p>The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?</p>
193
2008-08-25T18:27:16Z
26,626
<p>You may want to read this <a href="http://mail.python.org/pipermail/python-list/2001-November/094920.html">object identity and equivalence</a>.</p> <p>The statement 'is' is used for object identity, it checks if objects refer to the same instance (same address in memory).</p> <p>And the '==' statement refers to equality (same value).</p>
46
2008-08-25T18:48:20Z
[ "python" ]
Is there any difference between "foo is None" and "foo == None"?
26,595
<p>Is there any difference between:</p> <pre><code>if foo is None: pass </code></pre> <p>and</p> <pre><code>if foo == None: pass </code></pre> <p>The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?</p>
193
2008-08-25T18:27:16Z
26,654
<p>For None there shouldn't be a difference between equality (==) and identity (is). The NoneType probably returns identity for equality. Since None is the only instance you can make of NoneType (I think this is true), the two operations are the same. In the case of other types this is not always the case. For example:</p> <pre><code>list1 = [1, 2, 3] list2 = [1, 2, 3] if list1==list2: print "Equal" if list1 is list2: print "Same" </code></pre> <p>This would print "Equal" since lists have a comparison operation that is not the default returning of identity.</p>
3
2008-08-25T19:04:59Z
[ "python" ]
Is there any difference between "foo is None" and "foo == None"?
26,595
<p>Is there any difference between:</p> <pre><code>if foo is None: pass </code></pre> <p>and</p> <pre><code>if foo == None: pass </code></pre> <p>The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?</p>
193
2008-08-25T18:27:16Z
26,963
<p>@<a href="http://stackoverflow.com/questions/26595/is-there-any-difference-between-foo-is-none-and-foo-none#26698" rel="nofollow">Jason</a>:</p> <blockquote> <p>I recommend using something more along the lines of</p> <pre><code>if foo: #foo isn't None else: #foo is None </code></pre> </blockquote> <p>I don't like using "if foo:" unless foo truly represents a boolean value (i.e. 0 or 1). If foo is a string or an object or something else, "if foo:" may work, but it looks like a lazy shortcut to me. If you're checking to see if x is None, say "if x is None:".</p>
4
2008-08-25T21:35:14Z
[ "python" ]
Is there any difference between "foo is None" and "foo == None"?
26,595
<p>Is there any difference between:</p> <pre><code>if foo is None: pass </code></pre> <p>and</p> <pre><code>if foo == None: pass </code></pre> <p>The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?</p>
193
2008-08-25T18:27:16Z
28,067
<p>A word of caution: </p> <pre><code>if foo: # do something </code></pre> <p>Is <strong>not</strong> exactly the same as:</p> <pre><code>if x is not None: # do something </code></pre> <p>The former is a boolean value test and can evaluate to false in different contexts. There are a number of things that represent false in a boolean value tests for example empty containers, boolean values. None also evaluates to false in this situation but other things do too.</p>
21
2008-08-26T13:44:11Z
[ "python" ]
Is there any difference between "foo is None" and "foo == None"?
26,595
<p>Is there any difference between:</p> <pre><code>if foo is None: pass </code></pre> <p>and</p> <pre><code>if foo == None: pass </code></pre> <p>The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?</p>
193
2008-08-25T18:27:16Z
585,491
<p><code>(ob1 is ob2)</code> equal to <code>(id(ob1) == id(ob2))</code></p>
12
2009-02-25T10:34:49Z
[ "python" ]
Is there any difference between "foo is None" and "foo == None"?
26,595
<p>Is there any difference between:</p> <pre><code>if foo is None: pass </code></pre> <p>and</p> <pre><code>if foo == None: pass </code></pre> <p>The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?</p>
193
2008-08-25T18:27:16Z
2,932,590
<p>The reason <code>foo is None</code> is the preferred way is that you might be handling an object that defines its own <code>__eq__</code>, and that defines the object to be equal to None. So, always use <code>foo is None</code> if you need to see if it is infact <code>None</code>.</p>
10
2010-05-28T21:15:53Z
[ "python" ]
Is there any difference between "foo is None" and "foo == None"?
26,595
<p>Is there any difference between:</p> <pre><code>if foo is None: pass </code></pre> <p>and</p> <pre><code>if foo == None: pass </code></pre> <p>The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?</p>
193
2008-08-25T18:27:16Z
5,451,786
<p>John Machin's conclusion that <code>None</code> is a singleton is a conclusion bolstered by this code.</p> <pre><code>&gt;&gt;&gt; x = None &gt;&gt;&gt; y = None &gt;&gt;&gt; x == y True &gt;&gt;&gt; x is y True &gt;&gt;&gt; </code></pre> <p>Since <code>None</code> is a singleton, <code>x == None</code> and <code>x is None</code> would have the same result. However, in my aesthetical opinion, <code>x == None</code> is best.</p>
1
2011-03-27T19:31:59Z
[ "python" ]
Is there any difference between "foo is None" and "foo == None"?
26,595
<p>Is there any difference between:</p> <pre><code>if foo is None: pass </code></pre> <p>and</p> <pre><code>if foo == None: pass </code></pre> <p>The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?</p>
193
2008-08-25T18:27:16Z
16,636,124
<p>Some more details:</p> <ol> <li><p>The <code>is</code> clause actually checks if the two <code>object</code>s are at the same memory location or not. i.e whether they both point to the same memory location and have the same <code>id</code>. </p></li> <li><p>As a consequence of 1, <code>is</code> ensures whether, or not, the two lexically represented <code>object</code>s have identical attributes (attributes-of-attributes...) or not</p></li> <li><p>Instantiation of primitive types like <code>bool</code>, <code>int</code>, <code>string</code>(with some exception), <code>NoneType</code> having a same value will always be in the same memory location.</p></li> </ol> <p>E.g.</p> <pre><code>&gt;&gt;&gt; int(1) is int(1) True &gt;&gt;&gt; str("abcd") is str("abcd") True &gt;&gt;&gt; bool(1) is bool(2) True &gt;&gt;&gt; bool(0) is bool(0) True &gt;&gt;&gt; bool(0) False &gt;&gt;&gt; bool(1) True </code></pre> <p>And since <code>NoneType</code> can only have one instance of itself in the python's "look-up" table therefore the former and the latter are more of a programming style of the developer who wrote the code(maybe for consistency) rather then having any subtle logical reason to choose one over the other.</p>
0
2013-05-19T15:08:49Z
[ "python" ]
Is there any difference between "foo is None" and "foo == None"?
26,595
<p>Is there any difference between:</p> <pre><code>if foo is None: pass </code></pre> <p>and</p> <pre><code>if foo == None: pass </code></pre> <p>The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?</p>
193
2008-08-25T18:27:16Z
16,636,358
<p>There is no difference because objects which are identical will of course be equal. However, <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow" title="PEP 8">PEP 8</a> clearly states you should use <code>is</code>:</p> <blockquote> <p>Comparisons to singletons like None should always be done with is or is not, never the equality operators.</p> </blockquote>
8
2013-05-19T15:35:38Z
[ "python" ]
Is there any difference between "foo is None" and "foo == None"?
26,595
<p>Is there any difference between:</p> <pre><code>if foo is None: pass </code></pre> <p>and</p> <pre><code>if foo == None: pass </code></pre> <p>The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?</p>
193
2008-08-25T18:27:16Z
27,559,554
<p><code>is</code> tests for identity, <strong>not</strong> equality. For your statement <code>foo is none</code>, Python simply compares the memory address of objects. It means you are asking the question "Do I have two names for the same object?"</p> <p><code>==</code> on the other hand tests for equality as determined by the <code>__eq__()</code> method. It doesn't cares about identity.</p> <pre><code>In [102]: x, y, z = 2, 2, 2.0 In [103]: id(x), id(y), id(z) Out[103]: (38641984, 38641984, 48420880) In [104]: x is y Out[104]: True In [105]: x == y Out[105]: True In [106]: x is z Out[106]: False In [107]: x == z Out[107]: True </code></pre> <p><code>None</code> is a singleton operator. So <code>None is None</code> is always true.</p> <pre><code>In [101]: None is None Out[101]: True </code></pre>
3
2014-12-19T04:05:39Z
[ "python" ]
wxpython: How do I examine dragged data in OnDragOver?
26,706
<p>I'm a bit perplexed by drag and drop in wxPython (but perhaps this questions pertains to drag and drop in other GUI frameworks as well). The frameworks provides a couple of callbacks (OnEnter and OnDragOver) that purportedly allow me to inform the system whether the current mouse position is a valid place to drop whatever it is that is being dragged. From these methods I can return wx.DragNone, wx.DragCopy, etc. What baffles me is that from within these methods I am not allowed to call GetData, which means I am not allowed to examine the data that the user is dragging. If I cannot see the data, how am I supposed to know whether it is OK for the user to drop here?</p>
5
2008-08-25T19:43:15Z
26,707
<p>One solution, which is a hack of limited usefulness, is when a drag is initiated, store the dragged data in a global or static reference somewhere. This way, in the OnEnter and OnDragOver handlers, it is possible to get a reference to the data being dragged. This is of course only useful for drags within the same application (the same instance of the application, actually).</p>
1
2008-08-25T19:45:40Z
[ "python", "user-interface", "drag-and-drop", "wxpython", "wxwidgets" ]
wxpython: How do I examine dragged data in OnDragOver?
26,706
<p>I'm a bit perplexed by drag and drop in wxPython (but perhaps this questions pertains to drag and drop in other GUI frameworks as well). The frameworks provides a couple of callbacks (OnEnter and OnDragOver) that purportedly allow me to inform the system whether the current mouse position is a valid place to drop whatever it is that is being dragged. From these methods I can return wx.DragNone, wx.DragCopy, etc. What baffles me is that from within these methods I am not allowed to call GetData, which means I am not allowed to examine the data that the user is dragging. If I cannot see the data, how am I supposed to know whether it is OK for the user to drop here?</p>
5
2008-08-25T19:43:15Z
139,047
<p>There is no way to see dragged data in <code>OnEnter</code> and <code>OnDragOver</code> methods.</p> <p>The only solution I found is to store the dragged item in some instance variable that is then readable inside these methods.</p>
1
2008-09-26T12:15:24Z
[ "python", "user-interface", "drag-and-drop", "wxpython", "wxwidgets" ]
Where can I learn more about PyPy's translation function?
27,567
<p>I've been having a hard time trying to understand PyPy's translation. It looks like something absolutely revolutionary from simply reading the description, however I'm hard-pressed to find good documentation on actually translating a real world piece of code to something such as LLVM. Does such a thing exist? The official PyPy documentation on it just skims over the functionality, rather than providing anything I can try out myself.</p>
9
2008-08-26T08:40:28Z
27,600
<p>Are you looking for Python specific translation, or just the general "how do you compile some code to bytecode"? If the latter is your case, check <a href="http://llvm.org/docs/tutorial/" rel="nofollow">the LLVM tutorial</a>. I especially find chapter two, which teaches you to write a compiler for your own language, interesting.</p>
2
2008-08-26T09:06:33Z
[ "python", "translation", "pypy" ]
Where can I learn more about PyPy's translation function?
27,567
<p>I've been having a hard time trying to understand PyPy's translation. It looks like something absolutely revolutionary from simply reading the description, however I'm hard-pressed to find good documentation on actually translating a real world piece of code to something such as LLVM. Does such a thing exist? The official PyPy documentation on it just skims over the functionality, rather than providing anything I can try out myself.</p>
9
2008-08-26T08:40:28Z
42,689
<p>This document seems to go into quite a bit of detail (and I think a complete description is out of scope for a stackoverflow answer):</p> <ul> <li><a href="http://codespeak.net/pypy/dist/pypy/doc/translation.html" rel="nofollow">http://codespeak.net/pypy/dist/pypy/doc/translation.html</a></li> </ul> <p>The general idea of translating from one language to another isn't particularly revolutionary, but it has only recently been gaining popularity / applicability in "real-world" applications. <a href="http://code.google.com/webtoolkit/" rel="nofollow">GWT</a> does this with Java (generating Javascript) and there is a library for translating Haskell into various other languages as well (called <a href="http://www.haskell.org/haskellwiki/Yhc" rel="nofollow">YHC</a>)</p>
4
2008-09-03T21:52:46Z
[ "python", "translation", "pypy" ]
Where can I learn more about PyPy's translation function?
27,567
<p>I've been having a hard time trying to understand PyPy's translation. It looks like something absolutely revolutionary from simply reading the description, however I'm hard-pressed to find good documentation on actually translating a real world piece of code to something such as LLVM. Does such a thing exist? The official PyPy documentation on it just skims over the functionality, rather than providing anything I can try out myself.</p>
9
2008-08-26T08:40:28Z
98,313
<p>If you want some hand-on examples, <a href="http://codespeak.net/pypy/dist/pypy/doc/getting-started.html" rel="nofollow">PyPy's Getting Started</a> document has a section titled "Trying out the translator".</p>
3
2008-09-19T00:24:38Z
[ "python", "translation", "pypy" ]
Where can I learn more about PyPy's translation function?
27,567
<p>I've been having a hard time trying to understand PyPy's translation. It looks like something absolutely revolutionary from simply reading the description, however I'm hard-pressed to find good documentation on actually translating a real world piece of code to something such as LLVM. Does such a thing exist? The official PyPy documentation on it just skims over the functionality, rather than providing anything I can try out myself.</p>
9
2008-08-26T08:40:28Z
1,041,655
<p>PyPy translator is in general, not intended for more public use. We use it for translating our own python interpreter (including JIT and GCs, both written in RPython, this restricted subset of Python). The idea is that with good JIT and GC, you'll be able to speedups even without knowing or using PyPy's translation toolchain (and more importantly, without restricting yourself to RPython).</p> <p>Cheers, fijal</p>
3
2009-06-25T00:41:19Z
[ "python", "translation", "pypy" ]
Where can I learn more about PyPy's translation function?
27,567
<p>I've been having a hard time trying to understand PyPy's translation. It looks like something absolutely revolutionary from simply reading the description, however I'm hard-pressed to find good documentation on actually translating a real world piece of code to something such as LLVM. Does such a thing exist? The official PyPy documentation on it just skims over the functionality, rather than providing anything I can try out myself.</p>
9
2008-08-26T08:40:28Z
1,041,857
<blockquote> <p>It looks like something absolutely revolutionary from simply reading the description,</p> </blockquote> <p>As far as I know, PyPy is novel in the sense that it is the first system expressly designed for <em>implementing</em> languages. Other tools exist to help with much of the very front end, such as parser generators, or for the very back end, such as code generation, but not much existed for connecting the two.</p>
1
2009-06-25T02:07:47Z
[ "python", "translation", "pypy" ]
Does PHP have an equivalent to this type of Python string substitution?
28,165
<p>Python has this wonderful way of handling string substitutions using dictionaries:</p> <pre><code>&gt;&gt;&gt; 'The %(site)s site %(adj)s because it %(adj)s' % {'site':'Stackoverflow', 'adj':'rocks'} 'The Stackoverflow site rocks because it rocks' </code></pre> <p>I love this because you can specify a value once in the dictionary and then replace it all over the place in the string.</p> <p>I've tried to achieve something similar in PHP using various string replace functions but everything I've come up with feels awkward.</p> <p>Does anybody have a nice clean way to do this kind of string substitution in PHP?</p> <p><em><strong>Edit</em></strong><br> Here's the code from the sprintf page that I liked best. </p> <pre><code>&lt;?php function sprintf3($str, $vars, $char = '%') { $tmp = array(); foreach($vars as $k =&gt; $v) { $tmp[$char . $k . $char] = $v; } return str_replace(array_keys($tmp), array_values($tmp), $str); } echo sprintf3( 'The %site% site %adj% because it %adj%', array('site'=&gt;'Stackoverflow', 'adj'=&gt;'rocks')); ?&gt; </code></pre>
10
2008-08-26T14:20:48Z
28,199
<p>Some of the user-contributed notes and functions in <a href="http://us3.php.net/sprintf" rel="nofollow">PHP's documentation for sprintf</a> come quite close.</p> <p>Note: search the page for "sprintf2".</p>
1
2008-08-26T14:30:17Z
[ "php", "python", "string" ]
Does PHP have an equivalent to this type of Python string substitution?
28,165
<p>Python has this wonderful way of handling string substitutions using dictionaries:</p> <pre><code>&gt;&gt;&gt; 'The %(site)s site %(adj)s because it %(adj)s' % {'site':'Stackoverflow', 'adj':'rocks'} 'The Stackoverflow site rocks because it rocks' </code></pre> <p>I love this because you can specify a value once in the dictionary and then replace it all over the place in the string.</p> <p>I've tried to achieve something similar in PHP using various string replace functions but everything I've come up with feels awkward.</p> <p>Does anybody have a nice clean way to do this kind of string substitution in PHP?</p> <p><em><strong>Edit</em></strong><br> Here's the code from the sprintf page that I liked best. </p> <pre><code>&lt;?php function sprintf3($str, $vars, $char = '%') { $tmp = array(); foreach($vars as $k =&gt; $v) { $tmp[$char . $k . $char] = $v; } return str_replace(array_keys($tmp), array_values($tmp), $str); } echo sprintf3( 'The %site% site %adj% because it %adj%', array('site'=&gt;'Stackoverflow', 'adj'=&gt;'rocks')); ?&gt; </code></pre>
10
2008-08-26T14:20:48Z
28,247
<pre><code>function subst($str, $dict){ return preg_replace(array_map(create_function('$a', 'return "/%\\($a\\)s/";'), array_keys($dict)), array_values($dict), $str); } </code></pre> <p>You call it like so:</p> <pre><code>echo subst('The %(site)s site %(adj)s because it %(adj)s', array('site'=&gt;'Stackoverflow', 'adj'=&gt;'rocks')); </code></pre>
4
2008-08-26T14:49:54Z
[ "php", "python", "string" ]
Does PHP have an equivalent to this type of Python string substitution?
28,165
<p>Python has this wonderful way of handling string substitutions using dictionaries:</p> <pre><code>&gt;&gt;&gt; 'The %(site)s site %(adj)s because it %(adj)s' % {'site':'Stackoverflow', 'adj':'rocks'} 'The Stackoverflow site rocks because it rocks' </code></pre> <p>I love this because you can specify a value once in the dictionary and then replace it all over the place in the string.</p> <p>I've tried to achieve something similar in PHP using various string replace functions but everything I've come up with feels awkward.</p> <p>Does anybody have a nice clean way to do this kind of string substitution in PHP?</p> <p><em><strong>Edit</em></strong><br> Here's the code from the sprintf page that I liked best. </p> <pre><code>&lt;?php function sprintf3($str, $vars, $char = '%') { $tmp = array(); foreach($vars as $k =&gt; $v) { $tmp[$char . $k . $char] = $v; } return str_replace(array_keys($tmp), array_values($tmp), $str); } echo sprintf3( 'The %site% site %adj% because it %adj%', array('site'=&gt;'Stackoverflow', 'adj'=&gt;'rocks')); ?&gt; </code></pre>
10
2008-08-26T14:20:48Z
28,349
<p>@<a href="http://stackoverflow.com/questions/28165/does-php-have-an-equivalent-to-this-type-of-python-string-substitution#28199" rel="nofollow">Marius</a></p> <p>I don't know if it's faster, but you can do it without regexes:</p> <pre><code>function subst($str, $dict) { foreach ($dict AS $key, $value) { $str = str_replace($key, $value, $str); } return $str; } </code></pre>
3
2008-08-26T15:21:51Z
[ "php", "python", "string" ]
Is "safe_eval" really safe?
28,369
<p>I'm looking for a "safe" eval function, to implement spreadsheet-like calculations (using numpy/scipy).</p> <p>The functionality to do this (the <a href="http://docs.python.org/lib/module-rexec.html" rel="nofollow">rexec module</a>) has been removed from Python since 2.3 due to apparently unfixable security problems. There are several third-party hacks out there that purport to do this - the most thought-out solution that I have found is <a href="http://code.activestate.com/recipes/496746/" rel="nofollow">this Python Cookbok recipe</a>, "safe_eval". </p> <p>Am I reasonably safe if I use this (or something similar), to protect from malicious code, or am I stuck with writing my own parser? Does anyone know of any better alternatives?</p> <p>EDIT: I just discovered <a href="http://pypi.python.org/pypi/RestrictedPython" rel="nofollow">RestrictedPython</a>, which is part of Zope. Any opinions on this are welcome.</p>
3
2008-08-26T15:27:03Z
28,436
<p>Writing your own parser could be fun! It might be a better option because people are expecting to use the familiar spreadsheet syntax (Excel, etc) and not Python when they're entering formulas. I'm not familiar with safe_eval but I would imagine that anything like this certainly has the potential for exploitation.</p>
2
2008-08-26T15:44:31Z
[ "python", "security" ]
Is "safe_eval" really safe?
28,369
<p>I'm looking for a "safe" eval function, to implement spreadsheet-like calculations (using numpy/scipy).</p> <p>The functionality to do this (the <a href="http://docs.python.org/lib/module-rexec.html" rel="nofollow">rexec module</a>) has been removed from Python since 2.3 due to apparently unfixable security problems. There are several third-party hacks out there that purport to do this - the most thought-out solution that I have found is <a href="http://code.activestate.com/recipes/496746/" rel="nofollow">this Python Cookbok recipe</a>, "safe_eval". </p> <p>Am I reasonably safe if I use this (or something similar), to protect from malicious code, or am I stuck with writing my own parser? Does anyone know of any better alternatives?</p> <p>EDIT: I just discovered <a href="http://pypi.python.org/pypi/RestrictedPython" rel="nofollow">RestrictedPython</a>, which is part of Zope. Any opinions on this are welcome.</p>
3
2008-08-26T15:27:03Z
29,390
<p>Although that code looks quite secure, I've always held the opinion that any sufficiently motivated person could break it given adequate time. I do think it will take quite a bit of determination to get through that, but I'm relatively sure it could be done.</p>
1
2008-08-27T02:37:05Z
[ "python", "security" ]
Is "safe_eval" really safe?
28,369
<p>I'm looking for a "safe" eval function, to implement spreadsheet-like calculations (using numpy/scipy).</p> <p>The functionality to do this (the <a href="http://docs.python.org/lib/module-rexec.html" rel="nofollow">rexec module</a>) has been removed from Python since 2.3 due to apparently unfixable security problems. There are several third-party hacks out there that purport to do this - the most thought-out solution that I have found is <a href="http://code.activestate.com/recipes/496746/" rel="nofollow">this Python Cookbok recipe</a>, "safe_eval". </p> <p>Am I reasonably safe if I use this (or something similar), to protect from malicious code, or am I stuck with writing my own parser? Does anyone know of any better alternatives?</p> <p>EDIT: I just discovered <a href="http://pypi.python.org/pypi/RestrictedPython" rel="nofollow">RestrictedPython</a>, which is part of Zope. Any opinions on this are welcome.</p>
3
2008-08-26T15:27:03Z
31,964
<p>Daniel, <a href="http://jinja.pocoo.org/2/documentation/intro" rel="nofollow">Jinja</a> implements a sandboxe environment that may or may not be useful to you. From what I remember, it doesn't yet "comprehend" list comprehensions. </p> <p><a href="http://jinja.pocoo.org/2/documentation/sandbox" rel="nofollow">Sanbox info</a> </p>
0
2008-08-28T10:12:03Z
[ "python", "security" ]
Is "safe_eval" really safe?
28,369
<p>I'm looking for a "safe" eval function, to implement spreadsheet-like calculations (using numpy/scipy).</p> <p>The functionality to do this (the <a href="http://docs.python.org/lib/module-rexec.html" rel="nofollow">rexec module</a>) has been removed from Python since 2.3 due to apparently unfixable security problems. There are several third-party hacks out there that purport to do this - the most thought-out solution that I have found is <a href="http://code.activestate.com/recipes/496746/" rel="nofollow">this Python Cookbok recipe</a>, "safe_eval". </p> <p>Am I reasonably safe if I use this (or something similar), to protect from malicious code, or am I stuck with writing my own parser? Does anyone know of any better alternatives?</p> <p>EDIT: I just discovered <a href="http://pypi.python.org/pypi/RestrictedPython" rel="nofollow">RestrictedPython</a>, which is part of Zope. Any opinions on this are welcome.</p>
3
2008-08-26T15:27:03Z
32,028
<p>Depends on your definition of safe I suppose. A lot of the security depends on what you pass in and what you are allowed to pass in the context. For instance, if a file is passed in, I can open arbitrary files:</p> <pre><code>&gt;&gt;&gt; names['f'] = open('foo', 'w+') &gt;&gt;&gt; safe_eval.safe_eval("baz = type(f)('baz', 'w+')", names) &gt;&gt;&gt; names['baz'] &lt;open file 'baz', mode 'w+' at 0x413da0&gt; </code></pre> <p>Furthermore, the environment is very restricted (you cannot pass in modules), thus, you can't simply pass in a module of utility functions like re or random.</p> <p>On the other hand, you don't need to write your own parser, you could just write your own evaluator for the python ast:</p> <pre><code>&gt;&gt;&gt; import compiler &gt;&gt;&gt; ast = compiler.parse("print 'Hello world!'") </code></pre> <p>That way, hopefully, you could implement safe imports. The other idea is to use Jython or IronPython and take advantage of Java/.Net sandboxing capabilities.</p>
1
2008-08-28T11:35:19Z
[ "python", "security" ]
Is "safe_eval" really safe?
28,369
<p>I'm looking for a "safe" eval function, to implement spreadsheet-like calculations (using numpy/scipy).</p> <p>The functionality to do this (the <a href="http://docs.python.org/lib/module-rexec.html" rel="nofollow">rexec module</a>) has been removed from Python since 2.3 due to apparently unfixable security problems. There are several third-party hacks out there that purport to do this - the most thought-out solution that I have found is <a href="http://code.activestate.com/recipes/496746/" rel="nofollow">this Python Cookbok recipe</a>, "safe_eval". </p> <p>Am I reasonably safe if I use this (or something similar), to protect from malicious code, or am I stuck with writing my own parser? Does anyone know of any better alternatives?</p> <p>EDIT: I just discovered <a href="http://pypi.python.org/pypi/RestrictedPython" rel="nofollow">RestrictedPython</a>, which is part of Zope. Any opinions on this are welcome.</p>
3
2008-08-26T15:27:03Z
6,909,802
<p>If you simply need to write down and read some data structure in Python, and don't need the actual capacity of executing custom code, this one is a better fit: <a href="http://code.activestate.com/recipes/364469-safe-eval/" rel="nofollow">http://code.activestate.com/recipes/364469-safe-eval/</a></p> <p>It garantees that no code is executed, only static data structures are evaluated: strings, lists, tuples, dictionnaries.</p>
1
2011-08-02T09:19:57Z
[ "python", "security" ]
Is "safe_eval" really safe?
28,369
<p>I'm looking for a "safe" eval function, to implement spreadsheet-like calculations (using numpy/scipy).</p> <p>The functionality to do this (the <a href="http://docs.python.org/lib/module-rexec.html" rel="nofollow">rexec module</a>) has been removed from Python since 2.3 due to apparently unfixable security problems. There are several third-party hacks out there that purport to do this - the most thought-out solution that I have found is <a href="http://code.activestate.com/recipes/496746/" rel="nofollow">this Python Cookbok recipe</a>, "safe_eval". </p> <p>Am I reasonably safe if I use this (or something similar), to protect from malicious code, or am I stuck with writing my own parser? Does anyone know of any better alternatives?</p> <p>EDIT: I just discovered <a href="http://pypi.python.org/pypi/RestrictedPython" rel="nofollow">RestrictedPython</a>, which is part of Zope. Any opinions on this are welcome.</p>
3
2008-08-26T15:27:03Z
8,765,435
<p>The functionality you want is in the compiler language services, see <a href="http://docs.python.org/library/language.html" rel="nofollow">http://docs.python.org/library/language.html</a> If you define your app to accept only expressions, you can compile the input as an expression and get an exception if it is not, e.g. if there are semicolons or statement forms.</p>
0
2012-01-06T22:41:54Z
[ "python", "security" ]
Most Pythonic way equivalent for: while ((x = next()) != END)
28,559
<p>What's the best Python idiom for this C construct?</p> <pre><code>while ((x = next()) != END) { .... } </code></pre> <p>I don't have the ability to recode next().</p> <p>update: and the answer from seems to be:</p> <pre><code>for x in iter(next, END): .... </code></pre>
9
2008-08-26T16:37:52Z
28,563
<p>Maybe it's not terribly idiomatic, but I'd be inclined to go with</p> <pre><code>x = next() while x != END: do_something_with_x x = next() </code></pre> <p>... but that's because I find that sort of thing easy to read</p>
2
2008-08-26T16:42:27Z
[ "c", "python" ]
Most Pythonic way equivalent for: while ((x = next()) != END)
28,559
<p>What's the best Python idiom for this C construct?</p> <pre><code>while ((x = next()) != END) { .... } </code></pre> <p>I don't have the ability to recode next().</p> <p>update: and the answer from seems to be:</p> <pre><code>for x in iter(next, END): .... </code></pre>
9
2008-08-26T16:37:52Z
28,566
<p>What are you trying to do here? If you're iterating over a list, you can use <code>for e in L</code> where e is the element and L is the list. If you're filtering a list, you can use list comprehensions (i.e. <code>[ e for e in L if e % 2 == 0 ]</code> to get all the even numbers in a list).</p>
1
2008-08-26T16:42:49Z
[ "c", "python" ]
Most Pythonic way equivalent for: while ((x = next()) != END)
28,559
<p>What's the best Python idiom for this C construct?</p> <pre><code>while ((x = next()) != END) { .... } </code></pre> <p>I don't have the ability to recode next().</p> <p>update: and the answer from seems to be:</p> <pre><code>for x in iter(next, END): .... </code></pre>
9
2008-08-26T16:37:52Z
28,568
<p>It depends a bit what you want to do. To match your example as far as possible, I would make next a generator and iterate over it:</p> <pre><code>def next(): for num in range(10): yield num for x in next(): print x </code></pre>
5
2008-08-26T16:44:42Z
[ "c", "python" ]
Most Pythonic way equivalent for: while ((x = next()) != END)
28,559
<p>What's the best Python idiom for this C construct?</p> <pre><code>while ((x = next()) != END) { .... } </code></pre> <p>I don't have the ability to recode next().</p> <p>update: and the answer from seems to be:</p> <pre><code>for x in iter(next, END): .... </code></pre>
9
2008-08-26T16:37:52Z
28,580
<p>If you need to do this more than once, the pythonic way would use an iterator</p> <pre><code>for x in iternext(): do_something_with_x </code></pre> <p>where <code>iternext</code> would be defined using something like (<a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">explicit is better than implicit!</a>):</p> <pre><code>def iternext(): x = next() while x != END: yield x x = next() </code></pre>
1
2008-08-26T16:49:52Z
[ "c", "python" ]
Most Pythonic way equivalent for: while ((x = next()) != END)
28,559
<p>What's the best Python idiom for this C construct?</p> <pre><code>while ((x = next()) != END) { .... } </code></pre> <p>I don't have the ability to recode next().</p> <p>update: and the answer from seems to be:</p> <pre><code>for x in iter(next, END): .... </code></pre>
9
2008-08-26T16:37:52Z
28,714
<p>Short answer: there's no way to do inline variable assignment in a while loop in Python. Meaning that I <strong>cannot</strong> say:</p> <pre><code>while x=next(): // do something here! </code></pre> <p>Since that's not possible, there are a number of "idiomatically correct" ways of doing this:</p> <pre><code>while 1: x = next() if x != END: // Blah else: break </code></pre> <p>Obviously, this is kind of ugly. You can also use one of the "iterator" approaches listed above, but, again, that may not be ideal. Finally, you can use the "pita pocket" approach that I actually just found while googling:</p> <pre><code>class Pita( object ): __slots__ = ('pocket',) marker = object() def __init__(self, v=marker): if v is not self.marker: self.pocket = v def __call__(self, v=marker): if v is not self.marker: self.pocket = v return self.pocket </code></pre> <p>Now you can do:</p> <pre><code>p = Pita() while p( next() ) != END: // do stuff with p.pocket! </code></pre> <p>Thanks for this question; learning about the <code>__call__</code> idiom was really cool! :)</p> <p>EDIT: I'd like to give credit where credit is due. The 'pita pocket' idiom was found <a href="http://mail.python.org/pipermail/python-list/2003-July/216789.html" rel="nofollow">here</a></p>
4
2008-08-26T17:50:30Z
[ "c", "python" ]
Most Pythonic way equivalent for: while ((x = next()) != END)
28,559
<p>What's the best Python idiom for this C construct?</p> <pre><code>while ((x = next()) != END) { .... } </code></pre> <p>I don't have the ability to recode next().</p> <p>update: and the answer from seems to be:</p> <pre><code>for x in iter(next, END): .... </code></pre>
9
2008-08-26T16:37:52Z
28,780
<p>Can you provide more information about what you're trying to accomplish? It's not clear to me why you can't just say</p> <pre><code>for x in everything(): ... </code></pre> <p>and have the everything function return everything, instead of writing a next function to just return one thing at a time. Generators can even do this quite efficiently.</p>
1
2008-08-26T18:18:42Z
[ "c", "python" ]
Most Pythonic way equivalent for: while ((x = next()) != END)
28,559
<p>What's the best Python idiom for this C construct?</p> <pre><code>while ((x = next()) != END) { .... } </code></pre> <p>I don't have the ability to recode next().</p> <p>update: and the answer from seems to be:</p> <pre><code>for x in iter(next, END): .... </code></pre>
9
2008-08-26T16:37:52Z
426,415
<p>@Mark Harrison's answer:</p> <pre><code>for x in iter(next_, END): .... </code></pre> <p>Here's an excerpt from <a href="http://docs.python.org/library/functions.html">Python's documentation</a>:</p> <pre><code>iter(o[, sentinel]) </code></pre> <blockquote> <p>Return an iterator object. <em>...(snip)...</em> If the second argument, <code>sentinel</code>, is given, then <code>o</code> must be a callable object. The iterator created in this case will call <code>o</code> with no arguments for each call to its <code>next()</code> method; if the value returned is equal to <code>sentinel</code>, <code>StopIteration</code> will be raised, otherwise the value will be returned.</p> </blockquote>
14
2009-01-08T23:06:34Z
[ "c", "python" ]
Best way to extract data from a FileMaker Pro database in a script?
28,668
<p>My job would be easier, or at least less tedious if I could come up with an automated way (preferably in a Python script) to extract useful information from a FileMaker Pro database. I am working on Linux machine and the FileMaker database is on the same LAN running on an OS X machine. I can log into the webby interface from my machine.</p> <p>I'm quite handy with SQL, and if somebody could point me to some FileMaker plug-in that could give me SQL access to the data within FileMaker, I would be pleased as punch. Everything I've found only goes the other way: Having FileMaker get data from SQL sources. Not useful.</p> <p>It's not my first choice, but I'd use Perl instead of Python if there was a Perl-y solution at hand.</p> <p><em>Note</em>: XML/XSLT services (as suggested by some folks) are only available on FM Server, not FM Pro. Otherwise, that would probably be the best solution. ODBC is turning out to be extremely difficult to even get working. There is absolutely zero feedback from FM when you set it up so you have to dig through /var/log/system.log and parse obscure error messages.</p> <p><em>Conclusion</em>: I got it working by running a python script locally on the machine that queries the FM database through the ODBC connections. The script is actually a TCPServer that accepts socket connections from other systems on the LAN, runs the queries, and returns the data through the socket connection. I had to do this to bypass the fact that FM Pro only accepts ODBC connections locally (FM server is required for external connections).</p>
8
2008-08-26T17:20:47Z
28,692
<p>It has been a <strong>really</strong> long time since I did anything with FileMaker Pro, but I know that it does have capabilities for an ODBC (and JDBC) connection to be made to it (however, I don't know how, or if, that translates to the linux/perl/python world though). </p> <p>This article shows how to share/expose your FileMaker data via ODBC &amp; JDBC:<br /> <a href="http://www.filemaker.com/help/15-Using%20ODBC2.html">Sharing FileMaker Pro data via ODBC or JDBC</a> </p> <p>From there, if you're able to create an ODBC/JDBC connection you could query out data as needed.</p>
5
2008-08-26T17:36:19Z
[ "python", "linux", "perl", "scripting", "filemaker" ]
Best way to extract data from a FileMaker Pro database in a script?
28,668
<p>My job would be easier, or at least less tedious if I could come up with an automated way (preferably in a Python script) to extract useful information from a FileMaker Pro database. I am working on Linux machine and the FileMaker database is on the same LAN running on an OS X machine. I can log into the webby interface from my machine.</p> <p>I'm quite handy with SQL, and if somebody could point me to some FileMaker plug-in that could give me SQL access to the data within FileMaker, I would be pleased as punch. Everything I've found only goes the other way: Having FileMaker get data from SQL sources. Not useful.</p> <p>It's not my first choice, but I'd use Perl instead of Python if there was a Perl-y solution at hand.</p> <p><em>Note</em>: XML/XSLT services (as suggested by some folks) are only available on FM Server, not FM Pro. Otherwise, that would probably be the best solution. ODBC is turning out to be extremely difficult to even get working. There is absolutely zero feedback from FM when you set it up so you have to dig through /var/log/system.log and parse obscure error messages.</p> <p><em>Conclusion</em>: I got it working by running a python script locally on the machine that queries the FM database through the ODBC connections. The script is actually a TCPServer that accepts socket connections from other systems on the LAN, runs the queries, and returns the data through the socket connection. I had to do this to bypass the fact that FM Pro only accepts ODBC connections locally (FM server is required for external connections).</p>
8
2008-08-26T17:20:47Z
36,852
<p>You'll need the FileMaker Pro installation CD to get the drivers. <a href="http://www.filemaker.com/downloads/pdf/fm9_odbc_jdbc_guide_en.pdf" rel="nofollow">This document</a> details the process for FMP 9 - it is similar for versions 7.x and 8.x as well. Versions 6.x and earlier are completely different and I wouldn't bother trying (xDBC support in those previous versions is "minimal" at best).</p> <p>FMP 9 supports SQL-92 standard syntax (mostly). Note that rather than querying tables directly you query using the "table occurrence" name which serves as a table alias of sorts. If the data tables are stored in multiple files it is possible to create a single FMP file with table occurrences/aliases pointing to those data tables. There's an "undocumented feature" where such a file must have a table defined in it as well and that table "related" to any other table on the relationships graph (doesn't matter which one) for ODBC access to work. Otherwise your queries will always return no results.</p> <p>The PDF document details all of the limitations of using the xDBC interface FMP provides. Performance of simple queries is reasonably fast, ymmv. I have found the performance of queries specifying the "LIKE" operator to be less than stellar.</p> <p>FMP also has an XML/XSLT interface that you can use to query FMP data over an HTTP connection. It also provides a PHP class for accessing and using FMP data in web applications.</p>
3
2008-08-31T13:11:03Z
[ "python", "linux", "perl", "scripting", "filemaker" ]
Best way to extract data from a FileMaker Pro database in a script?
28,668
<p>My job would be easier, or at least less tedious if I could come up with an automated way (preferably in a Python script) to extract useful information from a FileMaker Pro database. I am working on Linux machine and the FileMaker database is on the same LAN running on an OS X machine. I can log into the webby interface from my machine.</p> <p>I'm quite handy with SQL, and if somebody could point me to some FileMaker plug-in that could give me SQL access to the data within FileMaker, I would be pleased as punch. Everything I've found only goes the other way: Having FileMaker get data from SQL sources. Not useful.</p> <p>It's not my first choice, but I'd use Perl instead of Python if there was a Perl-y solution at hand.</p> <p><em>Note</em>: XML/XSLT services (as suggested by some folks) are only available on FM Server, not FM Pro. Otherwise, that would probably be the best solution. ODBC is turning out to be extremely difficult to even get working. There is absolutely zero feedback from FM when you set it up so you have to dig through /var/log/system.log and parse obscure error messages.</p> <p><em>Conclusion</em>: I got it working by running a python script locally on the machine that queries the FM database through the ODBC connections. The script is actually a TCPServer that accepts socket connections from other systems on the LAN, runs the queries, and returns the data through the socket connection. I had to do this to bypass the fact that FM Pro only accepts ODBC connections locally (FM server is required for external connections).</p>
8
2008-08-26T17:20:47Z
51,132
<p>If your leaning is to Python, you may be interested in checking out the Python Wrapper for Filemaker. It provides two way access to the Filemaker data via Filemaker's built-in XML services. You can find some quite thorough information on this at:</p> <p><a href="http://code.google.com/p/pyfilemaker/" rel="nofollow">http://code.google.com/p/pyfilemaker/</a></p>
2
2008-09-09T02:25:33Z
[ "python", "linux", "perl", "scripting", "filemaker" ]
What refactoring tools do you use for Python?
28,796
<p>I have a bunch of classes I want to rename. Some of them have names that are small and that name is reused in other class names, where I don't want that name changed. Most of this lives in Python code, but we also have some XML code that references class names.</p> <p>Simple search and replace only gets me so far. In my case, I want to rename AdminAction to AdminActionPlug and AdminActionLogger to AdminActionLoggerPlug, so the first one's search-and-replace would also hit the second, wrongly.</p> <p>Does anyone have experience with Python refactoring tools ? Bonus points if they can fix class names in the XML documents too.</p>
52
2008-08-26T18:26:51Z
29,347
<p>Most editors support the "whole word" search option. It's usually a checkbox in the search dialog, and what it does is only match the search term if it has leading and trailing spaces, dots, and most other delimiters. It will probably work in your case.</p>
-18
2008-08-27T01:50:48Z
[ "python", "refactoring" ]
What refactoring tools do you use for Python?
28,796
<p>I have a bunch of classes I want to rename. Some of them have names that are small and that name is reused in other class names, where I don't want that name changed. Most of this lives in Python code, but we also have some XML code that references class names.</p> <p>Simple search and replace only gets me so far. In my case, I want to rename AdminAction to AdminActionPlug and AdminActionLogger to AdminActionLoggerPlug, so the first one's search-and-replace would also hit the second, wrongly.</p> <p>Does anyone have experience with Python refactoring tools ? Bonus points if they can fix class names in the XML documents too.</p>
52
2008-08-26T18:26:51Z
29,770
<p>In the meantime, I've tried it two tools that have some sort of integration with vim.</p> <p>The first is <a href="http://rope.sourceforge.net/">Rope</a>, a python refactoring library that comes with a Vim (and emacs) plug-in. I tried it for a few renames, and that definitely worked as expected. It allowed me to preview the refactoring as a diff, which is nice. It is a bit text-driven, but that's alright for me, just takes longer to learn.</p> <p>The second is <a href="http://bicyclerepair.sourceforge.net/">Bicycle Repair Man</a> which I guess wins points on name. Also plugs into vim and emacs. Haven't played much with it yet, but I remember trying it a long time ago.</p> <p>Haven't played with both enough yet, or tried more types of refactoring, but I will do some more hacking with them.</p>
43
2008-08-27T09:15:42Z
[ "python", "refactoring" ]
What refactoring tools do you use for Python?
28,796
<p>I have a bunch of classes I want to rename. Some of them have names that are small and that name is reused in other class names, where I don't want that name changed. Most of this lives in Python code, but we also have some XML code that references class names.</p> <p>Simple search and replace only gets me so far. In my case, I want to rename AdminAction to AdminActionPlug and AdminActionLogger to AdminActionLoggerPlug, so the first one's search-and-replace would also hit the second, wrongly.</p> <p>Does anyone have experience with Python refactoring tools ? Bonus points if they can fix class names in the XML documents too.</p>
52
2008-08-26T18:26:51Z
1,813,244
<p>Your IDE can support refactorings !! Check it Eric, Eclipse, WingIDE have build in tools for refactorings (Rename including). And that are very safe refactorings - if something can go wrong IDE wont do ref.</p> <p>Also consider adding few unit test to ensure your code did not suffer during refactorings.</p>
4
2009-11-28T18:07:40Z
[ "python", "refactoring" ]
What refactoring tools do you use for Python?
28,796
<p>I have a bunch of classes I want to rename. Some of them have names that are small and that name is reused in other class names, where I don't want that name changed. Most of this lives in Python code, but we also have some XML code that references class names.</p> <p>Simple search and replace only gets me so far. In my case, I want to rename AdminAction to AdminActionPlug and AdminActionLogger to AdminActionLoggerPlug, so the first one's search-and-replace would also hit the second, wrongly.</p> <p>Does anyone have experience with Python refactoring tools ? Bonus points if they can fix class names in the XML documents too.</p>
52
2008-08-26T18:26:51Z
4,882,243
<p>WingIDE 4.0 (WingIDE is my python IDE of choice) will support a few refactorings, but I just tried out the latest beta, beta6, and... there's still work to be done. Retract Method works nicely, but Rename Symbol does not.</p> <p>Update: The 4.0 release has fixed all of the refactoring tools. They work great now.</p>
4
2011-02-03T02:57:10Z
[ "python", "refactoring" ]
What refactoring tools do you use for Python?
28,796
<p>I have a bunch of classes I want to rename. Some of them have names that are small and that name is reused in other class names, where I don't want that name changed. Most of this lives in Python code, but we also have some XML code that references class names.</p> <p>Simple search and replace only gets me so far. In my case, I want to rename AdminAction to AdminActionPlug and AdminActionLogger to AdminActionLoggerPlug, so the first one's search-and-replace would also hit the second, wrongly.</p> <p>Does anyone have experience with Python refactoring tools ? Bonus points if they can fix class names in the XML documents too.</p>
52
2008-08-26T18:26:51Z
14,046,877
<p>You can use sed to perform this. The trick is to recall that regular expressions can recognize word boundaries. This works on all platforms provided you get the tools, which on Windows is Cygwin, Mac OS may require installing the dev tools, I'm not sure, and Linux has this out of the box. So grep, xargs, and sed should do the trick, after 12 hours of reading man pages and trial and error ;)</p>
-4
2012-12-26T22:12:43Z
[ "python", "refactoring" ]
What refactoring tools do you use for Python?
28,796
<p>I have a bunch of classes I want to rename. Some of them have names that are small and that name is reused in other class names, where I don't want that name changed. Most of this lives in Python code, but we also have some XML code that references class names.</p> <p>Simple search and replace only gets me so far. In my case, I want to rename AdminAction to AdminActionPlug and AdminActionLogger to AdminActionLoggerPlug, so the first one's search-and-replace would also hit the second, wrongly.</p> <p>Does anyone have experience with Python refactoring tools ? Bonus points if they can fix class names in the XML documents too.</p>
52
2008-08-26T18:26:51Z
25,765,376
<p><a href="http://www.jetbrains.com/pycharm/features/" rel="nofollow">PyCharm</a> have some refactoring features.</p> <blockquote> <h3>PYTHON REFACTORING</h3> <p><strong>Rename</strong> refactoring allows to perform global code changes safely and instantly. Local changes within a file are performed in-place. Refactorings work in plain Python and Django projects.</p> <p>Use <strong>Introduce Variable/Field/Constant</strong> and <strong>Inline Local</strong> for improving the code structure within a method, <strong>Extract Method</strong> to break up longer methods, <strong>Extract Superclass</strong>, <strong>Push Up</strong>, <strong>Pull Down</strong> and <strong>Move</strong> to move the methods and classes.</p> </blockquote>
2
2014-09-10T12:21:58Z
[ "python", "refactoring" ]
What refactoring tools do you use for Python?
28,796
<p>I have a bunch of classes I want to rename. Some of them have names that are small and that name is reused in other class names, where I don't want that name changed. Most of this lives in Python code, but we also have some XML code that references class names.</p> <p>Simple search and replace only gets me so far. In my case, I want to rename AdminAction to AdminActionPlug and AdminActionLogger to AdminActionLoggerPlug, so the first one's search-and-replace would also hit the second, wrongly.</p> <p>Does anyone have experience with Python refactoring tools ? Bonus points if they can fix class names in the XML documents too.</p>
52
2008-08-26T18:26:51Z
26,381,548
<p>I would strongly recommend <a href="https://www.jetbrains.com/pycharm/" rel="nofollow">PyCharm</a> - not just for refactorings. Since the first PyCharm answer was posted here a few years ago the refactoring support in PyCharm has improved significantly.</p> <p><a href="https://www.jetbrains.com/pycharm/webhelp/refactoring-source-code.html" rel="nofollow">Python Refactorings available in PyCharm</a> (last checked 2016/07/27 in PyCharm 2016.2)</p> <ul> <li>Change Signature</li> <li>Convert to Python Package/Module</li> <li>Copy</li> <li>Extract Refactorings</li> <li>Inline</li> <li>Invert Boolean</li> <li>Make Top-Level Function</li> <li>Move Refactorings</li> <li>Push Members down</li> <li>Pull Members up</li> <li>Rename Refactorings</li> <li>Safe Delete</li> </ul> <p>XML refactorings (I checked in context menu in an XML file):</p> <ul> <li>Rename</li> <li>Move</li> <li>Copy</li> <li>Extract Subquery as CTE</li> <li>Inline</li> </ul> <p>Javascript refactorings:</p> <ul> <li>Extract Parameter in JavaScript</li> <li>Change Signature in JavaScript</li> <li>Extract Variable in JavaScript</li> </ul>
12
2014-10-15T11:34:58Z
[ "python", "refactoring" ]
What's the best way to use web services in python?
28,961
<p>I have a medium sized application that runs as a .net web-service which I do not control, and I want to create a loose pythonic API above it to enable easy scripting.</p> <p>I wanted to know what is the best/most practical solution for using web-services in python.</p> <p>Edit: I need to consume a complex soap WS and I have no control over it.</p>
7
2008-08-26T19:49:54Z
31,926
<p>If I have to expose APIs, I prefer doing it as JSON. Python has excellent support for JSON objects (JSON Objects are infact python dictionaries)</p>
3
2008-08-28T09:47:57Z
[ "python", "web-services", "soap" ]
What's the best way to use web services in python?
28,961
<p>I have a medium sized application that runs as a .net web-service which I do not control, and I want to create a loose pythonic API above it to enable easy scripting.</p> <p>I wanted to know what is the best/most practical solution for using web-services in python.</p> <p>Edit: I need to consume a complex soap WS and I have no control over it.</p>
7
2008-08-26T19:49:54Z
322,393
<p><a href="http://www.jython.org" rel="nofollow">Jython</a> and <a href="http://www.codeplex.com/IronPython" rel="nofollow">IronPython</a> give access to great Java &amp; .NET SOAP libraries.</p> <p>If you need CPython, <a href="http://pywebsvcs.sourceforge.net/" rel="nofollow">ZSI</a> has been flaky for me, but it could be possible to use a tool like <a href="http://robin.python-hosting.com/" rel="nofollow">Robin</a> to wrap a good C++ SOAP library such as <a href="http://gsoap2.sourceforge.net/" rel="nofollow">gSOAP</a> or <a href="http://ws.apache.org/axis/cpp/index.html" rel="nofollow">Apache Axis C++</a></p>
1
2008-11-26T22:34:53Z
[ "python", "web-services", "soap" ]
What's the best way to use web services in python?
28,961
<p>I have a medium sized application that runs as a .net web-service which I do not control, and I want to create a loose pythonic API above it to enable easy scripting.</p> <p>I wanted to know what is the best/most practical solution for using web-services in python.</p> <p>Edit: I need to consume a complex soap WS and I have no control over it.</p>
7
2008-08-26T19:49:54Z
33,471,869
<p>Most of the packages on python that a SOAP service through them can be called works on python 2.x, but had problems on Python 3.x</p> <p>The best fit for python 3.x that I've found is <a href="https://pypi.python.org/pypi/suds-jurko/0.6" rel="nofollow">suds-jurko</a></p>
0
2015-11-02T06:26:22Z
[ "python", "web-services", "soap" ]
How do I create an xml document in python
29,243
<p>Here is my sample code:</p> <pre><code>from xml.dom.minidom import * def make_xml(): doc = Document() node = doc.createElement('foo') node.innerText = 'bar' doc.appendChild(node) return doc if __name__ == '__main__': make_xml().writexml(sys.stdout) </code></pre> <p>when I run the above code I get this:</p> <pre><code>&lt;?xml version="1.0" ?&gt; &lt;foo/&gt; </code></pre> <p>I would like to get:</p> <pre><code>&lt;?xml version="1.0" ?&gt; &lt;foo&gt;bar&lt;/foo&gt; </code></pre> <p>I just guessed that there was an innerText property, it gives no compiler error, but does not seem to work... how do I go about creating a text node?</p>
14
2008-08-27T00:21:35Z
29,255
<p>Setting an attribute on an object won't give a compile-time or a run-time error, it will just do nothing useful if the object doesn't access it (i.e. "<code>node.noSuchAttr = 'bar'</code>" would also not give an error).</p> <p>Unless you need a specific feature of <code>minidom</code>, I would look at <code>ElementTree</code>:</p> <pre><code>import sys from xml.etree.cElementTree import Element, ElementTree def make_xml(): node = Element('foo') node.text = 'bar' doc = ElementTree(node) return doc if __name__ == '__main__': make_xml().write(sys.stdout) </code></pre>
8
2008-08-27T00:35:29Z
[ "python", "xml" ]
How do I create an xml document in python
29,243
<p>Here is my sample code:</p> <pre><code>from xml.dom.minidom import * def make_xml(): doc = Document() node = doc.createElement('foo') node.innerText = 'bar' doc.appendChild(node) return doc if __name__ == '__main__': make_xml().writexml(sys.stdout) </code></pre> <p>when I run the above code I get this:</p> <pre><code>&lt;?xml version="1.0" ?&gt; &lt;foo/&gt; </code></pre> <p>I would like to get:</p> <pre><code>&lt;?xml version="1.0" ?&gt; &lt;foo&gt;bar&lt;/foo&gt; </code></pre> <p>I just guessed that there was an innerText property, it gives no compiler error, but does not seem to work... how do I go about creating a text node?</p>
14
2008-08-27T00:21:35Z
29,262
<p>@Daniel</p> <p>Thanks for the reply, I also figured out how to do it with the minidom (I'm not sure of the difference between the ElementTree vs the minidom)</p> <pre> <code> from xml.dom.minidom import * def make_xml(): doc = Document(); node = doc.createElement('foo') node.appendChild(doc.createTextNode('bar')) doc.appendChild(node) return doc if __name__ == '__main__': make_xml().writexml(sys.stdout) </code> </pre> <p>I swear I tried this before posting my question...</p>
8
2008-08-27T00:42:32Z
[ "python", "xml" ]
How do I create an xml document in python
29,243
<p>Here is my sample code:</p> <pre><code>from xml.dom.minidom import * def make_xml(): doc = Document() node = doc.createElement('foo') node.innerText = 'bar' doc.appendChild(node) return doc if __name__ == '__main__': make_xml().writexml(sys.stdout) </code></pre> <p>when I run the above code I get this:</p> <pre><code>&lt;?xml version="1.0" ?&gt; &lt;foo/&gt; </code></pre> <p>I would like to get:</p> <pre><code>&lt;?xml version="1.0" ?&gt; &lt;foo&gt;bar&lt;/foo&gt; </code></pre> <p>I just guessed that there was an innerText property, it gives no compiler error, but does not seem to work... how do I go about creating a text node?</p>
14
2008-08-27T00:21:35Z
29,264
<p>I found a <a href="http://www.boddie.org.uk/python/XML_intro.html" rel="nofollow">pretty verbose tutorial on the minidom method</a></p> <p>Here's a <a href="http://drfox.com/cgi-bin/topic_display.py?name=climbing_etree" rel="nofollow">tutorial for the etree method</a>. It's much nicer to read, and seems quite simple. It also goes over parsing of xml (briefly)</p>
3
2008-08-27T00:45:14Z
[ "python", "xml" ]
Python distutils - does anyone know how to use it?
29,562
<p>I wrote a quick program in python to add a gtk GUI to a cli program. I was wondering how I can create an installer using distutils. Since it's just a GUI frontend for a command line app it only works in *nix anyway so I'm not worried about it being cross platform.</p> <p>my main goal is to create a .deb package for debian/ubuntu users, but I don't understand make/configure files. I've primarily been a web developer up until now.</p> <p>Thanks for your help!</p> <p><strong>edit</strong>: Does anyone know of a project that uses distutils so I could see it in action and, you know, actually try building it?</p> <h2>Here are a few useful links</h2> <ul> <li><p><a href="https://wiki.ubuntu.com/PackagingGuide/Python">Ubuntu Python Packaging Guide</a></p> <p>This Guide is <strong><em>very</em></strong> helpful. I don't know how I missed it during my initial wave of gooling. It even walks you through packaging up an existing python application</p></li> <li><p><a href="https://wiki.ubuntu.com/MOTU/GettingStarted">The Ubuntu MOTU Project</a></p> <p>This is the official package maintaining project at ubuntu. Anyone can join, and there are lots of tutorials and info about creating packages, of all types, which include the above 'python packaging guide'.</p></li> <li><p><a href="http://episteme.arstechnica.com/eve/forums/a/tpc/f/96509133/m/808004952931">"Python distutils to deb?" - Ars Technica Forum discussion</a></p> <p>According to this conversation, you can't just use distutils. It doesn't follow the debian packaging format (or something like that). I guess that's why you need dh_make as seen in the Ubuntu Packaging guide</p></li> <li><p><a href="http://osdir.com/ml/linux.debian.devel.python/2004-10/msg00013.html">"A bdist_deb command for distutils</a></p> <p>This one has some interesting discussion (it's also how I found the ubuntu guide) about concatenating a zip-file and a shell script to create some kind of universal executable (anything with python and bash that is). weird. Let me know if anyone finds more info on this practice because I've never heard of it.</p></li> <li><p><A href="http://mail.python.org/pipermail/distutils-sig/2000-May/001000.html">Description of the deb format and how distutils fit in - python mailing list</a></p></li> </ul>
23
2008-08-27T05:03:07Z
29,575
<p>See the <a href="http://docs.python.org/dist/simple-example.html" rel="nofollow">distutils simple example</a>. That's basically what it is like, except real install scripts usually contain a bit more information. I have not seen any that are fundamentally more complicated, though. In essence, you just give it a list of what needs to be installed. Sometimes you need to give it some mapping dicts since the source and installed trees might not be the same.</p> <p>Here is a real-life (anonymized) example:</p> <pre><code>#!/usr/bin/python from distutils.core import setup setup (name = 'Initech Package 3', description = "Services and libraries ABC, DEF", author = "That Guy, Initech Ltd", author_email = "that.guy@initech.com", version = '1.0.5', package_dir = {'Package3' : 'site-packages/Package3'}, packages = ['Package3', 'Package3.Queries'], data_files = [ ('/etc/Package3', ['etc/Package3/ExternalResources.conf']) ]) </code></pre>
13
2008-08-27T05:12:47Z
[ "python", "linux", "installer", "debian", "distutils" ]
Python distutils - does anyone know how to use it?
29,562
<p>I wrote a quick program in python to add a gtk GUI to a cli program. I was wondering how I can create an installer using distutils. Since it's just a GUI frontend for a command line app it only works in *nix anyway so I'm not worried about it being cross platform.</p> <p>my main goal is to create a .deb package for debian/ubuntu users, but I don't understand make/configure files. I've primarily been a web developer up until now.</p> <p>Thanks for your help!</p> <p><strong>edit</strong>: Does anyone know of a project that uses distutils so I could see it in action and, you know, actually try building it?</p> <h2>Here are a few useful links</h2> <ul> <li><p><a href="https://wiki.ubuntu.com/PackagingGuide/Python">Ubuntu Python Packaging Guide</a></p> <p>This Guide is <strong><em>very</em></strong> helpful. I don't know how I missed it during my initial wave of gooling. It even walks you through packaging up an existing python application</p></li> <li><p><a href="https://wiki.ubuntu.com/MOTU/GettingStarted">The Ubuntu MOTU Project</a></p> <p>This is the official package maintaining project at ubuntu. Anyone can join, and there are lots of tutorials and info about creating packages, of all types, which include the above 'python packaging guide'.</p></li> <li><p><a href="http://episteme.arstechnica.com/eve/forums/a/tpc/f/96509133/m/808004952931">"Python distutils to deb?" - Ars Technica Forum discussion</a></p> <p>According to this conversation, you can't just use distutils. It doesn't follow the debian packaging format (or something like that). I guess that's why you need dh_make as seen in the Ubuntu Packaging guide</p></li> <li><p><a href="http://osdir.com/ml/linux.debian.devel.python/2004-10/msg00013.html">"A bdist_deb command for distutils</a></p> <p>This one has some interesting discussion (it's also how I found the ubuntu guide) about concatenating a zip-file and a shell script to create some kind of universal executable (anything with python and bash that is). weird. Let me know if anyone finds more info on this practice because I've never heard of it.</p></li> <li><p><A href="http://mail.python.org/pipermail/distutils-sig/2000-May/001000.html">Description of the deb format and how distutils fit in - python mailing list</a></p></li> </ul>
23
2008-08-27T05:03:07Z
29,839
<p>Most Python programs will use distutils. <a href="http://www.djangoproject.com" rel="nofollow">Django</a> is a one - see <a href="http://code.djangoproject.com/svn/django/trunk/setup.py" rel="nofollow">http://code.djangoproject.com/svn/django/trunk/setup.py</a></p> <p>You should also read <a href="http://docs.python.org/dist/dist.html" rel="nofollow">the documentation</a>, as it's very comprehensive and has some good examples.</p>
2
2008-08-27T10:04:25Z
[ "python", "linux", "installer", "debian", "distutils" ]
Python distutils - does anyone know how to use it?
29,562
<p>I wrote a quick program in python to add a gtk GUI to a cli program. I was wondering how I can create an installer using distutils. Since it's just a GUI frontend for a command line app it only works in *nix anyway so I'm not worried about it being cross platform.</p> <p>my main goal is to create a .deb package for debian/ubuntu users, but I don't understand make/configure files. I've primarily been a web developer up until now.</p> <p>Thanks for your help!</p> <p><strong>edit</strong>: Does anyone know of a project that uses distutils so I could see it in action and, you know, actually try building it?</p> <h2>Here are a few useful links</h2> <ul> <li><p><a href="https://wiki.ubuntu.com/PackagingGuide/Python">Ubuntu Python Packaging Guide</a></p> <p>This Guide is <strong><em>very</em></strong> helpful. I don't know how I missed it during my initial wave of gooling. It even walks you through packaging up an existing python application</p></li> <li><p><a href="https://wiki.ubuntu.com/MOTU/GettingStarted">The Ubuntu MOTU Project</a></p> <p>This is the official package maintaining project at ubuntu. Anyone can join, and there are lots of tutorials and info about creating packages, of all types, which include the above 'python packaging guide'.</p></li> <li><p><a href="http://episteme.arstechnica.com/eve/forums/a/tpc/f/96509133/m/808004952931">"Python distutils to deb?" - Ars Technica Forum discussion</a></p> <p>According to this conversation, you can't just use distutils. It doesn't follow the debian packaging format (or something like that). I guess that's why you need dh_make as seen in the Ubuntu Packaging guide</p></li> <li><p><a href="http://osdir.com/ml/linux.debian.devel.python/2004-10/msg00013.html">"A bdist_deb command for distutils</a></p> <p>This one has some interesting discussion (it's also how I found the ubuntu guide) about concatenating a zip-file and a shell script to create some kind of universal executable (anything with python and bash that is). weird. Let me know if anyone finds more info on this practice because I've never heard of it.</p></li> <li><p><A href="http://mail.python.org/pipermail/distutils-sig/2000-May/001000.html">Description of the deb format and how distutils fit in - python mailing list</a></p></li> </ul>
23
2008-08-27T05:03:07Z
31,225
<p>distutils really isn't all that difficult once you get the hang of it. It's really just a matter of putting in some meta-information (program name, author, version, etc) and then selecting what files you want to include. For example, here's a sample distutils setup.py module from a decently complex python library:</p> <p><a href="http://code.google.com/p/kamaelia/source/browse/trunk/Code/Python/Kamaelia/setup.py" rel="nofollow">Kamaelia setup.py</a></p> <p>Note that this doesn't deal with any data files or or whatnot, so YMMV.</p> <p>On another note, I agree that the distutils documentation is probably some of python's worst documentation. It is extremely inclusive in some areas, but neglects some really important information in others.</p>
1
2008-08-27T20:42:16Z
[ "python", "linux", "installer", "debian", "distutils" ]
Python distutils - does anyone know how to use it?
29,562
<p>I wrote a quick program in python to add a gtk GUI to a cli program. I was wondering how I can create an installer using distutils. Since it's just a GUI frontend for a command line app it only works in *nix anyway so I'm not worried about it being cross platform.</p> <p>my main goal is to create a .deb package for debian/ubuntu users, but I don't understand make/configure files. I've primarily been a web developer up until now.</p> <p>Thanks for your help!</p> <p><strong>edit</strong>: Does anyone know of a project that uses distutils so I could see it in action and, you know, actually try building it?</p> <h2>Here are a few useful links</h2> <ul> <li><p><a href="https://wiki.ubuntu.com/PackagingGuide/Python">Ubuntu Python Packaging Guide</a></p> <p>This Guide is <strong><em>very</em></strong> helpful. I don't know how I missed it during my initial wave of gooling. It even walks you through packaging up an existing python application</p></li> <li><p><a href="https://wiki.ubuntu.com/MOTU/GettingStarted">The Ubuntu MOTU Project</a></p> <p>This is the official package maintaining project at ubuntu. Anyone can join, and there are lots of tutorials and info about creating packages, of all types, which include the above 'python packaging guide'.</p></li> <li><p><a href="http://episteme.arstechnica.com/eve/forums/a/tpc/f/96509133/m/808004952931">"Python distutils to deb?" - Ars Technica Forum discussion</a></p> <p>According to this conversation, you can't just use distutils. It doesn't follow the debian packaging format (or something like that). I guess that's why you need dh_make as seen in the Ubuntu Packaging guide</p></li> <li><p><a href="http://osdir.com/ml/linux.debian.devel.python/2004-10/msg00013.html">"A bdist_deb command for distutils</a></p> <p>This one has some interesting discussion (it's also how I found the ubuntu guide) about concatenating a zip-file and a shell script to create some kind of universal executable (anything with python and bash that is). weird. Let me know if anyone finds more info on this practice because I've never heard of it.</p></li> <li><p><A href="http://mail.python.org/pipermail/distutils-sig/2000-May/001000.html">Description of the deb format and how distutils fit in - python mailing list</a></p></li> </ul>
23
2008-08-27T05:03:07Z
4,189,217
<p>I found the following <a href="http://wiki.python.org/moin/Distutils/Tutorial" rel="nofollow">tutorial</a> to be very helpful. It's shorter than the distutils documentation and explains how to setup a typical project step by step. </p>
2
2010-11-15T21:57:26Z
[ "python", "linux", "installer", "debian", "distutils" ]
Python distutils - does anyone know how to use it?
29,562
<p>I wrote a quick program in python to add a gtk GUI to a cli program. I was wondering how I can create an installer using distutils. Since it's just a GUI frontend for a command line app it only works in *nix anyway so I'm not worried about it being cross platform.</p> <p>my main goal is to create a .deb package for debian/ubuntu users, but I don't understand make/configure files. I've primarily been a web developer up until now.</p> <p>Thanks for your help!</p> <p><strong>edit</strong>: Does anyone know of a project that uses distutils so I could see it in action and, you know, actually try building it?</p> <h2>Here are a few useful links</h2> <ul> <li><p><a href="https://wiki.ubuntu.com/PackagingGuide/Python">Ubuntu Python Packaging Guide</a></p> <p>This Guide is <strong><em>very</em></strong> helpful. I don't know how I missed it during my initial wave of gooling. It even walks you through packaging up an existing python application</p></li> <li><p><a href="https://wiki.ubuntu.com/MOTU/GettingStarted">The Ubuntu MOTU Project</a></p> <p>This is the official package maintaining project at ubuntu. Anyone can join, and there are lots of tutorials and info about creating packages, of all types, which include the above 'python packaging guide'.</p></li> <li><p><a href="http://episteme.arstechnica.com/eve/forums/a/tpc/f/96509133/m/808004952931">"Python distutils to deb?" - Ars Technica Forum discussion</a></p> <p>According to this conversation, you can't just use distutils. It doesn't follow the debian packaging format (or something like that). I guess that's why you need dh_make as seen in the Ubuntu Packaging guide</p></li> <li><p><a href="http://osdir.com/ml/linux.debian.devel.python/2004-10/msg00013.html">"A bdist_deb command for distutils</a></p> <p>This one has some interesting discussion (it's also how I found the ubuntu guide) about concatenating a zip-file and a shell script to create some kind of universal executable (anything with python and bash that is). weird. Let me know if anyone finds more info on this practice because I've never heard of it.</p></li> <li><p><A href="http://mail.python.org/pipermail/distutils-sig/2000-May/001000.html">Description of the deb format and how distutils fit in - python mailing list</a></p></li> </ul>
23
2008-08-27T05:03:07Z
4,716,772
<p><code>apt-get install python-stdeb</code></p> <p>Python to Debian source package conversion utility</p> <p>This package provides some tools to produce Debian packages from Python packages via a new distutils command, sdist_dsc. Automatic defaults are provided for the Debian package, but many aspects of the resulting package can be customized via a configuration file.</p> <ul> <li>pypi-install will query the Python Package Index (PyPI) for a package, download it, create a .deb from it, and then install the .deb.</li> <li>py2dsc will convert a distutils-built source tarball into a Debian source package.</li> </ul>
6
2011-01-17T19:00:23Z
[ "python", "linux", "installer", "debian", "distutils" ]
Install Python to match directory layout in OS X 10.5
29,856
<p>The default Python install on OS X 10.5 is 2.5.1 with a fat 32 bit (Intel and PPC) client. I want to setup apache and mysql to run django. In the past I have run apache and mysql to match this install in 32 bit mode (even stripping out the 64 bit stuff from apache to make it work).</p> <p>I want to upgrade Python to 64 bit. I am completely comfortable with compiling it from source with one caveat. How to I match the way that the default install is laid out? Especially with regards to site-packages being in <code>/Library/Python/2.5/</code> and not the one in buried at the top of the framework once I compile it. </p>
2
2008-08-27T10:22:09Z
30,591
<p>Not sure I entirely understand your question, but can't you simply build and install a 64 bit version and then create symbolic links so that /Library/Python/2.5 and below point to your freshly built version of python?</p>
1
2008-08-27T16:30:06Z
[ "python", "osx", "64bit" ]
Install Python to match directory layout in OS X 10.5
29,856
<p>The default Python install on OS X 10.5 is 2.5.1 with a fat 32 bit (Intel and PPC) client. I want to setup apache and mysql to run django. In the past I have run apache and mysql to match this install in 32 bit mode (even stripping out the 64 bit stuff from apache to make it work).</p> <p>I want to upgrade Python to 64 bit. I am completely comfortable with compiling it from source with one caveat. How to I match the way that the default install is laid out? Especially with regards to site-packages being in <code>/Library/Python/2.5/</code> and not the one in buried at the top of the framework once I compile it. </p>
2
2008-08-27T10:22:09Z
31,331
<p>Essentially, yes. I was not sure you could do it like that (current version does not do it like that). When using the python install script, however, there is no option (that I can find) to specify where to put directories and files (eg --prefix). I was hoping to match the current layout of python related files so as to avoid 'polluting' my machine with redundant files.</p>
0
2008-08-27T23:38:27Z
[ "python", "osx", "64bit" ]
Install Python to match directory layout in OS X 10.5
29,856
<p>The default Python install on OS X 10.5 is 2.5.1 with a fat 32 bit (Intel and PPC) client. I want to setup apache and mysql to run django. In the past I have run apache and mysql to match this install in 32 bit mode (even stripping out the 64 bit stuff from apache to make it work).</p> <p>I want to upgrade Python to 64 bit. I am completely comfortable with compiling it from source with one caveat. How to I match the way that the default install is laid out? Especially with regards to site-packages being in <code>/Library/Python/2.5/</code> and not the one in buried at the top of the framework once I compile it. </p>
2
2008-08-27T10:22:09Z
31,384
<p>Personally, I wouldn't worry about it until you see a problem. Messing with the default python install on a *Nix system can cause more trouble than it's worth. I can say from personal experience that you never truly understand what python has done for the nix world until you have a problem with it.</p> <p>You can also add a second python installation, but that also causes more problems than it's worth IMO.</p> <p>So I suppose the best question to start out with would be why exactly do you want to use the 64 bit version of python?</p>
1
2008-08-28T00:09:56Z
[ "python", "osx", "64bit" ]
Install Python to match directory layout in OS X 10.5
29,856
<p>The default Python install on OS X 10.5 is 2.5.1 with a fat 32 bit (Intel and PPC) client. I want to setup apache and mysql to run django. In the past I have run apache and mysql to match this install in 32 bit mode (even stripping out the 64 bit stuff from apache to make it work).</p> <p>I want to upgrade Python to 64 bit. I am completely comfortable with compiling it from source with one caveat. How to I match the way that the default install is laid out? Especially with regards to site-packages being in <code>/Library/Python/2.5/</code> and not the one in buried at the top of the framework once I compile it. </p>
2
2008-08-27T10:22:09Z
31,425
<p>The short answer is because I can. The long answer, expanding on what the OP said, is to be more compatible with apache and mysql/postgresql. They are all 64bit (apache is a fat binary with ppc, ppc64 x86 and x86 and x86_64, the others just straight 64bit). <strong>Mysqldb and mod_python wont compile unless they are all running the same architecture.</strong> Yes I could run them all in 32bit (and have in the past) but this is much more work then compiling one program.</p> <p>EDIT: You pretty much convinced though to just let the installer do its thing and update the PATH to reflect this.</p>
0
2008-08-28T00:33:52Z
[ "python", "osx", "64bit" ]
Install Python to match directory layout in OS X 10.5
29,856
<p>The default Python install on OS X 10.5 is 2.5.1 with a fat 32 bit (Intel and PPC) client. I want to setup apache and mysql to run django. In the past I have run apache and mysql to match this install in 32 bit mode (even stripping out the 64 bit stuff from apache to make it work).</p> <p>I want to upgrade Python to 64 bit. I am completely comfortable with compiling it from source with one caveat. How to I match the way that the default install is laid out? Especially with regards to site-packages being in <code>/Library/Python/2.5/</code> and not the one in buried at the top of the framework once I compile it. </p>
2
2008-08-27T10:22:09Z
31,765
<p>Hyposaurus,</p> <p>It is possible to have multiple versions of Python installed simultaneously. Installing two versions in parallel solves your problem and helps avoid the problems laid out by Jason Baker above. </p> <p>The easiest way, and the way I recommend, is to use <a href="http://www.macports.org/" rel="nofollow">MacPorts</a>, which will install all its software separately. By default, for example, everything is installed in /opt/local</p> <p>Another method is to simply download the source and compile with a specified prefix. Note that this method doesn't modify your PATH environment variable, so you'll need to do that yourself if you want to avoid typing the fully qualified path to the python executable each time</p> <pre><code>./configure --prefix=/usr/local/python64 make sudo make install </code></pre> <p>Then you can simply point your Apache install at the new version using mod_python's <a href="http://www.modpython.org/live/current/doc-html/dir-other-pi.html" rel="nofollow">PythonInterpreter</a> directive</p>
1
2008-08-28T07:16:15Z
[ "python", "osx", "64bit" ]
How do threads work in Python, and what are common Python-threading specific pitfalls?
31,340
<p>I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up.</p> <p>From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so?</p> <p>Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.</p>
71
2008-08-27T23:44:47Z
31,358
<p>Below is a basic threading sample. It will spawn 20 threads; each thread will output its thread number. Run it and observe the order in which they print.</p> <pre><code>import threading class Foo (threading.Thread): def __init__(self,x): self.__x = x threading.Thread.__init__(self) def run (self): print str(self.__x) for x in xrange(20): Foo(x).start() </code></pre> <p>As you have hinted at Python threads are implemented through time-slicing. This is how they get the "parallel" effect. </p> <p>In my example my Foo class extends thread, I then implement the <code>run</code> method, which is where the code that you would like to run in a thread goes. To start the thread you call <code>start()</code> on the thread object, which will automatically invoke the <code>run</code> method...</p> <p>Of course, this is just the very basics. You will eventually want to learn about semaphores, mutexes, and locks for thread synchronization and message passing.</p>
18
2008-08-27T23:52:59Z
[ "python", "multithreading" ]
How do threads work in Python, and what are common Python-threading specific pitfalls?
31,340
<p>I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up.</p> <p>From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so?</p> <p>Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.</p>
71
2008-08-27T23:44:47Z
31,372
<p>Python's a fairly easy language to thread in, but there are caveats. The biggest thing you need to know about is the Global Interpreter Lock. This allows only one thread to access the interpreter. This means two things: 1) you rarely ever find yourself using a lock statement in python and 2) if you want to take advantage of multi-processor systems, you have to use separate processes. EDIT: I should also point out that you can put some of the code in C/C++ if you want to get around the GIL as well.</p> <p>Thus, you need to re-consider why you want to use threads. If you want to parallelize your app to take advantage of dual-core architecture, you need to consider breaking your app up into multiple processes.</p> <p>If you want to improve responsiveness, you should CONSIDER using threads. There are other alternatives though, namely <a href="http://en.wikipedia.org/wiki/Microthread" rel="nofollow">microthreading</a>. There are also some frameworks that you should look into:</p> <ul> <li><a href="http://www.stackless.com/" rel="nofollow">stackless python</a></li> <li><a href="http://greenlet.readthedocs.org/en/latest/" rel="nofollow">greenlets</a></li> <li><a href="http://www.gevent.org/" rel="nofollow">gevent</a></li> <li><a href="https://github.com/saucelabs/monocle" rel="nofollow">monocle</a></li> </ul>
32
2008-08-28T00:00:18Z
[ "python", "multithreading" ]
How do threads work in Python, and what are common Python-threading specific pitfalls?
31,340
<p>I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up.</p> <p>From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so?</p> <p>Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.</p>
71
2008-08-27T23:44:47Z
31,398
<p>Yes, because of the Global Interpreter Lock (GIL) there can only run one thread at a time. Here are some links with some insights about this:</p> <ul> <li><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=214235">http://www.artima.com/weblogs/viewpost.jsp?thread=214235</a></li> <li><a href="http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/">http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/</a></li> </ul> <p>From the last link an interesting quote:</p> <blockquote> <p>Let me explain what all that means. Threads run inside the same virtual machine, and hence run on the same physical machine. Processes can run on the same physical machine or in another physical machine. If you architect your application around threads, you’ve done nothing to access multiple machines. So, you can scale to as many cores are on the single machine (which will be quite a few over time), but to really reach web scales, you’ll need to solve the multiple machine problem anyway.</p> </blockquote> <p>If you want to use multi core, <a href="http://www.python.org/dev/peps/pep-0371/">pyprocessing</a> defines an process based API to do real parallelization. The <a href="http://en.wikipedia.org/wiki/Python_Enhancement_Proposal#Development">PEP</a> also includes some interesting benchmarks.</p>
41
2008-08-28T00:19:50Z
[ "python", "multithreading" ]
How do threads work in Python, and what are common Python-threading specific pitfalls?
31,340
<p>I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up.</p> <p>From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so?</p> <p>Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.</p>
71
2008-08-27T23:44:47Z
31,552
<p>Use threads in python if the individual workers are doing I/O bound operations. If you are trying to scale across multiple cores on a machine either find a good <a href="http://www.python.org/dev/peps/pep-0371/">IPC</a> framework for python or pick a different language.</p>
9
2008-08-28T02:34:18Z
[ "python", "multithreading" ]
How do threads work in Python, and what are common Python-threading specific pitfalls?
31,340
<p>I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up.</p> <p>From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so?</p> <p>Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.</p>
71
2008-08-27T23:44:47Z
1,197,151
<p>Try to remember that the GIL is set to poll around every so often in order to do show the appearance of multiple tasks. This setting can be fine tuned, but I offer the suggestion that there should be work that the threads are doing or lots of context switches are going to cause problems.</p> <p>I would go so far as to suggest multiple parents on processors and try to keep like jobs on the same core(s).</p>
1
2009-07-28T22:40:05Z
[ "python", "multithreading" ]
How do threads work in Python, and what are common Python-threading specific pitfalls?
31,340
<p>I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up.</p> <p>From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so?</p> <p>Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.</p>
71
2008-08-27T23:44:47Z
21,608,282
<p>One easy solution to the GIL is the <a href="http://docs.python.org/2/library/multiprocessing.html" rel="nofollow" title="Python docs link">multiprocessing</a> module. It can be used as a drop in replacement to the threading module but uses multiple Interpreter processes instead of threads. Because of this there is a little more overhead than plain threading for simple things but it gives you the advantage of real parallelization if you need it. It also easily scales to multiple physical machines.</p> <p>If you need truly large scale parallelization than I would look further but if you just want to scale to all the cores of one computer or a few different ones without all the work that would go into implementing a more comprehensive framework, than this is for you.</p>
2
2014-02-06T16:19:03Z
[ "python", "multithreading" ]
How can I render a tree structure (recursive) using a django template?
32,044
<p>I have a tree structure in memory that I would like to render in HTML using a Django template. </p> <pre><code>class Node(): name = "node name" children = [] </code></pre> <p>There will be some object <code>root</code> that is a <code>Node</code>, and <code>children</code> is a list of <code>Node</code>s. <code>root</code> will be passed in the content of the template.</p> <p>I have found <a href="http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/">this</a> one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment.</p> <p>Does anybody know of a better way?</p>
44
2008-08-28T11:43:10Z
32,125
<p>I think the canonical answer is: "Don't".</p> <p>What you should probably do instead is unravel the thing in your <em>view</em> code, so it's just a matter of iterating over (in|de)dents in the template. I think I'd do it by appending indents and dedents to a list while recursing through the tree and then sending that "travelogue" list to the template. (the template would then insert <code>&lt;li&gt;</code> and <code>&lt;/li&gt;</code> from that list, creating the recursive structure with "understanding" it.)</p> <p>I'm also pretty sure recursively including template files is really a <em>wrong</em> way to do it...</p>
23
2008-08-28T12:47:29Z
[ "python", "django" ]
How can I render a tree structure (recursive) using a django template?
32,044
<p>I have a tree structure in memory that I would like to render in HTML using a Django template. </p> <pre><code>class Node(): name = "node name" children = [] </code></pre> <p>There will be some object <code>root</code> that is a <code>Node</code>, and <code>children</code> is a list of <code>Node</code>s. <code>root</code> will be passed in the content of the template.</p> <p>I have found <a href="http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/">this</a> one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment.</p> <p>Does anybody know of a better way?</p>
44
2008-08-28T11:43:10Z
32,857
<p>this might be way more than you need, but there is a django module called 'mptt' - this stores a hierarchical tree structure in an sql database, and includes templates for display in the view code. you might be able to find something useful there.</p> <p>here's the link : <a href="https://github.com/django-mptt/django-mptt/" rel="nofollow">django-mptt</a></p>
18
2008-08-28T17:23:22Z
[ "python", "django" ]
How can I render a tree structure (recursive) using a django template?
32,044
<p>I have a tree structure in memory that I would like to render in HTML using a Django template. </p> <pre><code>class Node(): name = "node name" children = [] </code></pre> <p>There will be some object <code>root</code> that is a <code>Node</code>, and <code>children</code> is a list of <code>Node</code>s. <code>root</code> will be passed in the content of the template.</p> <p>I have found <a href="http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/">this</a> one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment.</p> <p>Does anybody know of a better way?</p>
44
2008-08-28T11:43:10Z
41,550
<p>I had a similar issue, however I had first implemented the solution using JavaScript, and just afterwards considered how I would have done the same thing in django templates.</p> <p>I used the serializer utility to turn a list off models into json, and used the json data as a basis for my hierarchy.</p>
-2
2008-09-03T12:25:19Z
[ "python", "django" ]
How can I render a tree structure (recursive) using a django template?
32,044
<p>I have a tree structure in memory that I would like to render in HTML using a Django template. </p> <pre><code>class Node(): name = "node name" children = [] </code></pre> <p>There will be some object <code>root</code> that is a <code>Node</code>, and <code>children</code> is a list of <code>Node</code>s. <code>root</code> will be passed in the content of the template.</p> <p>I have found <a href="http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/">this</a> one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment.</p> <p>Does anybody know of a better way?</p>
44
2008-08-28T11:43:10Z
48,262
<p>Django has a built in template helper for this exact scenario:</p> <p><a href="https://docs.djangoproject.com/en/dev/ref/templates/builtins/#unordered-list" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/templates/builtins/#unordered-list</a></p>
9
2008-09-07T08:49:51Z
[ "python", "django" ]
How can I render a tree structure (recursive) using a django template?
32,044
<p>I have a tree structure in memory that I would like to render in HTML using a Django template. </p> <pre><code>class Node(): name = "node name" children = [] </code></pre> <p>There will be some object <code>root</code> that is a <code>Node</code>, and <code>children</code> is a list of <code>Node</code>s. <code>root</code> will be passed in the content of the template.</p> <p>I have found <a href="http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/">this</a> one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment.</p> <p>Does anybody know of a better way?</p>
44
2008-08-28T11:43:10Z
957,761
<p>I had the same problem and I wrote a template tag. I know there are other tags like this out there but I needed to learn to make custom tags anyway :) I think it turned out pretty well.</p> <p>Read the docstring for usage instructions.</p> <p><a href="http://github.com/skid/django-recurse" rel="nofollow">github.com/skid/django-recurse</a></p>
7
2009-06-05T19:40:13Z
[ "python", "django" ]
How can I render a tree structure (recursive) using a django template?
32,044
<p>I have a tree structure in memory that I would like to render in HTML using a Django template. </p> <pre><code>class Node(): name = "node name" children = [] </code></pre> <p>There will be some object <code>root</code> that is a <code>Node</code>, and <code>children</code> is a list of <code>Node</code>s. <code>root</code> will be passed in the content of the template.</p> <p>I have found <a href="http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/">this</a> one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment.</p> <p>Does anybody know of a better way?</p>
44
2008-08-28T11:43:10Z
11,644,588
<p>Using <code>with</code> template tag, I could do tree/recursive list.</p> <p>Sample code:</p> <p>main template: assuming 'all_root_elems' is list of one or more root of tree</p> <pre><code>&lt;ul&gt; {%for node in all_root_elems %} {%include "tree_view_template.html" %} {%endfor%} &lt;/ul&gt; </code></pre> <p>tree_view_template.html renders the nested <code>ul</code>, <code>li</code> and uses <code>node</code> template variable as below:</p> <pre><code>&lt;li&gt; {{node.name}} {%if node.has_childs %} &lt;ul&gt; {%for ch in node.all_childs %} {%with node=ch template_name="tree_view_template.html" %} {%include template_name%} {%endwith%} {%endfor%} &lt;/ul&gt; {%endif%} &lt;/li&gt; </code></pre>
51
2012-07-25T07:21:27Z
[ "python", "django" ]
How can I render a tree structure (recursive) using a django template?
32,044
<p>I have a tree structure in memory that I would like to render in HTML using a Django template. </p> <pre><code>class Node(): name = "node name" children = [] </code></pre> <p>There will be some object <code>root</code> that is a <code>Node</code>, and <code>children</code> is a list of <code>Node</code>s. <code>root</code> will be passed in the content of the template.</p> <p>I have found <a href="http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/">this</a> one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment.</p> <p>Does anybody know of a better way?</p>
44
2008-08-28T11:43:10Z
12,558,610
<p>Yes, you can do it. It's a little trick, passing the filename to {% include %} as a variable:</p> <pre><code>{% with template_name="file/to_include.html" %} {% include template_name %} {% endwith %} </code></pre>
9
2012-09-24T03:50:27Z
[ "python", "django" ]
How can I render a tree structure (recursive) using a django template?
32,044
<p>I have a tree structure in memory that I would like to render in HTML using a Django template. </p> <pre><code>class Node(): name = "node name" children = [] </code></pre> <p>There will be some object <code>root</code> that is a <code>Node</code>, and <code>children</code> is a list of <code>Node</code>s. <code>root</code> will be passed in the content of the template.</p> <p>I have found <a href="http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/">this</a> one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment.</p> <p>Does anybody know of a better way?</p>
44
2008-08-28T11:43:10Z
26,045,234
<p>Does no one like dicts ? I might be missing something here but it would seem the most natural way to setup menus. Using keys as entries and values as links pop it in a DIV/NAV and away you go !</p> <p>From your base</p> <pre><code># Base.html &lt;nav&gt; {% with dict=contents template="treedict.html" %} {% include template %} {% endwith %} &lt;nav&gt; </code></pre> <p>call this</p> <pre><code># TreeDict.html &lt;ul&gt; {% for key,val in dict.items %} {% if val.items %} &lt;li&gt;{{ key }}&lt;/li&gt; {%with dict=val template="treedict.html" %} {%include template%} {%endwith%} {% else %} &lt;li&gt;&lt;a href="{{ val }}"&gt;{{ key }}&lt;/a&gt;&lt;/li&gt; {% endif %} {% endfor %} &lt;/ul&gt; </code></pre> <p>It haven't tried the default or the ordered yet perhaps you have ?</p>
0
2014-09-25T18:06:37Z
[ "python", "django" ]
How can I render a tree structure (recursive) using a django template?
32,044
<p>I have a tree structure in memory that I would like to render in HTML using a Django template. </p> <pre><code>class Node(): name = "node name" children = [] </code></pre> <p>There will be some object <code>root</code> that is a <code>Node</code>, and <code>children</code> is a list of <code>Node</code>s. <code>root</code> will be passed in the content of the template.</p> <p>I have found <a href="http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/">this</a> one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment.</p> <p>Does anybody know of a better way?</p>
44
2008-08-28T11:43:10Z
33,340,554
<p>I'm too late) All of you use so much unnecessary <strong><em>with</em></strong> tags, this is how i do recuesive:</p> <p>in main template:</p> <pre><code>&lt;!-- lets say that menu_list is already defined --&gt; &lt;ul&gt; {% include "menu.html" %} &lt;/ul&gt; </code></pre> <p>then in menu.html:</p> <pre><code>{% for menu in menu_list %} &lt;li&gt; {{ menu.name }} {% if menu.submenus|length %} &lt;ul&gt; {% include "menu.html" with menu_list=menu.submenus %} &lt;/ul&gt; {% endif %} &lt;/li&gt; {% endfor %} </code></pre>
3
2015-10-26T07:31:07Z
[ "python", "django" ]
Programmatically editing Python source
32,385
<p>This is something that I think would be very useful. Basically, I'd like there to be a way to edit Python source programmatically without requiring human intervention. There are a couple of things I would like to do with this:</p> <ol> <li><p>Edit the configuration of Python apps that use source modules for configuration.</p></li> <li><p>Set up a "template" so that I can customize a Python source file on the fly. This way, I can set up a "project" system on an open source app I'm working on and allow certain files to be customized.</p></li> </ol> <p>I could probably write something that can do this myself, but I can see that opening up a lot of "devil's in the details" type issues. Are there any ways to do this currently, or am I just going to have to bite the bullet and implement it myself?</p>
6
2008-08-28T14:23:00Z
32,402
<p>Python's standard library provides pretty good facilities for working with Python source; note the <a href="https://docs.python.org/2/library/tokenize.html" rel="nofollow">tokenize</a> and <a href="https://docs.python.org/2/library/parser.html" rel="nofollow">parser</a> modules.</p>
2
2008-08-28T14:27:37Z
[ "python", "file-io" ]
Programmatically editing Python source
32,385
<p>This is something that I think would be very useful. Basically, I'd like there to be a way to edit Python source programmatically without requiring human intervention. There are a couple of things I would like to do with this:</p> <ol> <li><p>Edit the configuration of Python apps that use source modules for configuration.</p></li> <li><p>Set up a "template" so that I can customize a Python source file on the fly. This way, I can set up a "project" system on an open source app I'm working on and allow certain files to be customized.</p></li> </ol> <p>I could probably write something that can do this myself, but I can see that opening up a lot of "devil's in the details" type issues. Are there any ways to do this currently, or am I just going to have to bite the bullet and implement it myself?</p>
6
2008-08-28T14:23:00Z
33,325
<p>I had the same issue and I simply opened the file and did some replace: then reload the file in the Python interpreter. This works fine and is easy to do. </p> <p>Otherwise AFAIK you have to use some conf objects.</p>
0
2008-08-28T20:33:29Z
[ "python", "file-io" ]
Programmatically editing Python source
32,385
<p>This is something that I think would be very useful. Basically, I'd like there to be a way to edit Python source programmatically without requiring human intervention. There are a couple of things I would like to do with this:</p> <ol> <li><p>Edit the configuration of Python apps that use source modules for configuration.</p></li> <li><p>Set up a "template" so that I can customize a Python source file on the fly. This way, I can set up a "project" system on an open source app I'm working on and allow certain files to be customized.</p></li> </ol> <p>I could probably write something that can do this myself, but I can see that opening up a lot of "devil's in the details" type issues. Are there any ways to do this currently, or am I just going to have to bite the bullet and implement it myself?</p>
6
2008-08-28T14:23:00Z
35,786
<p>Most of these kinds of things can be determined programatically in Python, using modules like sys, os, and the special <a href="http://pyref.infogami.com/__file__" rel="nofollow"></a> identifier which tells you where you are in the filesystem path.</p> <p>It's important to keep in mind that when a module is first imported it will execute everything in the file-scope, which is important for developing system-dependent behaviors. For example, the os module basically determines what operating system you're using on import and then adjusts its implementation accordingly (by importing another module corresponding to Linux, OSX, Windows, etc.).</p> <p>There's a lot of power in this feature and something along these lines is probably what you're looking for. :)</p> <p>[Edit] I've also used socket.gethostname() in some rare, hackish instances. ;)</p>
0
2008-08-30T08:35:08Z
[ "python", "file-io" ]
Is it possible to run a Python script as a service in Windows? If possible, how?
32,404
<p>I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service.</p> <p>I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to demonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services.</p> <p><strong>Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)?</strong> I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines.</p> <p><i>Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: <b>How is Windows aware of my service? Can I manage it with the native Windows utilities?</b> <strong>Basically, what is the equivalent of putting a start/stop script in /etc/init.d?</i></strong></p>
165
2008-08-28T14:28:04Z
32,440
<p>Yes you can. I do it using the pythoncom libraries that come included with <a href="http://www.activestate.com/Products/activepython/index.mhtml" rel="nofollow">ActivePython</a> or can be installed with <a href="https://sourceforge.net/projects/pywin32/" rel="nofollow">pywin32</a> (Python for Windows extensions).</p> <p>This is a basic skeleton for a simple service:</p> <pre><code>import win32serviceutil import win32service import win32event import servicemanager import socket class AppServerSvc (win32serviceutil.ServiceFramework): _svc_name_ = "TestService" _svc_display_name_ = "Test Service" def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) socket.setdefaulttimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'')) self.main() def main(self): pass if __name__ == '__main__': win32serviceutil.HandleCommandLine(AppServerSvc) </code></pre> <p>Your code would go in the main() method, usually with some kind of infinite loop that might be interrumped by checking a flag, that you set in the SvcStop method</p>
169
2008-08-28T14:39:04Z
[ "python", "windows", "cross-platform" ]
Is it possible to run a Python script as a service in Windows? If possible, how?
32,404
<p>I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service.</p> <p>I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to demonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services.</p> <p><strong>Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)?</strong> I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines.</p> <p><i>Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: <b>How is Windows aware of my service? Can I manage it with the native Windows utilities?</b> <strong>Basically, what is the equivalent of putting a start/stop script in /etc/init.d?</i></strong></p>
165
2008-08-28T14:28:04Z
597,750
<p>There are a couple alternatives for installing as a service virtually any Windows executable.</p> <h2>Method 1: Use instsrv and srvany from rktools.exe</h2> <p>For Windows Home Server or Windows Server 2003 (works with WinXP too), the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=9D467A69-57FF-4AE7-96EE-B18C4790CFFD&amp;displaylang=en">Windows Server 2003 Resource Kit Tools</a> comes with utilities that can be used in tandem for this, called <strong>instsrv.exe</strong> and <strong>srvany.exe</strong>. See this Microsoft KB article <a href="http://support.microsoft.com/kb/137890">KB137890</a> for details on how to use these utils. </p> <p>For Windows Home Server, there is a great user friendly wrapper for these utilities named aptly "<a href="http://forum.wegotserved.com/index.php?autocom=downloads&amp;showfile=7">Any Service Installer</a>". </p> <h2>Method 2: Use ServiceInstaller for Windows NT</h2> <p>There is another alternative using <a href="http://www.kcmultimedia.com/smaster/">ServiceInstaller for Windows NT</a> (<a href="http://www.kcmultimedia.com/smaster/download.html">download-able here</a>) with <a href="http://conort.googlepages.com/runanywindowsapplicationasntservice">python instructions available</a>. Contrary to the name, it works with both Windows 2000 and Windows XP as well. Here are some instructions for how to install a python script as a service.</p> <blockquote> <p><strong>Installing a Python script</strong></p> <p>Run ServiceInstaller to create a new service. (In this example, it is assumed that python is installed at c:\python25)</p> <pre><code>Service Name : PythonTest Display Name : PythonTest Startup : Manual (or whatever you like) Dependencies : (Leave blank or fill to fit your needs) Executable : c:\python25\python.exe Arguments : c:\path_to_your_python_script\test.py Working Directory : c:\path_to_your_python_script </code></pre> <p>After installing, open the Control Panel's Services applet, select and start the PythonTest service.</p> </blockquote> <p>After my initial answer, I noticed there were closely related Q&amp;A already posted on SO. See also:</p> <p><a href="http://stackoverflow.com/questions/32404/can-i-run-a-python-script-as-a-service-in-windows-how">Can I run a Python script as a service (in Windows)? How?</a></p> <p><a href="http://stackoverflow.com/questions/34328/how-do-i-make-windows-aware-of-a-service-i-have-written-in-python">How do I make Windows aware of a service I have written in Python?</a></p>
19
2009-02-28T08:30:54Z
[ "python", "windows", "cross-platform" ]
Is it possible to run a Python script as a service in Windows? If possible, how?
32,404
<p>I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service.</p> <p>I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to demonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services.</p> <p><strong>Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)?</strong> I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines.</p> <p><i>Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: <b>How is Windows aware of my service? Can I manage it with the native Windows utilities?</b> <strong>Basically, what is the equivalent of putting a start/stop script in /etc/init.d?</i></strong></p>
165
2008-08-28T14:28:04Z
24,996,607
<p>Although I upvoted the chosen answer a couple of weeks back, in the meantime I struggled a lot more with this topic. It feels like having a special Python installation and using special modules to run a script as a service is simply the wrong way. What about portability and such?</p> <p>I stumbled across the wonderful <a href="http://nssm.cc/">Non-sucking Service Manager</a>, which made it really simple and sane to deal with Windows Services. I figured since I could pass options to an installed service, I could just as well select my Python executable and pass my script as an option.</p> <p>I have not yet tried this solution, but I will do so right now and update this post along the process. I am also interested in using virtualenvs on Windows, so I might come up with a tutorial sooner or later and link to it here.</p>
17
2014-07-28T13:41:31Z
[ "python", "windows", "cross-platform" ]
How to generate dynamic (parametrized) unit tests in python?
32,899
<p>I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
111
2008-08-28T17:49:02Z
32,939
<p>i use something like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequense(unittest.TestCase): pass def test_generator(a, b): def test(self): self.assertEqual(a,b) return test if __name__ == '__main__': for t in l: test_name = 'test_%s' % t[0] test = test_generator(t[1], t[2]) setattr(TestSequense, test_name, test) unittest.main() </code></pre> <p>The <a href="https://github.com/wolever/nose-parameterized"><code>nose-parameterized</code></a> package can be used to automate this process:</p> <pre><code>from nose_parameterized import parameterized class TestSequence(unittest.TestCase): @parameterized.expand([ ["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"], ]) def test_sequence(self, name, a, b): self.assertEqual(a,b) </code></pre> <p>Which will generate the tests:</p> <pre><code>test_sequence_0_foo (__main__.TestSequence) ... ok test_sequence_1_bar (__main__.TestSequence) ... FAIL test_sequence_2_lee (__main__.TestSequence) ... ok ====================================================================== FAIL: test_sequence_1_bar (__main__.TestSequence) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/nose_parameterized/parameterized.py", line 233, in &lt;lambda&gt; standalone_func = lambda *a: func(*(a + p.args), **p.kwargs) File "x.py", line 12, in test_sequence self.assertEqual(a,b) AssertionError: 'a' != 'b' </code></pre>
75
2008-08-28T18:02:33Z
[ "python", "unit-testing", "parameterized-unit-test" ]
How to generate dynamic (parametrized) unit tests in python?
32,899
<p>I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
111
2008-08-28T17:49:02Z
34,094
<p>The <a href="https://nose.readthedocs.org/en/latest/">nose</a> testing framework <a href="https://nose.readthedocs.org/en/latest/writing_tests.html#test-generators">supports this</a>. </p> <p>Example (the code below is the entire contents of the file containing the test):</p> <pre><code>param_list = [('a', 'a'), ('a', 'b'), ('b', 'b')] def test_generator(): for params in param_list: yield check_em, params[0], params[1] def check_em(a, b): assert a == b </code></pre> <p>The output of the nosetests command:</p> <pre><code>> nosetests -v testgen.test_generator('a', 'a') ... ok testgen.test_generator('a', 'b') ... FAIL testgen.test_generator('b', 'b') ... ok ====================================================================== FAIL: testgen.test_generator('a', 'b') ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.5/site-packages/nose-0.10.1-py2.5.egg/nose/case.py", line 203, in runTest self.test(*self.arg) File "testgen.py", line 7, in check_em assert a == b AssertionError ---------------------------------------------------------------------- Ran 3 tests in 0.006s FAILED (failures=1) </code></pre>
48
2008-08-29T07:10:31Z
[ "python", "unit-testing", "parameterized-unit-test" ]
How to generate dynamic (parametrized) unit tests in python?
32,899
<p>I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
111
2008-08-28T17:49:02Z
810,127
<p>You would benefit from trying the <a href="https://launchpad.net/testscenarios">TestScenarios</a> library.</p> <blockquote> <p>testscenarios provides clean dependency injection for python unittest style tests. This can be used for interface testing (testing many implementations via a single test suite) or for classic dependency injection (provide tests with dependencies externally to the test code itself, allowing easy testing in different situations).</p> </blockquote>
6
2009-05-01T03:59:06Z
[ "python", "unit-testing", "parameterized-unit-test" ]
How to generate dynamic (parametrized) unit tests in python?
32,899
<p>I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
111
2008-08-28T17:49:02Z
20,870,875
<p>This can be solved elegantly using Metaclasses:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequenceMeta(type): def __new__(mcs, name, bases, dict): def gen_test(a, b): def test(self): self.assertEqual(a, b) return test for tname, a, b in l: test_name = "test_%s" % tname dict[test_name] = gen_test(a,b) return type.__new__(mcs, name, bases, dict) class TestSequence(unittest.TestCase): __metaclass__ = TestSequenceMeta if __name__ == '__main__': unittest.main() </code></pre>
31
2014-01-01T16:52:24Z
[ "python", "unit-testing", "parameterized-unit-test" ]
How to generate dynamic (parametrized) unit tests in python?
32,899
<p>I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
111
2008-08-28T17:49:02Z
23,508,426
<p><a href="https://docs.python.org/2/library/unittest.html#load-tests-protocol">load_tests</a> is a little known mechanism introduced in 2.7 to dynamically create a TestSuite. With it, you can easily create parametrized tests.</p> <p>For example:</p> <pre><code>import unittest class GeneralTestCase(unittest.TestCase): def __init__(self, methodName, param1=None, param2=None): super(GeneralTestCase, self).__init__(methodName) self.param1 = param1 self.param2 = param2 def runTest(self): pass # Test that depends on param 1 and 2. def load_tests(loader, tests, pattern): test_cases = unittest.TestSuite() for p1, p2 in [(1, 2), (3, 4)]: test_cases.addTest(GeneralTestCase('runTest', p1, p2)) return test_cases </code></pre> <p>That code will run all the TestCases in the TestSuite returned by load_tests. No other tests are automatically run by the discovery mechanism.</p> <p>Alternatively, you can also use inheritance as shown in this ticket: <a href="http://bugs.python.org/msg151444">http://bugs.python.org/msg151444</a></p>
18
2014-05-07T03:55:21Z
[ "python", "unit-testing", "parameterized-unit-test" ]
How to generate dynamic (parametrized) unit tests in python?
32,899
<p>I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
111
2008-08-28T17:49:02Z
25,626,660
<p>It can be done by using <a href="http://pytest.org">pytest</a>. Just write the file <code>test_me.py</code> with content: </p> <pre><code>import pytest @pytest.mark.parametrize('name, left, right', [['foo', 'a', 'a'], ['bar', 'a', 'b'], ['baz', 'b', 'b']]) def test_me(name, left, right): assert left == right, name </code></pre> <p>And run your test with command <code>py.test --tb=short test_me.py</code>. Then the output will be looks like: </p> <pre><code>=========================== test session starts ============================ platform darwin -- Python 2.7.6 -- py-1.4.23 -- pytest-2.6.1 collected 3 items test_me.py .F. ================================= FAILURES ================================= _____________________________ test_me[bar-a-b] _____________________________ test_me.py:8: in test_me assert left == right, name E AssertionError: bar ==================== 1 failed, 2 passed in 0.01 seconds ==================== </code></pre> <p>It simple!. Also <a href="http://pytest.org">pytest</a> has more features like <code>fixtures</code>, <code>mark</code>, <code>assert</code>, etc ...</p>
12
2014-09-02T15:08:01Z
[ "python", "unit-testing", "parameterized-unit-test" ]
How to generate dynamic (parametrized) unit tests in python?
32,899
<p>I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
111
2008-08-28T17:49:02Z
27,250,866
<p>You can use <a href="https://github.com/taykey/nose-ittr" rel="nofollow">nose-ittr</a> plugin (<code>pip install nose-ittr</code>).</p> <p>It's very easy to integrate with existing tests, minimal changes (if any) are required. It also supports <em>nose</em> multiprocessing plugin.</p> <p>Not that you can also have a customize <code>setup</code> function per test.</p> <pre><code>@ittr(number=[1, 2, 3, 4]) def test_even(self): assert_equal(self.number % 2, 0) </code></pre> <p>It is also possible to pass <code>nosetest</code> parameters like with their build-in plugin <code>attrib</code>, this way you can run only a specific test with specific parameter:</p> <pre><code>nosetest -a number=2 </code></pre>
4
2014-12-02T13:39:03Z
[ "python", "unit-testing", "parameterized-unit-test" ]
How to generate dynamic (parametrized) unit tests in python?
32,899
<p>I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
111
2008-08-28T17:49:02Z
28,890,882
<p>I came across <a href="https://pypi.python.org/pypi/ParamUnittest" rel="nofollow"><strong>ParamUnittest</strong></a> the other day when looking at the source code to <a href="https://pypi.python.org/pypi/radon" rel="nofollow">radon</a> (<a href="https://github.com/rubik/radon/blob/master/radon/tests/test_other_metrics.py" rel="nofollow">example usage on the github repo</a>). It should work with other frameworks that extend TestCase (like Nose).</p> <p>Here is an example:</p> <pre><code>import unittest import paramunittest @paramunittest.parametrized( ('1', '2'), #(4, 3), &lt;---- uncomment to have a failing test ('2', '3'), (('4', ), {'b': '5'}), ((), {'a': 5, 'b': 6}), {'a': 5, 'b': 6}, ) class TestBar(TestCase): def setParameters(self, a, b): self.a = a self.b = b def testLess(self): self.assertLess(self.a, self.b) </code></pre>
1
2015-03-06T01:21:50Z
[ "python", "unit-testing", "parameterized-unit-test" ]
How to generate dynamic (parametrized) unit tests in python?
32,899
<p>I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
111
2008-08-28T17:49:02Z
29,384,495
<p>As of Python 3.4 subtests have been introduced to unittest for this purpose. See <a href="https://docs.python.org/3/library/unittest.html#distinguishing-test-iterations-using-subtests" rel="nofollow">the documentation</a> for details. TestCase.subTest is a context manager which allows to isolate asserts in a test so that a failure will be reported with parameter information but does not stop the test execution. Here's the example from the documentation:</p> <pre><code>class NumbersTest(unittest.TestCase): def test_even(self): """ Test that numbers between 0 and 5 are all even. """ for i in range(0, 6): with self.subTest(i=i): self.assertEqual(i % 2, 0) </code></pre> <p>The output of a test run would be:</p> <pre><code>====================================================================== FAIL: test_even (__main__.NumbersTest) (i=1) ---------------------------------------------------------------------- Traceback (most recent call last): File "subtests.py", line 32, in test_even self.assertEqual(i % 2, 0) AssertionError: 1 != 0 ====================================================================== FAIL: test_even (__main__.NumbersTest) (i=3) ---------------------------------------------------------------------- Traceback (most recent call last): File "subtests.py", line 32, in test_even self.assertEqual(i % 2, 0) AssertionError: 1 != 0 ====================================================================== FAIL: test_even (__main__.NumbersTest) (i=5) ---------------------------------------------------------------------- Traceback (most recent call last): File "subtests.py", line 32, in test_even self.assertEqual(i % 2, 0) AssertionError: 1 != 0 </code></pre> <p>This is also part of <a href="https://pypi.python.org/pypi/unittest2" rel="nofollow">unittest2</a>, so it is available for earlier versions of Python.</p>
13
2015-04-01T06:46:45Z
[ "python", "unit-testing", "parameterized-unit-test" ]
How to generate dynamic (parametrized) unit tests in python?
32,899
<p>I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
111
2008-08-28T17:49:02Z
29,766,722
<p>Use <a href="https://technomilk.wordpress.com/2012/02/12/multiplying-python-unit-test-cases-with-different-sets-of-data/" rel="nofollow">tdd</a> library. It adds simple decorators for the test methods:</p> <pre><code>import unittest from ddt import ddt, data from mycode import larger_than_two @ddt class FooTestCase(unittest.TestCase): @data(3, 4, 12, 23) def test_larger_than_two(self, value): self.assertTrue(larger_than_two(value)) @data(1, -3, 2, 0) def test_not_larger_than_two(self, value): self.assertFalse(larger_than_two(value)) </code></pre> <p>This library can be installed with <code>pip</code>. It doesn't require <code>nose</code>, works excellent with the standard <code>unittest</code>.</p>
3
2015-04-21T08:24:35Z
[ "python", "unit-testing", "parameterized-unit-test" ]
How to generate dynamic (parametrized) unit tests in python?
32,899
<p>I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
111
2008-08-28T17:49:02Z
30,150,971
<p>Just use metaclasses, as seen here;</p> <pre><code>class DocTestMeta(type): """ Test functions are generated in metaclass due to the way some test loaders work. For example, setupClass() won't get called unless there are other existing test methods, and will also prevent unit test loader logic being called before the test methods have been defined. """ def __init__(self, name, bases, attrs): super(DocTestMeta, self).__init__(name, bases, attrs) def __new__(cls, name, bases, attrs): def func(self): """Inner test method goes here""" self.assertTrue(1) func.__name__ = 'test_sample' attrs[func.__name__] = func return super(DocTestMeta, cls).__new__(cls, name, bases, attrs) class ExampleTestCase(TestCase): """Our example test case, with no methods defined""" __metaclass__ = DocTestMeta </code></pre> <p>Output:</p> <pre><code>test_sample (ExampleTestCase) ... OK </code></pre>
1
2015-05-10T11:43:23Z
[ "python", "unit-testing", "parameterized-unit-test" ]