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
opengl set texture color with vertex color
244,720
<p>Because I need to display a <a href="http://codeflow.org/ubuntu.png" rel="nofollow">huge number of labels</a> that <a href="http://www.youtube.com/watch?v=A_ah-SE-cNY" rel="nofollow">move independently</a>, I need to render a label in <a href="http://pyglet.org" rel="nofollow">pyglet</a> to a texture (otherwise updating the vertex list for each glyph is too slow).</p> <p>I have a solution to do this, but my problem is that the texture that contains the glyphs is black, but I'd like it to be red. See the example below:</p> <pre><code>from pyglet.gl import * def label2texture(label): vertex_list = label._vertex_lists[0].vertices[:] xpos = map(int, vertex_list[::8]) ypos = map(int, vertex_list[1::8]) glyphs = label._get_glyphs() xstart = xpos[0] xend = xpos[-1] + glyphs[-1].width width = xend - xstart ystart = min(ypos) yend = max(ystart+glyph.height for glyph in glyphs) height = yend - ystart texture = pyglet.image.Texture.create(width, height, pyglet.gl.GL_RGBA) for glyph, x, y in zip(glyphs, xpos, ypos): data = glyph.get_image_data() x = x - xstart y = height - glyph.height - y + ystart texture.blit_into(data, x, y, 0) return texture.get_transform(flip_y=True) window = pyglet.window.Window() label = pyglet.text.Label('Hello World!', font_size = 36) texture = label2texture(label) @window.event def on_draw(): hoff = (window.width / 2) - (texture.width / 2) voff = (window.height / 2) - (texture.height / 2) glClear(GL_COLOR_BUFFER_BIT) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glClearColor(0.0, 1.0, 0.0, 1.0) window.clear() glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture.id) glColor4f(1.0, 0.0, 0.0, 1.0) #I'd like the font to be red glBegin(GL_QUADS); glTexCoord2d(0.0,1.0); glVertex2d(hoff,voff); glTexCoord2d(1.0,1.0); glVertex2d(hoff+texture.width,voff); glTexCoord2d(1.0,0.0); glVertex2d(hoff+texture.width,voff+texture.height); glTexCoord2d(0.0,0.0); glVertex2d(hoff, voff+texture.height); glEnd(); pyglet.app.run() </code></pre> <p>Any idea how I could color this?</p>
1
2008-10-28T20:25:55Z
405,855
<p>You want to set <code>glEnable(GL_COLOR_MATERIAL)</code>. This makes the texture color mix with the current OpenGL color. You can also use the <code>glColorMaterial</code> function to specify whether the front/back/both of each polygon should be affected. Docs <a href="http://www.glprogramming.com/blue/ch05.html#id37922" rel="nofollow">here</a>.</p>
2
2009-01-02T02:00:08Z
[ "python", "opengl", "pyglet" ]
AJAX console window with ANSI/VT100 support?
244,750
<p>I'm planning to write gateway web application, which would need "terminal window" with VT100/ANSI escape code support. Are there any AJAX based alternatives for such a task?</p> <p>I'm thinking something like this: <a href="http://tryruby.hobix.com/">http://tryruby.hobix.com/</a></p> <p>My preferred backend for the system is Python/Twisted/Pylons, but since I'm just planning, I will explore every option.</p>
8
2008-10-28T20:32:24Z
244,817
<p>AjaxTerm has a terminal, with mostly felicitous terminal emulation, done on the Python backend (it just pushes display updates to the client Javascript).</p> <p>The <a href="http://antony.lesuisse.org/qweb/trac/wiki/AjaxTerm" rel="nofollow">AjaxTerm</a> website has been down for some time, but you can still find it <a href="http://packages.debian.org/etch/ajaxterm" rel="nofollow">packaged</a> in Debian.</p>
3
2008-10-28T20:47:37Z
[ "python", "ajax", "vt100" ]
AJAX console window with ANSI/VT100 support?
244,750
<p>I'm planning to write gateway web application, which would need "terminal window" with VT100/ANSI escape code support. Are there any AJAX based alternatives for such a task?</p> <p>I'm thinking something like this: <a href="http://tryruby.hobix.com/">http://tryruby.hobix.com/</a></p> <p>My preferred backend for the system is Python/Twisted/Pylons, but since I'm just planning, I will explore every option.</p>
8
2008-10-28T20:32:24Z
244,823
<p>Try</p> <p><a href="http://wiki.kartbuilding.net/index.php/Anyterm">AnyTerm</a></p> <p><a href="http://wiki.kartbuilding.net/index.php/Ajaxterm">AjaxTerm</a></p> <p><a href="http://www-personal.umich.edu/~mressl/webshell/">WebShell</a></p>
9
2008-10-28T20:49:22Z
[ "python", "ajax", "vt100" ]
AJAX console window with ANSI/VT100 support?
244,750
<p>I'm planning to write gateway web application, which would need "terminal window" with VT100/ANSI escape code support. Are there any AJAX based alternatives for such a task?</p> <p>I'm thinking something like this: <a href="http://tryruby.hobix.com/">http://tryruby.hobix.com/</a></p> <p>My preferred backend for the system is Python/Twisted/Pylons, but since I'm just planning, I will explore every option.</p>
8
2008-10-28T20:32:24Z
963,694
<p>There's also <a href="http://shellinabox.com">Shell In A Box</a>.</p>
7
2009-06-08T06:47:26Z
[ "python", "ajax", "vt100" ]
Porting MATLAB functions to Scilab. How do I use symbolic?
244,803
<p>I'm porting some <a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow">MATLAB</a> functions to <a href="https://en.wikipedia.org/wiki/Scilab" rel="nofollow">Scilab</a>. The cool thing is that there is a <a href="http://ralyx.inria.fr/2004/Raweb/scilab/uid96.html" rel="nofollow">conversion toolbox</a> that make things very easy.</p> <p>The problem is I did not find the counterpart to the <strong>syms</strong> function, and the symbolic toolbox in general. (I'd like a port of the <em>Control System Toolbox</em> too, amd I'm still searching for some functions I'd may need).</p> <p>The only thing about symbolic toolbox I've found is <a href="http://www.cert.fr/dcsd/idco/perso/Magni/s_sym/doc/index.html" rel="nofollow">this</a>, but it was a little trcky and not so easy (actually I was not able to set up it correctly in 30&nbsp;minutes, and I gave up for now. I'm going to try later), and it needs Maxima to be installed. Does anyone know anything about that?</p> <p>Scilab is not exactly a must. The project aims to give a more <em>free</em> and <em>open source</em> alternative to MATLAB. I saw there is <a href="http://code.google.com/p/sympy/" rel="nofollow">SymPy</a> for <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="nofollow">Python</a>, and I just could use it with <a href="http://www.scipy.org/" rel="nofollow">SciPy</a>, but I'd lost the <a href="http://ralyx.inria.fr/2004/Raweb/scilab/uid96.html" rel="nofollow">conversion toolbox</a> thing :\</p> <p>That said, what should be better? Get SciLab and Maxima work together or move to Python &amp; co.? This is the start of the project, so the earlier I choose this, the better.</p>
3
2008-10-28T20:44:25Z
245,207
<p>Not to discourage your project, but if you just want a <em>free</em> and <em>open source</em> alternative to <a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow">MATLAB</a>, have you looked at the <a href="http://en.wikipedia.org/wiki/GNU_Octave" rel="nofollow">Octave</a> project? Contributing there might be more productive than building your own MATLAB alternative.</p> <p>If your project requires the functionality of MATLAB's Symbolic then take a look at</p> <ul> <li><a href="http://wiki.octave.org/wiki.pl?CategorySymbolic" rel="nofollow">http://wiki.octave.org/wiki.pl?CategorySymbolic</a></li> </ul> <p>From my quick Google search I didn't find anything comparable to MATLAB's Simulink.</p> <p>Also, Python and SciPy do have most of the functionality of MATLAB, and I guess Scilab's conversion utility would be useful in porting your own M-Files into Scilab code.</p> <p>Your question seems to imply you want to port over MATLAB Toolboxes</p> <blockquote> <p>The only thing about symbolic toolbox I've found is this...</p> </blockquote> <p>I hope I am just misinterpreting you. If you are then there might be licensing issues if you were to distribute your system because the MATLAB Toolbox. Just a thought. But perhaps you wish to port your MATLAB code to, so that it doesn't not have the MATLAB dependency.</p> <h3>Update</h3> <p>For Control System functionality Octave, I just found that Octave does have a toolbox, see:</p> <ul> <li><a href="http://www.obihiro.ac.jp/~suzukim/masuda/octave/html/octave_125.html" rel="nofollow">Octave Control Systems Toolbox</a></li> </ul> <p>Which has some of the functionality of Simulink, but it doesn't seem to have the graphical interface for building block diagrams.</p>
1
2008-10-28T23:04:13Z
[ "python", "matlab", "porting", "scilab", "sympy" ]
Porting MATLAB functions to Scilab. How do I use symbolic?
244,803
<p>I'm porting some <a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow">MATLAB</a> functions to <a href="https://en.wikipedia.org/wiki/Scilab" rel="nofollow">Scilab</a>. The cool thing is that there is a <a href="http://ralyx.inria.fr/2004/Raweb/scilab/uid96.html" rel="nofollow">conversion toolbox</a> that make things very easy.</p> <p>The problem is I did not find the counterpart to the <strong>syms</strong> function, and the symbolic toolbox in general. (I'd like a port of the <em>Control System Toolbox</em> too, amd I'm still searching for some functions I'd may need).</p> <p>The only thing about symbolic toolbox I've found is <a href="http://www.cert.fr/dcsd/idco/perso/Magni/s_sym/doc/index.html" rel="nofollow">this</a>, but it was a little trcky and not so easy (actually I was not able to set up it correctly in 30&nbsp;minutes, and I gave up for now. I'm going to try later), and it needs Maxima to be installed. Does anyone know anything about that?</p> <p>Scilab is not exactly a must. The project aims to give a more <em>free</em> and <em>open source</em> alternative to MATLAB. I saw there is <a href="http://code.google.com/p/sympy/" rel="nofollow">SymPy</a> for <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="nofollow">Python</a>, and I just could use it with <a href="http://www.scipy.org/" rel="nofollow">SciPy</a>, but I'd lost the <a href="http://ralyx.inria.fr/2004/Raweb/scilab/uid96.html" rel="nofollow">conversion toolbox</a> thing :\</p> <p>That said, what should be better? Get SciLab and Maxima work together or move to Python &amp; co.? This is the start of the project, so the earlier I choose this, the better.</p>
3
2008-10-28T20:44:25Z
246,449
<p>See <a href="http://vnoel.wordpress.com/2008/05/03/bye-matlab-hello-python-thanks-sage/" rel="nofollow">Bye MATLAB, hello Python, thanks Sage</a> for a first-hand experience of migrating from <a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow">MATLAB</a> to Python.</p>
3
2008-10-29T11:24:13Z
[ "python", "matlab", "porting", "scilab", "sympy" ]
Upgrading Google Application Engine program to use unicode
245,094
<p>I have a simple Google App Engine app, that I wrote using ordinary strings. I realize I want to make it handle unicode. Are there any gotchas with this? I'm thinking of all the strings that I currently already have in the live database. (From real users who I don't want to upset.)</p>
3
2008-10-28T22:20:23Z
245,159
<p>The datastore internally keeps all strings <a href="http://code.google.com/appengine/docs/datastore/typesandpropertyclasses.html#str" rel="nofollow">in unicode</a>.</p>
1
2008-10-28T22:43:27Z
[ "python", "google-app-engine", "unicode" ]
Upgrading Google Application Engine program to use unicode
245,094
<p>I have a simple Google App Engine app, that I wrote using ordinary strings. I realize I want to make it handle unicode. Are there any gotchas with this? I'm thinking of all the strings that I currently already have in the live database. (From real users who I don't want to upset.)</p>
3
2008-10-28T22:20:23Z
245,172
<p><a href="http://stackoverflow.com/questions/245094/upgrading-google-application-engine-program-to-use-unicode#245159">Alexander Kojevnikov</a> said: "The datastore internally keeps all strings in unicode."</p> <p>In other words, your application is already using unicode everywhere. Thank the google folks for a sensible API. No further work required.</p>
2
2008-10-28T22:53:14Z
[ "python", "google-app-engine", "unicode" ]
Upgrading Google Application Engine program to use unicode
245,094
<p>I have a simple Google App Engine app, that I wrote using ordinary strings. I realize I want to make it handle unicode. Are there any gotchas with this? I'm thinking of all the strings that I currently already have in the live database. (From real users who I don't want to upset.)</p>
3
2008-10-28T22:20:23Z
1,515,542
<p>When storing to a db.TextProperty() you need to use db.Text() like:</p> <p><code>instance.xml = db.Text(xml_string, encoding="utf_8")</code></p> <p>And specify the correct encoding if the string doesn't have a BOM on it. Like if you get unexpected unicode data from an XML stream.</p> <p>This happened to me when using Amazon.com's product API.</p> <p>Also Google's urlfetch had unicode problems dealing with that stream. So I ended up running minidom's parse() function instead of parseString() on the urllib.urlopen()'s return which acts like a stream like so to fix the problem:</p> <pre><code>response = urllib.urlopen(url) xml = minidom.parse(response) </code></pre>
1
2009-10-04T03:53:15Z
[ "python", "google-app-engine", "unicode" ]
What are "first class" objects?
245,192
<p>When are objects or something else said to be "first class" in a given programming language, and why? In what do they differ from languages where they are not?</p> <p>EDIT. When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"?</p>
85
2008-10-28T22:58:47Z
245,208
<p>In short, it means there are no restrictions on the object's use. It's the same as any other object.</p> <p>A first class object is an entity that can be dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have. </p> <blockquote> <p>Depending on the language, this can imply:</p> <ul> <li>being expressible as an anonymous literal value</li> <li>being storable in variables</li> <li>being storable in data structures</li> <li>having an intrinsic identity (independent of any given name)</li> <li>being comparable for equality with other entities</li> <li>being passable as a parameter to a procedure/function</li> <li>being returnable as the result of a procedure/function</li> <li>being constructible at runtime</li> <li>being printable</li> <li>being readable</li> <li>being transmissible among distributed processes</li> <li>being storable outside running processes</li> </ul> </blockquote> <p><a href="http://en.wikipedia.org/wiki/First-class_object">Source</a>.</p> <p>In C++ functions themselves are not first class objects, however:</p> <ul> <li>You can override the '()' operator making it possible to have an object function, which is first class.</li> <li>Function pointers are first class. </li> <li>boost bind, lambda and function do offer first class functions</li> </ul> <p>In C++, classes are not first class objects but instances of those classes are. In Python both the classes <em>and</em> the objects are first class objects. (See <a href="http://stackoverflow.com/a/6581949/1612701">this answer</a> for more details about classes as objects).</p> <p>Here is an example of Javascript first class functions:</p> <pre><code>// f: function that takes a number and returns a number // deltaX: small positive number // returns a function that is an approximate derivative of f function makeDerivative( f, deltaX ) { var deriv = function(x) { return ( f(x + deltaX) - f(x) )/ deltaX; } return deriv; } var cos = makeDerivative( Math.sin, 0.000001); // cos(0) ~&gt; 1 // cos(pi/2) ~&gt; 0 </code></pre> <p><a href="http://en.wikipedia.org/wiki/First-class_function">Source</a>.</p> <p>Entities that are not first class objects are referred to as second-class objects. Functions in C++ are second class because they can't be dynamically created. </p> <p><strong>Regarding the edit:</strong></p> <blockquote> <p>EDIT. When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"?</p> </blockquote> <p>The term object can be used loosely and doesn't imply being first class. And it would probably make more sense to call the whole concept 'first class entities'. But in Python they do aim to make everything first class. I believe the intent of the person who made your statement meant first class. </p>
82
2008-10-28T23:04:22Z
[ "python", "language-agnostic" ]
What are "first class" objects?
245,192
<p>When are objects or something else said to be "first class" in a given programming language, and why? In what do they differ from languages where they are not?</p> <p>EDIT. When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"?</p>
85
2008-10-28T22:58:47Z
245,209
<p>“First class” means you can operate on them in the usual manner. Most of the times, this just means you can pass these first-class citizens as arguments to functions, or return them from functions.</p> <p>This is self-evident for objects but not always so evident for functions, or even classes:</p> <pre><code>void f(int n) { return n * 2; } void g(Action&lt;int&gt; a, int n) { return a(n); } // Now call g and pass f: g(f, 10); // = 20 </code></pre> <p>This is an example in C# where functions actually <em>aren't</em> first-class objects. The above code therefore uses a small workaround (namely a generic delegate called <code>Action&lt;&gt;</code>) to pass a function as an argument. Other languages, such as Ruby, allow treating even classes and code blocks as normal variables (or in the case of Ruby, constants).</p>
14
2008-10-28T23:04:36Z
[ "python", "language-agnostic" ]
What are "first class" objects?
245,192
<p>When are objects or something else said to be "first class" in a given programming language, and why? In what do they differ from languages where they are not?</p> <p>EDIT. When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"?</p>
85
2008-10-28T22:58:47Z
245,238
<p>IMO this is one of those metaphors used to describe things in a natural language. The term is essentially used in context of describing functions as first class objects. </p> <p>If you consider a object oriented language, we can impart various features to objects for eg: inheritance, class definition, ability to pass to other sections of code(method arguments), ability to store in a data structure etc. If we can do the same with an entity which is not normally considered as a object, like functions in the case of java script, such entities are considered to be first class objects.</p> <p>First class essentially here means, not handled as second class (with degraded behaviour). Essentially the mocking is perfect or indistinguishable.</p>
0
2008-10-28T23:16:37Z
[ "python", "language-agnostic" ]
What are "first class" objects?
245,192
<p>When are objects or something else said to be "first class" in a given programming language, and why? In what do they differ from languages where they are not?</p> <p>EDIT. When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"?</p>
85
2008-10-28T22:58:47Z
245,295
<p>"When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"?"</p> <p>Yes.</p> <p>Everything in Python is a proper object. Even things that are "primitive types" in other languages.</p> <p>You find that an object like <code>2</code> actually has a fairly rich and sophisticated interface.</p> <pre><code>&gt;&gt;&gt; dir(2) ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__'] </code></pre> <p>Because everything's a first-class object in Python, there are relatively few obscure special cases. </p> <p>In Java, for example, there are primitive types (int, bool, double, char) that aren't proper objects. That's why Java has to introduce Integer, Boolean, Double and Character as first-class types. This can be hard to teach to beginners -- it isn't obvious why both a primitive type and an class have to exist side-by-side.</p> <p>It also means that an object's class is -- itself -- an object. This is different from C++, where the classes don't always have a distinct existence at run-time.</p> <p>The type of <code>2</code> is the <code>type 'int'</code> object, which has methods, attributes and a type.</p> <pre><code>&gt;&gt;&gt; type(2) &lt;type 'int'&gt; </code></pre> <p>The type of a built-in type like <code>int</code> is the <code>type 'type'</code> object. This has methods and attributes, also.</p> <pre><code>&gt;&gt;&gt; type(type(2)) &lt;type 'type'&gt; </code></pre>
9
2008-10-28T23:49:30Z
[ "python", "language-agnostic" ]
What are "first class" objects?
245,192
<p>When are objects or something else said to be "first class" in a given programming language, and why? In what do they differ from languages where they are not?</p> <p>EDIT. When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"?</p>
85
2008-10-28T22:58:47Z
417,721
<p>From a slide in <a href="http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/">Structure and Interpretation of Computer Programs</a>, lecture 2A (1986), which in turns quotes <a href="http://en.wikipedia.org/wiki/Christopher_Strachey">Christopher Stracey</a>:</p> <p><strong>The rights and privileges of first-class citizens:</strong></p> <ul> <li>To be named by variables.</li> <li>To be passed as arguments to procedures.</li> <li>To be returned as values of procedures.</li> <li>To be incorporated into data structures</li> </ul>
7
2009-01-06T19:03:53Z
[ "python", "language-agnostic" ]
Which library should I use to write an XLS from Linux / Python?
245,225
<p>I'd love a <em>good</em> native Python library to write XLS, but it doesn't seem to exist. Happily, Jython does.</p> <p>So I'm trying to decide between jexcelapi and Apache HSSF: <a href="http://www.andykhan.com/jexcelapi/tutorial.html#writing">http://www.andykhan.com/jexcelapi/tutorial.html#writing</a> <a href="http://poi.apache.org/hssf/quick-guide.html">http://poi.apache.org/hssf/quick-guide.html</a></p> <p>(I can't use COM automation because I'm not on Windows, and even if I was, I couldn't afford Office licenses.)</p> <p>My initial thoughts are that POI/HSSF is very thorough, but also very Java-- everything seems a bit harder than it needs to be. Good documentation, but my head hurts trying to bridge the gap between what it describes and what I need to accomplish.</p> <p>jexcepapi seems to have a simpler, nicer (for me) interface, but doesn't have very good documentation or community.</p> <p>Which would you use, and why?</p>
7
2008-10-28T23:11:54Z
245,267
<p>Excel exposes the same OLE automation API used by VBA to anything that supports COM. You can use win32com (which is included with ActiveState Python by default) to manipulate spreadsheets in much the same way that you would do in VBA.</p>
0
2008-10-28T23:33:20Z
[ "java", "python", "xls", "jexcelapi", "hssf" ]
Which library should I use to write an XLS from Linux / Python?
245,225
<p>I'd love a <em>good</em> native Python library to write XLS, but it doesn't seem to exist. Happily, Jython does.</p> <p>So I'm trying to decide between jexcelapi and Apache HSSF: <a href="http://www.andykhan.com/jexcelapi/tutorial.html#writing">http://www.andykhan.com/jexcelapi/tutorial.html#writing</a> <a href="http://poi.apache.org/hssf/quick-guide.html">http://poi.apache.org/hssf/quick-guide.html</a></p> <p>(I can't use COM automation because I'm not on Windows, and even if I was, I couldn't afford Office licenses.)</p> <p>My initial thoughts are that POI/HSSF is very thorough, but also very Java-- everything seems a bit harder than it needs to be. Good documentation, but my head hurts trying to bridge the gap between what it describes and what I need to accomplish.</p> <p>jexcepapi seems to have a simpler, nicer (for me) interface, but doesn't have very good documentation or community.</p> <p>Which would you use, and why?</p>
7
2008-10-28T23:11:54Z
245,272
<p>I'd use JExcelApi, but only because I've used it before. Never have touched HSSF. Biggest show-stopper I can recall is JExcelApi doesn't support multiple formats in one cell (e.g. half the text in bold, the other half in italic or something like that). I think in general JExcelApi is more limited than HSSF, but the limitations never got in my way. <p> And yes, documentation is sparse for the interface (and nonexistent for the underlying mechanisms), but I thought it was doable...</p>
1
2008-10-28T23:34:49Z
[ "java", "python", "xls", "jexcelapi", "hssf" ]
Which library should I use to write an XLS from Linux / Python?
245,225
<p>I'd love a <em>good</em> native Python library to write XLS, but it doesn't seem to exist. Happily, Jython does.</p> <p>So I'm trying to decide between jexcelapi and Apache HSSF: <a href="http://www.andykhan.com/jexcelapi/tutorial.html#writing">http://www.andykhan.com/jexcelapi/tutorial.html#writing</a> <a href="http://poi.apache.org/hssf/quick-guide.html">http://poi.apache.org/hssf/quick-guide.html</a></p> <p>(I can't use COM automation because I'm not on Windows, and even if I was, I couldn't afford Office licenses.)</p> <p>My initial thoughts are that POI/HSSF is very thorough, but also very Java-- everything seems a bit harder than it needs to be. Good documentation, but my head hurts trying to bridge the gap between what it describes and what I need to accomplish.</p> <p>jexcepapi seems to have a simpler, nicer (for me) interface, but doesn't have very good documentation or community.</p> <p>Which would you use, and why?</p>
7
2008-10-28T23:11:54Z
245,275
<p>What's wrong with <a href="http://pypi.python.org/pypi/xlwt">xlwt</a>?</p>
16
2008-10-28T23:37:26Z
[ "java", "python", "xls", "jexcelapi", "hssf" ]
Which library should I use to write an XLS from Linux / Python?
245,225
<p>I'd love a <em>good</em> native Python library to write XLS, but it doesn't seem to exist. Happily, Jython does.</p> <p>So I'm trying to decide between jexcelapi and Apache HSSF: <a href="http://www.andykhan.com/jexcelapi/tutorial.html#writing">http://www.andykhan.com/jexcelapi/tutorial.html#writing</a> <a href="http://poi.apache.org/hssf/quick-guide.html">http://poi.apache.org/hssf/quick-guide.html</a></p> <p>(I can't use COM automation because I'm not on Windows, and even if I was, I couldn't afford Office licenses.)</p> <p>My initial thoughts are that POI/HSSF is very thorough, but also very Java-- everything seems a bit harder than it needs to be. Good documentation, but my head hurts trying to bridge the gap between what it describes and what I need to accomplish.</p> <p>jexcepapi seems to have a simpler, nicer (for me) interface, but doesn't have very good documentation or community.</p> <p>Which would you use, and why?</p>
7
2008-10-28T23:11:54Z
245,591
<p>+1 for xlwt. See Matt Harrison's blog for posts on <a href="http://panela.blog-city.com/pyexcelerator_xlwt_cheatsheet_create_native_excel_from_pu.htm" rel="nofollow">how to use xlwt</a> and <a href="http://panela.blog-city.com/creating_large_excel_spreadsheets_xlwt_in_python.htm" rel="nofollow">how to deal with large spreadsheets</a>. Also, check out the <a href="http://groups.google.com.au/group/python-excel?lnk=li&amp;hl=en" rel="nofollow">python-excel</a> group on Google "If you use Python to read, write or otherwise manipulate Excel files".</p>
3
2008-10-29T02:14:27Z
[ "java", "python", "xls", "jexcelapi", "hssf" ]
Which library should I use to write an XLS from Linux / Python?
245,225
<p>I'd love a <em>good</em> native Python library to write XLS, but it doesn't seem to exist. Happily, Jython does.</p> <p>So I'm trying to decide between jexcelapi and Apache HSSF: <a href="http://www.andykhan.com/jexcelapi/tutorial.html#writing">http://www.andykhan.com/jexcelapi/tutorial.html#writing</a> <a href="http://poi.apache.org/hssf/quick-guide.html">http://poi.apache.org/hssf/quick-guide.html</a></p> <p>(I can't use COM automation because I'm not on Windows, and even if I was, I couldn't afford Office licenses.)</p> <p>My initial thoughts are that POI/HSSF is very thorough, but also very Java-- everything seems a bit harder than it needs to be. Good documentation, but my head hurts trying to bridge the gap between what it describes and what I need to accomplish.</p> <p>jexcepapi seems to have a simpler, nicer (for me) interface, but doesn't have very good documentation or community.</p> <p>Which would you use, and why?</p>
7
2008-10-28T23:11:54Z
1,158,884
<p>i personally dis-advise JExcel if you intent to use anything more then very simple text to excel and vice versa.</p> <p>the more advanced features are abstracted very leaky from the underlying (basically undocumented) low-level code / (documented) Excel specs.</p> <p>another problem we ran into is jexcel fails fatally when encountering invalid formulas. and if you need to parse client supplied spreadsheets this is a problem.</p> <p>also the new POI version support (almost) seemless both xls and xlsx at the same time.</p>
1
2009-07-21T12:26:55Z
[ "java", "python", "xls", "jexcelapi", "hssf" ]
Running Django with FastCGI or with mod_python
245,237
<p>which would you recommend? which is faster, reliable? apache mod_python or nginx/lighttpd FastCGI?</p>
20
2008-10-28T23:16:23Z
245,259
<p>Personally I've had it working with FastCGI for some time now (6 months or so) and the response times 'seem' quicker when loading a page that way vs mod___python. The critical reason for me though is that I couldn't see an obvious way to do multiple sites from the same apache / mod_python install whereas FastCGI was a relative no-brainer.</p> <p>I've not conducted any particularly thorough experiments though :-)</p> <p><strong>[Edit]</strong> Speaking from experience though, setting up FastCGI can be a bit of a pain the first time around. I keep meaning to write a guide..!</p>
2
2008-10-28T23:29:58Z
[ "python", "django", "apache", "fastcgi" ]
Running Django with FastCGI or with mod_python
245,237
<p>which would you recommend? which is faster, reliable? apache mod_python or nginx/lighttpd FastCGI?</p>
20
2008-10-28T23:16:23Z
245,264
<p>lighttpd with FastCGI will be nominally faster, but really the time it takes to run your python code and any database hits it does is going to absolutely dwarf any performance benefit you get between web servers.</p> <p>mod_python and apache will give you a bit more flexibility feature-wise if you want to write code outside of django that does stuff like digest auth, or any fancy HTTP header getting/setting. Perhaps you want to use other builtin features of apache such as mod_rewrite.</p> <p>If memory is a concern, staying away form apache/mod_python will help a lot. Apache tends to use a lot of RAM, and the mod_python code that glues into all of the apache functionality occupies a lot of memory-space as well. Not to mention the multiprocess nature of apache tends to eat up more RAM, as each process grows to the size of it's most intensive request.</p>
6
2008-10-28T23:32:27Z
[ "python", "django", "apache", "fastcgi" ]
Running Django with FastCGI or with mod_python
245,237
<p>which would you recommend? which is faster, reliable? apache mod_python or nginx/lighttpd FastCGI?</p>
20
2008-10-28T23:16:23Z
245,464
<p>I'm using it with nginx. not sure if it's really faster, but certainly less RAM/CPU load. Also it's easier to run several Django processes and have nginx map each URL prefix to a different socket. still not taking full advantage of nginx's memcached module, but first tests show <em>huge</em> speed advantage.</p>
2
2008-10-29T01:14:18Z
[ "python", "django", "apache", "fastcgi" ]
Running Django with FastCGI or with mod_python
245,237
<p>which would you recommend? which is faster, reliable? apache mod_python or nginx/lighttpd FastCGI?</p>
20
2008-10-28T23:16:23Z
245,484
<p>There's also mod_wsgi, it seems to be faster than mod_python and the daemon mode operates similar to FastCGI</p>
2
2008-10-29T01:25:43Z
[ "python", "django", "apache", "fastcgi" ]
Running Django with FastCGI or with mod_python
245,237
<p>which would you recommend? which is faster, reliable? apache mod_python or nginx/lighttpd FastCGI?</p>
20
2008-10-28T23:16:23Z
245,660
<p>I've done both, and Apache/mod_python tended to be easier to work with and more stable. But these days I've jumped over to Apache/mod_wsgi, which is everything I've ever wanted and more:</p> <ul> <li>Easy management of daemon processes.</li> <li>As a result, <strong>much</strong> better process isolation (running multiple sites in the same Apache config with mod_python almost always ends in trouble -- environment variables and C extensions leak across sites when you do that).</li> <li>Easy code reloads (set it up right and you can just touch the <code>.wsgi</code> file to reload instead of restarting Apache).</li> <li>More predictable resource usage. With mod_python, a given Apache child process' memory use can jump around a lot. With mod_wsgi it's pretty stable: once everything's loaded, you know that's how much memory it'll use.</li> </ul>
21
2008-10-29T03:06:03Z
[ "python", "django", "apache", "fastcgi" ]
Running Django with FastCGI or with mod_python
245,237
<p>which would you recommend? which is faster, reliable? apache mod_python or nginx/lighttpd FastCGI?</p>
20
2008-10-28T23:16:23Z
258,159
<p>Nginx with mod_wsgi</p>
5
2008-11-03T08:51:51Z
[ "python", "django", "apache", "fastcgi" ]
Running Django with FastCGI or with mod_python
245,237
<p>which would you recommend? which is faster, reliable? apache mod_python or nginx/lighttpd FastCGI?</p>
20
2008-10-28T23:16:23Z
304,369
<p>I'd recommend WSGI configurations; I keep meaning to ditch apache, but there is always some legacy app on the server that seems to require it. Additionally, the WSGI app ecology is very diverse, and it allows neat tricks such as daisy-chaining WSGI "middleware" between the server and the app.</p> <p>However, there are currently <a href="http://groups.google.com/group/modwsgi/browse_thread/thread/a488d2551c4c7df0" rel="nofollow">known issues with some apps and apache mod_wsgi</a>, particularly some ctypes apps, so be wary if you are trying to run, say, <a href="http://geodjango.org/" rel="nofollow">geodjango</a> which uses ctypes extensively. I'm currently working around those issues by going back to fastcgi myself.</p>
2
2008-11-20T05:01:46Z
[ "python", "django", "apache", "fastcgi" ]
How do I get the name of a function or method from within a Python function or method?
245,304
<p>I feel like I should know this, but I haven't been able to figure it out...</p> <p>I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.</p>
36
2008-10-28T23:52:09Z
245,314
<p>I think the <a href="http://www.python.org/doc/2.5.2/lib/module-traceback.html" rel="nofollow"><code>traceback</code></a> module might have what you're looking for. In particular, the <code>extract_stack</code> function looks like it will do the job.</p>
3
2008-10-28T23:56:35Z
[ "python" ]
How do I get the name of a function or method from within a Python function or method?
245,304
<p>I feel like I should know this, but I haven't been able to figure it out...</p> <p>I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.</p>
36
2008-10-28T23:52:09Z
245,333
<p>This decorator makes the name of the method available inside the function by passing it as a keyword argument.</p> <pre><code>from functools import wraps def pass_func_name(func): "Name of decorated function will be passed as keyword arg _func_name" @wraps(func) def _pass_name(*args, **kwds): kwds['_func_name'] = func.func_name return func(*args, **kwds) return _pass_name </code></pre> <p>You would use it this way:</p> <pre><code>@pass_func_name def sum(a, b, _func_name): print "running function %s" % _func_name return a + b print sum(2, 4) </code></pre> <p>But maybe you'd want to write what you want directly inside the decorator itself. Then the code is an example of a way to get the function name in a decorator. If you give more details about what you want to do in the function, that requires the name, maybe I can suggest something else.</p>
15
2008-10-29T00:07:24Z
[ "python" ]
How do I get the name of a function or method from within a Python function or method?
245,304
<p>I feel like I should know this, but I haven't been able to figure it out...</p> <p>I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.</p>
36
2008-10-28T23:52:09Z
245,346
<p>This seems to be the simplest way using module <code>inspect</code>:</p> <pre><code>import inspect def somefunc(a,b,c): print "My name is: %s" % inspect.stack()[0][3] </code></pre> <p>You could generalise this with:</p> <pre><code>def funcname(): return inspect.stack()[1][3] def somefunc(a,b,c): print "My name is: %s" % funcname() </code></pre> <p>Credit to <a href="http://stefaanlippens.net/python_inspect">Stefaan Lippens</a> which was found via google.</p>
52
2008-10-29T00:13:35Z
[ "python" ]
How do I get the name of a function or method from within a Python function or method?
245,304
<p>I feel like I should know this, but I haven't been able to figure it out...</p> <p>I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.</p>
36
2008-10-28T23:52:09Z
245,561
<pre><code># file "foo.py" import sys import os def LINE( back = 0 ): return sys._getframe( back + 1 ).f_lineno def FILE( back = 0 ): return sys._getframe( back + 1 ).f_code.co_filename def FUNC( back = 0): return sys._getframe( back + 1 ).f_code.co_name def WHERE( back = 0 ): frame = sys._getframe( back + 1 ) return "%s/%s %s()" % ( os.path.basename( frame.f_code.co_filename ), frame.f_lineno, frame.f_code.co_name ) def testit(): print "Here in %s, file %s, line %s" % ( FUNC(), FILE(), LINE() ) print "WHERE says '%s'" % WHERE() testit() </code></pre> <p>Output:</p> <pre><code>$ python foo.py Here in testit, file foo.py, line 17 WHERE says 'foo.py/18 testit()' </code></pre> <p>Use "back = 1" to find info regarding two levels back down the stack, etc.</p>
10
2008-10-29T01:58:33Z
[ "python" ]
How do I get the name of a function or method from within a Python function or method?
245,304
<p>I feel like I should know this, but I haven't been able to figure it out...</p> <p>I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.</p>
36
2008-10-28T23:52:09Z
245,581
<p>The answers involving introspection via <code>inspect</code> and the like are reasonable. But there may be another option, depending on your situation:</p> <p>If your integration test is written with the <a href="http://docs.python.org/library/unittest.html">unittest</a> module, then you could use <code>self.id()</code> within your TestCase.</p>
21
2008-10-29T02:09:48Z
[ "python" ]
How do I draw text at an angle using python's PIL?
245,447
<p>Using Python I want to be able to draw text at different angles using PIL.</p> <p>For example, imagine you were drawing the number around the face of a clock. The number <strong>3</strong> would appear as expected whereas <strong>12</strong> would we drawn rotated counter-clockwise 90 degrees.</p> <p>Therefore, I need to be able to draw many different strings at many different angles.</p>
15
2008-10-29T01:04:48Z
245,837
<p>I'm not saying this is going to be easy, or that this solution will necessarily be perfect for you, but look at the documentation here:<p> <a href="http://effbot.org/imagingbook/pil-index.htm" rel="nofollow"><a href="http://effbot.org/imagingbook/pil-index.htm" rel="nofollow">http://effbot.org/imagingbook/pil-index.htm</a></a> <p> and especially pay attention to the Image, ImageDraw, and ImageFont modules.</p> <p>Here's an example to help you out:<p></p> <pre><code> import Image im = Image.new("RGB", (100, 100)) import ImageDraw draw = ImageDraw.Draw(im) draw.text((50, 50), "hey") im.rotate(45).show() </code></pre> <p>To do what you really want you may need to make a bunch of separate correctly rotated text images and then compose them all together with some more fancy manipulation. And after all that it still may not look great. I'm not sure how antialiasing and such is handled for instance, but it might not be good. Good luck, and if anyone has an easier way, I'd be interested to know as well.</p>
2
2008-10-29T04:55:33Z
[ "python", "python-imaging-library", "imaging" ]
How do I draw text at an angle using python's PIL?
245,447
<p>Using Python I want to be able to draw text at different angles using PIL.</p> <p>For example, imagine you were drawing the number around the face of a clock. The number <strong>3</strong> would appear as expected whereas <strong>12</strong> would we drawn rotated counter-clockwise 90 degrees.</p> <p>Therefore, I need to be able to draw many different strings at many different angles.</p>
15
2008-10-29T01:04:48Z
245,892
<p>Draw text into a temporary blank image, rotate that, then paste that onto the original image. You could wrap up the steps in a function. Good luck figuring out the exact coordinates to use - my cold-fogged brain isn't up to it right now. </p> <p>This demo writes yellow text on a slant over an image:</p> <pre><code># Demo to add rotated text to an image using PIL import Image import ImageFont, ImageDraw, ImageOps im=Image.open("stormy100.jpg") f = ImageFont.load_default() txt=Image.new('L', (500,50)) d = ImageDraw.Draw(txt) d.text( (0, 0), "Someplace Near Boulder", font=f, fill=255) w=txt.rotate(17.5, expand=1) im.paste( ImageOps.colorize(w, (0,0,0), (255,255,84)), (242,60), w) </code></pre>
22
2008-10-29T05:31:25Z
[ "python", "python-imaging-library", "imaging" ]
How do I draw text at an angle using python's PIL?
245,447
<p>Using Python I want to be able to draw text at different angles using PIL.</p> <p>For example, imagine you were drawing the number around the face of a clock. The number <strong>3</strong> would appear as expected whereas <strong>12</strong> would we drawn rotated counter-clockwise 90 degrees.</p> <p>Therefore, I need to be able to draw many different strings at many different angles.</p>
15
2008-10-29T01:04:48Z
741,592
<p>It's also usefull to know our text's size in pixels before we create an Image object. I used such code when drawing graphs. Then I got no problems e.g. with alignment of data labels (the image is exactly as big as the text).</p> <pre><code>(...) img_main = Image.new("RGB", (200, 200)) font = ImageFont.load_default() # Text to be rotated... rotate_text = u'This text should be rotated.' # Image for text to be rotated img_txt = Image.new('L', font.getsize(rotate_text)) draw_txt = ImageDraw.Draw(img_txt) draw_txt.text((0,0), rotate_text, font=font, fill=255) t = img_value_axis.rotate(90, expand=1) </code></pre> <p>The rest of joining the two images together is already described on this page. When you rotate by an "unregular" angle, you have to improve this code a little bit. It actually works for 90, 180, 270...</p>
7
2009-04-12T10:48:23Z
[ "python", "python-imaging-library", "imaging" ]
How do I draw text at an angle using python's PIL?
245,447
<p>Using Python I want to be able to draw text at different angles using PIL.</p> <p>For example, imagine you were drawing the number around the face of a clock. The number <strong>3</strong> would appear as expected whereas <strong>12</strong> would we drawn rotated counter-clockwise 90 degrees.</p> <p>Therefore, I need to be able to draw many different strings at many different angles.</p>
15
2008-10-29T01:04:48Z
35,586,716
<p>Here is a working version, inspired by the answer, but it works without opening or saving images.</p> <p>The two images have colored background and alpha channel different from zero to show what's going on. Changing the two alpha channels from 92 to 0 will make them completely transparent.</p> <pre><code>from PIL import Image, ImageFont, ImageDraw text = 'TEST' font = ImageFont.truetype(r'C:\Windows\Fonts\Arial.ttf', 50) width, height = font.getsize(text) image1 = Image.new('RGBA', (200, 150), (0, 128, 0, 92)) draw1 = ImageDraw.Draw(image1) draw1.text((0, 0), text=text, font=font, fill=(255, 128, 0)) image2 = Image.new('RGBA', (width, height), (0, 0, 128, 92)) draw2 = ImageDraw.Draw(image2) draw2.text((0, 0), text=text, font=font, fill=(0, 255, 128)) image2 = image2.rotate(30, expand=1) px, py = 10, 10 sx, sy = image2.size image1.paste(image2, (px, py, px + sx, py + sy), image2) image1.show() </code></pre>
1
2016-02-23T19:44:14Z
[ "python", "python-imaging-library", "imaging" ]
Upload a file in Django and then send it somewhere else through REST?
245,725
<p>I am building a simple Django app that will use scribd to display documents. I would like to have a page where the administrator can upload documents to scribd through the website, since I need to know a few things about it before it gets to scribd. What is the best/easiest way to do this, display an upload page and then take the file that is uploaded and send it to scribd through the <a href="http://www.scribd.com/publisher/api?method_name=docs.upload" rel="nofollow">docs.upload</a> method of their api? I'm a little new at this Python/Django/REST API thing, so sorry if this is too many questions at once.</p>
1
2008-10-29T03:45:09Z
245,815
<p>What you want to do (at least from what I read here and on the Django documentation site) is create a <a href="http://docs.djangoproject.com/en/dev/howto/custom-file-storage/#howto-custom-file-storage" rel="nofollow">custom storage system.</a></p> <p>This should give you exactly what you need - it's the motivation they use to start the example, after all!</p>
1
2008-10-29T04:41:23Z
[ "python", "django", "api", "rest", "scribd" ]
Upload a file in Django and then send it somewhere else through REST?
245,725
<p>I am building a simple Django app that will use scribd to display documents. I would like to have a page where the administrator can upload documents to scribd through the website, since I need to know a few things about it before it gets to scribd. What is the best/easiest way to do this, display an upload page and then take the file that is uploaded and send it to scribd through the <a href="http://www.scribd.com/publisher/api?method_name=docs.upload" rel="nofollow">docs.upload</a> method of their api? I'm a little new at this Python/Django/REST API thing, so sorry if this is too many questions at once.</p>
1
2008-10-29T03:45:09Z
245,821
<p>That is quite a few questions. </p> <p>Handling the file upload is pretty straight-forward with Django, see the <a href="http://docs.djangoproject.com/en/dev/topics/http/file-uploads/" rel="nofollow">File Uploads documentation</a> for examples. In short you can access the uploaded file via <code>request.FILES['file']</code>.</p> <p>To call the scribd api you can use urllib2; see this <a href="http://www.hackorama.com/python/upload.shtml" rel="nofollow">Hackoarama page</a> for instructions. urllib2 can be a little convoluted but it works once you get a hang of it.</p> <p>You can call the scribd api directly from within your Django view, but it'd be better practice to separate it out: from within your Django view save the file somewhere on disk and put an "upload this" message on messaging system (eg. <a href="http://xph.us/software/beanstalkd/" rel="nofollow">beanstalkd</a>). Have a separate process pick up the message and upload the file to scribd. That way you shield your http process and user from any issues accessing the API and the associated delays.</p>
3
2008-10-29T04:45:06Z
[ "python", "django", "api", "rest", "scribd" ]
When is not a good time to use python generators?
245,792
<p>This is rather the inverse of <a href="http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for">What can you use Python generator functions for?</a>: python generators, generator expressions, and the <code>itertools</code> module are some of my favorite features of python these days. They're especially useful when setting up chains of operations to perform on a big pile of data--I often use them when processing DSV files.</p> <p><strong>So when is it <em>not</em> a good time to use a generator, or a generator expression, or an <code>itertools</code> function?</strong></p> <ul> <li>When should I prefer <code>zip()</code> over <code>itertools.izip()</code>, or</li> <li><code>range()</code> over <code>xrange()</code>, or</li> <li><code>[x for x in foo]</code> over <code>(x for x in foo)</code>?</li> </ul> <p>Obviously, we eventually need to "resolve" a generator into actual data, usually by creating a list or iterating over it with a non-generator loop. Sometimes we just need to know the length. This isn't what I'm asking.</p> <p>We use generators so that we're not assigning new lists into memory for interim data. This especially makes sense for large datasets. Does it make sense for small datasets too? Is there a noticeable memory/cpu trade-off?</p> <p>I'm especially interested if anyone has done some profiling on this, in light of the eye-opening discussion of <a href="http://www.gossamer-threads.com/lists/python/python/76267">list comprehension performance vs. map() and filter()</a>. (<a href="https://mail.python.org/pipermail//python-list/2001-December/096256.html">alt link</a>)</p>
55
2008-10-29T04:25:02Z
245,797
<p>You should never favor <a href="http://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip</code></a> over <a href="http://docs.python.org/2/library/itertools.html#itertools.izip" rel="nofollow"><code>izip</code></a>, <code>range</code> over <code>xrange</code>, or list comprehensions over generator comprehensions. In Python 3.0 <code>range</code> has <code>xrange</code>-like semantics and <code>zip</code> has <code>izip</code>-like semantics.</p> <p>List comprehensions are actually clearer like <code>list(frob(x) for x in foo)</code> for those times you need an actual list.</p>
16
2008-10-29T04:28:58Z
[ "python", "optimization", "iterator", "generator" ]
When is not a good time to use python generators?
245,792
<p>This is rather the inverse of <a href="http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for">What can you use Python generator functions for?</a>: python generators, generator expressions, and the <code>itertools</code> module are some of my favorite features of python these days. They're especially useful when setting up chains of operations to perform on a big pile of data--I often use them when processing DSV files.</p> <p><strong>So when is it <em>not</em> a good time to use a generator, or a generator expression, or an <code>itertools</code> function?</strong></p> <ul> <li>When should I prefer <code>zip()</code> over <code>itertools.izip()</code>, or</li> <li><code>range()</code> over <code>xrange()</code>, or</li> <li><code>[x for x in foo]</code> over <code>(x for x in foo)</code>?</li> </ul> <p>Obviously, we eventually need to "resolve" a generator into actual data, usually by creating a list or iterating over it with a non-generator loop. Sometimes we just need to know the length. This isn't what I'm asking.</p> <p>We use generators so that we're not assigning new lists into memory for interim data. This especially makes sense for large datasets. Does it make sense for small datasets too? Is there a noticeable memory/cpu trade-off?</p> <p>I'm especially interested if anyone has done some profiling on this, in light of the eye-opening discussion of <a href="http://www.gossamer-threads.com/lists/python/python/76267">list comprehension performance vs. map() and filter()</a>. (<a href="https://mail.python.org/pipermail//python-list/2001-December/096256.html">alt link</a>)</p>
55
2008-10-29T04:25:02Z
245,816
<p>In general, don't use a generator when you need list operations, like len(), reversed(), and so on.</p> <p>There may also be times when you don't want lazy evaluation (e.g. to do all the calculation up front so you can release a resource). In that case, a list expression might be better.</p>
33
2008-10-29T04:42:05Z
[ "python", "optimization", "iterator", "generator" ]
When is not a good time to use python generators?
245,792
<p>This is rather the inverse of <a href="http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for">What can you use Python generator functions for?</a>: python generators, generator expressions, and the <code>itertools</code> module are some of my favorite features of python these days. They're especially useful when setting up chains of operations to perform on a big pile of data--I often use them when processing DSV files.</p> <p><strong>So when is it <em>not</em> a good time to use a generator, or a generator expression, or an <code>itertools</code> function?</strong></p> <ul> <li>When should I prefer <code>zip()</code> over <code>itertools.izip()</code>, or</li> <li><code>range()</code> over <code>xrange()</code>, or</li> <li><code>[x for x in foo]</code> over <code>(x for x in foo)</code>?</li> </ul> <p>Obviously, we eventually need to "resolve" a generator into actual data, usually by creating a list or iterating over it with a non-generator loop. Sometimes we just need to know the length. This isn't what I'm asking.</p> <p>We use generators so that we're not assigning new lists into memory for interim data. This especially makes sense for large datasets. Does it make sense for small datasets too? Is there a noticeable memory/cpu trade-off?</p> <p>I'm especially interested if anyone has done some profiling on this, in light of the eye-opening discussion of <a href="http://www.gossamer-threads.com/lists/python/python/76267">list comprehension performance vs. map() and filter()</a>. (<a href="https://mail.python.org/pipermail//python-list/2001-December/096256.html">alt link</a>)</p>
55
2008-10-29T04:25:02Z
246,155
<p>As you mention, "This especially makes sense for large datasets", I think this answers your question.</p> <p>If your not hitting any walls, performance-wise, I would stick to lists and standard functions. Then when you run into problems with performance make the switch.</p>
3
2008-10-29T08:50:47Z
[ "python", "optimization", "iterator", "generator" ]
When is not a good time to use python generators?
245,792
<p>This is rather the inverse of <a href="http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for">What can you use Python generator functions for?</a>: python generators, generator expressions, and the <code>itertools</code> module are some of my favorite features of python these days. They're especially useful when setting up chains of operations to perform on a big pile of data--I often use them when processing DSV files.</p> <p><strong>So when is it <em>not</em> a good time to use a generator, or a generator expression, or an <code>itertools</code> function?</strong></p> <ul> <li>When should I prefer <code>zip()</code> over <code>itertools.izip()</code>, or</li> <li><code>range()</code> over <code>xrange()</code>, or</li> <li><code>[x for x in foo]</code> over <code>(x for x in foo)</code>?</li> </ul> <p>Obviously, we eventually need to "resolve" a generator into actual data, usually by creating a list or iterating over it with a non-generator loop. Sometimes we just need to know the length. This isn't what I'm asking.</p> <p>We use generators so that we're not assigning new lists into memory for interim data. This especially makes sense for large datasets. Does it make sense for small datasets too? Is there a noticeable memory/cpu trade-off?</p> <p>I'm especially interested if anyone has done some profiling on this, in light of the eye-opening discussion of <a href="http://www.gossamer-threads.com/lists/python/python/76267">list comprehension performance vs. map() and filter()</a>. (<a href="https://mail.python.org/pipermail//python-list/2001-December/096256.html">alt link</a>)</p>
55
2008-10-29T04:25:02Z
246,481
<p>Profile, Profile, Profile.</p> <p>Profiling your code is the only way to know if what you're doing has any effect at all.</p> <p>Most usages of xrange, generators, etc are over static size, small datasets. It's only when you get to large datasets that it really makes a difference. range() vs. xrange() is mostly just a matter of making the code look a tiny little bit more ugly, and not losing anything, and maybe gaining something.</p> <p>Profile, Profile, Profile.</p>
21
2008-10-29T11:37:31Z
[ "python", "optimization", "iterator", "generator" ]
When is not a good time to use python generators?
245,792
<p>This is rather the inverse of <a href="http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for">What can you use Python generator functions for?</a>: python generators, generator expressions, and the <code>itertools</code> module are some of my favorite features of python these days. They're especially useful when setting up chains of operations to perform on a big pile of data--I often use them when processing DSV files.</p> <p><strong>So when is it <em>not</em> a good time to use a generator, or a generator expression, or an <code>itertools</code> function?</strong></p> <ul> <li>When should I prefer <code>zip()</code> over <code>itertools.izip()</code>, or</li> <li><code>range()</code> over <code>xrange()</code>, or</li> <li><code>[x for x in foo]</code> over <code>(x for x in foo)</code>?</li> </ul> <p>Obviously, we eventually need to "resolve" a generator into actual data, usually by creating a list or iterating over it with a non-generator loop. Sometimes we just need to know the length. This isn't what I'm asking.</p> <p>We use generators so that we're not assigning new lists into memory for interim data. This especially makes sense for large datasets. Does it make sense for small datasets too? Is there a noticeable memory/cpu trade-off?</p> <p>I'm especially interested if anyone has done some profiling on this, in light of the eye-opening discussion of <a href="http://www.gossamer-threads.com/lists/python/python/76267">list comprehension performance vs. map() and filter()</a>. (<a href="https://mail.python.org/pipermail//python-list/2001-December/096256.html">alt link</a>)</p>
55
2008-10-29T04:25:02Z
246,494
<p>As far as performance is concerned, I can't think of any times that you would want to use a list over a generator.</p>
2
2008-10-29T11:44:06Z
[ "python", "optimization", "iterator", "generator" ]
When is not a good time to use python generators?
245,792
<p>This is rather the inverse of <a href="http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for">What can you use Python generator functions for?</a>: python generators, generator expressions, and the <code>itertools</code> module are some of my favorite features of python these days. They're especially useful when setting up chains of operations to perform on a big pile of data--I often use them when processing DSV files.</p> <p><strong>So when is it <em>not</em> a good time to use a generator, or a generator expression, or an <code>itertools</code> function?</strong></p> <ul> <li>When should I prefer <code>zip()</code> over <code>itertools.izip()</code>, or</li> <li><code>range()</code> over <code>xrange()</code>, or</li> <li><code>[x for x in foo]</code> over <code>(x for x in foo)</code>?</li> </ul> <p>Obviously, we eventually need to "resolve" a generator into actual data, usually by creating a list or iterating over it with a non-generator loop. Sometimes we just need to know the length. This isn't what I'm asking.</p> <p>We use generators so that we're not assigning new lists into memory for interim data. This especially makes sense for large datasets. Does it make sense for small datasets too? Is there a noticeable memory/cpu trade-off?</p> <p>I'm especially interested if anyone has done some profiling on this, in light of the eye-opening discussion of <a href="http://www.gossamer-threads.com/lists/python/python/76267">list comprehension performance vs. map() and filter()</a>. (<a href="https://mail.python.org/pipermail//python-list/2001-December/096256.html">alt link</a>)</p>
55
2008-10-29T04:25:02Z
247,527
<p>I've never found a situation where generators would hinder what you're trying to do. There are, however, plenty of instances where using generators would not help you any more than not using them.</p> <p>For example:</p> <pre><code>sorted(xrange(5)) </code></pre> <p>Does not offer any improvement over:</p> <pre><code>sorted(range(5)) </code></pre>
2
2008-10-29T16:44:36Z
[ "python", "optimization", "iterator", "generator" ]
When is not a good time to use python generators?
245,792
<p>This is rather the inverse of <a href="http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for">What can you use Python generator functions for?</a>: python generators, generator expressions, and the <code>itertools</code> module are some of my favorite features of python these days. They're especially useful when setting up chains of operations to perform on a big pile of data--I often use them when processing DSV files.</p> <p><strong>So when is it <em>not</em> a good time to use a generator, or a generator expression, or an <code>itertools</code> function?</strong></p> <ul> <li>When should I prefer <code>zip()</code> over <code>itertools.izip()</code>, or</li> <li><code>range()</code> over <code>xrange()</code>, or</li> <li><code>[x for x in foo]</code> over <code>(x for x in foo)</code>?</li> </ul> <p>Obviously, we eventually need to "resolve" a generator into actual data, usually by creating a list or iterating over it with a non-generator loop. Sometimes we just need to know the length. This isn't what I'm asking.</p> <p>We use generators so that we're not assigning new lists into memory for interim data. This especially makes sense for large datasets. Does it make sense for small datasets too? Is there a noticeable memory/cpu trade-off?</p> <p>I'm especially interested if anyone has done some profiling on this, in light of the eye-opening discussion of <a href="http://www.gossamer-threads.com/lists/python/python/76267">list comprehension performance vs. map() and filter()</a>. (<a href="https://mail.python.org/pipermail//python-list/2001-December/096256.html">alt link</a>)</p>
55
2008-10-29T04:25:02Z
255,570
<p>Regarding performance: if using psyco, lists can be quite a bit faster than generators. In the example below, lists are almost 50% faster when using psyco.full()</p> <pre><code>import psyco import time import cStringIO def time_func(func): """The amount of time it requires func to run""" start = time.clock() func() return time.clock() - start def fizzbuzz(num): """That algorithm we all know and love""" if not num % 3 and not num % 5: return "%d fizz buzz" % num elif not num % 3: return "%d fizz" % num elif not num % 5: return "%d buzz" % num return None def with_list(num): """Try getting fizzbuzz with a list comprehension and range""" out = cStringIO.StringIO() for fibby in [fizzbuzz(x) for x in range(1, num) if fizzbuzz(x)]: print &gt;&gt; out, fibby return out.getvalue() def with_genx(num): """Try getting fizzbuzz with generator expression and xrange""" out = cStringIO.StringIO() for fibby in (fizzbuzz(x) for x in xrange(1, num) if fizzbuzz(x)): print &gt;&gt; out, fibby return out.getvalue() def main(): """ Test speed of generator expressions versus list comprehensions, with and without psyco. """ #our variables nums = [10000, 100000] funcs = [with_list, with_genx] # first, try without psyco print "without psyco" for num in nums: print " number:", num for func in funcs: print func.__name__, time_func(lambda : func(num)), "seconds" print # now with pscyo print "with psyco" psyco.full() for num in nums: print " number:", num for func in funcs: print func.__name__, time_func(lambda : func(num)), "seconds" print if __name__ == "__main__": main() </code></pre> <p>Results:</p> <pre><code>without psyco number: 10000 with_list 0.0519102208309 seconds with_genx 0.0535933367509 seconds number: 100000 with_list 0.542204280744 seconds with_genx 0.557837353115 seconds with psyco number: 10000 with_list 0.0286369007033 seconds with_genx 0.0513424889137 seconds number: 100000 with_list 0.335414877839 seconds with_genx 0.580363490491 seconds </code></pre>
5
2008-11-01T05:53:31Z
[ "python", "optimization", "iterator", "generator" ]
When is not a good time to use python generators?
245,792
<p>This is rather the inverse of <a href="http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for">What can you use Python generator functions for?</a>: python generators, generator expressions, and the <code>itertools</code> module are some of my favorite features of python these days. They're especially useful when setting up chains of operations to perform on a big pile of data--I often use them when processing DSV files.</p> <p><strong>So when is it <em>not</em> a good time to use a generator, or a generator expression, or an <code>itertools</code> function?</strong></p> <ul> <li>When should I prefer <code>zip()</code> over <code>itertools.izip()</code>, or</li> <li><code>range()</code> over <code>xrange()</code>, or</li> <li><code>[x for x in foo]</code> over <code>(x for x in foo)</code>?</li> </ul> <p>Obviously, we eventually need to "resolve" a generator into actual data, usually by creating a list or iterating over it with a non-generator loop. Sometimes we just need to know the length. This isn't what I'm asking.</p> <p>We use generators so that we're not assigning new lists into memory for interim data. This especially makes sense for large datasets. Does it make sense for small datasets too? Is there a noticeable memory/cpu trade-off?</p> <p>I'm especially interested if anyone has done some profiling on this, in light of the eye-opening discussion of <a href="http://www.gossamer-threads.com/lists/python/python/76267">list comprehension performance vs. map() and filter()</a>. (<a href="https://mail.python.org/pipermail//python-list/2001-December/096256.html">alt link</a>)</p>
55
2008-10-29T04:25:02Z
256,272
<p>You should prefer list comprehensions if you need to keep the values around for something else later and the size of your set is not too large.</p> <p>For example: you are creating a list that you will loop over several times later in your program. </p> <p>To some extent you can think of generators as a replacement for iteration (loops) vs. list comprehensions as a type of data structure initialization. If you want to keep the data structure then use list comprehensions.</p>
2
2008-11-01T23:49:09Z
[ "python", "optimization", "iterator", "generator" ]
When is not a good time to use python generators?
245,792
<p>This is rather the inverse of <a href="http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for">What can you use Python generator functions for?</a>: python generators, generator expressions, and the <code>itertools</code> module are some of my favorite features of python these days. They're especially useful when setting up chains of operations to perform on a big pile of data--I often use them when processing DSV files.</p> <p><strong>So when is it <em>not</em> a good time to use a generator, or a generator expression, or an <code>itertools</code> function?</strong></p> <ul> <li>When should I prefer <code>zip()</code> over <code>itertools.izip()</code>, or</li> <li><code>range()</code> over <code>xrange()</code>, or</li> <li><code>[x for x in foo]</code> over <code>(x for x in foo)</code>?</li> </ul> <p>Obviously, we eventually need to "resolve" a generator into actual data, usually by creating a list or iterating over it with a non-generator loop. Sometimes we just need to know the length. This isn't what I'm asking.</p> <p>We use generators so that we're not assigning new lists into memory for interim data. This especially makes sense for large datasets. Does it make sense for small datasets too? Is there a noticeable memory/cpu trade-off?</p> <p>I'm especially interested if anyone has done some profiling on this, in light of the eye-opening discussion of <a href="http://www.gossamer-threads.com/lists/python/python/76267">list comprehension performance vs. map() and filter()</a>. (<a href="https://mail.python.org/pipermail//python-list/2001-December/096256.html">alt link</a>)</p>
55
2008-10-29T04:25:02Z
26,635,939
<p><strong>Use a list instead of a generator when:</strong></p> <p>1) You need to access the data <strong>multiple</strong> times (i.e. cache the results instead of recomputing them):</p> <pre><code>for i in outer: # used once, okay to be a generator or return a list for j in inner: # used multiple times, reusing a list is better ... </code></pre> <p>2) You need <strong>random access</strong> (or any access other than forward sequential order):</p> <pre><code>for i in reversed(data): ... # generators aren't reversible s[i], s[j] = s[j], s[i] # generators aren't indexable </code></pre> <p>3) You need to <strong>join</strong> strings (which requires two passes over the data):</p> <pre><code>s = ''.join(data) # lists are faster than generators in this use case </code></pre> <p>4) You are using <strong>PyPy</strong> which sometimes can't optimize generator code as much as it can with normal function calls and list manipulations.</p>
24
2014-10-29T16:36:57Z
[ "python", "optimization", "iterator", "generator" ]
HTTP compliance testing
246,123
<p>What would you use to perform a compliance testing of an HTTP proxy? I've seen two projects so far:</p> <ul> <li><a href="http://www.web-polygraph.org/" rel="nofollow">Web Polygraph</a> (the feedback I got from a coworker is mostly negative)</li> <li><a href="http://funkload.nuxeo.com/" rel="nofollow">Funkload</a></li> </ul>
1
2008-10-29T08:29:59Z
248,806
<p>Take a look here: <a href="http://www.measurement-factory.com/" rel="nofollow">http://www.measurement-factory.com/</a></p> <p>The Co-Advisor product might be what you are after. Note that this is by the same mob that created Web-Polygraph/</p>
0
2008-10-29T23:36:02Z
[ "python", "http", "testing", "standards-compliance" ]
Can I call and set the Python gettext module in a library and a module using it at the same time?
246,137
<p>Im a coding a library inluding textual feedback that I need to translate.</p> <p>I put the following lines in a _config.py module that I import everywhere in my app :</p> <pre><code>import gettext, os, sys pathname = os.path.dirname(sys.argv[0]) localdir = os.path.abspath(pathname) + "/locale" gettext.install("messages", localdir) </code></pre> <p>I have the *.mo files in ./locale/lang_LANG/LC_MESSAGES and I apply the _() function to all the strings that need to be translated.</p> <p>Now I just added a feature for the user, supposedly a programmer, to be able to create his own messages. I don't want him to care about the underlying implementation, so I want him to be apple to make it something straightforward like :</p> <pre><code>lib_object.message = "My message" </code></pre> <p>I used properties to make it clean, but what if my user whats to translate his own code (that uses mine) and does something like :</p> <pre><code>import gettext, os, sys pathname = os.path.dirname(sys.argv[0]) localdir = os.path.abspath(pathname) + "/locale" gettext.install("user_app", localdir) lib_object.message = _("My message") </code></pre> <p>Is it a problem ? What can I do to avoid troubles without bothering my user ?</p>
2
2008-10-29T08:40:36Z
246,254
<p>You can only gettext.install() once. In general it's useless for library work -- gettext.install() will only do the right thing if the module calling it is in charge of the whole program, since it will only provide you with one catalog to load from. Library code should do something akin to what Mailman does: have their own wrapper for gettext() that passes the right arguments for this module, then imports that as '_' in each module that wants to use it.</p>
1
2008-10-29T09:43:07Z
[ "python", "internationalization", "gettext" ]
Can I call and set the Python gettext module in a library and a module using it at the same time?
246,137
<p>Im a coding a library inluding textual feedback that I need to translate.</p> <p>I put the following lines in a _config.py module that I import everywhere in my app :</p> <pre><code>import gettext, os, sys pathname = os.path.dirname(sys.argv[0]) localdir = os.path.abspath(pathname) + "/locale" gettext.install("messages", localdir) </code></pre> <p>I have the *.mo files in ./locale/lang_LANG/LC_MESSAGES and I apply the _() function to all the strings that need to be translated.</p> <p>Now I just added a feature for the user, supposedly a programmer, to be able to create his own messages. I don't want him to care about the underlying implementation, so I want him to be apple to make it something straightforward like :</p> <pre><code>lib_object.message = "My message" </code></pre> <p>I used properties to make it clean, but what if my user whats to translate his own code (that uses mine) and does something like :</p> <pre><code>import gettext, os, sys pathname = os.path.dirname(sys.argv[0]) localdir = os.path.abspath(pathname) + "/locale" gettext.install("user_app", localdir) lib_object.message = _("My message") </code></pre> <p>Is it a problem ? What can I do to avoid troubles without bothering my user ?</p>
2
2008-10-29T08:40:36Z
398,420
<p>You can use the class based gettext api to isolate message catalogs. This is also what is recommended in the <a href="http://docs.python.org/library/gettext.html#class-based-api" rel="nofollow">python gettext documentation</a>.</p> <p>The drawback is that you, or the other dev, will have to use the gettext method or define the <code>_()</code> method in the local scope, bound to the specific gettext class. An example of a class with its own string catalog:</p> <pre><code>import gettext class MyClass(object): def __init__(self, locale_for_instance): self.lang = gettext.translation("appname", localedir, \ locale=locale_for_instance) def some_method(self, arg): return self.lang.gettext("You called some method") def other_method(self, arg): # does the same thing _ = self.lang.gettext return _("You called some method") </code></pre> <p>You could stick the code for adding the <code>_()</code> in a decorator, so all the methods that need it is prefixed with something like <code>@with_local_gettext</code></p> <p>(Note, I've not tested the above could but It Should Work Just Fine(tm) )</p> <p>If the goal is to not bother your user (and he's not very good) I guess you could use the class based approach in your code and let the user use the global one.</p>
2
2008-12-29T19:29:16Z
[ "python", "internationalization", "gettext" ]
How can I draw a bezier curve using Python's PIL?
246,525
<p>I'm using Python's Imaging Library and I would like to draw some bezier curves. I guess I could calculate pixel by pixel but I'm hoping there is something simpler.</p>
11
2008-10-29T11:59:08Z
246,628
<p>A bezier curve isn't that hard to draw yourself. Given three points <code>A</code>, <code>B</code>, <code>C</code> you require three linear interpolations in order to draw the curve. We use the scalar <code>t</code> as the parameter for the linear interpolation:</p> <pre><code>P0 = A * t + (1 - t) * B P1 = B * t + (1 - t) * C </code></pre> <p>This interpolates between two edges we've created, edge AB and edge BC. The only thing we now have to do to calculate the point we have to draw is interpolate between P0 and P1 using the same t like so:</p> <pre><code>Pfinal = P0 * t + (1 - t) * P1 </code></pre> <p>There are a couple of things that need to be done before we actually draw the curve. First off we have will walk some <code>dt</code> (delta t) and we need to be aware that <code>0 &lt;= t &lt;= 1</code>. As you might be able to imagine, this will not give us a smooth curve, instead it yields only a discrete set of positions at which to plot. The easiest way to solve this is to simply draw a line between the current point and the previous point.</p>
10
2008-10-29T12:39:15Z
[ "python", "python-imaging-library", "bezier", "imaging" ]
How can I draw a bezier curve using Python's PIL?
246,525
<p>I'm using Python's Imaging Library and I would like to draw some bezier curves. I guess I could calculate pixel by pixel but I'm hoping there is something simpler.</p>
11
2008-10-29T11:59:08Z
246,933
<p>You can use the <a href="http://effbot.org/zone/aggdraw-index.htm">aggdraw</a> on top of PIL, bezier curves are <a href="http://effbot.org/zone/pythondoc-aggdraw.htm#aggdraw.Path-class">supported</a>.</p> <p><strong>EDIT:</strong></p> <p>I made an example only to discover there is a bug in the <code>Path</code> class regarding <code>curveto</code> :(</p> <p>Here is the example anyway:</p> <pre><code>from PIL import Image import aggdraw img = Image.new("RGB", (200, 200), "white") canvas = aggdraw.Draw(img) pen = aggdraw.Pen("black") path = aggdraw.Path() path.moveto(0, 0) path.curveto(0, 60, 40, 100, 100, 100) canvas.path(path.coords(), path, pen) canvas.flush() img.save("curve.png", "PNG") img.show() </code></pre> <p><a href="http://www.mail-archive.com/[email protected]/msg02108.html">This</a> should fix the bug if you're up for recompiling the module...</p>
7
2008-10-29T14:09:59Z
[ "python", "python-imaging-library", "bezier", "imaging" ]
How can I draw a bezier curve using Python's PIL?
246,525
<p>I'm using Python's Imaging Library and I would like to draw some bezier curves. I guess I could calculate pixel by pixel but I'm hoping there is something simpler.</p>
11
2008-10-29T11:59:08Z
2,292,690
<pre><code>def make_bezier(xys): # xys should be a sequence of 2-tuples (Bezier control points) n = len(xys) combinations = pascal_row(n-1) def bezier(ts): # This uses the generalized formula for bezier curves # http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Generalization result = [] for t in ts: tpowers = (t**i for i in range(n)) upowers = reversed([(1-t)**i for i in range(n)]) coefs = [c*a*b for c, a, b in zip(combinations, tpowers, upowers)] result.append( tuple(sum([coef*p for coef, p in zip(coefs, ps)]) for ps in zip(*xys))) return result return bezier def pascal_row(n): # This returns the nth row of Pascal's Triangle result = [1] x, numerator = 1, n for denominator in range(1, n//2+1): # print(numerator,denominator,x) x *= numerator x /= denominator result.append(x) numerator -= 1 if n&amp;1 == 0: # n is even result.extend(reversed(result[:-1])) else: result.extend(reversed(result)) return result </code></pre> <p>This, for example, draws a heart:</p> <pre><code>from PILL import Image from PIL import ImageDraw if __name__ == '__main__': im = Image.new('RGBA', (100, 100), (0, 0, 0, 0)) draw = ImageDraw.Draw(im) ts = [t/100.0 for t in range(101)] xys = [(50, 100), (80, 80), (100, 50)] bezier = make_bezier(xys) points = bezier(ts) xys = [(100, 50), (100, 0), (50, 0), (50, 35)] bezier = make_bezier(xys) points.extend(bezier(ts)) xys = [(50, 35), (50, 0), (0, 0), (0, 50)] bezier = make_bezier(xys) points.extend(bezier(ts)) xys = [(0, 50), (20, 80), (50, 100)] bezier = make_bezier(xys) points.extend(bezier(ts)) draw.polygon(points, fill = 'red') im.save('out.png') </code></pre>
16
2010-02-18T22:23:02Z
[ "python", "python-imaging-library", "bezier", "imaging" ]
How can I draw a bezier curve using Python's PIL?
246,525
<p>I'm using Python's Imaging Library and I would like to draw some bezier curves. I guess I could calculate pixel by pixel but I'm hoping there is something simpler.</p>
11
2008-10-29T11:59:08Z
21,416,678
<p>Although bezier curveto paths don't work with Aggdraw, as mentioned by @ToniRuža, there is another way to do this in Aggdraw. The benefit of using Aggdraw instead of PIL or your own bezier functions is that Aggdraw will antialias the image making it look smoother (see pic at bottom).</p> <p><strong>Aggdraw Symbols</strong></p> <p>Instead of using the aggdraw.Path() class to draw, you can use the <code>aggdraw.Symbol(pathstring)</code> class which is basically the same except you write the path as a string. According to the Aggdraw docs the way to write your path as a string is to use SVG path syntax (see: <a href="http://www.w3.org/TR/SVG/paths.html" rel="nofollow">http://www.w3.org/TR/SVG/paths.html</a>). Basically, each addition (node) to the path normally starts with</p> <ul> <li>a letter representing the drawing action (uppercase for absolute path, lowercase for relative path), followed by (no spaces in between)</li> <li>the x coordinate (precede by a minus sign if it is a negative number or direction)</li> <li>a comma</li> <li>the y coordinate (precede by a minus sign if it is a negative number or direction)</li> </ul> <p>In your pathstring just separate your multiple nodes with a space. Once you have created your symbol, just remember to draw it by passing it as one of the arguments to <code>draw.symbol(args)</code>. </p> <p><strong>Bezier Curves in Aggdraw Symbols</strong></p> <p>Specifically for cubic bezier curves you write the letter "C" or "c" followed by 6 numbers (3 sets of xy coordinates x1,y1,x2,y2,x3,y3 with commas in between the numbers but not between the first number and the letter). According the docs there are also other bezier versions by using the letter "S (smooth cubic bezier), Q (quadratic bezier), T (smooth quadratic bezier)". Here is a complete example code (requires PIL and aggdraw):</p> <pre><code>print "initializing script" # imports from PIL import Image import aggdraw # setup img = Image.new("RGBA", (1000,1000)) # last part is image dimensions draw = aggdraw.Draw(img) outline = aggdraw.Pen("black", 5) # 5 is the outlinewidth in pixels fill = aggdraw.Brush("yellow") # the pathstring: #m for starting point #c for bezier curves #z for closing up the path, optional #(all lowercase letters for relative path) pathstring = " m0,0 c300,300,700,600,300,900 z" # create symbol symbol = aggdraw.Symbol(pathstring) # draw and save it xy = (20,20) # xy position to place symbol draw.symbol(xy, symbol, outline, fill) draw.flush() img.save("testbeziercurves.png") # this image gets saved to same folder as the script print "finished drawing and saved!" </code></pre> <p>And the output is a smooth-looking curved bezier figure: <img src="http://i.stack.imgur.com/tqW5g.png" alt="Result from script above using aggdraw bezier curve symbol"></p>
3
2014-01-28T20:58:36Z
[ "python", "python-imaging-library", "bezier", "imaging" ]
How do I add tab completion to the Python shell?
246,725
<p>When starting a django application using <code>python manage.py shell</code>, I get an InteractiveConsole shell - I can use tab completion, etc.</p> <pre><code>Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) </code></pre> <p>When just starting a python interpreter using <code>python</code>, it doesn't offer tab completion.</p> <p>Can someone tell me what django is doing to give me an interactive console, or what I need to do to start an interactive console without a django app?</p>
55
2008-10-29T13:09:10Z
246,774
<p>I think django does something like <a href="https://docs.python.org/library/rlcompleter.html">https://docs.python.org/library/rlcompleter.html</a></p> <p>If you want to have a really good interactive interpreter have a look at <a href="http://ipython.scipy.org/">http://ipython.scipy.org/</a>.</p>
30
2008-10-29T13:21:43Z
[ "python", "shell", "interpreter" ]
How do I add tab completion to the Python shell?
246,725
<p>When starting a django application using <code>python manage.py shell</code>, I get an InteractiveConsole shell - I can use tab completion, etc.</p> <pre><code>Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) </code></pre> <p>When just starting a python interpreter using <code>python</code>, it doesn't offer tab completion.</p> <p>Can someone tell me what django is doing to give me an interactive console, or what I need to do to start an interactive console without a django app?</p>
55
2008-10-29T13:09:10Z
246,779
<p>I may have found a way to do it.</p> <p>Create a file .pythonrc</p> <pre><code># ~/.pythonrc # enable syntax completion try: import readline except ImportError: print("Module readline not available.") else: import rlcompleter readline.parse_and_bind("tab: complete") </code></pre> <p>then in your .bashrc file, add</p> <pre><code>export PYTHONSTARTUP=~/.pythonrc </code></pre> <p>That seems to work.</p>
91
2008-10-29T13:24:39Z
[ "python", "shell", "interpreter" ]
How do I add tab completion to the Python shell?
246,725
<p>When starting a django application using <code>python manage.py shell</code>, I get an InteractiveConsole shell - I can use tab completion, etc.</p> <pre><code>Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) </code></pre> <p>When just starting a python interpreter using <code>python</code>, it doesn't offer tab completion.</p> <p>Can someone tell me what django is doing to give me an interactive console, or what I need to do to start an interactive console without a django app?</p>
55
2008-10-29T13:09:10Z
247,513
<p>For the record, this is covered in the tutorial: <a href="http://docs.python.org/tutorial/interactive.html">http://docs.python.org/tutorial/interactive.html</a></p>
21
2008-10-29T16:39:03Z
[ "python", "shell", "interpreter" ]
How do I add tab completion to the Python shell?
246,725
<p>When starting a django application using <code>python manage.py shell</code>, I get an InteractiveConsole shell - I can use tab completion, etc.</p> <pre><code>Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) </code></pre> <p>When just starting a python interpreter using <code>python</code>, it doesn't offer tab completion.</p> <p>Can someone tell me what django is doing to give me an interactive console, or what I need to do to start an interactive console without a django app?</p>
55
2008-10-29T13:09:10Z
32,135,426
<p>I use ptpython. <a href="https://github.com/jonathanslenders/ptpython/" rel="nofollow">https://github.com/jonathanslenders/ptpython/</a></p> <p>ptpython is a wonderful tool autocomplete shell cmd. install ptpython is very easy,use pip tool</p> <blockquote> <p>pip install ptpython</p> </blockquote> <p><strong>and for django shell,you should import the django env,like this</strong></p> <blockquote> <p>import os</p> <p>os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testweb.settings")</p> </blockquote> <p>Trust me,this is the best way to you!!!</p>
1
2015-08-21T08:11:38Z
[ "python", "shell", "interpreter" ]
How can I launch an instance of an application using Python?
247,724
<p>I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script?</p>
11
2008-10-29T17:40:12Z
247,730
<p>os.system("open file.xls")</p>
0
2008-10-29T17:41:19Z
[ "python", "scripting", "ipc" ]
How can I launch an instance of an application using Python?
247,724
<p>I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script?</p>
11
2008-10-29T17:40:12Z
247,740
<p>or </p> <pre><code>os.system("start excel.exe &lt;path/to/file&gt;") </code></pre> <p>(presuming it's in the path, and you're on windows)</p> <p>and also on Windows, just <code>start &lt;filename&gt;</code> works, too - if it's an associated extension already (as xls would be)</p>
8
2008-10-29T17:44:31Z
[ "python", "scripting", "ipc" ]
How can I launch an instance of an application using Python?
247,724
<p>I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script?</p>
11
2008-10-29T17:40:12Z
247,761
<p>I like popen2 for the ability to monitor the process.</p> <pre><code>excelProcess = popen2.Popen4("start excel %s" % (excelFile)) status = excelProcess.wait() </code></pre> <p><a href="http://www.python.org/doc/2.5.2/lib/module-popen2.html" rel="nofollow">http://www.python.org/doc/2.5.2/lib/module-popen2.html</a></p> <p><strong>EDIT</strong>: be aware that calling wait() will block until the process returns. Depending on your script, this may not be your desired behavior.</p>
6
2008-10-29T17:50:13Z
[ "python", "scripting", "ipc" ]
How can I launch an instance of an application using Python?
247,724
<p>I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script?</p>
11
2008-10-29T17:40:12Z
248,080
<p>While the <code>Popen</code> answers are reasonable for the general case, I would recommend <code>win32api</code> for this specific case, if you want to do something useful with it:</p> <p>It goes something like this:</p> <pre><code>from win32com.client import Dispatch xl = Dispatch('Excel.Application') wb = xl.Workbooks.Open('C:\\Documents and Settings\\GradeBook.xls') xl.Visible = True # optional: if you want to see the spreadsheet </code></pre> <p>Taken from <a href="https://mail.python.org/pipermail/python-list/2005-June/315330.html" rel="nofollow">a mailing list post</a> but there are plenty of examples around.</p>
10
2008-10-29T19:22:09Z
[ "python", "scripting", "ipc" ]
How can I launch an instance of an application using Python?
247,724
<p>I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script?</p>
11
2008-10-29T17:40:12Z
249,571
<p>The <strong>subprocess</strong> module intends to replace several other, older modules and functions, such as:</p> <ul> <li>os.system</li> <li>os.spawn*</li> <li>os.popen*</li> <li>popen2.*</li> <li>commands.*</li> </ul> <p>.</p> <pre><code>import subprocess process_one = subprocess.Popen(['gqview', '/home/toto/my_images']) print process_one.pid </code></pre>
5
2008-10-30T08:27:03Z
[ "python", "scripting", "ipc" ]
How can I launch an instance of an application using Python?
247,724
<p>I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script?</p>
11
2008-10-29T17:40:12Z
6,351,029
<p>As others have stated, I would suggest os.system. In case anyone is looking for a Mac-compatible solution, here is an example:</p> <pre><code>import os os.system("open /Applications/Safari.app") </code></pre>
1
2011-06-14T22:42:54Z
[ "python", "scripting", "ipc" ]
Retrieving python module path
247,770
<p>I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.</p> <p>How do I retrieve a module's path in python?</p>
351
2008-10-29T17:52:40Z
248,066
<p>This was trivial.</p> <p>Each module has a <code>__file__</code> variable that shows its relative path from where you are right now.</p> <p>Therefore, getting a directory for the module to notify it is simple as:</p> <pre><code>os.path.dirname(__file__) </code></pre>
13
2008-10-29T19:18:15Z
[ "python", "module", "inotify" ]
Retrieving python module path
247,770
<p>I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.</p> <p>How do I retrieve a module's path in python?</p>
351
2008-10-29T17:52:40Z
248,862
<pre><code>import a_module print a_module.__file__ </code></pre> <p>Will actually give you the path to the .pyc file that was loaded, at least on Mac OS X. So I guess you can do</p> <pre><code>import os path = os.path.dirname(amodule.__file__) </code></pre> <p>You can also try</p> <pre><code>path = os.path.abspath(amodule.__file__) </code></pre> <p>To get the directory to look for changes.</p>
385
2008-10-29T23:57:13Z
[ "python", "module", "inotify" ]
Retrieving python module path
247,770
<p>I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.</p> <p>How do I retrieve a module's path in python?</p>
351
2008-10-29T17:52:40Z
4,431,672
<pre><code>import os path = os.path.abspath(__file__) dir_path = os.path.dirname(path) </code></pre>
12
2010-12-13T17:35:17Z
[ "python", "module", "inotify" ]
Retrieving python module path
247,770
<p>I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.</p> <p>How do I retrieve a module's path in python?</p>
351
2008-10-29T17:52:40Z
6,416,114
<p>As the other answers have said, the best way to do this is with <code>__file__</code> (demonstrated again below). However, there is an important caveat, which is that <code>__file__</code> does NOT exist if you are running the module on its own (i.e. as <code>__main__</code>).</p> <p>For example, say you have two files (both of which are on your PYTHONPATH):</p> <pre><code>#/path1/foo.py import bar print bar.__file__ </code></pre> <p>and</p> <pre><code>#/path2/bar.py import os print os.getcwd() print __file__ </code></pre> <p>Running foo.py will give the output:</p> <pre><code>/path1 # "import bar" causes the line "print os.getcwd()" to run /path2/bar.py # then "print __file__" runs /path2/bar.py # then the import statement finishes and "print bar.__file__" runs </code></pre> <p>HOWEVER if you try to run bar.py on its own, you will get:</p> <pre><code>/path2 # "print os.getcwd()" still works fine Traceback (most recent call last): # but __file__ doesn't exist if bar.py is running as main File "/path2/bar.py", line 3, in &lt;module&gt; print __file__ NameError: name '__file__' is not defined </code></pre> <p>Hope this helps. This caveat cost me a lot of time and confusion while testing the other solutions presented.</p>
49
2011-06-20T19:05:40Z
[ "python", "module", "inotify" ]
Retrieving python module path
247,770
<p>I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.</p> <p>How do I retrieve a module's path in python?</p>
351
2008-10-29T17:52:40Z
9,759,993
<p>So I spent a fair amount of time trying to do this with py2exe The problem was to get the base folder of the script whether it was being run as a python script or as a py2exe executable. Also to have it work whether it was being run from the current folder, another folder or (this was the hardest) from the system's path.</p> <p>Eventually I used this approach, using sys.frozen as an indicator of running in py2exe:</p> <pre><code>import os,sys if hasattr(sys,'frozen'): # only when running in py2exe this exists base = sys.prefix else: # otherwise this is a regular python script base = os.path.dirname(os.path.realpath(__file__)) </code></pre>
6
2012-03-18T16:28:43Z
[ "python", "module", "inotify" ]
Retrieving python module path
247,770
<p>I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.</p> <p>How do I retrieve a module's path in python?</p>
351
2008-10-29T17:52:40Z
12,154,601
<p>There is <code>inspect</code> module in python.</p> <h2><a href="http://docs.python.org/library/inspect.html">Official documentation</a></h2> <blockquote> <p>The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback.</p> </blockquote> <p>Example:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; import inspect &gt;&gt;&gt; inspect.getfile(os) '/usr/lib64/python2.7/os.pyc' &gt;&gt;&gt; inspect.getfile(inspect) '/usr/lib64/python2.7/inspect.pyc' &gt;&gt;&gt; os.path.dirname(inspect.getfile(inspect)) '/usr/lib64/python2.7' </code></pre>
121
2012-08-28T07:24:09Z
[ "python", "module", "inotify" ]
Retrieving python module path
247,770
<p>I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.</p> <p>How do I retrieve a module's path in python?</p>
351
2008-10-29T17:52:40Z
16,826,913
<p>I will try tackling a few variations on this question as well:</p> <ol> <li>finding the path of the called script </li> <li>finding the path of the currently executing script </li> <li>finding the directory of the called script</li> </ol> <p>(Some of these questions have been asked on SO, but have been closed as duplicates and redirected here.)</p> <h2>Caveats of Using <code>__file__</code></h2> <p>For a module that you have imported:</p> <pre><code>import something something.__file__ </code></pre> <p>will return the <strong>absolute</strong> path of the module. However, given the folowing script foo.py:</p> <pre><code>#foo.py print '__file__', __file__ </code></pre> <p>Calling it with 'python foo.py' Will return simply 'foo.py'. If you add a shebang:</p> <pre><code>#!/usr/bin/python #foo.py print '__file__', __file__ </code></pre> <p>and call it using ./foo.py, it will return './foo.py'. Calling it from a different directory, (eg put foo.py in directory bar), then calling either</p> <pre><code>python bar/foo.py </code></pre> <p>or adding a shebang and executing the file directly:</p> <pre><code>bar/foo.py </code></pre> <p>will return 'bar/foo.py' (the <strong>relative</strong> path).</p> <h2>Finding the directory</h2> <p>Now going from there to get the directory, <code>os.path.dirname(__file__)</code> can also be tricky. At least on my system, it returns an empty string if you call it from the same directory as the file. ex.</p> <pre><code># foo.py import os print '__file__ is:', __file__ print 'os.path.dirname(__file__) is:', os.path.dirname(__file__) </code></pre> <p>will output:</p> <pre><code>__file__ is: foo.py os.path.dirname(__file__) is: </code></pre> <p>In other words, it returns an empty string, so this does not seem reliable if you want to use it for the current <strong>file</strong> (as opposed to the <strong>file</strong> of an imported module). To get around this, you can wrap it in a call to abspath:</p> <pre><code># foo.py import os print 'os.path.abspath(__file__) is:', os.path.abspath(__file__) print 'os.path.dirname(os.path.abspath(__file__)) is:', os.path.dirname(os.path.abspath(__file__)) </code></pre> <p>which outputs something like:</p> <pre><code>os.path.abspath(__file__) is: /home/user/bar/foo.py os.path.dirname(os.path.abspath(__file__)) is: /home/user/bar </code></pre> <p>Note that abspath() does NOT resolve symlinks. If you want to do this, use realpath() instead. For example, making a symlink file_import_testing_link pointing to file_import_testing.py, with the following content:</p> <pre><code>import os print 'abspath(__file__)',os.path.abspath(__file__) print 'realpath(__file__)',os.path.realpath(__file__) </code></pre> <p>executing will print absolute paths something like:</p> <pre><code>abspath(__file__) /home/user/file_test_link realpath(__file__) /home/user/file_test.py </code></pre> <p>file_import_testing_link -> file_import_testing.py</p> <h2>Using inspect</h2> <p>@SummerBreeze mentions using the <a href="http://docs.python.org/2/library/inspect.html">inspect</a> module.</p> <p>This seems to work well, and is quite concise, for imported modules:</p> <pre><code>import os import inspect print 'inspect.getfile(os) is:', inspect.getfile(os) </code></pre> <p>obediently returns the absolute path. However for finding the path of the currently executing script, I did not see a way to use it.</p>
22
2013-05-30T02:15:40Z
[ "python", "module", "inotify" ]
Retrieving python module path
247,770
<p>I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.</p> <p>How do I retrieve a module's path in python?</p>
351
2008-10-29T17:52:40Z
25,319,974
<p>If the only caveat of using <code>__file__</code> is when current, relative directory is blank (ie, when running as a script from the same directory where the script is), then a trivial solution is:</p> <pre class="lang-py prettyprint-override"><code>import os.path mydir = os.path.dirname(__file__) or '.' full = os.path.abspath(mydir) print __file__, mydir, full </code></pre> <p>And the result:</p> <pre><code>$ python teste.py teste.py . /home/user/work/teste </code></pre> <p>The trick is in <code>or '.'</code> after the <code>dirname()</code> call. It sets the dir as <code>.</code>, which means <em>current directory</em> and is a valid directory for any path-related function.</p> <p>Thus, using <code>abspath()</code> is not truly needed. But if you use it anyway, the trick is not needed: <code>abspath()</code> accepts blank paths and properly interprets it as the current directory.</p>
2
2014-08-15T01:22:39Z
[ "python", "module", "inotify" ]
Retrieving python module path
247,770
<p>I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.</p> <p>How do I retrieve a module's path in python?</p>
351
2008-10-29T17:52:40Z
25,344,804
<blockquote> <p>Packages support one more special attribute, <code>__path__</code>. This is initialized to be a list containing the name of the directory holding the package’s <code>__init__.py</code> before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.</p> <p>While this feature is not often needed, it can be used to extend the set of modules found in a package.</p> </blockquote> <p><a href="https://docs.python.org/2/tutorial/modules.html#packages-in-multiple-directories" rel="nofollow">Source</a></p> <pre><code>import module print module.__path__ </code></pre>
3
2014-08-16T23:04:03Z
[ "python", "module", "inotify" ]
Retrieving python module path
247,770
<p>I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.</p> <p>How do I retrieve a module's path in python?</p>
351
2008-10-29T17:52:40Z
27,934,408
<p>If you wish to do this dynamically in a "program" try this code:<br> My point is, you may not know the exact name of the module to "hardcode" it. It may be selected from a list or may not be currently running to use __file__.</p> <p>(I know, it will not work in Python 3)</p> <pre><code>global modpath modname = 'os' #This can be any module name on the fly #Create a file called "modname.py" f=open("modname.py","w") f.write("import "+modname+"\n") f.write("modpath = "+modname+"\n") f.close() #Call the file with execfile() execfile('modname.py') print modpath &lt;module 'os' from 'C:\Python27\lib\os.pyc'&gt; </code></pre> <p>I tried to get rid of the "global" issue but found cases where it did not work I think "execfile()" can be emulated in Python 3 Since this is in a program, it can easily be put in a method or module for reuse.</p>
0
2015-01-14T01:23:25Z
[ "python", "module", "inotify" ]
Retrieving python module path
247,770
<p>I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.</p> <p>How do I retrieve a module's path in python?</p>
351
2008-10-29T17:52:40Z
28,976,381
<p>I don't get why no one is talking about this, but to me the simplest solution is using <strong>imp.find_module("modulename")</strong> (documentation <a href="https://docs.python.org/2/library/imp.html?highlight=import#module-imp">here</a>):</p> <pre><code>import imp imp.find_module("os") </code></pre> <p>It gives a tuple with the path in second position:</p> <pre><code>(&lt;open file '/usr/lib/python2.7/os.py', mode 'U' at 0x7f44528d7540&gt;, '/usr/lib/python2.7/os.py', ('.py', 'U', 1)) </code></pre> <p>The advantage of this method over the "inspect" one is that you don't need to import the module to make it work, and you can use a string in input. Useful when checking modules called in another script for example.</p> <p><strong>EDIT</strong>:</p> <p>In python3, <code>importlib</code> module should do:</p> <p>Doc of <code>importlib.util.find_spec</code>:</p> <blockquote> <p>Return the spec for the specified module.</p> <p>First, sys.modules is checked to see if the module was already imported. If so, then sys.modules[name].<strong>spec</strong> is returned. If that happens to be set to None, then ValueError is raised. If the module is not in sys.modules, then sys.meta_path is searched for a suitable spec with the value of 'path' given to the finders. None is returned if no spec could be found.</p> <p>If the name is for submodule (contains a dot), the parent module is automatically imported.</p> <p>The name and package arguments work the same as importlib.import_module(). In other words, relative module names (with leading dots) work.</p> </blockquote>
10
2015-03-11T00:10:44Z
[ "python", "module", "inotify" ]
Retrieving python module path
247,770
<p>I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.</p> <p>How do I retrieve a module's path in python?</p>
351
2008-10-29T17:52:40Z
30,192,316
<p>From within modules of a python package I had to refer to a file that resided in the same directory as package. Ex.</p> <pre><code>some_dir/ maincli.py top_package/ __init__.py level_one_a/ __init__.py my_lib_a.py level_two/ __init__.py hello_world.py level_one_b/ __init__.py my_lib_b.py </code></pre> <p>So in above I had to call maincli.py from my_lib_a.py module knowing that top_package and maincli.py are in the same directory. Here's how I get the path to maincli.py:</p> <pre><code>import sys import os import imp class ConfigurationException(Exception): pass # inside of my_lib_a.py def get_maincli_path(): maincli_path = os.path.abspath(imp.find_module('maincli')[1]) # top_package = __package__.split('.')[0] # mod = sys.modules.get(top_package) # modfile = mod.__file__ # pkg_in_dir = os.path.dirname(os.path.dirname(os.path.abspath(modfile))) # maincli_path = os.path.join(pkg_in_dir, 'maincli.py') if not os.path.exists(maincli_path): err_msg = 'This script expects that "maincli.py" be installed to the '\ 'same directory: "{0}"'.format(maincli_path) raise ConfigurationException(err_msg) return maincli_path </code></pre> <p>Based on posting by PlasmaBinturong I modified the code.</p>
0
2015-05-12T13:27:01Z
[ "python", "module", "inotify" ]
Retrieving python module path
247,770
<p>I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.</p> <p>How do I retrieve a module's path in python?</p>
351
2008-10-29T17:52:40Z
32,026,782
<h2>Command Line Utility</h2> <p>You can tweak it to a command line utility,</p> <pre><code>python-which &lt;package name&gt; </code></pre> <p><a href="http://i.stack.imgur.com/pjVSO.png" rel="nofollow"><img src="http://i.stack.imgur.com/pjVSO.png" alt="enter image description here"></a></p> <hr> <p>Create <code>/usr/local/bin/python-which</code></p> <pre><code>#!/usr/bin/env python import importlib import os import sys args = sys.argv[1:] if len(args) &gt; 0: module = importlib.import_module(args[0]) print os.path.dirname(module.__file__) </code></pre> <p>Make it executable </p> <pre><code>sudo chmod +x /usr/local/bin/python-which </code></pre>
1
2015-08-15T16:27:18Z
[ "python", "module", "inotify" ]
Is it possible to get the value of an item contained in Django's "changed_data" list?
247,922
<p>I have the following code in my Django application:</p> <pre><code>if 'book' in authorForm.changed_data: #Do something here... </code></pre> <p>I realize Django can tell me which values have changed in my form by utilizing the "changed_data" list object, but I'd like to know the new values of the fields that have changed.</p> <p>Any thoughts?</p>
0
2008-10-29T18:38:46Z
248,200
<p>Hmm... Try this:</p> <pre><code>if authorForm.is_valid() and 'book' in authorForm.changed_data: new_value = authorForm.cleaned_data['book'] </code></pre>
2
2008-10-29T19:58:24Z
[ "python", "django" ]
Is it possible to get the value of an item contained in Django's "changed_data" list?
247,922
<p>I have the following code in my Django application:</p> <pre><code>if 'book' in authorForm.changed_data: #Do something here... </code></pre> <p>I realize Django can tell me which values have changed in my form by utilizing the "changed_data" list object, but I'd like to know the new values of the fields that have changed.</p> <p>Any thoughts?</p>
0
2008-10-29T18:38:46Z
3,086,204
<p>The short answer to my original question is "No".</p>
0
2010-06-21T15:56:26Z
[ "python", "django" ]
Is there something between a normal user account and root?
248,730
<p>I'm developing an application that manages network interfaces on behalf of the user and it calls out to several external programs (such as ifconfig) that requires root to make changes. (Specifically, changing the IP address of a local interface, etc.) During development, I have been running the IDE as root (ugh) and the debugger as root (double-ugh). Is there a nice way for the end-user to run these under a non-root account? I strongly dislike the size of the attack surface presented by GTK, wxPython, Python, and my application when it runs as root.</p> <p>I have looked into capabilities, but they look half-baked and I'm not sure if I'd be able to use them in Python, especially if they are on a thread basis. The only option I haven't explored is a daemon that has the setuid bit set and does all the root-type stuff on behalf of the UI. I'm hesitant to introduce that complexity this early in the project, as running as root is not a dealbreaker for the users.</p>
3
2008-10-29T23:02:30Z
248,743
<p>There's no single user that is halfway between a "normal" user and root. You have root, and then you have users; users can have differing levels of capabilities. If you want something that's more powerful than a "normal" user but not as powerful as root, you just create a new user with the capabilities you want, but don't give it the privileges you don't want it to have.</p>
0
2008-10-29T23:06:28Z
[ "python", "linux", "root" ]
Is there something between a normal user account and root?
248,730
<p>I'm developing an application that manages network interfaces on behalf of the user and it calls out to several external programs (such as ifconfig) that requires root to make changes. (Specifically, changing the IP address of a local interface, etc.) During development, I have been running the IDE as root (ugh) and the debugger as root (double-ugh). Is there a nice way for the end-user to run these under a non-root account? I strongly dislike the size of the attack surface presented by GTK, wxPython, Python, and my application when it runs as root.</p> <p>I have looked into capabilities, but they look half-baked and I'm not sure if I'd be able to use them in Python, especially if they are on a thread basis. The only option I haven't explored is a daemon that has the setuid bit set and does all the root-type stuff on behalf of the UI. I'm hesitant to introduce that complexity this early in the project, as running as root is not a dealbreaker for the users.</p>
3
2008-10-29T23:02:30Z
248,756
<p>You could create and distribute a selinux policy for your application. Selinux allows the kind of fine-grained access that you need. If you can't or won't use selinux, then the daemon is the way to go.</p>
1
2008-10-29T23:10:17Z
[ "python", "linux", "root" ]
Is there something between a normal user account and root?
248,730
<p>I'm developing an application that manages network interfaces on behalf of the user and it calls out to several external programs (such as ifconfig) that requires root to make changes. (Specifically, changing the IP address of a local interface, etc.) During development, I have been running the IDE as root (ugh) and the debugger as root (double-ugh). Is there a nice way for the end-user to run these under a non-root account? I strongly dislike the size of the attack surface presented by GTK, wxPython, Python, and my application when it runs as root.</p> <p>I have looked into capabilities, but they look half-baked and I'm not sure if I'd be able to use them in Python, especially if they are on a thread basis. The only option I haven't explored is a daemon that has the setuid bit set and does all the root-type stuff on behalf of the UI. I'm hesitant to introduce that complexity this early in the project, as running as root is not a dealbreaker for the users.</p>
3
2008-10-29T23:02:30Z
248,757
<p>I would not run the application full time as root, but you might want to explore making your application setuid root, or setuid to some id that can become root using something like sudo for particular applications. You might be able to set up an account that cannot login, use setuid to change your program's id (temporarily when needed) and have sudo set up to not prompt for password, but always allow access to that account for specific tasks.</p> <p>This way your program has no special privileges when running normally, only elevates it's privileges when needed, and is restricted by sudo to only running certain programs.</p> <p>It's been awhile since I've done much Unix development, so I'm not really sure whether it's possible to set up sudo to not prompt for a password (or even if there is an API for it), but as a fallback you could enable setuid to root only when needed.</p> <p>[EDIT] Looks like <a href="http://www.sudo.ws/sudo/sudo.html" rel="nofollow">sudo</a> has a NOPASSWD mode so I think it should work since you're running the programs as external commands.</p>
1
2008-10-29T23:10:23Z
[ "python", "linux", "root" ]
Is there something between a normal user account and root?
248,730
<p>I'm developing an application that manages network interfaces on behalf of the user and it calls out to several external programs (such as ifconfig) that requires root to make changes. (Specifically, changing the IP address of a local interface, etc.) During development, I have been running the IDE as root (ugh) and the debugger as root (double-ugh). Is there a nice way for the end-user to run these under a non-root account? I strongly dislike the size of the attack surface presented by GTK, wxPython, Python, and my application when it runs as root.</p> <p>I have looked into capabilities, but they look half-baked and I'm not sure if I'd be able to use them in Python, especially if they are on a thread basis. The only option I haven't explored is a daemon that has the setuid bit set and does all the root-type stuff on behalf of the UI. I'm hesitant to introduce that complexity this early in the project, as running as root is not a dealbreaker for the users.</p>
3
2008-10-29T23:02:30Z
248,758
<p>Your idea about the daemon has much merit, despite the complexity it introduces. As long as the actions don't require some user interface interaction <em>as root</em>, a daemon allows you to control what operations are allowed and disallowed.</p> <p>However, you can use SUDO to create a controlled compromise between ROOT and normal users... simply grant SUDO access to the users in question for the specific tools they need. That reduces the attack surface by allowing only "permitted" root launches.</p>
7
2008-10-29T23:11:01Z
[ "python", "linux", "root" ]
Is there something between a normal user account and root?
248,730
<p>I'm developing an application that manages network interfaces on behalf of the user and it calls out to several external programs (such as ifconfig) that requires root to make changes. (Specifically, changing the IP address of a local interface, etc.) During development, I have been running the IDE as root (ugh) and the debugger as root (double-ugh). Is there a nice way for the end-user to run these under a non-root account? I strongly dislike the size of the attack surface presented by GTK, wxPython, Python, and my application when it runs as root.</p> <p>I have looked into capabilities, but they look half-baked and I'm not sure if I'd be able to use them in Python, especially if they are on a thread basis. The only option I haven't explored is a daemon that has the setuid bit set and does all the root-type stuff on behalf of the UI. I'm hesitant to introduce that complexity this early in the project, as running as root is not a dealbreaker for the users.</p>
3
2008-10-29T23:02:30Z
248,759
<p>What you want is a "Group"</p> <p>You create a group, specify that the account wanting to do the action belongs to the group, then you specify that the resource you want access to is a member of that group.</p> <p>Sometimes group management can be kind of irritating, but it should allow you to do anything you want, and it's the user that is authorized, not your program.</p> <p>(If you want your program authorized, you can create a specific user to run it as and give that user the proper group membership, then su to that group within your program to execute the operation without giving the running user the ability.)</p>
3
2008-10-29T23:11:35Z
[ "python", "linux", "root" ]
Is there something between a normal user account and root?
248,730
<p>I'm developing an application that manages network interfaces on behalf of the user and it calls out to several external programs (such as ifconfig) that requires root to make changes. (Specifically, changing the IP address of a local interface, etc.) During development, I have been running the IDE as root (ugh) and the debugger as root (double-ugh). Is there a nice way for the end-user to run these under a non-root account? I strongly dislike the size of the attack surface presented by GTK, wxPython, Python, and my application when it runs as root.</p> <p>I have looked into capabilities, but they look half-baked and I'm not sure if I'd be able to use them in Python, especially if they are on a thread basis. The only option I haven't explored is a daemon that has the setuid bit set and does all the root-type stuff on behalf of the UI. I'm hesitant to introduce that complexity this early in the project, as running as root is not a dealbreaker for the users.</p>
3
2008-10-29T23:02:30Z
248,874
<p>I'm not familiar enough with Python to tell you what the necessary commands would be in that language, but you should be able to accomplish this by forking and using a pipe to communicate between the parent and child processes. Something along the lines of:</p> <ul> <li>Run the program as root via sudo or suid</li> <li>On startup, the program immediately forks and establishes a pipe for communication between the parent and child processes</li> <li>The child process retains root power, but just sits there waiting for input from the pipe</li> <li>The parent process drops root (changes its uid back to that of the user running it), then displays the GUI, interacts with the user, and handles all operations which are available to a non-privileged user</li> <li>When an operation is to be performed which requires root privileges, the (non-root) parent process sends a command down the pipe to the (root) child process which executes it and optionally reports back to the parent</li> </ul> <p>This is likely to be a bit easier to write than an independent daemon, as well as more convenient to run (since you don't need to worry about whether the daemon is running or not), while also allowing the GUI and other things which don't need root powers to be run as non-root.</p>
0
2008-10-30T00:04:26Z
[ "python", "linux", "root" ]
Is there something between a normal user account and root?
248,730
<p>I'm developing an application that manages network interfaces on behalf of the user and it calls out to several external programs (such as ifconfig) that requires root to make changes. (Specifically, changing the IP address of a local interface, etc.) During development, I have been running the IDE as root (ugh) and the debugger as root (double-ugh). Is there a nice way for the end-user to run these under a non-root account? I strongly dislike the size of the attack surface presented by GTK, wxPython, Python, and my application when it runs as root.</p> <p>I have looked into capabilities, but they look half-baked and I'm not sure if I'd be able to use them in Python, especially if they are on a thread basis. The only option I haven't explored is a daemon that has the setuid bit set and does all the root-type stuff on behalf of the UI. I'm hesitant to introduce that complexity this early in the project, as running as root is not a dealbreaker for the users.</p>
3
2008-10-29T23:02:30Z
248,882
<p>The traditional way would be to create and use a setuid helper to do whatever you need. Note that, however, properly writing a setuid helper is tricky (there are several attack vectors you have to protect against).</p> <p>The modern way would be to use a daemon (running as root, started on boot) which listens to requests from the rest of the application. This way, your attack surface is mostly limited to whichever IPC you chose (I'd suggest d-bus, which seems to be the modern way).</p> <p>Finally, if you are managing network interfaces, what you doing is very similar to what network-manager does on a modern distribution. It would be a good idea to either try to somehow integrate what you are doing with network-manager (so it will not conflict with your manipulations), or at least looks at how it works.</p>
1
2008-10-30T00:08:28Z
[ "python", "linux", "root" ]
Python: using a recursive algorithm as a generator
248,830
<p>Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list with all the sequences.</p> <p>Here is an example. Suppose we want to compute all the permutations of a string with a recursive function. The following naive algorithm takes an extra argument 'storage' and appends a permutation to it whenever it finds one:</p> <pre><code>def getPermutations(string, storage, prefix=""): if len(string) == 1: storage.append(prefix + string) # &lt;----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], storage, prefix+string[i]) storage = [] getPermutations("abcd", storage) for permutation in storage: print permutation </code></pre> <p>(Please don't care about inefficiency, this is only an example.)</p> <p>Now I want to turn my function into a generator, i.e. to yield a permutation instead of appending it to the storage list:</p> <pre><code>def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string # &lt;----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], prefix+string[i]) for permutation in getPermutations("abcd"): print permutation </code></pre> <p>This code does <em>not</em> work (the function behaves like an empty generator).</p> <p>Am I missing something? Is there a way to turn the above recursive algorithm into a generator <em>without replacing it with an iterative one</em>?</p>
79
2008-10-29T23:45:56Z
248,854
<pre><code>def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string else: for i in xrange(len(string)): for perm in getPermutations(string[:i] + string[i+1:], prefix+string[i]): yield perm </code></pre> <p>Or without an accumulator:</p> <pre><code>def getPermutations(string): if len(string) == 1: yield string else: for i in xrange(len(string)): for perm in getPermutations(string[:i] + string[i+1:]): yield string[i] + perm </code></pre>
96
2008-10-29T23:53:47Z
[ "python", "recursion", "generator" ]
Python: using a recursive algorithm as a generator
248,830
<p>Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list with all the sequences.</p> <p>Here is an example. Suppose we want to compute all the permutations of a string with a recursive function. The following naive algorithm takes an extra argument 'storage' and appends a permutation to it whenever it finds one:</p> <pre><code>def getPermutations(string, storage, prefix=""): if len(string) == 1: storage.append(prefix + string) # &lt;----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], storage, prefix+string[i]) storage = [] getPermutations("abcd", storage) for permutation in storage: print permutation </code></pre> <p>(Please don't care about inefficiency, this is only an example.)</p> <p>Now I want to turn my function into a generator, i.e. to yield a permutation instead of appending it to the storage list:</p> <pre><code>def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string # &lt;----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], prefix+string[i]) for permutation in getPermutations("abcd"): print permutation </code></pre> <p>This code does <em>not</em> work (the function behaves like an empty generator).</p> <p>Am I missing something? Is there a way to turn the above recursive algorithm into a generator <em>without replacing it with an iterative one</em>?</p>
79
2008-10-29T23:45:56Z
248,857
<p>The interior call to getPermutations -- it's a generator, too.</p> <pre><code>def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], prefix+string[i]) # &lt;----- </code></pre> <p>You need to iterate through that with a for-loop (see @MizardX posting, which edged me out by seconds!)</p>
19
2008-10-29T23:54:51Z
[ "python", "recursion", "generator" ]
Python: using a recursive algorithm as a generator
248,830
<p>Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list with all the sequences.</p> <p>Here is an example. Suppose we want to compute all the permutations of a string with a recursive function. The following naive algorithm takes an extra argument 'storage' and appends a permutation to it whenever it finds one:</p> <pre><code>def getPermutations(string, storage, prefix=""): if len(string) == 1: storage.append(prefix + string) # &lt;----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], storage, prefix+string[i]) storage = [] getPermutations("abcd", storage) for permutation in storage: print permutation </code></pre> <p>(Please don't care about inefficiency, this is only an example.)</p> <p>Now I want to turn my function into a generator, i.e. to yield a permutation instead of appending it to the storage list:</p> <pre><code>def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string # &lt;----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], prefix+string[i]) for permutation in getPermutations("abcd"): print permutation </code></pre> <p>This code does <em>not</em> work (the function behaves like an empty generator).</p> <p>Am I missing something? Is there a way to turn the above recursive algorithm into a generator <em>without replacing it with an iterative one</em>?</p>
79
2008-10-29T23:45:56Z
252,199
<p>This avoids the <code>len(string)</code>-deep recursion, and is in general a nice way to handle generators-inside-generators:</p> <pre><code>from types import GeneratorType def flatten(*stack): stack = list(stack) while stack: try: x = stack[0].next() except StopIteration: stack.pop(0) continue if isinstance(x, GeneratorType): stack.insert(0, x) else: yield x def _getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string else: yield (_getPermutations(string[:i]+string[i+1:], prefix+string[i]) for i in range(len(string))) def getPermutations(string): return flatten(_getPermutations(string)) for permutation in getPermutations("abcd"): print permutation </code></pre> <p><code>flatten</code> allows us to continue progress in another generator by simply <code>yield</code>ing it, instead of iterating through it and <code>yield</code>ing each item manually.</p> <hr> <p>Python 3.3 will add <a href="http://docs.python.org/dev/whatsnew/3.3.html#pep-380-syntax-for-delegating-to-a-subgenerator"><code>yield from</code></a> to the syntax, which allows for natural delegation to a sub-generator:</p> <pre><code>def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string else: for i in range(len(string)): yield from getPermutations(string[:i]+string[i+1:], prefix+string[i]) </code></pre>
24
2008-10-31T00:05:38Z
[ "python", "recursion", "generator" ]
I need a really good reason to use Python
249,064
<p>I have been trying to make a case for using Python at my work. We use C# and ASP.NET for basically all of our development. 80% or more of our projects are web applications. It seems natural that we would look at some of the nice dynamic web languages (Ruby, Python, etc), and with things like <a href="http://en.wikipedia.org/wiki/Ironruby" rel="nofollow">IronRuby</a> and <a href="http://en.wikipedia.org/wiki/Ironpython" rel="nofollow">IronPython</a>, I started seriously investigating.</p> <p>I love Python. It's a beautiful, expressive language. It's a joy to code in, for sure. The multitude of python modules and frameworks make it very appealing. Problem is, I cannot think of any specific problems, any specific hurdles that would <b>require</b> a language like Python. ASP.NET gives us RAD, it gives us a full-featured framework and all that good stuff. Also, we all already know C# and have lots of projects in C#, learning a new language just <i>because</i> doesn't quite work. </p> <p>Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects?</p> <p>Edit: I know that no problem requires only one language, I just meant, are there any specific problems in which dynamic languages excel over static languages.</p> <p>Edit again: Let me also mention that my boss prompted ME to investigate this. He has put aside hours to research these languages, find a good one, learn it, and then figure out how we can use it. I'm at the last step here, I do not need a lecture on why I should consider my motivation for changing something my company does because they do it for a reason. </p>
10
2008-10-30T01:59:48Z
249,075
<p>Almost no problem <strong>requires</strong> a specific programming language, that's just not how things work.</p> <p>The easiest way to get a new language into an environment like yours is to start a new work project in your own time in the new language. Make it do something you need doing, and write it on your own time. Use it yourself, and other people will probably notice it. They then say "Can you send me that program?" and boom, they're using your new language.</p> <p>If you really want to something, I would probably write a site in Django, simply because its admin interface blows everyone away.</p> <p>The main point to remember is that if you start using python, that's one more thing everyone else has to learn, and it's another bullet point that will need to be on every prospective employee's resume. That can get expensive, and management won't like it.</p>
12
2008-10-30T02:04:09Z
[ "python" ]
I need a really good reason to use Python
249,064
<p>I have been trying to make a case for using Python at my work. We use C# and ASP.NET for basically all of our development. 80% or more of our projects are web applications. It seems natural that we would look at some of the nice dynamic web languages (Ruby, Python, etc), and with things like <a href="http://en.wikipedia.org/wiki/Ironruby" rel="nofollow">IronRuby</a> and <a href="http://en.wikipedia.org/wiki/Ironpython" rel="nofollow">IronPython</a>, I started seriously investigating.</p> <p>I love Python. It's a beautiful, expressive language. It's a joy to code in, for sure. The multitude of python modules and frameworks make it very appealing. Problem is, I cannot think of any specific problems, any specific hurdles that would <b>require</b> a language like Python. ASP.NET gives us RAD, it gives us a full-featured framework and all that good stuff. Also, we all already know C# and have lots of projects in C#, learning a new language just <i>because</i> doesn't quite work. </p> <p>Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects?</p> <p>Edit: I know that no problem requires only one language, I just meant, are there any specific problems in which dynamic languages excel over static languages.</p> <p>Edit again: Let me also mention that my boss prompted ME to investigate this. He has put aside hours to research these languages, find a good one, learn it, and then figure out how we can use it. I'm at the last step here, I do not need a lecture on why I should consider my motivation for changing something my company does because they do it for a reason. </p>
10
2008-10-30T01:59:48Z
249,101
<p>"Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects?"</p> <p>Nope. </p> <p>Nothing succeeds like success. Use Python. Be successful. Make people jealous. </p> <p>When asked why you're successful, you can talk about Python. Not before.</p> <p>Choose projects wisely: things where a dynamic language has significant advantages. Things where the requirements are <strong>not</strong> nailed down in detail. Things like data transformations, log-file scraping, and super-sophisticated replacements for BAT files.</p> <p>Use Python to get started doing something useful while everyone else is standing around trying to get enough business and domain information to launch a project to develop a complicated MVC design.</p> <p><hr /></p> <p>Edit: Some Python to the Rescue stories.</p> <ul> <li><a href="http://homepage.mac.com/s_lott/iblog/architecture/C551260341/E20081005191603/index.html">Exploratory Programming</a></li> <li><a href="http://homepage.mac.com/s_lott/iblog/architecture/C20071019092637/E20080830091128/index.html">Tooling to build test cases</a></li> <li><a href="http://homepage.mac.com/s_lott/iblog/architecture/C465799452/E20080712112540/index.html">What's Central Here?</a></li> <li><a href="http://homepage.mac.com/s_lott/iblog/architecture/C588245363/E20060206184914/index.html">Control-Break Reporting</a></li> <li><a href="http://homepage.mac.com/s_lott/iblog/architecture/C588245363/E20051022112554/index.html">One More Cool Thing About Python Is...</a></li> <li><a href="http://homepage.mac.com/s_lott/iblog/architecture/C465799452/E20080603055001/index.html">In Praise of Serialization</a></li> </ul> <p>And that's just me.</p> <p><hr /></p> <p>Edit: "boss prompted ME to investigate", "figure out how we can use it" changes everything.</p> <p>The "finally convince my boss to really learn Python" is misleading. You aren't swimming upstream. See <a href="http://stackoverflow.com/questions/202337/how-do-i-make-the-business-case-for-python">How Do I Make the Business Case for Python</a> for the "convince my boss" problem. The edit says you're past this phase.</p> <p>Dynamic languages offer flexibility. Exploit that. My two sets of examples above are two areas where flexibility matters.</p> <ul> <li><p>Requirements aren't totally nailed down. With a dynamic language, you can get started. Rework won't be a deal-breaker. With Java (and C++ and C#) you are reluctant to tackle devastating design changes because it's hard to break everything and get it to compile and work again. In Python, devastating changes aren't as expensive.</p></li> <li><p>Design is in flux because you can't pick components. You can write Wrappers and Facades very easily in Python. It's a scripting language. And, Python modules compose into larger aggregates very simply.</p></li> <li><p>Coding is in flux because requirements and design keep changing. It's scripted -- not compiled. You just make a change to the code and you're off and running. Testing is easier because the work cycle is shorter. It isn't code-compile-build-test it's code-test.</p></li> <li><p>Testing is in flux because the requirements keep changing. Same as above. The work cycle is shorter and faster.</p></li> </ul>
28
2008-10-30T02:12:10Z
[ "python" ]
I need a really good reason to use Python
249,064
<p>I have been trying to make a case for using Python at my work. We use C# and ASP.NET for basically all of our development. 80% or more of our projects are web applications. It seems natural that we would look at some of the nice dynamic web languages (Ruby, Python, etc), and with things like <a href="http://en.wikipedia.org/wiki/Ironruby" rel="nofollow">IronRuby</a> and <a href="http://en.wikipedia.org/wiki/Ironpython" rel="nofollow">IronPython</a>, I started seriously investigating.</p> <p>I love Python. It's a beautiful, expressive language. It's a joy to code in, for sure. The multitude of python modules and frameworks make it very appealing. Problem is, I cannot think of any specific problems, any specific hurdles that would <b>require</b> a language like Python. ASP.NET gives us RAD, it gives us a full-featured framework and all that good stuff. Also, we all already know C# and have lots of projects in C#, learning a new language just <i>because</i> doesn't quite work. </p> <p>Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects?</p> <p>Edit: I know that no problem requires only one language, I just meant, are there any specific problems in which dynamic languages excel over static languages.</p> <p>Edit again: Let me also mention that my boss prompted ME to investigate this. He has put aside hours to research these languages, find a good one, learn it, and then figure out how we can use it. I'm at the last step here, I do not need a lecture on why I should consider my motivation for changing something my company does because they do it for a reason. </p>
10
2008-10-30T01:59:48Z
249,113
<blockquote> <p>Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects?</p> </blockquote> <p>Unfortunately, the answer is no. As Harley said, no problem is going to <strong>require</strong> a specific language. The approach Harley suggested is also a good one. Learn on your time, build an useful app on your time, and maybe, just maybe, someone at your work will want to use it, like it, love it, then want to learn more about it.</p> <p>Another approach you could take is to get a better understanding of why your company uses .Net (therefore, Windows Server, and probably SQL server) for nearly all development. Once you have a good understanding of why they aren't open to other languages, then you have some fire power to build a business case for the "why not?". </p> <p>Why pay licensing costs when you have tools that can accomplish the same things? There are free alternatives out there, like Python, that run on free servers.</p> <p>Why not give your team the chance to grow their professional tool-belt? This is my opinion, but a good developer is a developer that isn't afraid to learn new ways of doing the same thing they've done before.</p> <p>But, in the end, I wouldn't get your hopes up. Bottom line, it costs money to introduce a new language/environment into an IT shop. Whether it's software, training, or employee rollover, there is a business reason behind utilizing a single language for a company, and sticking to it.</p> <p>I'm in the exact scenario you're in. I work in a .Net shop, and that's not going to change any time soon. I get by, by working on my own projects in my "free" time. I enjoy it, and it makes for a good balance. </p> <p>Hope this helps.</p>
3
2008-10-30T02:21:05Z
[ "python" ]
I need a really good reason to use Python
249,064
<p>I have been trying to make a case for using Python at my work. We use C# and ASP.NET for basically all of our development. 80% or more of our projects are web applications. It seems natural that we would look at some of the nice dynamic web languages (Ruby, Python, etc), and with things like <a href="http://en.wikipedia.org/wiki/Ironruby" rel="nofollow">IronRuby</a> and <a href="http://en.wikipedia.org/wiki/Ironpython" rel="nofollow">IronPython</a>, I started seriously investigating.</p> <p>I love Python. It's a beautiful, expressive language. It's a joy to code in, for sure. The multitude of python modules and frameworks make it very appealing. Problem is, I cannot think of any specific problems, any specific hurdles that would <b>require</b> a language like Python. ASP.NET gives us RAD, it gives us a full-featured framework and all that good stuff. Also, we all already know C# and have lots of projects in C#, learning a new language just <i>because</i> doesn't quite work. </p> <p>Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects?</p> <p>Edit: I know that no problem requires only one language, I just meant, are there any specific problems in which dynamic languages excel over static languages.</p> <p>Edit again: Let me also mention that my boss prompted ME to investigate this. He has put aside hours to research these languages, find a good one, learn it, and then figure out how we can use it. I'm at the last step here, I do not need a lecture on why I should consider my motivation for changing something my company does because they do it for a reason. </p>
10
2008-10-30T01:59:48Z
249,118
<p>Take a step back, and look at your approach. "I know what I want the answer to be, but I can't find any evidence to support it." </p> <p>Despite the fact that Python is my current first choice language, I am afraid I find myself on the side of your boss! Sorry.</p> <p>I think you should open your mind and consider all the options from the stance of your organisation's best interest, and see if you don't come to a different conclusion about the best language.</p> <p>There are many factors in the choice of language, and how pretty it is is a fairly minor one. The availability of staff is a key one. The cost of retraining, availability of the libraries and meta-tools, performance, etc. etc.</p> <p>Once you have taken into consideration all the different factors (and not just "Oooh! It'd be fun!") and made a balanced assessment (rather than a predetermined answer), you may find that your boss is more willing to listen.</p> <p>p.s. The suggestion to secretly use Python for work code, and leaving the company with a terrible code debt in a language they are not prepared for seems very unprofessional to me.</p>
3
2008-10-30T02:23:40Z
[ "python" ]
I need a really good reason to use Python
249,064
<p>I have been trying to make a case for using Python at my work. We use C# and ASP.NET for basically all of our development. 80% or more of our projects are web applications. It seems natural that we would look at some of the nice dynamic web languages (Ruby, Python, etc), and with things like <a href="http://en.wikipedia.org/wiki/Ironruby" rel="nofollow">IronRuby</a> and <a href="http://en.wikipedia.org/wiki/Ironpython" rel="nofollow">IronPython</a>, I started seriously investigating.</p> <p>I love Python. It's a beautiful, expressive language. It's a joy to code in, for sure. The multitude of python modules and frameworks make it very appealing. Problem is, I cannot think of any specific problems, any specific hurdles that would <b>require</b> a language like Python. ASP.NET gives us RAD, it gives us a full-featured framework and all that good stuff. Also, we all already know C# and have lots of projects in C#, learning a new language just <i>because</i> doesn't quite work. </p> <p>Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects?</p> <p>Edit: I know that no problem requires only one language, I just meant, are there any specific problems in which dynamic languages excel over static languages.</p> <p>Edit again: Let me also mention that my boss prompted ME to investigate this. He has put aside hours to research these languages, find a good one, learn it, and then figure out how we can use it. I'm at the last step here, I do not need a lecture on why I should consider my motivation for changing something my company does because they do it for a reason. </p>
10
2008-10-30T01:59:48Z
249,125
<p>Sneaking a language in is often done by automating tedious manual tasks (especially dynamic/scripting languages like Python/Ruby etc). Set it up so something like deploying builds, or shuffling backups, or whatever is done with Python.</p> <p>Then casually slip in how easy it was to do, and try to spread some of the enthusiasm around.</p> <p>Acceptance and awareness should slowly grow from that, and before you know it, management is seriously considering Python for a new project.</p>
6
2008-10-30T02:28:20Z
[ "python" ]
I need a really good reason to use Python
249,064
<p>I have been trying to make a case for using Python at my work. We use C# and ASP.NET for basically all of our development. 80% or more of our projects are web applications. It seems natural that we would look at some of the nice dynamic web languages (Ruby, Python, etc), and with things like <a href="http://en.wikipedia.org/wiki/Ironruby" rel="nofollow">IronRuby</a> and <a href="http://en.wikipedia.org/wiki/Ironpython" rel="nofollow">IronPython</a>, I started seriously investigating.</p> <p>I love Python. It's a beautiful, expressive language. It's a joy to code in, for sure. The multitude of python modules and frameworks make it very appealing. Problem is, I cannot think of any specific problems, any specific hurdles that would <b>require</b> a language like Python. ASP.NET gives us RAD, it gives us a full-featured framework and all that good stuff. Also, we all already know C# and have lots of projects in C#, learning a new language just <i>because</i> doesn't quite work. </p> <p>Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects?</p> <p>Edit: I know that no problem requires only one language, I just meant, are there any specific problems in which dynamic languages excel over static languages.</p> <p>Edit again: Let me also mention that my boss prompted ME to investigate this. He has put aside hours to research these languages, find a good one, learn it, and then figure out how we can use it. I'm at the last step here, I do not need a lecture on why I should consider my motivation for changing something my company does because they do it for a reason. </p>
10
2008-10-30T01:59:48Z
249,143
<p>The best leverage you're likely going to have is tools and libraries; as others have pointed out, no language is <em>required</em> to solve any particular program. So let's look at Things You Can Leverage Using Python:</p> <ul> <li>Google App Engine</li> <li>SciPy</li> <li>pywinauto</li> <li>django</li> </ul> <p>Those are off the top of my head; finding what's applicable to your team and your company is left as an exercise for the questioner :)</p>
2
2008-10-30T02:46:42Z
[ "python" ]
I need a really good reason to use Python
249,064
<p>I have been trying to make a case for using Python at my work. We use C# and ASP.NET for basically all of our development. 80% or more of our projects are web applications. It seems natural that we would look at some of the nice dynamic web languages (Ruby, Python, etc), and with things like <a href="http://en.wikipedia.org/wiki/Ironruby" rel="nofollow">IronRuby</a> and <a href="http://en.wikipedia.org/wiki/Ironpython" rel="nofollow">IronPython</a>, I started seriously investigating.</p> <p>I love Python. It's a beautiful, expressive language. It's a joy to code in, for sure. The multitude of python modules and frameworks make it very appealing. Problem is, I cannot think of any specific problems, any specific hurdles that would <b>require</b> a language like Python. ASP.NET gives us RAD, it gives us a full-featured framework and all that good stuff. Also, we all already know C# and have lots of projects in C#, learning a new language just <i>because</i> doesn't quite work. </p> <p>Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects?</p> <p>Edit: I know that no problem requires only one language, I just meant, are there any specific problems in which dynamic languages excel over static languages.</p> <p>Edit again: Let me also mention that my boss prompted ME to investigate this. He has put aside hours to research these languages, find a good one, learn it, and then figure out how we can use it. I'm at the last step here, I do not need a lecture on why I should consider my motivation for changing something my company does because they do it for a reason. </p>
10
2008-10-30T01:59:48Z
249,258
<p>Well, <a href="http://www.paulgraham.com/pypar.html" rel="nofollow">here's a view</a> of why Python programmers make better Java programmers; the concepts are much the same as for your situation.</p> <p>Essentially, people who learn a language because they want to show that they enjoy programming, like to learn new things, and are more likely to think outside the box.</p> <blockquote> <p>...if a company chooses to write its software in a comparatively esoteric language, they'll be able to hire better programmers, because they'll attract only those who cared enough to learn it. And for programmers the paradox is even more pronounced: the language to learn, if you want to get a good job, is a language that people don't learn merely to get a job.</p> </blockquote> <p>Not only that, but Python enforces "good looking" code and you don't have to do the whole code/compile routine. With IronPython, you can simply code in Python and use it as is; just another .NET tool.</p>
1
2008-10-30T04:16:21Z
[ "python" ]
I need a really good reason to use Python
249,064
<p>I have been trying to make a case for using Python at my work. We use C# and ASP.NET for basically all of our development. 80% or more of our projects are web applications. It seems natural that we would look at some of the nice dynamic web languages (Ruby, Python, etc), and with things like <a href="http://en.wikipedia.org/wiki/Ironruby" rel="nofollow">IronRuby</a> and <a href="http://en.wikipedia.org/wiki/Ironpython" rel="nofollow">IronPython</a>, I started seriously investigating.</p> <p>I love Python. It's a beautiful, expressive language. It's a joy to code in, for sure. The multitude of python modules and frameworks make it very appealing. Problem is, I cannot think of any specific problems, any specific hurdles that would <b>require</b> a language like Python. ASP.NET gives us RAD, it gives us a full-featured framework and all that good stuff. Also, we all already know C# and have lots of projects in C#, learning a new language just <i>because</i> doesn't quite work. </p> <p>Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects?</p> <p>Edit: I know that no problem requires only one language, I just meant, are there any specific problems in which dynamic languages excel over static languages.</p> <p>Edit again: Let me also mention that my boss prompted ME to investigate this. He has put aside hours to research these languages, find a good one, learn it, and then figure out how we can use it. I'm at the last step here, I do not need a lecture on why I should consider my motivation for changing something my company does because they do it for a reason. </p>
10
2008-10-30T01:59:48Z
249,277
<p>The language is almost never the key to success. Good programmers can be successful in a variety of languages, and you'll find successful projects in almost any language. You won't find the failures that much because those projects just go away never to be heard of again. If you're looking for a new language because you don't have good programmers, even the best language in the world isn't going to help.</p> <p>And, you haven't said anything about the sort of work you're doing. Python might be a good choice because it has well-supported and widely-used libraries that are critical for you. On the other hand, C# might have better support for the stuff that you want to do. A tool outside of context has no intrinsic merit. You might love screwdrivers, but that doesn't help you row a boat.</p> <p>If you want to use Python, or any other language, just because you like it, be honest with yourself and those around you. It looks like you've made a decision to switch, don't know why you are switching, and now need to rationalize it with reasons that had nothing to do with your desire to switch. If you had a good reason, you wouldn't be asking here :)</p> <p>That's not entirely a bad thing, though. Programming is a human enterprise. If the programmers (at whatever level) insanely love a particular language, no matter how stupid the reason, they are probably going to produce more. It's just not a technological solution though.</p> <p>Good luck, :)</p>
1
2008-10-30T04:27:55Z
[ "python" ]
I need a really good reason to use Python
249,064
<p>I have been trying to make a case for using Python at my work. We use C# and ASP.NET for basically all of our development. 80% or more of our projects are web applications. It seems natural that we would look at some of the nice dynamic web languages (Ruby, Python, etc), and with things like <a href="http://en.wikipedia.org/wiki/Ironruby" rel="nofollow">IronRuby</a> and <a href="http://en.wikipedia.org/wiki/Ironpython" rel="nofollow">IronPython</a>, I started seriously investigating.</p> <p>I love Python. It's a beautiful, expressive language. It's a joy to code in, for sure. The multitude of python modules and frameworks make it very appealing. Problem is, I cannot think of any specific problems, any specific hurdles that would <b>require</b> a language like Python. ASP.NET gives us RAD, it gives us a full-featured framework and all that good stuff. Also, we all already know C# and have lots of projects in C#, learning a new language just <i>because</i> doesn't quite work. </p> <p>Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects?</p> <p>Edit: I know that no problem requires only one language, I just meant, are there any specific problems in which dynamic languages excel over static languages.</p> <p>Edit again: Let me also mention that my boss prompted ME to investigate this. He has put aside hours to research these languages, find a good one, learn it, and then figure out how we can use it. I'm at the last step here, I do not need a lecture on why I should consider my motivation for changing something my company does because they do it for a reason. </p>
10
2008-10-30T01:59:48Z
251,632
<p>Python got a good start in the Java world as Jython for unit testing. In fact many Java people started using it first that way. Its dynamic scripting nature makes it a great fit for unit tests. Just yesterday I was wishing I could use it or something like it for the unit tests I was writing for a VB.Net project. I'd have to say that it isn't so much about the individual language IronRuby or IronPython as it is about the style of development that they enable. You can write static language like code in either but you don't fully reap the benefits until you can start to think dynamically. Once you grasp those concepts you'll start to slowly change the way you code and your projects will require less classes and less code to implement. Testing, particularly unit tests will become a must since you give up the warm blanket known as a compiler with type safety checks for other efficiencies.</p>
1
2008-10-30T20:24:07Z
[ "python" ]
I need a really good reason to use Python
249,064
<p>I have been trying to make a case for using Python at my work. We use C# and ASP.NET for basically all of our development. 80% or more of our projects are web applications. It seems natural that we would look at some of the nice dynamic web languages (Ruby, Python, etc), and with things like <a href="http://en.wikipedia.org/wiki/Ironruby" rel="nofollow">IronRuby</a> and <a href="http://en.wikipedia.org/wiki/Ironpython" rel="nofollow">IronPython</a>, I started seriously investigating.</p> <p>I love Python. It's a beautiful, expressive language. It's a joy to code in, for sure. The multitude of python modules and frameworks make it very appealing. Problem is, I cannot think of any specific problems, any specific hurdles that would <b>require</b> a language like Python. ASP.NET gives us RAD, it gives us a full-featured framework and all that good stuff. Also, we all already know C# and have lots of projects in C#, learning a new language just <i>because</i> doesn't quite work. </p> <p>Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects?</p> <p>Edit: I know that no problem requires only one language, I just meant, are there any specific problems in which dynamic languages excel over static languages.</p> <p>Edit again: Let me also mention that my boss prompted ME to investigate this. He has put aside hours to research these languages, find a good one, learn it, and then figure out how we can use it. I'm at the last step here, I do not need a lecture on why I should consider my motivation for changing something my company does because they do it for a reason. </p>
10
2008-10-30T01:59:48Z
37,058,004
<p>I am pretty sure (100%) that you don't need to use Python for MS Windows at least.</p> <p>In cases of other platforms you can use any language you like.</p>
0
2016-05-05T18:44:23Z
[ "python" ]
Django: Arbitrary number of unnamed urls.py parameters
249,110
<p>I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this:</p> <pre><code>/browse/&lt;name1&gt;/&lt;value1&gt;/&lt;name2&gt;/&lt;value2&gt;/ .... etc .... </code></pre> <p>where 'name' maps to a model attribute and 'value' is the search criteria for that attribute. Each "name" will be treated like a category to return subsets of the model instances where the categories match.</p> <p>Now, this could be handled with GET parameters, but I prefer more readable URLs for both the user's sake and the search engines. These URLs subsets will be embedded on each page that displays this model, so it seems worth the effort to make pretty URLs.</p> <p>Ideally each name/value pair will be passed to the view function as a parameter named <code>name1</code>, <code>name2</code>, etc. However, I don't believe it's possible to defined named patterns via a regex's matched text. Am I wrong there?</p> <p>So, it seems I need to do something like this:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/(?:([\w]+)/([\w]+)/)+$', 'app.views.view', name="model_browse"), ) </code></pre> <p>It seems this should match any sets of two name/value pairs. While it matches it successfully, it only passes the last name/value pair as parameters to the view function. My guess is that each match is overwriting the previous match. Under the guess that the containing (?:...)+ is causing it, I tried a simple repeating pattern instead:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/([\w]+/)+$', 'app.views.view', name="model_browse"), ) </code></pre> <p>... and got the same problem, but this time <code>*args</code> only includes the last matched pattern.</p> <p>Is this a limitation of Django's url dispatcher, and/or Python's regex support? It seems either of these methods should work. Is there a way to achieve this without hardcoding each possible model attribute in the URL as an optional (.*) pattern?</p>
16
2008-10-30T02:18:32Z
249,524
<p>A possibility that you might consider is matching the entire string of possible values within the url pattern portion and pull out the specific pieces within your view. As an example:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/(?P&lt;match&gt;.+)/$', 'app.views.view', name='model_browse'), ) def view(request, match): pieces = match.split('/') # even indexed pieces are the names, odd are values ... </code></pre> <p>No promises about the regexp I used, but I think you understand what I mean.</p> <p>(Edited to try and fix the regexp.)</p>
11
2008-10-30T07:52:30Z
[ "python", "django", "django-urls" ]
Django: Arbitrary number of unnamed urls.py parameters
249,110
<p>I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this:</p> <pre><code>/browse/&lt;name1&gt;/&lt;value1&gt;/&lt;name2&gt;/&lt;value2&gt;/ .... etc .... </code></pre> <p>where 'name' maps to a model attribute and 'value' is the search criteria for that attribute. Each "name" will be treated like a category to return subsets of the model instances where the categories match.</p> <p>Now, this could be handled with GET parameters, but I prefer more readable URLs for both the user's sake and the search engines. These URLs subsets will be embedded on each page that displays this model, so it seems worth the effort to make pretty URLs.</p> <p>Ideally each name/value pair will be passed to the view function as a parameter named <code>name1</code>, <code>name2</code>, etc. However, I don't believe it's possible to defined named patterns via a regex's matched text. Am I wrong there?</p> <p>So, it seems I need to do something like this:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/(?:([\w]+)/([\w]+)/)+$', 'app.views.view', name="model_browse"), ) </code></pre> <p>It seems this should match any sets of two name/value pairs. While it matches it successfully, it only passes the last name/value pair as parameters to the view function. My guess is that each match is overwriting the previous match. Under the guess that the containing (?:...)+ is causing it, I tried a simple repeating pattern instead:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/([\w]+/)+$', 'app.views.view', name="model_browse"), ) </code></pre> <p>... and got the same problem, but this time <code>*args</code> only includes the last matched pattern.</p> <p>Is this a limitation of Django's url dispatcher, and/or Python's regex support? It seems either of these methods should work. Is there a way to achieve this without hardcoding each possible model attribute in the URL as an optional (.*) pattern?</p>
16
2008-10-30T02:18:32Z
251,253
<p>I agree with Adam, but I think the pattern in urls.py should be:</p> <pre><code>... r'^browse/(?P&lt;match&gt;.+)/$' ... </code></pre> <p>The '\w' will only match 'word' characters, but the '.' will match anything.</p>
3
2008-10-30T18:32:46Z
[ "python", "django", "django-urls" ]