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 |
---|---|---|---|---|---|---|---|---|---|
A good multithreaded python webserver? | 213,483 | <p>I am looking for a python webserver which is multithreaded instead of being multi-process (as in case of mod_python for apache). I want it to be multithreaded because I want to have an in memory object cache that will be used by various http threads. My webserver does a lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing. This is not possible in a multi-process web server environment. Storing this information in memcache is also not a good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of IPC.</p>
<p>I implemented a simple webserver using BaseHttpServer, it gives good performance but it gets stuck after a few hours time. I need some more matured webserver. Is it possible to configure apache to use mod_python under a thread model so that I can do some object caching?</p>
| 13 | 2008-10-17T19:12:38Z | 213,572 | <p>Consider reconsidering your design. Maintaining that much state in your webserver is probably a bad idea. Multi-process is a much better way to go for stability. </p>
<p>Is there another way to share state between separate processes? What about a service? Database? Index? </p>
<p>It seems unlikely that maintaining a huge array of data in memory and relying on a single multi-threaded process to serve all your requests is the best design or architecture for your app. </p>
| 7 | 2008-10-17T19:35:04Z | [
"python",
"apache",
"webserver",
"mod-python"
] |
A good multithreaded python webserver? | 213,483 | <p>I am looking for a python webserver which is multithreaded instead of being multi-process (as in case of mod_python for apache). I want it to be multithreaded because I want to have an in memory object cache that will be used by various http threads. My webserver does a lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing. This is not possible in a multi-process web server environment. Storing this information in memcache is also not a good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of IPC.</p>
<p>I implemented a simple webserver using BaseHttpServer, it gives good performance but it gets stuck after a few hours time. I need some more matured webserver. Is it possible to configure apache to use mod_python under a thread model so that I can do some object caching?</p>
| 13 | 2008-10-17T19:12:38Z | 213,736 | <p>Just to point out something different from the usual suspects...</p>
<p>Some years ago while I was using <a href="http://zope.org/" rel="nofollow">Zope</a> 2.x I read about <a href="http://www.nightmare.com/medusa/medusa.html" rel="nofollow">Medusa</a> as it was the web server used for the platform. They advertised it to work well under heavy load and it can provide you with the functionality you asked. </p>
| 0 | 2008-10-17T20:31:57Z | [
"python",
"apache",
"webserver",
"mod-python"
] |
A good multithreaded python webserver? | 213,483 | <p>I am looking for a python webserver which is multithreaded instead of being multi-process (as in case of mod_python for apache). I want it to be multithreaded because I want to have an in memory object cache that will be used by various http threads. My webserver does a lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing. This is not possible in a multi-process web server environment. Storing this information in memcache is also not a good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of IPC.</p>
<p>I implemented a simple webserver using BaseHttpServer, it gives good performance but it gets stuck after a few hours time. I need some more matured webserver. Is it possible to configure apache to use mod_python under a thread model so that I can do some object caching?</p>
| 13 | 2008-10-17T19:12:38Z | 213,742 | <p>Its hard to give a definitive answer without knowing what kind of site you are working on and what kind of load you are expecting. Sub second performance may be a serious requirement or it may not. If you really need to save that last millisecond then you absolutely need to keep your arrays in memory. However as others have suggested it is more than likely that you don't and could get by with something else. Your usage pattern of the data in the array may affect what kinds of choices you make. You probably don't need access to the entire set of data from the array all at once so you could break your data up into smaller chunks and put those chunks in the cache instead of the one big lump. Depending on how often your array data needs to get updated you might make a choice between memcached, local db (berkley, sqlite, small mysql installation, etc) or a remote db. I'd say memcached for fairly frequent updates. A local db for something in the frequency of hourly and remote for the frequency of daily. One thing to consider also is what happens after a cache miss. If 50 clients all of a sudden get a cache miss and all of them at the same time decide to start regenerating those expensive arrays your box(es) will quickly be reduced to 8086's. So you have to take in to consideration how you will handle that. Many articles out there cover how to recover from cache misses. Hope this is helpful.</p>
| 3 | 2008-10-17T20:34:06Z | [
"python",
"apache",
"webserver",
"mod-python"
] |
A good multithreaded python webserver? | 213,483 | <p>I am looking for a python webserver which is multithreaded instead of being multi-process (as in case of mod_python for apache). I want it to be multithreaded because I want to have an in memory object cache that will be used by various http threads. My webserver does a lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing. This is not possible in a multi-process web server environment. Storing this information in memcache is also not a good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of IPC.</p>
<p>I implemented a simple webserver using BaseHttpServer, it gives good performance but it gets stuck after a few hours time. I need some more matured webserver. Is it possible to configure apache to use mod_python under a thread model so that I can do some object caching?</p>
| 13 | 2008-10-17T19:12:38Z | 214,495 | <p><a href="http://twistedmatrix.com/" rel="nofollow">Twisted</a> can serve as such a web server. While not multithreaded itself, there is a (not yet released) multithreaded WSGI container present in the current trunk. You can check out the SVN repository and then run:</p>
<pre><code>twistd web --wsgi=your.wsgi.application
</code></pre>
| 6 | 2008-10-18T03:32:42Z | [
"python",
"apache",
"webserver",
"mod-python"
] |
A good multithreaded python webserver? | 213,483 | <p>I am looking for a python webserver which is multithreaded instead of being multi-process (as in case of mod_python for apache). I want it to be multithreaded because I want to have an in memory object cache that will be used by various http threads. My webserver does a lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing. This is not possible in a multi-process web server environment. Storing this information in memcache is also not a good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of IPC.</p>
<p>I implemented a simple webserver using BaseHttpServer, it gives good performance but it gets stuck after a few hours time. I need some more matured webserver. Is it possible to configure apache to use mod_python under a thread model so that I can do some object caching?</p>
| 13 | 2008-10-17T19:12:38Z | 215,288 | <p>I actually had the same issue recently. Namely: we wrote a simple server using BaseHTTPServer and found that the fact that it's not multi-threaded was a big drawback.</p>
<p>My solution was to port the server to Pylons (<a href="http://pylonshq.com/" rel="nofollow">http://pylonshq.com/</a>). The port was fairly easy and one benefit was it's very easy to create a GUI using Pylons so I was able to throw a status page on top of what's basically a daemon process. </p>
<p>I would summarize Pylons this way:</p>
<ul>
<li>it's similar to Ruby on Rails in that it aims to be very easy to deploy web apps</li>
<li>it's default templating language, Mako, is very nice to work with</li>
<li>it uses a system of routing urls that's very convenient</li>
<li>for us performance is not an issue, so I can't guarantee that Pylons would perform adequately for your needs</li>
<li>you can use it with Apache & Lighthttpd, though I've not tried this</li>
</ul>
<p>We also run an app with Twisted and are happy with it. Twisted has good performance, but I find Twisted's single-threaded/defer-to-thread programming model fairly complicated. It has lots of advantages, but would not be my choice for a simple app.</p>
<p>Good luck.</p>
| 1 | 2008-10-18T17:04:14Z | [
"python",
"apache",
"webserver",
"mod-python"
] |
A good multithreaded python webserver? | 213,483 | <p>I am looking for a python webserver which is multithreaded instead of being multi-process (as in case of mod_python for apache). I want it to be multithreaded because I want to have an in memory object cache that will be used by various http threads. My webserver does a lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing. This is not possible in a multi-process web server environment. Storing this information in memcache is also not a good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of IPC.</p>
<p>I implemented a simple webserver using BaseHttpServer, it gives good performance but it gets stuck after a few hours time. I need some more matured webserver. Is it possible to configure apache to use mod_python under a thread model so that I can do some object caching?</p>
| 13 | 2008-10-17T19:12:38Z | 215,292 | <p>web.py has made me happy in the past. Consider checking it out.</p>
<p>But it does sound like an architectural redesign might be the proper, though more expensive, solution.</p>
| 2 | 2008-10-18T17:12:17Z | [
"python",
"apache",
"webserver",
"mod-python"
] |
How to convert a C string (char array) into a Python string when there are non-ASCII characters in the string? | 213,628 | <p>I have embedded a Python interpreter in a C program. Suppose the C program reads some bytes from a file into a char array and learns (somehow) that the bytes represent text with a certain encoding (e.g., ISO 8859-1, Windows-1252, or UTF-8). How do I decode the contents of this char array into a Python string?</p>
<p>The Python string should in general be of type <code>unicode</code>âfor instance, a <code>0x93</code> in Windows-1252 encoded input becomes a <code>u'\u0201c'</code>.</p>
<p>I have attempted to use <code>PyString_Decode</code>, but it always fails when there are non-ASCII characters in the string. Here is an example that fails:</p>
<pre><code>#include <Python.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char c_string[] = { (char)0x93, 0 };
PyObject *py_string;
Py_Initialize();
py_string = PyString_Decode(c_string, 1, "windows_1252", "replace");
if (!py_string) {
PyErr_Print();
return 1;
}
return 0;
}
</code></pre>
<p>The error message is <code>UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 0: ordinal not in range(128)</code>, which indicates that the <code>ascii</code> encoding is used even though we specify <code>windows_1252</code> in the call to <code>PyString_Decode</code>.</p>
<p>The following code works around the problem by using <code>PyString_FromString</code> to create a Python string of the undecoded bytes, then calling its <code>decode</code> method:</p>
<pre><code>#include <Python.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char c_string[] = { (char)0x93, 0 };
PyObject *raw, *decoded;
Py_Initialize();
raw = PyString_FromString(c_string);
printf("Undecoded: ");
PyObject_Print(raw, stdout, 0);
printf("\n");
decoded = PyObject_CallMethod(raw, "decode", "s", "windows_1252");
Py_DECREF(raw);
printf("Decoded: ");
PyObject_Print(decoded, stdout, 0);
printf("\n");
return 0;
}
</code></pre>
| 7 | 2008-10-17T19:58:07Z | 213,639 | <p>You don't want to decode the string into a Unicode representation, you just want to treat it as an array of bytes, right?</p>
<p>Just use <code>PyString_FromString</code>:</p>
<pre><code>char *cstring;
PyObject *pystring = PyString_FromString(cstring);
</code></pre>
<p>That's all. Now you have a Python <code>str()</code> object. See docs here: <a href="https://docs.python.org/2/c-api/string.html" rel="nofollow">https://docs.python.org/2/c-api/string.html</a></p>
<p>I'm a little bit confused about how to specify "str" or "unicode." They are quite different if you have non-ASCII characters. If you want to decode a C string <strong>and</strong> you know exactly what character set it's in, then yes, <code>PyString_DecodeString</code> is a good place to start.</p>
| 3 | 2008-10-17T20:00:47Z | [
"python",
"c",
"character-encoding",
"embedding"
] |
How to convert a C string (char array) into a Python string when there are non-ASCII characters in the string? | 213,628 | <p>I have embedded a Python interpreter in a C program. Suppose the C program reads some bytes from a file into a char array and learns (somehow) that the bytes represent text with a certain encoding (e.g., ISO 8859-1, Windows-1252, or UTF-8). How do I decode the contents of this char array into a Python string?</p>
<p>The Python string should in general be of type <code>unicode</code>âfor instance, a <code>0x93</code> in Windows-1252 encoded input becomes a <code>u'\u0201c'</code>.</p>
<p>I have attempted to use <code>PyString_Decode</code>, but it always fails when there are non-ASCII characters in the string. Here is an example that fails:</p>
<pre><code>#include <Python.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char c_string[] = { (char)0x93, 0 };
PyObject *py_string;
Py_Initialize();
py_string = PyString_Decode(c_string, 1, "windows_1252", "replace");
if (!py_string) {
PyErr_Print();
return 1;
}
return 0;
}
</code></pre>
<p>The error message is <code>UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 0: ordinal not in range(128)</code>, which indicates that the <code>ascii</code> encoding is used even though we specify <code>windows_1252</code> in the call to <code>PyString_Decode</code>.</p>
<p>The following code works around the problem by using <code>PyString_FromString</code> to create a Python string of the undecoded bytes, then calling its <code>decode</code> method:</p>
<pre><code>#include <Python.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char c_string[] = { (char)0x93, 0 };
PyObject *raw, *decoded;
Py_Initialize();
raw = PyString_FromString(c_string);
printf("Undecoded: ");
PyObject_Print(raw, stdout, 0);
printf("\n");
decoded = PyObject_CallMethod(raw, "decode", "s", "windows_1252");
Py_DECREF(raw);
printf("Decoded: ");
PyObject_Print(decoded, stdout, 0);
printf("\n");
return 0;
}
</code></pre>
| 7 | 2008-10-17T19:58:07Z | 213,795 | <p>Try calling <a href="https://docs.python.org/c-api/exceptions.html" rel="nofollow"><code>PyErr_Print()</code></a> in the "<code>if (!py_string)</code>" clause. Perhaps the python exception will give you some more information.</p>
| 2 | 2008-10-17T20:47:20Z | [
"python",
"c",
"character-encoding",
"embedding"
] |
How to convert a C string (char array) into a Python string when there are non-ASCII characters in the string? | 213,628 | <p>I have embedded a Python interpreter in a C program. Suppose the C program reads some bytes from a file into a char array and learns (somehow) that the bytes represent text with a certain encoding (e.g., ISO 8859-1, Windows-1252, or UTF-8). How do I decode the contents of this char array into a Python string?</p>
<p>The Python string should in general be of type <code>unicode</code>âfor instance, a <code>0x93</code> in Windows-1252 encoded input becomes a <code>u'\u0201c'</code>.</p>
<p>I have attempted to use <code>PyString_Decode</code>, but it always fails when there are non-ASCII characters in the string. Here is an example that fails:</p>
<pre><code>#include <Python.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char c_string[] = { (char)0x93, 0 };
PyObject *py_string;
Py_Initialize();
py_string = PyString_Decode(c_string, 1, "windows_1252", "replace");
if (!py_string) {
PyErr_Print();
return 1;
}
return 0;
}
</code></pre>
<p>The error message is <code>UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 0: ordinal not in range(128)</code>, which indicates that the <code>ascii</code> encoding is used even though we specify <code>windows_1252</code> in the call to <code>PyString_Decode</code>.</p>
<p>The following code works around the problem by using <code>PyString_FromString</code> to create a Python string of the undecoded bytes, then calling its <code>decode</code> method:</p>
<pre><code>#include <Python.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char c_string[] = { (char)0x93, 0 };
PyObject *raw, *decoded;
Py_Initialize();
raw = PyString_FromString(c_string);
printf("Undecoded: ");
PyObject_Print(raw, stdout, 0);
printf("\n");
decoded = PyObject_CallMethod(raw, "decode", "s", "windows_1252");
Py_DECREF(raw);
printf("Decoded: ");
PyObject_Print(decoded, stdout, 0);
printf("\n");
return 0;
}
</code></pre>
| 7 | 2008-10-17T19:58:07Z | 215,507 | <p>PyString_Decode does this:</p>
<pre><code>PyObject *PyString_Decode(const char *s,
Py_ssize_t size,
const char *encoding,
const char *errors)
{
PyObject *v, *str;
str = PyString_FromStringAndSize(s, size);
if (str == NULL)
return NULL;
v = PyString_AsDecodedString(str, encoding, errors);
Py_DECREF(str);
return v;
}
</code></pre>
<p>IOW, it does basically what you're doing in your second example - converts to a string, then decode the string. The problem here arises from PyString_AsDecodedString, rather than PyString_AsDecodedObject. PyString_AsDecodedString does PyString_AsDecodedObject, but then tries to convert the resulting unicode object into a string object with the default encoding (for you, looks like that's ASCII). That's where it fails.</p>
<p>I believe you'll need to do two calls - but you can use PyString_AsDecodedObject rather than calling the python "decode" method. Something like:</p>
<pre><code>#include <Python.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char c_string[] = { (char)0x93, 0 };
PyObject *py_string, *py_unicode;
Py_Initialize();
py_string = PyString_FromStringAndSize(c_string, 1);
if (!py_string) {
PyErr_Print();
return 1;
}
py_unicode = PyString_AsDecodedObject(py_string, "windows_1252", "replace");
Py_DECREF(py_string);
return 0;
}
</code></pre>
<p>I'm not entirely sure what the reasoning behind PyString_Decode working this way is. A <a href="http://mail.python.org/pipermail/python-dev/2001-May/014547.html" rel="nofollow">very old thread on python-dev</a> seems to indicate that it has something to do with chaining the output, but since the Python methods don't do the same, I'm not sure if that's still relevant.</p>
| 6 | 2008-10-18T19:59:25Z | [
"python",
"c",
"character-encoding",
"embedding"
] |
Would Python make a good substitute for the Windows command-line/batch scripts? | 213,798 | <p>I've got some experience with <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29">Bash</a>, which I don't mind, but now that I'm doing a lot of Windows development I'm needing to do basic stuff/write basic scripts using
the Windows command-line language. For some reason said language really irritates me, so I was considering learning Python and using that instead.</p>
<p>Is Python suitable for such things? Moving files around, creating scripts to do things like unzipping a backup and restoring a SQL database, etc.</p>
| 20 | 2008-10-17T20:48:26Z | 213,810 | <p>Python is well suited for these tasks, and I would guess much easier to develop in and debug than Windows batch files.</p>
<p>The question is, I think, how easy and painless it is to ensure that all the computers that you have to run these scripts on, have Python installed.</p>
| 17 | 2008-10-17T20:50:57Z | [
"python",
"command-line",
"scripting"
] |
Would Python make a good substitute for the Windows command-line/batch scripts? | 213,798 | <p>I've got some experience with <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29">Bash</a>, which I don't mind, but now that I'm doing a lot of Windows development I'm needing to do basic stuff/write basic scripts using
the Windows command-line language. For some reason said language really irritates me, so I was considering learning Python and using that instead.</p>
<p>Is Python suitable for such things? Moving files around, creating scripts to do things like unzipping a backup and restoring a SQL database, etc.</p>
| 20 | 2008-10-17T20:48:26Z | 213,812 | <p>Are you aware of <a href="http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx" rel="nofollow">PowerShell</a>?</p>
| 4 | 2008-10-17T20:51:13Z | [
"python",
"command-line",
"scripting"
] |
Would Python make a good substitute for the Windows command-line/batch scripts? | 213,798 | <p>I've got some experience with <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29">Bash</a>, which I don't mind, but now that I'm doing a lot of Windows development I'm needing to do basic stuff/write basic scripts using
the Windows command-line language. For some reason said language really irritates me, so I was considering learning Python and using that instead.</p>
<p>Is Python suitable for such things? Moving files around, creating scripts to do things like unzipping a backup and restoring a SQL database, etc.</p>
| 20 | 2008-10-17T20:48:26Z | 213,820 | <p>Sure, python is a pretty good choice for those tasks (I'm sure many will recommend PowerShell instead).</p>
<p>Here is a fine introduction from that point of view:</p>
<p><a href="http://www.redhatmagazine.com/2008/02/07/python-for-bash-scripters-a-well-kept-secret/">http://www.redhatmagazine.com/2008/02/07/python-for-bash-scripters-a-well-kept-secret/</a></p>
<p>EDIT: About gnud's concern: <a href="http://www.portablepython.com/">http://www.portablepython.com/</a></p>
| 7 | 2008-10-17T20:54:39Z | [
"python",
"command-line",
"scripting"
] |
Would Python make a good substitute for the Windows command-line/batch scripts? | 213,798 | <p>I've got some experience with <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29">Bash</a>, which I don't mind, but now that I'm doing a lot of Windows development I'm needing to do basic stuff/write basic scripts using
the Windows command-line language. For some reason said language really irritates me, so I was considering learning Python and using that instead.</p>
<p>Is Python suitable for such things? Moving files around, creating scripts to do things like unzipping a backup and restoring a SQL database, etc.</p>
| 20 | 2008-10-17T20:48:26Z | 213,827 | <p>Python is certainly well suited to that. If you're going down that road, you might also want to investigate <a href="http://scons.org" rel="nofollow">SCons</a> which is a build system itself built with Python. The cool thing is the build scripts are actually full-blown Python scripts themselves, so you can do anything in the build script that you could otherwise do in Python. It makes <code>make</code> look pretty anemic in comparison.</p>
<p>Upon rereading your question, I should note that SCons is more suited to building software projects than to writing system maintenance scripts. But I wouldn't hesitate to recommend Python to you in any case.</p>
| 2 | 2008-10-17T20:57:23Z | [
"python",
"command-line",
"scripting"
] |
Would Python make a good substitute for the Windows command-line/batch scripts? | 213,798 | <p>I've got some experience with <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29">Bash</a>, which I don't mind, but now that I'm doing a lot of Windows development I'm needing to do basic stuff/write basic scripts using
the Windows command-line language. For some reason said language really irritates me, so I was considering learning Python and using that instead.</p>
<p>Is Python suitable for such things? Moving files around, creating scripts to do things like unzipping a backup and restoring a SQL database, etc.</p>
| 20 | 2008-10-17T20:48:26Z | 213,832 | <p>Anything is a good replacement for the Batch file system in windows. Perl, Python, Powershell are all good choices.</p>
| 4 | 2008-10-17T20:59:11Z | [
"python",
"command-line",
"scripting"
] |
Would Python make a good substitute for the Windows command-line/batch scripts? | 213,798 | <p>I've got some experience with <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29">Bash</a>, which I don't mind, but now that I'm doing a lot of Windows development I'm needing to do basic stuff/write basic scripts using
the Windows command-line language. For some reason said language really irritates me, so I was considering learning Python and using that instead.</p>
<p>Is Python suitable for such things? Moving files around, creating scripts to do things like unzipping a backup and restoring a SQL database, etc.</p>
| 20 | 2008-10-17T20:48:26Z | 214,287 | <p>@BKB definitely has a valid concern. Here's a couple links you'll want to check if you run into any issues that can't be solved with the standard library:</p>
<ul>
<li><a href="http://sourceforge.net/projects/pywin32/">Pywin32</a> is a package for working with low-level win32 APIs (advanced file system modifications, COM interfaces, etc.)</li>
<li><a href="http://timgolden.me.uk/python/">Tim Golden's Python page</a>: he maintains a WMI wrapper package that builds off of Pywin32, but be sure to also check out his <a href="http://timgolden.me.uk/python/win32_how_do_i.html">"Win32 How Do I"</a> page for details on how to accomplish typical Windows tasks in Python.</li>
</ul>
| 5 | 2008-10-18T00:45:15Z | [
"python",
"command-line",
"scripting"
] |
Would Python make a good substitute for the Windows command-line/batch scripts? | 213,798 | <p>I've got some experience with <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29">Bash</a>, which I don't mind, but now that I'm doing a lot of Windows development I'm needing to do basic stuff/write basic scripts using
the Windows command-line language. For some reason said language really irritates me, so I was considering learning Python and using that instead.</p>
<p>Is Python suitable for such things? Moving files around, creating scripts to do things like unzipping a backup and restoring a SQL database, etc.</p>
| 20 | 2008-10-17T20:48:26Z | 214,294 | <p>I've been using a lot of <a href="http://msdn.microsoft.com/en-us/library/15x4407c.aspx" rel="nofollow">Windows Script Files</a> lately. More powerful than batch scripts, and since it uses Windows scripting, there's nothing to install.</p>
| 0 | 2008-10-18T00:47:48Z | [
"python",
"command-line",
"scripting"
] |
Would Python make a good substitute for the Windows command-line/batch scripts? | 213,798 | <p>I've got some experience with <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29">Bash</a>, which I don't mind, but now that I'm doing a lot of Windows development I'm needing to do basic stuff/write basic scripts using
the Windows command-line language. For some reason said language really irritates me, so I was considering learning Python and using that instead.</p>
<p>Is Python suitable for such things? Moving files around, creating scripts to do things like unzipping a backup and restoring a SQL database, etc.</p>
| 20 | 2008-10-17T20:48:26Z | 214,333 | <p>Python, along with <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">Pywin32</a>, would be fine for Windows automation. However, VBScript or JScript used with the Winows Scripting Host works just as well, and requires nothing additional to install.</p>
| 1 | 2008-10-18T01:14:20Z | [
"python",
"command-line",
"scripting"
] |
Would Python make a good substitute for the Windows command-line/batch scripts? | 213,798 | <p>I've got some experience with <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29">Bash</a>, which I don't mind, but now that I'm doing a lot of Windows development I'm needing to do basic stuff/write basic scripts using
the Windows command-line language. For some reason said language really irritates me, so I was considering learning Python and using that instead.</p>
<p>Is Python suitable for such things? Moving files around, creating scripts to do things like unzipping a backup and restoring a SQL database, etc.</p>
| 20 | 2008-10-17T20:48:26Z | 214,412 | <p>As much as I love python, I don't think it a good choice to replace basic windows batch scripts. </p>
<p>I can't see see someone having to import modules like sys, os or getopt to do basic things you can do with shell like call a program, check environment variable or an argument.</p>
<p>Also, in my experience, goto is much easier to understand to most sysadmins than a function call.</p>
| -2 | 2008-10-18T02:12:40Z | [
"python",
"command-line",
"scripting"
] |
Would Python make a good substitute for the Windows command-line/batch scripts? | 213,798 | <p>I've got some experience with <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29">Bash</a>, which I don't mind, but now that I'm doing a lot of Windows development I'm needing to do basic stuff/write basic scripts using
the Windows command-line language. For some reason said language really irritates me, so I was considering learning Python and using that instead.</p>
<p>Is Python suitable for such things? Moving files around, creating scripts to do things like unzipping a backup and restoring a SQL database, etc.</p>
| 20 | 2008-10-17T20:48:26Z | 214,428 | <p>I've done a decent amount of scripting in both Linux/Unix and Windows environments, in Python, Perl, batch files, Bash, etc. My advice is that if it's possible, install Cygwin and use Bash (it sounds from your description like installing a scripting language or env isn't a problem?). You'll be more comfortable with that since the transition is minimal.</p>
<p>If that's not an option, then here's my take. Batch files are very kludgy and limited, but make a lot of sense for simple tasks like 'copy some files' or 'restart this service'. Python will be cleaner, easier to maintain, and much more powerful. However, the downside is that either you end up calling external applications from Python with subprocess, popen or similar. Otherwise, you end up writing a bunch more code to do things that are comparatively simple in batch files, like copying a folder full of files. A lot of this depends on what your scripts are doing. Text/string processing is going to be much cleaner in Python, for example.</p>
<p>Lastly, it's probably not an attractive alternative, but you might also consider VBScript as an alternative. I don't enjoy working with it as a language personally, but if portability is any kind of concern then it wins out by virtue of being available out of the box in any copy of Windows. Because of this I've found myself writing scripts that were unwieldy as batch files in VBScript instead, since I can't usually depend on Python or Perl or Bash being available on Windows.</p>
| 0 | 2008-10-18T02:27:51Z | [
"python",
"command-line",
"scripting"
] |
Would Python make a good substitute for the Windows command-line/batch scripts? | 213,798 | <p>I've got some experience with <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29">Bash</a>, which I don't mind, but now that I'm doing a lot of Windows development I'm needing to do basic stuff/write basic scripts using
the Windows command-line language. For some reason said language really irritates me, so I was considering learning Python and using that instead.</p>
<p>Is Python suitable for such things? Moving files around, creating scripts to do things like unzipping a backup and restoring a SQL database, etc.</p>
| 20 | 2008-10-17T20:48:26Z | 216,285 | <h2>Summary</h2>
<p><strong>Windows</strong>: no need to think, use Python.
<strong>Unix</strong>: quick or run-it-once scripts are for Bash, serious and/or long life time scripts are for Python.</p>
<h2>The big talk</h2>
<p>In a Windows environment, Python is definitely the best choice since <a href="http://en.wikipedia.org/wiki/Command_Prompt" rel="nofollow">cmd</a> is crappy and PowerShell has not really settled yet. What's more Python can run on several platform so it's a better investment. Finally, Python has a huge set of library so you will almost never hit the "god-I-can't-do-that" wall. This is not true for cmd and PowerShell.</p>
<p>In a Linux environment, this is a bit different. A lot of one liners are shorter, faster, more efficient and often more readable in pure Bash. But if you know your quick and dirty script is going to stay around for a while or will need to be improved, go for Python since it's far easier to maintain and extend and <a href="http://www.google.fr/url?sa=t&source=web&ct=res&cd=2&url=http%3A%2F%2Fwww.dabeaz.com%2Fgenerators%2FGenerators.pdf&ei=yRn7SJDYCIbS0QXFvq2JDw&usg=AFQjCNE6b1w4feELQFUppm2-GFCzYyd2UQ&sig2=nUjS8CM2Pd77W_HXUq4tRw" rel="nofollow">you will be able to do most of the task you can do with GNU tools with the standard library</a>. And if you can't, you can still call the command-line from a Python script.</p>
<p>And of course you can call Python from the shell using -c option:</p>
<pre><code>python -c "for line in open('/etc/fstab') : print line"
</code></pre>
<p>Some more literature about Python used for system administration tasks:</p>
<ul>
<li><p><a href="http://www.ibm.com/developerworks/aix/library/au-python/" rel="nofollow">The IBM lab point of view</a>.</p></li>
<li><p><a href="http://www.unixreview.com/documents/s=9083/sam0401d/" rel="nofollow">A nice example to compare bash and python to script report</a>.</p></li>
<li><p><a href="http://www.samag.com/documents/s=8964/sam0312a/0312a.htm" rel="nofollow">The basics</a>.</p></li>
<li><p><a href="http://rads.stackoverflow.com/amzn/click/0596515820" rel="nofollow">The must-have book</a>.</p></li>
</ul>
| 9 | 2008-10-19T11:14:49Z | [
"python",
"command-line",
"scripting"
] |
Would Python make a good substitute for the Windows command-line/batch scripts? | 213,798 | <p>I've got some experience with <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29">Bash</a>, which I don't mind, but now that I'm doing a lot of Windows development I'm needing to do basic stuff/write basic scripts using
the Windows command-line language. For some reason said language really irritates me, so I was considering learning Python and using that instead.</p>
<p>Is Python suitable for such things? Moving files around, creating scripts to do things like unzipping a backup and restoring a SQL database, etc.</p>
| 20 | 2008-10-17T20:48:26Z | 496,964 | <p>As a follow up, after some experimentation the thing I've found Python most useful for is any situation involving text manipulation (yourStringHere.replace(), regexes for more complex stuff) or testing some basic concept really quickly, which it is excellent for.</p>
<p>For stuff like SQL DB restore scripts I find I still usually just resort to batch files, as it's usually either something short enough that it actually takes more Python code to make the appropriate system calls or I can reuse snippets of code from other people reducing the writing time to just enough to tweak existing code to fit my needs.</p>
<p>As an addendum I would highly recommend <a href="http://ipython.scipy.org/" rel="nofollow">IPython</a> as a great interactive shell complete with tab completion and easy docstring access.</p>
| 1 | 2009-01-30T19:52:36Z | [
"python",
"command-line",
"scripting"
] |
How to improve Trac's performance | 213,838 | <p>I have noticed that my particular instance of Trac is not running quickly and has big lags. This is at the very onset of a project, so not much is in Trac (except for plugins and code loaded into SVN).</p>
<p><strong>Setup Info:</strong> This is via a SELinux system hosted by WebFaction. It is behind Apache, and connections are over SSL. Currently the .htpasswd file is what I use to control access.</p>
<p>Are there any recommend ways to improve the performance of Trac?</p>
| 3 | 2008-10-17T21:02:43Z | 214,162 | <p>It's hard to say without knowing more about your setup, but one easy win is to make sure that Trac is running in something like <code>mod_python</code>, which keeps the Python runtime in memory. Otherwise, every HTTP request will cause Python to run, import all the modules, and then finally handle the request. Using <code>mod_python</code> (or FastCGI, whichever you prefer) will eliminate that loading and skip straight to the good stuff.</p>
<p>Also, as your Trac database grows and you get more people using the site, you'll probably outgrow the default SQLite database. At that point, you should think about migrating the database to PostgreSQL or MySQL, because they'll be able to handle concurrent requests much faster.</p>
| 5 | 2008-10-17T23:19:49Z | [
"python",
"performance",
"trac"
] |
How to improve Trac's performance | 213,838 | <p>I have noticed that my particular instance of Trac is not running quickly and has big lags. This is at the very onset of a project, so not much is in Trac (except for plugins and code loaded into SVN).</p>
<p><strong>Setup Info:</strong> This is via a SELinux system hosted by WebFaction. It is behind Apache, and connections are over SSL. Currently the .htpasswd file is what I use to control access.</p>
<p>Are there any recommend ways to improve the performance of Trac?</p>
| 3 | 2008-10-17T21:02:43Z | 215,084 | <p>We've had the best luck with FastCGI. Another critical factor was to only use <code>https</code> for authentication but use <code>http</code> for all other traffic -- I was really surprised how much that made a difference.</p>
| 3 | 2008-10-18T14:13:36Z | [
"python",
"performance",
"trac"
] |
How to improve Trac's performance | 213,838 | <p>I have noticed that my particular instance of Trac is not running quickly and has big lags. This is at the very onset of a project, so not much is in Trac (except for plugins and code loaded into SVN).</p>
<p><strong>Setup Info:</strong> This is via a SELinux system hosted by WebFaction. It is behind Apache, and connections are over SSL. Currently the .htpasswd file is what I use to control access.</p>
<p>Are there any recommend ways to improve the performance of Trac?</p>
| 3 | 2008-10-17T21:02:43Z | 636,060 | <p>Serving the chrome files statically with and expires-header could help too. See the end of <a href="http://bannister.us/weblog/2007/07/23/example-of-configuring-trac-and-subversion-on-ubuntu/" rel="nofollow">this page</a>.</p>
| 1 | 2009-03-11T19:48:30Z | [
"python",
"performance",
"trac"
] |
How to improve Trac's performance | 213,838 | <p>I have noticed that my particular instance of Trac is not running quickly and has big lags. This is at the very onset of a project, so not much is in Trac (except for plugins and code loaded into SVN).</p>
<p><strong>Setup Info:</strong> This is via a SELinux system hosted by WebFaction. It is behind Apache, and connections are over SSL. Currently the .htpasswd file is what I use to control access.</p>
<p>Are there any recommend ways to improve the performance of Trac?</p>
| 3 | 2008-10-17T21:02:43Z | 806,271 | <p>I have noticed that if </p>
<pre><code>select disctinct name from wiki
</code></pre>
<p>takes more than 5 seconds (for example due to a million rows in this table - this is a true story (We had a script that filled it)), browsing wiki pages becomes very slow and takes over <code>2*t*n</code>, where <code>t</code> is time of execution of the quoted query (>5s of course), and <code>n</code> is a number of tracwiki links present on the viewed page.
This is due to trac having a (hardcoded) 5s cache expire for this query. It is used by trac to tell what the colour should the link be. We re-hardcoded the value to 30s (We need that many pages, so every 30s someone has to wait 6-7s).</p>
<p>It may not be what caused Your problem, but it may be. Good luck on speeding up Your Trac instance.</p>
| 2 | 2009-04-30T10:13:03Z | [
"python",
"performance",
"trac"
] |
How can I write a wrapper around ngrep that highlights matches? | 214,059 | <p>I just learned about <a href="http://ngrep.sourceforge.net/" rel="nofollow">ngrep</a>, a cool program that lets you easily sniff packets that match a particular string.</p>
<p>The only problem is that it can be hard to see the match in the big blob of output. I'd like to write a wrapper script to highlight these matches -- it could use ANSI escape sequences:</p>
<pre><code>echo -e 'This is \e[31mRED\e[0m.'
</code></pre>
<p>I'm most familiar with Perl, but I'm perfectly happy with a solution in Python or any other language. The simplest approach would be something like:</p>
<pre><code>while (<STDIN>) {
s/$keyword/\e[31m$keyword\e[0m/g;
print;
}
</code></pre>
<p>However, this isn't a nice solution, because ngrep prints out hash marks without newlines whenever it receives a non-matching packet, and the code above will suppress the printing of these hashmarks until the script sees a newline.</p>
<p>Is there any way to do the highlighting without inhibiting the instant appearance of the hashmarks?</p>
| 2 | 2008-10-17T22:32:58Z | 214,149 | <p>It shouldn't be too hard if you have the answer <a href="http://stackoverflow.com/questions/213901/in-perl-how-do-i-process-input-as-soon-as-it-arrives-instead-of-waiting-for-new">this question</a>.</p>
<p>(Essentially, read one character at a time and if it's a hash, print it. If it isn't a hash, save the character to print out later.)</p>
| 1 | 2008-10-17T23:12:53Z | [
"python",
"perl",
"unix",
"networking"
] |
How can I write a wrapper around ngrep that highlights matches? | 214,059 | <p>I just learned about <a href="http://ngrep.sourceforge.net/" rel="nofollow">ngrep</a>, a cool program that lets you easily sniff packets that match a particular string.</p>
<p>The only problem is that it can be hard to see the match in the big blob of output. I'd like to write a wrapper script to highlight these matches -- it could use ANSI escape sequences:</p>
<pre><code>echo -e 'This is \e[31mRED\e[0m.'
</code></pre>
<p>I'm most familiar with Perl, but I'm perfectly happy with a solution in Python or any other language. The simplest approach would be something like:</p>
<pre><code>while (<STDIN>) {
s/$keyword/\e[31m$keyword\e[0m/g;
print;
}
</code></pre>
<p>However, this isn't a nice solution, because ngrep prints out hash marks without newlines whenever it receives a non-matching packet, and the code above will suppress the printing of these hashmarks until the script sees a newline.</p>
<p>Is there any way to do the highlighting without inhibiting the instant appearance of the hashmarks?</p>
| 2 | 2008-10-17T22:32:58Z | 214,186 | <p>Ah, forget it. This is too much of a pain. It was a lot easier to get the source to ngrep and make it print the hash marks to stderr:</p>
<pre><code>--- ngrep.c 2006-11-28 05:38:43.000000000 -0800
+++ ngrep.c.new 2008-10-17 16:28:29.000000000 -0700
@@ -687,8 +687,7 @@
}
if (quiet < 1) {
- printf("#");
- fflush(stdout);
+ fprintf (stderr, "#");
}
switch (ip_proto) {
</code></pre>
<p>Then, filtering is a piece of cake:</p>
<pre><code>while (<CMD>) {
s/($keyword)/\e[93m$1\e[0m/g;
print;
}
</code></pre>
| 3 | 2008-10-17T23:30:24Z | [
"python",
"perl",
"unix",
"networking"
] |
How can I write a wrapper around ngrep that highlights matches? | 214,059 | <p>I just learned about <a href="http://ngrep.sourceforge.net/" rel="nofollow">ngrep</a>, a cool program that lets you easily sniff packets that match a particular string.</p>
<p>The only problem is that it can be hard to see the match in the big blob of output. I'd like to write a wrapper script to highlight these matches -- it could use ANSI escape sequences:</p>
<pre><code>echo -e 'This is \e[31mRED\e[0m.'
</code></pre>
<p>I'm most familiar with Perl, but I'm perfectly happy with a solution in Python or any other language. The simplest approach would be something like:</p>
<pre><code>while (<STDIN>) {
s/$keyword/\e[31m$keyword\e[0m/g;
print;
}
</code></pre>
<p>However, this isn't a nice solution, because ngrep prints out hash marks without newlines whenever it receives a non-matching packet, and the code above will suppress the printing of these hashmarks until the script sees a newline.</p>
<p>Is there any way to do the highlighting without inhibiting the instant appearance of the hashmarks?</p>
| 2 | 2008-10-17T22:32:58Z | 214,198 | <p>This is easy in python.</p>
<pre><code>#!/usr/bin/env python
import sys, re
keyword = 'RED'
while 1:
c = sys.stdin.read(1)
if not c:
break
if c in '#\n':
sys.stdout.write(c)
else:
sys.stdout.write(
(c+sys.stdin.readline()).replace(
keyword, '\x1b[31m%s\x1b[0m\r' % keyword))
</code></pre>
| 0 | 2008-10-17T23:40:02Z | [
"python",
"perl",
"unix",
"networking"
] |
How can I write a wrapper around ngrep that highlights matches? | 214,059 | <p>I just learned about <a href="http://ngrep.sourceforge.net/" rel="nofollow">ngrep</a>, a cool program that lets you easily sniff packets that match a particular string.</p>
<p>The only problem is that it can be hard to see the match in the big blob of output. I'd like to write a wrapper script to highlight these matches -- it could use ANSI escape sequences:</p>
<pre><code>echo -e 'This is \e[31mRED\e[0m.'
</code></pre>
<p>I'm most familiar with Perl, but I'm perfectly happy with a solution in Python or any other language. The simplest approach would be something like:</p>
<pre><code>while (<STDIN>) {
s/$keyword/\e[31m$keyword\e[0m/g;
print;
}
</code></pre>
<p>However, this isn't a nice solution, because ngrep prints out hash marks without newlines whenever it receives a non-matching packet, and the code above will suppress the printing of these hashmarks until the script sees a newline.</p>
<p>Is there any way to do the highlighting without inhibiting the instant appearance of the hashmarks?</p>
| 2 | 2008-10-17T22:32:58Z | 214,557 | <p>You could also pipe the output through <a href="http://petdance.com/ack/" rel="nofollow">ack</a>. The --passthru flag will help.</p>
| 3 | 2008-10-18T04:13:42Z | [
"python",
"perl",
"unix",
"networking"
] |
How can I write a wrapper around ngrep that highlights matches? | 214,059 | <p>I just learned about <a href="http://ngrep.sourceforge.net/" rel="nofollow">ngrep</a>, a cool program that lets you easily sniff packets that match a particular string.</p>
<p>The only problem is that it can be hard to see the match in the big blob of output. I'd like to write a wrapper script to highlight these matches -- it could use ANSI escape sequences:</p>
<pre><code>echo -e 'This is \e[31mRED\e[0m.'
</code></pre>
<p>I'm most familiar with Perl, but I'm perfectly happy with a solution in Python or any other language. The simplest approach would be something like:</p>
<pre><code>while (<STDIN>) {
s/$keyword/\e[31m$keyword\e[0m/g;
print;
}
</code></pre>
<p>However, this isn't a nice solution, because ngrep prints out hash marks without newlines whenever it receives a non-matching packet, and the code above will suppress the printing of these hashmarks until the script sees a newline.</p>
<p>Is there any way to do the highlighting without inhibiting the instant appearance of the hashmarks?</p>
| 2 | 2008-10-17T22:32:58Z | 214,635 | <p>See the script at <a href="http://www.mail-archive.com/[email protected]/msg52876.html" rel="nofollow">this post to Linux-IL where someone asked a similar question</a>. It's written in Perl and uses the CPAN Term::ANSIColor module.</p>
| -1 | 2008-10-18T05:30:13Z | [
"python",
"perl",
"unix",
"networking"
] |
How can I write a wrapper around ngrep that highlights matches? | 214,059 | <p>I just learned about <a href="http://ngrep.sourceforge.net/" rel="nofollow">ngrep</a>, a cool program that lets you easily sniff packets that match a particular string.</p>
<p>The only problem is that it can be hard to see the match in the big blob of output. I'd like to write a wrapper script to highlight these matches -- it could use ANSI escape sequences:</p>
<pre><code>echo -e 'This is \e[31mRED\e[0m.'
</code></pre>
<p>I'm most familiar with Perl, but I'm perfectly happy with a solution in Python or any other language. The simplest approach would be something like:</p>
<pre><code>while (<STDIN>) {
s/$keyword/\e[31m$keyword\e[0m/g;
print;
}
</code></pre>
<p>However, this isn't a nice solution, because ngrep prints out hash marks without newlines whenever it receives a non-matching packet, and the code above will suppress the printing of these hashmarks until the script sees a newline.</p>
<p>Is there any way to do the highlighting without inhibiting the instant appearance of the hashmarks?</p>
| 2 | 2008-10-17T22:32:58Z | 214,782 | <p>This seems to do the trick, at least comparing two windows, one running a straight ngrep (e.g. ngrep whatever) and one being piped into the following program (with ngrep whatever | ngrephl target-string).</p>
<pre><code>#! /usr/bin/perl
use strict;
use warnings;
$| = 1; # autoflush on
my $keyword = shift or die "No pattern specified\n";
my $cache = '';
while (read STDIN, my $ch, 1) {
if ($ch eq '#') {
$cache =~ s/($keyword)/\e[31m$1\e[0m/g;
syswrite STDOUT, "$cache$ch";
$cache = '';
}
else {
$cache .= $ch;
}
}
</code></pre>
| 4 | 2008-10-18T08:57:37Z | [
"python",
"perl",
"unix",
"networking"
] |
How can I write a wrapper around ngrep that highlights matches? | 214,059 | <p>I just learned about <a href="http://ngrep.sourceforge.net/" rel="nofollow">ngrep</a>, a cool program that lets you easily sniff packets that match a particular string.</p>
<p>The only problem is that it can be hard to see the match in the big blob of output. I'd like to write a wrapper script to highlight these matches -- it could use ANSI escape sequences:</p>
<pre><code>echo -e 'This is \e[31mRED\e[0m.'
</code></pre>
<p>I'm most familiar with Perl, but I'm perfectly happy with a solution in Python or any other language. The simplest approach would be something like:</p>
<pre><code>while (<STDIN>) {
s/$keyword/\e[31m$keyword\e[0m/g;
print;
}
</code></pre>
<p>However, this isn't a nice solution, because ngrep prints out hash marks without newlines whenever it receives a non-matching packet, and the code above will suppress the printing of these hashmarks until the script sees a newline.</p>
<p>Is there any way to do the highlighting without inhibiting the instant appearance of the hashmarks?</p>
| 2 | 2008-10-17T22:32:58Z | 513,068 | <p>why not just call ngrep with the -q parameter to eliminate the hash marks?</p>
| 0 | 2009-02-04T20:08:55Z | [
"python",
"perl",
"unix",
"networking"
] |
Using trellis as a framework for managing UI interaction rules | 214,430 | <p>Does anyone have experience with <a href="http://pypi.python.org/pypi/Trellis" rel="nofollow">trellis</a>? Looking at it as a framework for defining rules for field interaction and validation in grids and data entry screens.</p>
| 1 | 2008-10-18T02:29:02Z | 3,280,594 | <p>It seems this project has died. No new stuff to the page has been added to it since your question. Also I think that new language features in Python 2.6 and Python 3 are removing the need of some of the offered constructs.</p>
| 1 | 2010-07-19T11:23:55Z | [
"python",
"user-interface"
] |
Python templates for web designers | 214,536 | <p>What are some good templating engines for web designers? I definitely have my preferences as to what I'd prefer to work with as a programmer. But web designers seem to have a different way of thinking about things and thus may prefer a different system.</p>
<p>So:</p>
<ul>
<li>Web designers: what templating engine do you prefer to work with?</li>
<li>programmers: what templating engines have you worked with that made working with web designers easy?</li>
</ul>
| 5 | 2008-10-18T03:56:06Z | 214,665 | <p>I personally found <a href="http://www.cheetahtemplate.org/" rel="nofollow">Cheetah templates</a> to be very designer-friendly. What needed some time was the idea of templates subclassing, and this was something hard to get at the beginning. But a designer creates a full template, duplicating his code... Then you can go clean things up a bit.</p>
| 2 | 2008-10-18T06:14:20Z | [
"python",
"templating"
] |
Python templates for web designers | 214,536 | <p>What are some good templating engines for web designers? I definitely have my preferences as to what I'd prefer to work with as a programmer. But web designers seem to have a different way of thinking about things and thus may prefer a different system.</p>
<p>So:</p>
<ul>
<li>Web designers: what templating engine do you prefer to work with?</li>
<li>programmers: what templating engines have you worked with that made working with web designers easy?</li>
</ul>
| 5 | 2008-10-18T03:56:06Z | 214,666 | <p><a href="http://docs.djangoproject.com/en/dev/topics/templates/#topics-templates" rel="nofollow">Django's templating engine</a> is quite decent. It's pretty robust while not stepping on too many toes. If you're working with Python I would recommend it. I don't know how to divorce it from Django, but I doubt it would be very difficult seeing as Django is quite modular.</p>
<p><strong>EDIT:</strong> Apparently the <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#configuring-the-template-system-in-standalone-mode" rel="nofollow">mini-guide to using Django's templating engine standalone</a> was sitting in front of me already, thanks <a href="http://stackoverflow.com/users/6760/insin">insin</a>.</p>
| 6 | 2008-10-18T06:14:36Z | [
"python",
"templating"
] |
Python templates for web designers | 214,536 | <p>What are some good templating engines for web designers? I definitely have my preferences as to what I'd prefer to work with as a programmer. But web designers seem to have a different way of thinking about things and thus may prefer a different system.</p>
<p>So:</p>
<ul>
<li>Web designers: what templating engine do you prefer to work with?</li>
<li>programmers: what templating engines have you worked with that made working with web designers easy?</li>
</ul>
| 5 | 2008-10-18T03:56:06Z | 214,932 | <p>Look at <a href="http://www.makotemplates.org/">Mako</a>.</p>
<p>Here's how I cope with web designers.</p>
<ol>
<li>Ask them to mock up the page. In HTML.</li>
<li>Use the HTML as the basis for the template, replacing the mocked-up content with <code>${...}</code> replacements.</li>
<li>Fold in loops to handle repeats.</li>
</ol>
<p>The use of if-statements requires negotiation, since the mock-up is one version of the page, and there are usually some explanations for conditional presentation of some material.</p>
| 5 | 2008-10-18T11:35:15Z | [
"python",
"templating"
] |
Python templates for web designers | 214,536 | <p>What are some good templating engines for web designers? I definitely have my preferences as to what I'd prefer to work with as a programmer. But web designers seem to have a different way of thinking about things and thus may prefer a different system.</p>
<p>So:</p>
<ul>
<li>Web designers: what templating engine do you prefer to work with?</li>
<li>programmers: what templating engines have you worked with that made working with web designers easy?</li>
</ul>
| 5 | 2008-10-18T03:56:06Z | 214,956 | <p>I had good votes when <a href="http://stackoverflow.com/questions/98245/what-is-your-single-favorite-python-templating-engine#98285">answering this same question's duplicate</a>.</p>
<p>My answer was:</p>
<p><a href="http://jinja.pocoo.org/2">Jinja2</a>.</p>
<p>Nice <a href="http://jinja.pocoo.org/2/documentation/templates">syntax</a>, good <a href="http://jinja.pocoo.org/2/documentation/extensions.html">customization possibilities</a>. </p>
<p>Integrates well. Can be sandboxed, so you don't have to trust completely your template authors. (Mako can't).</p>
<p>It is also pretty fast, with the bonus of compiling your template to bytecode and cache it, as in the demonstration below:</p>
<pre><code>>>> import jinja2
>>> print jinja2.Environment().compile('{% for row in data %}{{ row.name | upper }}{% endfor %}', raw=True)
from __future__ import division
from jinja2.runtime import LoopContext, Context, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_join
name = None
def root(context, environment=environment):
l_data = context.resolve('data')
t_1 = environment.filters['upper']
if 0: yield None
for l_row in l_data:
if 0: yield None
yield unicode(t_1(environment.getattr(l_row, 'name')))
blocks = {}
debug_info = '1=9'
</code></pre>
<p>This code has been generated on the fly by Jinja2. Of course the compiler optmizes it further (e.g. removing <code>if 0: yield None</code>)</p>
| 6 | 2008-10-18T12:00:40Z | [
"python",
"templating"
] |
Python templates for web designers | 214,536 | <p>What are some good templating engines for web designers? I definitely have my preferences as to what I'd prefer to work with as a programmer. But web designers seem to have a different way of thinking about things and thus may prefer a different system.</p>
<p>So:</p>
<ul>
<li>Web designers: what templating engine do you prefer to work with?</li>
<li>programmers: what templating engines have you worked with that made working with web designers easy?</li>
</ul>
| 5 | 2008-10-18T03:56:06Z | 214,972 | <p>Mi vote goes to <a href="http://www.clearsilver.net/" rel="nofollow">Clearsilver</a>, it is the template engine used in Trac before 0.11, it's also used in pages like Google Groups or Orkut. The main benefits of this template engine is that it's very fast and language-independent.</p>
| 1 | 2008-10-18T12:25:04Z | [
"python",
"templating"
] |
Python templates for web designers | 214,536 | <p>What are some good templating engines for web designers? I definitely have my preferences as to what I'd prefer to work with as a programmer. But web designers seem to have a different way of thinking about things and thus may prefer a different system.</p>
<p>So:</p>
<ul>
<li>Web designers: what templating engine do you prefer to work with?</li>
<li>programmers: what templating engines have you worked with that made working with web designers easy?</li>
</ul>
| 5 | 2008-10-18T03:56:06Z | 215,300 | <p>To add to @Jaime Soriano's comment, <a href="http://genshi.edgewall.org/" rel="nofollow">Genshi</a> is the template engine used in Trac post- 0.11. It's can be used as a generic templating solution, but has a focus on HTML/XHTML. It has automatic escaping for reducing XSS vulnerabilities.</p>
| 2 | 2008-10-18T17:24:16Z | [
"python",
"templating"
] |
Python templates for web designers | 214,536 | <p>What are some good templating engines for web designers? I definitely have my preferences as to what I'd prefer to work with as a programmer. But web designers seem to have a different way of thinking about things and thus may prefer a different system.</p>
<p>So:</p>
<ul>
<li>Web designers: what templating engine do you prefer to work with?</li>
<li>programmers: what templating engines have you worked with that made working with web designers easy?</li>
</ul>
| 5 | 2008-10-18T03:56:06Z | 215,700 | <p>I've played both roles and at heart I prefer more of a programmer's templating language. However, I freelance for a few graphic designers doing the "heavy lifting" backed and db programming and can tell you that I've had the best luck with XML templating languages (SimpleTAL, Genshi, etc). </p>
<p>When I'm trying to be web designer friendly I look for something that can be loaded into Dreamweaver and see results. This allows me to provide all the hooks in a template and let the designer tweak it without worrying about breaking what I've already written. It allows us to share the code and work better together where we're both comfortable with the format. </p>
<p>If the designer codes without a WYSIWYG editor, I think you're options are less limited and you could go with your own personal favorite.</p>
| 1 | 2008-10-18T23:16:03Z | [
"python",
"templating"
] |
How to create a numpy record array from C | 214,549 | <p>On the Python side, I can create new numpy record arrays as follows:</p>
<pre><code>numpy.zeros((3,), dtype=[('a', 'i4'), ('b', 'U5')])
</code></pre>
<p>How do I do the same from a C program? I suppose I have to call <code>PyArray_SimpleNewFromDescr(nd, dims, descr)</code>, but how do I construct a <code>PyArray_Descr</code> that is appropriate for passing as the third argument to <code>PyArray_SimpleNewFromDescr</code>?</p>
| 7 | 2008-10-18T04:03:35Z | 214,574 | <p>See the <a href="http://csc.ucdavis.edu/~chaos/courses/nlp/Software/NumPyBook.pdf" rel="nofollow">Guide to NumPy</a>, section 13.3.10. There's lots of different ways to make a descriptor, although it's not nearly as easy as writing <code>[('a', 'i4'), ('b', 'U5')]</code>.</p>
| 4 | 2008-10-18T04:33:02Z | [
"python",
"c",
"numpy"
] |
How to create a numpy record array from C | 214,549 | <p>On the Python side, I can create new numpy record arrays as follows:</p>
<pre><code>numpy.zeros((3,), dtype=[('a', 'i4'), ('b', 'U5')])
</code></pre>
<p>How do I do the same from a C program? I suppose I have to call <code>PyArray_SimpleNewFromDescr(nd, dims, descr)</code>, but how do I construct a <code>PyArray_Descr</code> that is appropriate for passing as the third argument to <code>PyArray_SimpleNewFromDescr</code>?</p>
| 7 | 2008-10-18T04:03:35Z | 215,090 | <p>Use <code>PyArray_DescrConverter</code>. Here's an example:</p>
<pre><code>#include <Python.h>
#include <stdio.h>
#include <numpy/arrayobject.h>
int main(int argc, char *argv[])
{
int dims[] = { 2, 3 };
PyObject *op, *array;
PyArray_Descr *descr;
Py_Initialize();
import_array();
op = Py_BuildValue("[(s, s), (s, s)]", "a", "i4", "b", "U5");
PyArray_DescrConverter(op, &descr);
Py_DECREF(op);
array = PyArray_SimpleNewFromDescr(2, dims, descr);
PyObject_Print(array, stdout, 0);
printf("\n");
Py_DECREF(array);
return 0;
}
</code></pre>
<p>Thanks to <a href="http://stackoverflow.com/users/9530/adam-rosenfield">Adam Rosenfield</a> for pointing to Section 13.3.10 of the <a href="http://numpy.scipy.org/numpybook.pdf">Guide to NumPy</a>.</p>
| 8 | 2008-10-18T14:19:14Z | [
"python",
"c",
"numpy"
] |
How do you convert YYYY-MM-DDTHH:mm:ss.000Z time format to MM/DD/YYYY time format in Python? | 214,777 | <p>For example, I'm trying to convert 2008-09-26T01:51:42.000Z to 09/26/2008. What's the simplest way of accomplishing this?</p>
| 18 | 2008-10-18T08:53:02Z | 214,786 | <pre><code>>>> import time
>>> timestamp = "2008-09-26T01:51:42.000Z"
>>> ts = time.strptime(timestamp[:19], "%Y-%m-%dT%H:%M:%S")
>>> time.strftime("%m/%d/%Y", ts)
'09/26/2008'
</code></pre>
<p>See the documentation of the Python <a href="http://python.org/doc/2.5/lib/module-time.html"><code>time</code></a> module for more information.</p>
| 14 | 2008-10-18T09:01:59Z | [
"python",
"datetime"
] |
How do you convert YYYY-MM-DDTHH:mm:ss.000Z time format to MM/DD/YYYY time format in Python? | 214,777 | <p>For example, I'm trying to convert 2008-09-26T01:51:42.000Z to 09/26/2008. What's the simplest way of accomplishing this?</p>
| 18 | 2008-10-18T08:53:02Z | 215,083 | <p><code>2008-09-26T01:51:42.000Z</code> is an ISO8601 date and the format can be very diverse. If you want to parse these dates see the python wiki on <a href="http://wiki.python.org/moin/WorkingWithTime" rel="nofollow">working with time</a>. It contains some useful links to modules.</p>
| 2 | 2008-10-18T14:13:19Z | [
"python",
"datetime"
] |
How do you convert YYYY-MM-DDTHH:mm:ss.000Z time format to MM/DD/YYYY time format in Python? | 214,777 | <p>For example, I'm trying to convert 2008-09-26T01:51:42.000Z to 09/26/2008. What's the simplest way of accomplishing this?</p>
| 18 | 2008-10-18T08:53:02Z | 215,313 | <p>The easiest way is to use <a href="http://labix.org/python-dateutil">dateutil</a>.parser.parse() to parse the date string into a timezone aware datetime object, then use strftime() to get the format you want.</p>
<pre><code>import datetime, dateutil.parser
d = dateutil.parser.parse('2008-09-26T01:51:42.000Z')
print d.strftime('%m/%d/%Y') #==> '09/26/2008'
</code></pre>
| 24 | 2008-10-18T17:33:30Z | [
"python",
"datetime"
] |
How do you convert YYYY-MM-DDTHH:mm:ss.000Z time format to MM/DD/YYYY time format in Python? | 214,777 | <p>For example, I'm trying to convert 2008-09-26T01:51:42.000Z to 09/26/2008. What's the simplest way of accomplishing this?</p>
| 18 | 2008-10-18T08:53:02Z | 2,904,561 | <pre><code>def datechange(datestr):
dateobj=datestr.split('-')
y=dateobj[0]
m=dateobj[1]
d=dateobj[2]
datestr=d +'-'+ m +'-'+y
return datestr
</code></pre>
<p>U can make a function like this which take date object andd returns you date in desired dateFormat....</p>
| 0 | 2010-05-25T12:32:41Z | [
"python",
"datetime"
] |
How do you convert YYYY-MM-DDTHH:mm:ss.000Z time format to MM/DD/YYYY time format in Python? | 214,777 | <p>For example, I'm trying to convert 2008-09-26T01:51:42.000Z to 09/26/2008. What's the simplest way of accomplishing this?</p>
| 18 | 2008-10-18T08:53:02Z | 39,155,014 | <p>I know this is really old question, but you can do it with python datetime.strptime()</p>
<pre><code>>>> from datetime import datetime
>>> date_format = "%Y-%m-%dT%H:%M:%S.%fZ"
>>> datetime.strptime('2008-09-26T01:51:42.000Z', date_format)
datetime.datetime(2008, 9, 26, 1, 51, 42)
</code></pre>
| 1 | 2016-08-25T21:30:54Z | [
"python",
"datetime"
] |
python module dlls | 214,852 | <p>Is there a way to make a python module load a dll in my application directory rather than the version that came with the python installation, without making changes to the python installation (which would then require I made an installer, and be careful I didn't break other apps for people by overwrting python modules and changing dll versions globaly...)?</p>
<p>Specifically I would like python to use my version of the sqlite3.dll, rather than the version that came with python (which is older and doesn't appear to have the fts3 module).</p>
| 11 | 2008-10-18T10:17:58Z | 214,855 | <p>If your version of sqlite is in sys.path <em>before</em> the systems version it will use that. So you can either put it in the current directory or change the <code>PYTHONPATH</code> environment variable to do that.</p>
| 0 | 2008-10-18T10:20:18Z | [
"python",
"module"
] |
python module dlls | 214,852 | <p>Is there a way to make a python module load a dll in my application directory rather than the version that came with the python installation, without making changes to the python installation (which would then require I made an installer, and be careful I didn't break other apps for people by overwrting python modules and changing dll versions globaly...)?</p>
<p>Specifically I would like python to use my version of the sqlite3.dll, rather than the version that came with python (which is older and doesn't appear to have the fts3 module).</p>
| 11 | 2008-10-18T10:17:58Z | 214,868 | <p>If you're talking about Python module DLLs, then simply modifying <code>sys.path</code> should be fine. However, if you're talking about DLLs <em>linked</em> against those DLLs; i.e. a <code>libfoo.dll</code> which a <code>foo.pyd</code> depends on, then you need to modify your PATH environment variable. I wrote about <a href="http://glyf.livejournal.com/7878.html">doing this for PyGTK a while ago</a>, but in your case I think it should be as simple as:</p>
<pre><code>import os
os.environ['PATH'] = 'my-app-dir' + ';' + os.environ['PATH']
</code></pre>
<p>That will insert <code>my-app-dir</code> at the head of your Windows path, which I believe also controls the load-order for DLLs.</p>
<p>Keep in mind that you will need to do this before loading the DLL in question, i.e., before importing anything interesting.</p>
<p>sqlite3 may be a bit of a special case, though, since it is distributed with Python; it's obviously kind of tricky to test this quickly, so I haven't checked <code>sqlite3.dll</code> specifically.</p>
| 14 | 2008-10-18T10:33:08Z | [
"python",
"module"
] |
python module dlls | 214,852 | <p>Is there a way to make a python module load a dll in my application directory rather than the version that came with the python installation, without making changes to the python installation (which would then require I made an installer, and be careful I didn't break other apps for people by overwrting python modules and changing dll versions globaly...)?</p>
<p>Specifically I would like python to use my version of the sqlite3.dll, rather than the version that came with python (which is older and doesn't appear to have the fts3 module).</p>
| 11 | 2008-10-18T10:17:58Z | 214,901 | <p>Ok it terns out python always loads the dll in the same directory as the pyd file, regardless of what the python and os paths are set to.</p>
<p>So I needed to copy the _sqlite3.pyd from python/v2.5/DLLS to my apps directory where the new sqlite3.dll is, making it load my new dll, rather than the one that comes with python (since the pyd files seem to follow the PYTHONPATH, even though the actaul dlls themselves dont).</p>
| 5 | 2008-10-18T11:04:43Z | [
"python",
"module"
] |
Can you add new statements to Python's syntax? | 214,881 | <p>Can you add new statements (like <code>print</code>, <code>raise</code>, <code>with</code>) to Python's syntax?</p>
<p>Say, to allow..</p>
<pre><code>mystatement "Something"
</code></pre>
<p>Or,</p>
<pre><code>new_if True:
print "example"
</code></pre>
<p>Not so much if you <em>should</em>, but rather if it's possible (short of modifying the python interpreters code)</p>
| 72 | 2008-10-18T10:47:21Z | 214,902 | <p>Ten years ago you couldn't, and I doubt that's changed. However, it wasn't that hard to modify the syntax back then if you were prepared to recompile python, and I doubt that's changed, either.</p>
| 0 | 2008-10-18T11:10:15Z | [
"python",
"syntax"
] |
Can you add new statements to Python's syntax? | 214,881 | <p>Can you add new statements (like <code>print</code>, <code>raise</code>, <code>with</code>) to Python's syntax?</p>
<p>Say, to allow..</p>
<pre><code>mystatement "Something"
</code></pre>
<p>Or,</p>
<pre><code>new_if True:
print "example"
</code></pre>
<p>Not so much if you <em>should</em>, but rather if it's possible (short of modifying the python interpreters code)</p>
| 72 | 2008-10-18T10:47:21Z | 214,910 | <p>Short of changing and recompiling the source code (which <em>is</em> possible with open source), changing the base language is not really possible.</p>
<p>Even if you do recompile the source, it wouldn't be python, just your hacked-up changed version which you need to be very careful not to introduce bugs into.</p>
<p>However, I'm not sure why you'd want to. Python's object-oriented features makes it quite simple to achieve similar results with the language as it stands.</p>
| 12 | 2008-10-18T11:16:45Z | [
"python",
"syntax"
] |
Can you add new statements to Python's syntax? | 214,881 | <p>Can you add new statements (like <code>print</code>, <code>raise</code>, <code>with</code>) to Python's syntax?</p>
<p>Say, to allow..</p>
<pre><code>mystatement "Something"
</code></pre>
<p>Or,</p>
<pre><code>new_if True:
print "example"
</code></pre>
<p>Not so much if you <em>should</em>, but rather if it's possible (short of modifying the python interpreters code)</p>
| 72 | 2008-10-18T10:47:21Z | 214,912 | <p>Not without modifying the interpreter. I know a lot of languages in the past several years have been described as "extensible", but not in the way you're describing. You extend Python by adding functions and classes.</p>
| 2 | 2008-10-18T11:18:17Z | [
"python",
"syntax"
] |
Can you add new statements to Python's syntax? | 214,881 | <p>Can you add new statements (like <code>print</code>, <code>raise</code>, <code>with</code>) to Python's syntax?</p>
<p>Say, to allow..</p>
<pre><code>mystatement "Something"
</code></pre>
<p>Or,</p>
<pre><code>new_if True:
print "example"
</code></pre>
<p>Not so much if you <em>should</em>, but rather if it's possible (short of modifying the python interpreters code)</p>
| 72 | 2008-10-18T10:47:21Z | 215,042 | <p>I've found a guide on adding new statements, converted from PDF to HTML by Google:</p>
<p><a href="http://209.85.173.104/search?q=cache:IjUb82taSq0J:www.troeger.eu/teaching/pythonvm08lab.pdf+python+add+statement&hl=en&ct=clnk&cd=10">http://209.85.173.104/search?q=cache:IjUb82taSq0J:www.troeger.eu/teaching/pythonvm08lab.pdf+python+add+statement&hl=en&ct=clnk&cd=10</a></p>
<p>Basically, to add new statements, you must edit <code>Python/ast.c</code> (among other things) and recompile the python binary.</p>
<p>While it's possible, don't. You can achieve almost everything via functions and classes (which wont require people to recompile python just to run your script..)</p>
| 5 | 2008-10-18T13:26:37Z | [
"python",
"syntax"
] |
Can you add new statements to Python's syntax? | 214,881 | <p>Can you add new statements (like <code>print</code>, <code>raise</code>, <code>with</code>) to Python's syntax?</p>
<p>Say, to allow..</p>
<pre><code>mystatement "Something"
</code></pre>
<p>Or,</p>
<pre><code>new_if True:
print "example"
</code></pre>
<p>Not so much if you <em>should</em>, but rather if it's possible (short of modifying the python interpreters code)</p>
| 72 | 2008-10-18T10:47:21Z | 215,697 | <p>One way to do things like this is to preprocess the source and modify it, translating your added statement to python. There are various problems this approach will bring, and I wouldn't recommend it for general usage, but for experimentation with language, or specific-purpose metaprogramming, it can occassionally be useful.</p>
<p>For instance, lets say we want to introduce a "myprint" statement, that instead of printing to the screen instead logs to a specific file. ie:</p>
<pre><code>myprint "This gets logged to file"
</code></pre>
<p>would be equivalent to</p>
<pre><code>print >>open('/tmp/logfile.txt','a'), "This gets logged to file"
</code></pre>
<p>There are various options as to how to do the replacing, from regex substitution to generating an AST, to writing your own parser depending on how close your syntax matches existing python. A good intermediate approach is to use the tokenizer module. This should allow you to add new keywords, control structures etc while interpreting the source similarly to the python interpreter, thus avoiding the breakage crude regex solutions would cause. For the above "myprint", you could write the following transformation code:</p>
<pre><code>import tokenize
LOGFILE = '/tmp/log.txt'
def translate(readline):
for type, name,_,_,_ in tokenize.generate_tokens(readline):
if type ==tokenize.NAME and name =='myprint':
yield tokenize.NAME, 'print'
yield tokenize.OP, '>>'
yield tokenize.NAME, "open"
yield tokenize.OP, "("
yield tokenize.STRING, repr(LOGFILE)
yield tokenize.OP, ","
yield tokenize.STRING, "'a'"
yield tokenize.OP, ")"
yield tokenize.OP, ","
else:
yield type,name
</code></pre>
<p>(This does make myprint effectively a keyword, so use as a variable elsewhere will likely cause problems)</p>
<p>The problem then is how to use it so that your code is usable from python. One way would just be to write your own import function, and use it to load code written in your custom language. ie:</p>
<pre><code>import new
def myimport(filename):
mod = new.module(filename)
f=open(filename)
data = tokenize.untokenize(translate(f.readline))
exec data in mod.__dict__
return mod
</code></pre>
<p>This requires you handle your customised code differently from normal python modules however. ie "<code>some_mod = myimport("some_mod.py")</code>" rather than "<code>import some_mod</code>"</p>
<p>Another fairly neat (albeit hacky) solution is to create a custom encoding (See <a href="http://www.python.org/dev/peps/pep-0263/">PEP 263</a>) as <a href="http://code.activestate.com/recipes/546539/">this</a> recipe demonstrates. You could implement this as:</p>
<pre><code>import codecs, cStringIO, encodings
from encodings import utf_8
class StreamReader(utf_8.StreamReader):
def __init__(self, *args, **kwargs):
codecs.StreamReader.__init__(self, *args, **kwargs)
data = tokenize.untokenize(translate(self.stream.readline))
self.stream = cStringIO.StringIO(data)
def search_function(s):
if s!='mylang': return None
utf8=encodings.search_function('utf8') # Assume utf8 encoding
return codecs.CodecInfo(
name='mylang',
encode = utf8.encode,
decode = utf8.decode,
incrementalencoder=utf8.incrementalencoder,
incrementaldecoder=utf8.incrementaldecoder,
streamreader=StreamReader,
streamwriter=utf8.streamwriter)
codecs.register(search_function)
</code></pre>
<p>Now after this code gets run (eg. you could place it in your .pythonrc or site.py) any code starting with the comment "# coding: mylang" will automatically be translated through the above preprocessing step. eg.</p>
<pre><code># coding: mylang
myprint "this gets logged to file"
for i in range(10):
myprint "so does this : ", i, "times"
myprint ("works fine" "with arbitrary" + " syntax"
"and line continuations")
</code></pre>
<p>Caveats:</p>
<p>There are problems to the preprocessor approach, as you'll probably be familiar with if you've worked with the C preprocessor. The main one is debugging. All python sees is the preprocessed file which means that text printed in the stack trace etc will refer to that. If you've performed significant translation, this may be very different from your source text. The example above doesn't change line numbers etc, so won't be too different, but the more you change it, the harder it will be to figure out.</p>
| 44 | 2008-10-18T23:15:04Z | [
"python",
"syntax"
] |
Can you add new statements to Python's syntax? | 214,881 | <p>Can you add new statements (like <code>print</code>, <code>raise</code>, <code>with</code>) to Python's syntax?</p>
<p>Say, to allow..</p>
<pre><code>mystatement "Something"
</code></pre>
<p>Or,</p>
<pre><code>new_if True:
print "example"
</code></pre>
<p>Not so much if you <em>should</em>, but rather if it's possible (short of modifying the python interpreters code)</p>
| 72 | 2008-10-18T10:47:21Z | 216,174 | <p>There is a language based on python called <a href="http://www.livelogix.net/logix/" rel="nofollow">Logix</a> with which you CAN do such things. It hasn't been under development for a while, but the features that you asked for <b>do work</b> with the latest version. </p>
| 2 | 2008-10-19T08:36:50Z | [
"python",
"syntax"
] |
Can you add new statements to Python's syntax? | 214,881 | <p>Can you add new statements (like <code>print</code>, <code>raise</code>, <code>with</code>) to Python's syntax?</p>
<p>Say, to allow..</p>
<pre><code>mystatement "Something"
</code></pre>
<p>Or,</p>
<pre><code>new_if True:
print "example"
</code></pre>
<p>Not so much if you <em>should</em>, but rather if it's possible (short of modifying the python interpreters code)</p>
| 72 | 2008-10-18T10:47:21Z | 216,795 | <p>Yes, to some extent it is possible. There is a <a href="http://entrian.com/goto/">module</a> out there that uses <code>sys.settrace()</code> to implement <code>goto</code> and <code>comefrom</code> "keywords":</p>
<pre><code>from goto import goto, label
for i in range(1, 10):
for j in range(1, 20):
print i, j
if j == 3:
goto .end # breaking out from nested loop
label .end
print "Finished"
</code></pre>
| 15 | 2008-10-19T18:52:00Z | [
"python",
"syntax"
] |
Can you add new statements to Python's syntax? | 214,881 | <p>Can you add new statements (like <code>print</code>, <code>raise</code>, <code>with</code>) to Python's syntax?</p>
<p>Say, to allow..</p>
<pre><code>mystatement "Something"
</code></pre>
<p>Or,</p>
<pre><code>new_if True:
print "example"
</code></pre>
<p>Not so much if you <em>should</em>, but rather if it's possible (short of modifying the python interpreters code)</p>
| 72 | 2008-10-18T10:47:21Z | 217,373 | <p>It's possible to do this using <a href="http://www.fiber-space.de/EasyExtend/doc/EE.html" rel="nofollow">EasyExtend</a>:</p>
<blockquote>
<p>EasyExtend (EE) is a preprocessor
generator and metaprogramming
framework written in pure Python and
integrated with CPython. The main
purpose of EasyExtend is the creation
of extension languages i.e. adding
custom syntax and semantics to Python.</p>
</blockquote>
| 3 | 2008-10-20T02:29:20Z | [
"python",
"syntax"
] |
Can you add new statements to Python's syntax? | 214,881 | <p>Can you add new statements (like <code>print</code>, <code>raise</code>, <code>with</code>) to Python's syntax?</p>
<p>Say, to allow..</p>
<pre><code>mystatement "Something"
</code></pre>
<p>Or,</p>
<pre><code>new_if True:
print "example"
</code></pre>
<p>Not so much if you <em>should</em>, but rather if it's possible (short of modifying the python interpreters code)</p>
| 72 | 2008-10-18T10:47:21Z | 220,857 | <p>General answer: you need to preprocess your source files. </p>
<p>More specific answer: install <a href="http://pypi.python.org/pypi/EasyExtend">EasyExtend</a>, and go through following steps</p>
<p>i) Create a new langlet ( extension language )</p>
<pre><code>import EasyExtend
EasyExtend.new_langlet("mystmts", prompt = "my> ", source_ext = "mypy")
</code></pre>
<p>Without additional specification a bunch of files shall be created under EasyExtend/langlets/mystmts/ .</p>
<p>ii) Open mystmts/parsedef/Grammar.ext and add following lines</p>
<pre><code>small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
import_stmt | global_stmt | exec_stmt | assert_stmt | my_stmt )
my_stmt: 'mystatement' expr
</code></pre>
<p>This is sufficient to define the syntax of your new statement. The small_stmt non-terminal is part of the Python grammar and it's the place where the new statement is hooked in. The parser will now recognize the new statement i.e. a source file containing it will be parsed. The compiler will reject it though because it still has to be transformed into valid Python.</p>
<p>iii) Now one has to add semantics of the statement. For this one has to edit
msytmts/langlet.py and add a my_stmt node visitor.</p>
<pre><code> def call_my_stmt(expression):
"defines behaviour for my_stmt"
print "my stmt called with", expression
class LangletTransformer(Transformer):
@transform
def my_stmt(self, node):
_expr = find_node(node, symbol.expr)
return any_stmt(CST_CallFunc("call_my_stmt", [_expr]))
__publish__ = ["call_my_stmt"]
</code></pre>
<p>iv) cd to langlets/mystmts and type</p>
<pre><code>python run_mystmts.py
</code></pre>
<p>Now a session shall be started and the newly defined statement can be used:</p>
<pre><code>__________________________________________________________________________________
mystmts
On Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)]
__________________________________________________________________________________
my> mystatement 40+2
my stmt called with 42
</code></pre>
<p>Quite a few steps to come to a trivial statement, right? There isn't an API yet that lets one define simple things without having to care about grammars. But EE is very reliable modulo some bugs. So it's just a matter of time that an API emerges that lets programmers define convenient stuff like infix operators or small statements using just convenient OO programming. For more complex things like embedding whole languages in Python by means of building a langlet there is no way of going around a full grammar approach.</p>
| 10 | 2008-10-21T05:26:58Z | [
"python",
"syntax"
] |
Can you add new statements to Python's syntax? | 214,881 | <p>Can you add new statements (like <code>print</code>, <code>raise</code>, <code>with</code>) to Python's syntax?</p>
<p>Say, to allow..</p>
<pre><code>mystatement "Something"
</code></pre>
<p>Or,</p>
<pre><code>new_if True:
print "example"
</code></pre>
<p>Not so much if you <em>should</em>, but rather if it's possible (short of modifying the python interpreters code)</p>
| 72 | 2008-10-18T10:47:21Z | 4,572,994 | <p>Here's a very simple but crappy way to add new statements, <em>in interpretive mode only</em>. I'm using it for little 1-letter commands for editing gene annotations using only sys.displayhook, but just so I could answer this question I added sys.excepthook for the syntax errors as well. The latter is really ugly, fetching the raw code from the readline buffer. The benefit is, it's trivially easy to add new statements this way.</p>
<pre><code>
jcomeau@intrepid:~/$ cat demo.py; ./demo.py
#!/usr/bin/python -i
'load everything needed under "package", such as package.common.normalize()'
import os, sys, readline, traceback
if __name__ == '__main__':
class t:
@staticmethod
def localfunction(*args):
print 'this is a test'
if args:
print 'ignoring %s' % repr(args)
def displayhook(whatever):
if hasattr(whatever, 'localfunction'):
return whatever.localfunction()
else:
print whatever
def excepthook(exctype, value, tb):
if exctype is SyntaxError:
index = readline.get_current_history_length()
item = readline.get_history_item(index)
command = item.split()
print 'command:', command
if len(command[0]) == 1:
try:
eval(command[0]).localfunction(*command[1:])
except:
traceback.print_exception(exctype, value, tb)
else:
traceback.print_exception(exctype, value, tb)
sys.displayhook = displayhook
sys.excepthook = excepthook
>>> t
this is a test
>>> t t
command: ['t', 't']
this is a test
ignoring ('t',)
>>> ^D
</code></pre>
| 7 | 2011-01-01T02:23:19Z | [
"python",
"syntax"
] |
Can you add new statements to Python's syntax? | 214,881 | <p>Can you add new statements (like <code>print</code>, <code>raise</code>, <code>with</code>) to Python's syntax?</p>
<p>Say, to allow..</p>
<pre><code>mystatement "Something"
</code></pre>
<p>Or,</p>
<pre><code>new_if True:
print "example"
</code></pre>
<p>Not so much if you <em>should</em>, but rather if it's possible (short of modifying the python interpreters code)</p>
| 72 | 2008-10-18T10:47:21Z | 9,108,164 | <p>You may find this useful - <a href="http://eli.thegreenplace.net/2010/06/30/python-internals-adding-a-new-statement-to-python/">Python internals: adding a new statement to Python</a>, quoted here:</p>
<hr>
<p>This article is an attempt to better understand how the front-end of Python works. Just reading documentation and source code may be a bit boring, so I'm taking a hands-on approach here: I'm going to add an <code>until</code> statement to Python.</p>
<p>All the coding for this article was done against the cutting-edge Py3k branch in the <a href="http://code.python.org/hg/branches/py3k/">Python Mercurial repository mirror</a>.</p>
<h3>The <code>until</code> statement</h3>
<p>Some languages, like Ruby, have an <code>until</code> statement, which is the complement to <code>while</code> (<code>until num == 0</code> is equivalent to <code>while num != 0</code>). In Ruby, I can write:</p>
<pre><code>num = 3
until num == 0 do
puts num
num -= 1
end
</code></pre>
<p>And it will print:</p>
<pre><code>3
2
1
</code></pre>
<p>So, I want to add a similar capability to Python. That is, being able to write:</p>
<pre><code>num = 3
until num == 0:
print(num)
num -= 1
</code></pre>
<h3>A language-advocacy digression</h3>
<p>This article doesn't attempt to suggest the addition of an <code>until</code> statement to Python. Although I think such a statement would make some code clearer, and this article displays how easy it is to add, I completely respect Python's philosophy of minimalism. All I'm trying to do here, really, is gain some insight into the inner workings of Python.</p>
<h3>Modifying the grammar</h3>
<p>Python uses a custom parser generator named <code>pgen</code>. This is a LL(1) parser that converts Python source code into a parse tree. The input to the parser generator is the file <code>Grammar/Grammar</code><strong>[1]</strong>. This is a simple text file that specifies the grammar of Python.</p>
<p><strong>[1]</strong>: From here on, references to files in the Python source are given relatively to the root of the source tree, which is the directory where you run configure and make to build Python.</p>
<p>Two modifications have to be made to the grammar file. The first is to add a definition for the <code>until</code> statement. I found where the <code>while</code> statement was defined (<code>while_stmt</code>), and added <code>until_stmt</code> below <strong>[2]</strong>:</p>
<pre><code>compound_stmt: if_stmt | while_stmt | until_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
while_stmt: 'while' test ':' suite ['else' ':' suite]
until_stmt: 'until' test ':' suite
</code></pre>
<p><strong>[2]</strong>: This demonstrates a common technique I use when modifying source code Iâm not familiar with: <em>work by similarity</em>. This principle wonât solve all your problems, but it can definitely ease the process. Since everything that has to be done for <code>while</code> also has to be done for <code>until</code>, it serves as a pretty good guideline.</p>
<p>Note that I've decided to exclude the <code>else</code> clause from my definition of <code>until</code>, just to make it a little bit different (and because frankly I dislike the <code>else</code> clause of loops and don't think it fits well with the Zen of Python).</p>
<p>The second change is to modify the rule for <code>compound_stmt</code> to include <code>until_stmt</code>, as you can see in the snippet above. It's right after <code>while_stmt</code>, again.</p>
<p>When you run <code>make</code> after modifying <code>Grammar/Grammar</code>, notice that the <code>pgen</code> program is run to re-generate <code>Include/graminit.h</code> and <code>Python/graminit.c</code>, and then several files get re-compiled.</p>
<h3>Modifying the AST generation code</h3>
<p>After the Python parser has created a parse tree, this tree is converted into an AST, since ASTs are <a href="http://eli.thegreenplace.net/2009/02/16/abstract-vs-concrete-syntax-trees/">much simpler to work with</a> in subsequent stages of the compilation process.</p>
<p>So, we're going to visit <code>Parser/Python.asdl</code> which defines the structure of Python's ASTs and add an AST node for our new <code>until</code> statement, again right below the <code>while</code>:</p>
<pre><code>| While(expr test, stmt* body, stmt* orelse)
| Until(expr test, stmt* body)
</code></pre>
<p>If you now run <code>make</code>, notice that before compiling a bunch of files, <code>Parser/asdl_c.py</code> is run to generate C code from the AST definition file. This (like <code>Grammar/Grammar</code>) is another example of the Python source-code using a mini-language (in other words, a DSL) to simplify programming. Also note that since <code>Parser/asdl_c.py</code> is a Python script, this is a kind of <a href="http://en.wikipedia.org/wiki/Bootstrapping_%28compilers%29">bootstrapping</a> - to build Python from scratch, Python already has to be available.</p>
<p>While <code>Parser/asdl_c.py</code> generated the code to manage our newly defined AST node (into the files <code>Include/Python-ast.h</code> and <code>Python/Python-ast.c</code>), we still have to write the code that converts a relevant parse-tree node into it by hand. This is done in the file <code>Python/ast.c</code>. There, a function named <code>ast_for_stmt</code> converts parse tree nodes for statements into AST nodes. Again, guided by our old friend <code>while</code>, we jump right into the big <code>switch</code> for handling compound statements and add a clause for <code>until_stmt</code>:</p>
<pre><code>case while_stmt:
return ast_for_while_stmt(c, ch);
case until_stmt:
return ast_for_until_stmt(c, ch);
</code></pre>
<p>Now we should implement <code>ast_for_until_stmt</code>. Here it is:</p>
<pre><code>static stmt_ty
ast_for_until_stmt(struct compiling *c, const node *n)
{
/* until_stmt: 'until' test ':' suite */
REQ(n, until_stmt);
if (NCH(n) == 4) {
expr_ty expression;
asdl_seq *suite_seq;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, 3));
if (!suite_seq)
return NULL;
return Until(expression, suite_seq, LINENO(n), n->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"wrong number of tokens for 'until' statement: %d",
NCH(n));
return NULL;
}
</code></pre>
<p>Again, this was coded while closely looking at the equivalent <code>ast_for_while_stmt</code>, with the difference that for <code>until</code> I've decided not to support the <code>else</code> clause. As expected, the AST is created recursively, using other AST creating functions like <code>ast_for_expr</code> for the condition expression and <code>ast_for_suite</code> for the body of the <code>until</code> statement. Finally, a new node named <code>Until</code> is returned.</p>
<p>Note that we access the parse-tree node <code>n</code> using some macros like <code>NCH</code> and <code>CHILD</code>. These are worth understanding - their code is in <code>Include/node.h</code>.</p>
<h3>Digression: AST composition</h3>
<p>I chose to create a new type of AST for the <code>until</code> statement, but actually this isn't necessary. I could've saved some work and implemented the new functionality using composition of existing AST nodes, since:</p>
<pre><code>until condition:
# do stuff
</code></pre>
<p>Is functionally equivalent to:</p>
<pre><code>while not condition:
# do stuff
</code></pre>
<p>Instead of creating the <code>Until</code> node in <code>ast_for_until_stmt</code>, I could have created a <code>Not</code> node with an <code>While</code> node as a child. Since the AST compiler already knows how to handle these nodes, the next steps of the process could be skipped.</p>
<h3>Compiling ASTs into bytecode</h3>
<p>The next step is compiling the AST into Python bytecode. The compilation has an intermediate result which is a CFG (Control Flow Graph), but since the same code handles it I will ignore this detail for now and leave it for another article.</p>
<p>The code we will look at next is <code>Python/compile.c</code>. Following the lead of <code>while</code>, we find the function <code>compiler_visit_stmt</code>, which is responsible for compiling statements into bytecode. We add a clause for <code>Until</code>:</p>
<pre><code>case While_kind:
return compiler_while(c, s);
case Until_kind:
return compiler_until(c, s);
</code></pre>
<p>If you wonder what <code>Until_kind</code> is, it's a constant (actually a value of the <code>_stmt_kind</code> enumeration) automatically generated from the AST definition file into <code>Include/Python-ast.h</code>. Anyway, we call <code>compiler_until</code> which, of course, still doesn't exist. I'll get to it an a moment.</p>
<p>If you're curious like me, you'll notice that <code>compiler_visit_stmt</code> is peculiar. No amount of <code>grep</code>-ping the source tree reveals where it is called. When this is the case, only one option remains - C macro-fu. Indeed, a short investigation leads us to the <code>VISIT</code> macro defined in <code>Python/compile.c</code>:</p>
<pre><code>#define VISIT(C, TYPE, V) {\
if (!compiler_visit_ ## TYPE((C), (V))) \
return 0; \
</code></pre>
<p>It's used to invoke <code>compiler_visit_stmt</code> in <code>compiler_body</code>. Back to our business, however...</p>
<p>As promised, here's <code>compiler_until</code>:</p>
<pre><code>static int
compiler_until(struct compiler *c, stmt_ty s)
{
basicblock *loop, *end, *anchor = NULL;
int constant = expr_constant(s->v.Until.test);
if (constant == 1) {
return 1;
}
loop = compiler_new_block(c);
end = compiler_new_block(c);
if (constant == -1) {
anchor = compiler_new_block(c);
if (anchor == NULL)
return 0;
}
if (loop == NULL || end == NULL)
return 0;
ADDOP_JREL(c, SETUP_LOOP, end);
compiler_use_next_block(c, loop);
if (!compiler_push_fblock(c, LOOP, loop))
return 0;
if (constant == -1) {
VISIT(c, expr, s->v.Until.test);
ADDOP_JABS(c, POP_JUMP_IF_TRUE, anchor);
}
VISIT_SEQ(c, stmt, s->v.Until.body);
ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
if (constant == -1) {
compiler_use_next_block(c, anchor);
ADDOP(c, POP_BLOCK);
}
compiler_pop_fblock(c, LOOP, loop);
compiler_use_next_block(c, end);
return 1;
}
</code></pre>
<p>I have a confession to make: this code wasn't written based on a deep understanding of Python bytecode. Like the rest of the article, it was done in imitation of the kin <code>compiler_while</code> function. By reading it carefully, however, keeping in mind that the Python VM is stack-based, and glancing into the documentation of the <code>dis</code> module, which has <a href="http://docs.python.org/py3k/library/dis.html">a list of Python bytecodes</a> with descriptions, it's possible to understand what's going on.</p>
<h3>That's it, we're done... Aren't we?</h3>
<p>After making all the changes and running <code>make</code>, we can run the newly compiled Python and try our new <code>until</code> statement:</p>
<pre><code>>>> until num == 0:
... print(num)
... num -= 1
...
3
2
1
</code></pre>
<p>Voila, it works! Let's see the bytecode created for the new statement by using the <code>dis</code> module as follows:</p>
<pre><code>import dis
def myfoo(num):
until num == 0:
print(num)
num -= 1
dis.dis(myfoo)
</code></pre>
<p>Here's the result:</p>
<pre><code>4 0 SETUP_LOOP 36 (to 39)
>> 3 LOAD_FAST 0 (num)
6 LOAD_CONST 1 (0)
9 COMPARE_OP 2 (==)
12 POP_JUMP_IF_TRUE 38
5 15 LOAD_NAME 0 (print)
18 LOAD_FAST 0 (num)
21 CALL_FUNCTION 1
24 POP_TOP
6 25 LOAD_FAST 0 (num)
28 LOAD_CONST 2 (1)
31 INPLACE_SUBTRACT
32 STORE_FAST 0 (num)
35 JUMP_ABSOLUTE 3
>> 38 POP_BLOCK
>> 39 LOAD_CONST 0 (None)
42 RETURN_VALUE
</code></pre>
<p>The most interesting operation is number 12: if the condition is true, we jump to after the loop. This is correct semantics for <code>until</code>. If the jump isn't executed, the loop body keeps running until it jumps back to the condition at operation 35.</p>
<p>Feeling good about my change, I then tried running the function (executing <code>myfoo(3)</code>) instead of showing its bytecode. The result was less than encouraging:</p>
<pre><code>Traceback (most recent call last):
File "zy.py", line 9, in
myfoo(3)
File "zy.py", line 5, in myfoo
print(num)
SystemError: no locals when loading 'print'
</code></pre>
<p>Whoa... this can't be good. So what went wrong?</p>
<h3>The case of the missing symbol table</h3>
<p>One of the steps the Python compiler performs when compiling the AST is create a symbol table for the code it compiles. The call to <code>PySymtable_Build</code> in <code>PyAST_Compile</code> calls into the symbol table module (<code>Python/symtable.c</code>), which walks the AST in a manner similar to the code generation functions. Having a symbol table for each scope helps the compiler figure out some key information, such as which variables are global and which are local to a scope.</p>
<p>To fix the problem, we have to modify the <code>symtable_visit_stmt</code> function in <code>Python/symtable.c</code>, adding code for handling <code>until</code> statements, after the similar code for <code>while</code> statements <strong>[3]</strong>:</p>
<pre><code>case While_kind:
VISIT(st, expr, s->v.While.test);
VISIT_SEQ(st, stmt, s->v.While.body);
if (s->v.While.orelse)
VISIT_SEQ(st, stmt, s->v.While.orelse);
break;
case Until_kind:
VISIT(st, expr, s->v.Until.test);
VISIT_SEQ(st, stmt, s->v.Until.body);
break;
</code></pre>
<p><strong>[3]</strong>: By the way, without this code thereâs a compiler warning for <code>Python/symtable.c</code>. The compiler notices that the <code>Until_kind</code> enumeration value isnât handled in the switch statement of <code>symtable_visit_stmt</code> and complains. Itâs always important to check for compiler warnings!</p>
<p>And now we really are done. Compiling the source after this change makes the execution of <code>myfoo(3)</code> work as expected.</p>
<h3>Conclusion</h3>
<p>In this article I've demonstrated how to add a new statement to Python. Albeit requiring quite a bit of tinkering in the code of the Python compiler, the change wasn't difficult to implement, because I used a similar and existing statement as a guideline.</p>
<p>The Python compiler is a sophisticated chunk of software, and I don't claim being an expert in it. However, I am really interested in the internals of Python, and particularly its front-end. Therefore, I found this exercise a very useful companion to theoretical study of the compiler's principles and source code. It will serve as a base for future articles that will get deeper into the compiler.</p>
<h3>References</h3>
<p>I used a few excellent references for the construction of this article. Here they are, in no particular order:</p>
<ul>
<li><a href="http://www.python.org/dev/peps/pep-0339/">PEP 339: Design of the CPython compiler</a> - probably the most important and comprehensive piece of <em>official</em> documentation for the Python compiler. Being very short, it painfully displays the scarcity of good documentation of the internals of Python.</li>
<li>"Python Compiler Internals" - an article by Thomas Lee</li>
<li>"Python: Design and Implementation" - a presentation by Guido van Rossum</li>
<li>Python (2.5) Virtual Machine, A guided tour - a presentation by Peter Tröger</li>
</ul>
<p><a href="http://eli.thegreenplace.net/2010/06/30/python-internals-adding-a-new-statement-to-python/">original source</a></p>
| 77 | 2012-02-02T06:39:44Z | [
"python",
"syntax"
] |
Can you add new statements to Python's syntax? | 214,881 | <p>Can you add new statements (like <code>print</code>, <code>raise</code>, <code>with</code>) to Python's syntax?</p>
<p>Say, to allow..</p>
<pre><code>mystatement "Something"
</code></pre>
<p>Or,</p>
<pre><code>new_if True:
print "example"
</code></pre>
<p>Not so much if you <em>should</em>, but rather if it's possible (short of modifying the python interpreters code)</p>
| 72 | 2008-10-18T10:47:21Z | 27,841,742 | <p>Some things can be done with decorators. Let's e.g. assume, Python had no <code>with</code> statement. We could then implement a similar behaviour like this: </p>
<pre><code># ====== Implementation of "mywith" decorator ======
def mywith(stream):
def decorator(function):
try: function(stream)
finally: stream.close()
return decorator
# ====== Using the decorator ======
@mywith(open("test.py","r"))
def _(infile):
for l in infile.readlines():
print(">>", l.rstrip())
</code></pre>
<p>It is a pretty unclean solution however as done here. Especially the behaviour where the decorator calls the function and sets <code>_</code> to <code>None</code> is unexpected. For clarification: This decorator is equivalent to writing </p>
<pre><code>def _(infile): ...
_ = mywith(open(...))(_) # mywith returns None.
</code></pre>
<p>and decorators are normally expected to modify, not to execute, functions. </p>
<p>I used such a method before in a script where I had to temporarily set the working directory for several functions.</p>
| 1 | 2015-01-08T13:53:13Z | [
"python",
"syntax"
] |
Can you add new statements to Python's syntax? | 214,881 | <p>Can you add new statements (like <code>print</code>, <code>raise</code>, <code>with</code>) to Python's syntax?</p>
<p>Say, to allow..</p>
<pre><code>mystatement "Something"
</code></pre>
<p>Or,</p>
<pre><code>new_if True:
print "example"
</code></pre>
<p>Not so much if you <em>should</em>, but rather if it's possible (short of modifying the python interpreters code)</p>
| 72 | 2008-10-18T10:47:21Z | 31,151,217 | <p>It's not exactly adding new statements to the language syntax, but macros are a powerful tool: <a href="https://github.com/lihaoyi/macropy" rel="nofollow">https://github.com/lihaoyi/macropy</a></p>
| 1 | 2015-07-01T01:34:23Z | [
"python",
"syntax"
] |
Efficient Image Thumbnail Control for Python? | 215,052 | <p>What is the best choice for a Python GUI application to display large number of thumbnails, e.g. 10000 or more? For performance reasons such thumbnail control must support virtual items, i.e. request application for those thumbnails only which are currently visible to user. </p>
| 3 | 2008-10-18T13:36:15Z | 215,175 | <p>If you had to resort to writing your own, I've had good results using the Python Imaging Library to create thumbnails in the past.
<a href="http://www.pythonware.com/products/pil/" rel="nofollow">http://www.pythonware.com/products/pil/</a></p>
| 1 | 2008-10-18T15:40:32Z | [
"python",
"image",
"wxpython",
"pyqt",
"thumbnails"
] |
Efficient Image Thumbnail Control for Python? | 215,052 | <p>What is the best choice for a Python GUI application to display large number of thumbnails, e.g. 10000 or more? For performance reasons such thumbnail control must support virtual items, i.e. request application for those thumbnails only which are currently visible to user. </p>
| 3 | 2008-10-18T13:36:15Z | 215,257 | <p>In <a href="http://wxpython.org/" rel="nofollow">wxPython</a> you can use <a href="http://docs.wxwidgets.org/stable/wx_wxgrid.html#wxgrid" rel="nofollow">wxGrid</a> for this as it supports virtual mode and custom cell renderers.</p>
<p><a href="http://docs.wxwidgets.org/stable/wx_wxgridtablebase.html#wxgridtablebase" rel="nofollow">This</a> is the minimal interface you have to implement for a wxGrid "data provider":</p>
<pre><code>class GridData(wx.grid.PyGridTableBase):
def GetColLabelValue(self, col):
pass
def GetNumberRows(self):
pass
def GetNumberCols(self):
pass
def IsEmptyCell(self, row, col):
pass
def GetValue(self, row, col):
pass
</code></pre>
<p><a href="http://docs.wxwidgets.org/stable/wx_wxgridcellrenderer.html#wxgridcellrenderer" rel="nofollow">This</a> is the minimal interface you have to implement for a wxGrid cell renderer:</p>
<pre><code>class CellRenderer(wx.grid.PyGridCellRenderer):
def Draw(self, grid, attr, dc, rect, row, col, isSelected):
pass
</code></pre>
<p>You can find a working example that utilizes these classes in <a href="http://wxpython.org/download.php" rel="nofollow">wxPython docs and demos</a>, it's called Grid_MegaExample.</p>
| 2 | 2008-10-18T16:48:04Z | [
"python",
"image",
"wxpython",
"pyqt",
"thumbnails"
] |
Efficient Image Thumbnail Control for Python? | 215,052 | <p>What is the best choice for a Python GUI application to display large number of thumbnails, e.g. 10000 or more? For performance reasons such thumbnail control must support virtual items, i.e. request application for those thumbnails only which are currently visible to user. </p>
| 3 | 2008-10-18T13:36:15Z | 455,191 | <p>Just for completeness: there is a <a href="http://xoomer.alice.it/infinity77/main/freeware.html#thumbnailctrl" rel="nofollow">thumbnailCtrl</a> written in/for wxPython, which might be a good starting point.</p>
| 1 | 2009-01-18T14:10:15Z | [
"python",
"image",
"wxpython",
"pyqt",
"thumbnails"
] |
wxpython - Expand list control vertically not horizontally | 215,132 | <p>I have a ListCtrl that displays a list of items for the user to select. This works fine except that when the ctrl is not large enough to show all the items, I want it to expand downwards with a vertical scoll bar rather than using a horizontal scroll bar as it expands to the right.</p>
<p>The ListCtrl's creation:</p>
<pre><code>self.subjectList = wx.ListCtrl(self, self.ID_SUBJECT, style = wx.LC_LIST | wx.LC_SINGLE_SEL | wx.LC_VRULES)
</code></pre>
<p>Items are inserted using wx.ListItem:</p>
<pre><code>item = wx.ListItem()
item.SetText(subject)
item.SetData(id)
item.SetWidth(200)
self.subjectList.InsertItem(item)
</code></pre>
| 2 | 2008-10-18T15:02:48Z | 215,216 | <p>Use the <a href="http://docs.wxwidgets.org/stable/wx_wxlistctrl.html#wxlistctrl" rel="nofollow">wxLC_REPORT</a> style.</p>
<pre><code>import wx
class Test(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
self.test = wx.ListCtrl(self, style = wx.LC_REPORT | wx.LC_NO_HEADER)
for i in range(5):
self.test.InsertColumn(i, 'Col %d' % (i + 1))
self.test.SetColumnWidth(i, 200)
for i in range(0, 100, 5):
index = self.test.InsertStringItem(self.test.GetItemCount(), "")
for j in range(5):
self.test.SetStringItem(index, j, str(i+j)*30)
self.Show()
app = wx.PySimpleApp()
app.TopWindow = Test()
app.MainLoop()
</code></pre>
| 3 | 2008-10-18T16:18:05Z | [
"python",
"wxpython",
"wxwidgets"
] |
wxpython - Expand list control vertically not horizontally | 215,132 | <p>I have a ListCtrl that displays a list of items for the user to select. This works fine except that when the ctrl is not large enough to show all the items, I want it to expand downwards with a vertical scoll bar rather than using a horizontal scroll bar as it expands to the right.</p>
<p>The ListCtrl's creation:</p>
<pre><code>self.subjectList = wx.ListCtrl(self, self.ID_SUBJECT, style = wx.LC_LIST | wx.LC_SINGLE_SEL | wx.LC_VRULES)
</code></pre>
<p>Items are inserted using wx.ListItem:</p>
<pre><code>item = wx.ListItem()
item.SetText(subject)
item.SetData(id)
item.SetWidth(200)
self.subjectList.InsertItem(item)
</code></pre>
| 2 | 2008-10-18T15:02:48Z | 215,335 | <p>Try this:</p>
<pre><code>import wx
class Test(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
self.test = wx.ListCtrl(self, style = wx.LC_ICON | wx.LC_AUTOARRANGE)
for i in range(100):
self.test.InsertStringItem(self.test.GetItemCount(), str(i))
self.Show()
app = wx.PySimpleApp()
app.TopWindow = Test()
app.MainLoop()
</code></pre>
| 1 | 2008-10-18T17:53:14Z | [
"python",
"wxpython",
"wxwidgets"
] |
How do you fix a Trac installation that begins giving errors relating to PYTHON_EGG_CACHE? | 215,267 | <p>We've been using Trac for task/defect tracking and things were going well enough, but this morning it started serving up a 500 error. Looking in the Apache error_log, I get a stack trace that culminates in:</p>
<pre>
PythonHandler trac.web.modpython_frontend:
ExtractionError: Can't extract file(s) to egg cache
The following error occurred while trying to extract file(s) to the Python egg
cache:
[Errno 13] Permission denied: '/.python-eggs'
The Python egg cache directory is currently set to:
/.python-eggs
Perhaps your account does not have write access to this directory? You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory
</pre>
<p>So I explicitly set PYTHON_EGG_CACHE to /srv/trac/plugin-cache. I restarted Apache. Yet I get the same error (it still says "egg cache directory current set to: \n\n /.python_eggs.")</p>
<p>How should I proceed? Is the simplest thing to do to reinstall Trac? If I go that route, what steps do I need to take to ensure that I don't lose existing data?</p>
| 1 | 2008-10-18T16:51:02Z | 215,298 | <p>That should be fixed in 0.11 according to their <a href="http://trac.edgewall.org/ticket/7320" rel="nofollow">bug tracking system</a>. </p>
<p>If that's not the case you should try to pass the environment var to apache, since doing a SetEnv in the configuration file doesn't work. Adding something like </p>
<pre><code>export PYTHON_EGG_CACHE=/tmp/python_eggs
</code></pre>
<p>to the script you use to start apache should work.</p>
| 3 | 2008-10-18T17:19:00Z | [
"python",
"configuration",
"trac",
"python-egg-cache"
] |
How do you fix a Trac installation that begins giving errors relating to PYTHON_EGG_CACHE? | 215,267 | <p>We've been using Trac for task/defect tracking and things were going well enough, but this morning it started serving up a 500 error. Looking in the Apache error_log, I get a stack trace that culminates in:</p>
<pre>
PythonHandler trac.web.modpython_frontend:
ExtractionError: Can't extract file(s) to egg cache
The following error occurred while trying to extract file(s) to the Python egg
cache:
[Errno 13] Permission denied: '/.python-eggs'
The Python egg cache directory is currently set to:
/.python-eggs
Perhaps your account does not have write access to this directory? You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory
</pre>
<p>So I explicitly set PYTHON_EGG_CACHE to /srv/trac/plugin-cache. I restarted Apache. Yet I get the same error (it still says "egg cache directory current set to: \n\n /.python_eggs.")</p>
<p>How should I proceed? Is the simplest thing to do to reinstall Trac? If I go that route, what steps do I need to take to ensure that I don't lose existing data?</p>
| 1 | 2008-10-18T16:51:02Z | 215,303 | <p>I ran into the same problem when upgrading from Trac 10.4 to 0.11 earlier this year. Something must have changed for this problem to have just suddenly appeared -- an updated Python or Apache installation?</p>
<p>I don't remember all of the permutations I tried to solve this, but I ended up having to use <code>SetEnv PYTHON_EGG_CACHE /.python-eggs</code> and create /.python-eggs with 777 permissions. This might not be the best solution, but it fixed the problem. </p>
<p>I never investigated what the root cause was. As <a href="http://stackoverflow.com/questions/215267/how-do-you-fix-a-trac-installation-that-begins-giving-errors-relating-to-python#215298">agnul</a> says, this may have been fixed in a subsequent Trac release.</p>
| 0 | 2008-10-18T17:25:16Z | [
"python",
"configuration",
"trac",
"python-egg-cache"
] |
How do you fix a Trac installation that begins giving errors relating to PYTHON_EGG_CACHE? | 215,267 | <p>We've been using Trac for task/defect tracking and things were going well enough, but this morning it started serving up a 500 error. Looking in the Apache error_log, I get a stack trace that culminates in:</p>
<pre>
PythonHandler trac.web.modpython_frontend:
ExtractionError: Can't extract file(s) to egg cache
The following error occurred while trying to extract file(s) to the Python egg
cache:
[Errno 13] Permission denied: '/.python-eggs'
The Python egg cache directory is currently set to:
/.python-eggs
Perhaps your account does not have write access to this directory? You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory
</pre>
<p>So I explicitly set PYTHON_EGG_CACHE to /srv/trac/plugin-cache. I restarted Apache. Yet I get the same error (it still says "egg cache directory current set to: \n\n /.python_eggs.")</p>
<p>How should I proceed? Is the simplest thing to do to reinstall Trac? If I go that route, what steps do I need to take to ensure that I don't lose existing data?</p>
| 1 | 2008-10-18T16:51:02Z | 215,401 | <p>I have wrestled many a battle with <code>PYTHON_EGG_CACHE</code> and I never figured out the correct way of setting it - apache's envvars, httpd.conf (SetEnv and PythonOption), nothing worked. In the end I just unpacked all python eggs manually, there were only two or three anyway - problem gone. I never understood why on earth people zip up files weighting no more than a few kilobytes in the first place...</p>
| 1 | 2008-10-18T18:40:52Z | [
"python",
"configuration",
"trac",
"python-egg-cache"
] |
How do you fix a Trac installation that begins giving errors relating to PYTHON_EGG_CACHE? | 215,267 | <p>We've been using Trac for task/defect tracking and things were going well enough, but this morning it started serving up a 500 error. Looking in the Apache error_log, I get a stack trace that culminates in:</p>
<pre>
PythonHandler trac.web.modpython_frontend:
ExtractionError: Can't extract file(s) to egg cache
The following error occurred while trying to extract file(s) to the Python egg
cache:
[Errno 13] Permission denied: '/.python-eggs'
The Python egg cache directory is currently set to:
/.python-eggs
Perhaps your account does not have write access to this directory? You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory
</pre>
<p>So I explicitly set PYTHON_EGG_CACHE to /srv/trac/plugin-cache. I restarted Apache. Yet I get the same error (it still says "egg cache directory current set to: \n\n /.python_eggs.")</p>
<p>How should I proceed? Is the simplest thing to do to reinstall Trac? If I go that route, what steps do I need to take to ensure that I don't lose existing data?</p>
| 1 | 2008-10-18T16:51:02Z | 219,233 | <p>I had the same problem. In my case the directory wasn't there so I created and chown'ed it over to the apache user (apache on my centos 4.3 box). Then made sure it had read-write permissions on the directory. You could get by with giving rw rights to the directory if the group that owns the directory contains the apache user. A simple ps aux|grep httpd should show you what account your server is running under if you don't know it. If you have trouble finding the directory remember the -a on the ls command since it is a "hidden" directory.</p>
| 0 | 2008-10-20T17:28:49Z | [
"python",
"configuration",
"trac",
"python-egg-cache"
] |
How do you fix a Trac installation that begins giving errors relating to PYTHON_EGG_CACHE? | 215,267 | <p>We've been using Trac for task/defect tracking and things were going well enough, but this morning it started serving up a 500 error. Looking in the Apache error_log, I get a stack trace that culminates in:</p>
<pre>
PythonHandler trac.web.modpython_frontend:
ExtractionError: Can't extract file(s) to egg cache
The following error occurred while trying to extract file(s) to the Python egg
cache:
[Errno 13] Permission denied: '/.python-eggs'
The Python egg cache directory is currently set to:
/.python-eggs
Perhaps your account does not have write access to this directory? You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory
</pre>
<p>So I explicitly set PYTHON_EGG_CACHE to /srv/trac/plugin-cache. I restarted Apache. Yet I get the same error (it still says "egg cache directory current set to: \n\n /.python_eggs.")</p>
<p>How should I proceed? Is the simplest thing to do to reinstall Trac? If I go that route, what steps do I need to take to ensure that I don't lose existing data?</p>
| 1 | 2008-10-18T16:51:02Z | 406,119 | <p>I found that using the PythonOption directive in the site config <em>did not</em> work, but SetEnv did. The environment variable route will also work though.</p>
| 0 | 2009-01-02T05:39:07Z | [
"python",
"configuration",
"trac",
"python-egg-cache"
] |
What's a good library to manipulate Apache2 config files? | 215,542 | <p>I'd like to create a script to manipulate Apache2 configuration directly, reading and writing its properties (like adding a new VirtualHost, changing settings of one that already exists).</p>
<p>Are there any libs out there, for Perl, Python or Java that automates that task?</p>
| 7 | 2008-10-18T20:38:57Z | 215,546 | <p>This is the ultimate Apache configurator:</p>
<p><a href="http://perl.apache.org/" rel="nofollow">http://perl.apache.org/</a></p>
<p>exposes many if not all Apache internals to programs written in Perl.</p>
<p>For instance: <a href="http://perl.apache.org/docs/2.0/api/Apache2/Directive.html" rel="nofollow">http://perl.apache.org/docs/2.0/api/Apache2/Directive.html</a></p>
<p>(Of course that it can do much much more than just configuring it).</p>
<p>On the other hand, it needs to be loaded and runs within Apache, it's not a config file parser/editor.</p>
| 2 | 2008-10-18T20:47:04Z | [
"java",
"python",
"perl",
"apache"
] |
What's a good library to manipulate Apache2 config files? | 215,542 | <p>I'd like to create a script to manipulate Apache2 configuration directly, reading and writing its properties (like adding a new VirtualHost, changing settings of one that already exists).</p>
<p>Are there any libs out there, for Perl, Python or Java that automates that task?</p>
| 7 | 2008-10-18T20:38:57Z | 215,552 | <p>Rather than manipulate the config files, you can use <a href="http://perl.apache.org/" rel="nofollow">mod_perl</a> to embed Perl directly into the config files. This could allow you, for example, to read required vhosts out of a database.</p>
<p>See <a href="http://perl.apache.org/start/tips/config.html" rel="nofollow">Configure Apache with Perl Example</a> for quick example and <a href="http://perl.apache.org/docs/1.0/guide/config.html#Apache_Configuration_in_Perl" rel="nofollow">Apache Configuration in Perl</a> for all the details.</p>
| 7 | 2008-10-18T20:52:03Z | [
"java",
"python",
"perl",
"apache"
] |
What's a good library to manipulate Apache2 config files? | 215,542 | <p>I'd like to create a script to manipulate Apache2 configuration directly, reading and writing its properties (like adding a new VirtualHost, changing settings of one that already exists).</p>
<p>Are there any libs out there, for Perl, Python or Java that automates that task?</p>
| 7 | 2008-10-18T20:38:57Z | 215,652 | <p>Try the <a href="http://search.cpan.org/~nwiger/Apache-ConfigFile-1.18/ConfigFile.pm" rel="nofollow">Apache::ConfigFile Perl module</a>.</p>
| 2 | 2008-10-18T22:21:13Z | [
"java",
"python",
"perl",
"apache"
] |
What's a good library to manipulate Apache2 config files? | 215,542 | <p>I'd like to create a script to manipulate Apache2 configuration directly, reading and writing its properties (like adding a new VirtualHost, changing settings of one that already exists).</p>
<p>Are there any libs out there, for Perl, Python or Java that automates that task?</p>
| 7 | 2008-10-18T20:38:57Z | 215,695 | <p>In Perl, you've got at least 2 modules for that:</p>
<p><a href="http://search.cpan.org/~nwiger/Apache-ConfigFile-1.18/ConfigFile.pm" rel="nofollow">Apache::ConfigFile</a></p>
<p><a href="https://metacpan.org/pod/Apache%3a%3aAdmin%3a%3aConfig" rel="nofollow">Apache::Admin::Config</a> </p>
| 7 | 2008-10-18T23:13:14Z | [
"java",
"python",
"perl",
"apache"
] |
What's a good library to manipulate Apache2 config files? | 215,542 | <p>I'd like to create a script to manipulate Apache2 configuration directly, reading and writing its properties (like adding a new VirtualHost, changing settings of one that already exists).</p>
<p>Are there any libs out there, for Perl, Python or Java that automates that task?</p>
| 7 | 2008-10-18T20:38:57Z | 215,932 | <p>Look at <a href="http://augeas.net/" rel="nofollow">Augeas</a>, it's not specifically for Apache-httpd config. files it's just a generic config. file "editor" API. One of it's major selling points is that it will keep comments/etc. is happy for other tools to alter the files and will refuse to let you save broken files.</p>
<p>Also the fact that you can use the same API in all the languages you asked about, and that you can edit other config. files using the same APIs are both major advantages IMO.</p>
| 3 | 2008-10-19T03:02:08Z | [
"java",
"python",
"perl",
"apache"
] |
What's a good library to manipulate Apache2 config files? | 215,542 | <p>I'd like to create a script to manipulate Apache2 configuration directly, reading and writing its properties (like adding a new VirtualHost, changing settings of one that already exists).</p>
<p>Are there any libs out there, for Perl, Python or Java that automates that task?</p>
| 7 | 2008-10-18T20:38:57Z | 217,879 | <p>Also see <a href="http://search.cpan.org/perldoc?Config::General" rel="nofollow">Config::General</a>, which claims to be fully compatible with Apache configuration files. I use it to parse my Apache configuration files for automatic regression testing after configuration changes.</p>
| 0 | 2008-10-20T09:26:09Z | [
"java",
"python",
"perl",
"apache"
] |
What's the difference between a parent and a reference property in Google App Engine? | 215,570 | <p>From what I understand, the parent attribute of a db.Model (typically defined/passed in the constructor call) allows you to define hierarchies in your data models. As a result, this increases the size of the entity group. However, it's not very clear to me why we would want to do that. Is this strictly for ACID compliance? I would like to see scenarios where each is best suited or more appropriate.</p>
| 10 | 2008-10-18T21:12:07Z | 215,902 | <p>The only purpose of entity groups (defined by the parent attribute) is to enable transactions among different entities. If you don't need the transactions, don't use the entity group relationships.</p>
<p>I suggest you re-reading the <a href="http://code.google.com/appengine/docs/datastore/keysandentitygroups.html">Keys and Entity Groups</a> section of the docs, it took me quite a few reads to grasp the idea.</p>
<p>Also watch these talks, among other things they discuss transactions and entity groups:</p>
<ul>
<li><a href="http://sites.google.com/site/io/building-scalable-web-applications-with-google-app-engine">Building Scalable Web Applications with Google App Engine</a></li>
<li><a href="http://sites.google.com/site/io/under-the-covers-of-the-google-app-engine-datastore">Under the Covers of the Google App Engine Datastore</a></li>
</ul>
| 8 | 2008-10-19T02:23:47Z | [
"python",
"api",
"google-app-engine"
] |
What's the difference between a parent and a reference property in Google App Engine? | 215,570 | <p>From what I understand, the parent attribute of a db.Model (typically defined/passed in the constructor call) allows you to define hierarchies in your data models. As a result, this increases the size of the entity group. However, it's not very clear to me why we would want to do that. Is this strictly for ACID compliance? I would like to see scenarios where each is best suited or more appropriate.</p>
| 10 | 2008-10-18T21:12:07Z | 216,187 | <p>There are several differences:</p>
<ul>
<li>All entities with the same ancestor are in the same entity group. Transactions can only affect entities inside a single entity group.</li>
<li>All writes to a single entity group are serialized, so throughput is limited.</li>
<li>The parent entity is set on creation and is fixed. References can be changed at any time.</li>
<li>With reference properties, you can only query for direct relationships, but with parent properties you can use the .ancestor() filter to find everything (directly or indirectly) descended from a given ancestor.</li>
<li>Each entity has only a single parent, but can have multiple reference properties.</li>
</ul>
| 15 | 2008-10-19T08:56:43Z | [
"python",
"api",
"google-app-engine"
] |
What is the purpose of the colon before a block in Python? | 215,581 | <p>What is the purpose of the colon before a block in Python?</p>
<p>Example:</p>
<pre><code>if n == 0:
print "The end"
</code></pre>
| 44 | 2008-10-18T21:18:46Z | 215,676 | <p>The colon is there to declare the start of an indented block.</p>
<p>Technically, it's not necessary; you could just indent and de-indent when the block is done. However, based on the <a href="http://www.python.org/dev/peps/pep-0020/">Python koan</a> âexplicit is better than implicitâ (EIBTI), I believe that Guido deliberately made the colon obligatory, so <em>any</em> statement that <em>should</em> be followed by indented code ends in a colon. (It also allows one-liners if you continue after the colon, but this style is not in wide use.)</p>
<p>It also makes the work of syntax-aware auto-indenting editors easier, which also counted in the decision.</p>
<hr>
<p>This question turns out to be a <a href="http://docs.python.org/faq/design.html#why-are-colons-required-for-the-if-while-def-class-statements">Python FAQ</a>, and I found one of its answers by Guido <a href="http://markmail.org/message/ve7mwqxhci4pm6lw">here</a>:</p>
<blockquote>
<p><strong>Why are colons required for the if/while/def/class statements?</strong></p>
<p>The colon is required primarily to enhance readability (one of the results of the experimental ABC language). Consider this:</p>
<pre><code>if a == b
print a
</code></pre>
<p>versus </p>
<pre><code>if a == b:
print a
</code></pre>
<p>Notice how the second one is slightly easier to read. Notice further how a colon sets off the example in this FAQ answer; itâs a standard usage in English.</p>
<p>Another minor reason is that the colon makes it easier for editors with syntax highlighting; they can look for colons to decide when indentation needs to be increased instead of having to do a more elaborate parsing of the program text.</p>
</blockquote>
| 56 | 2008-10-18T22:49:32Z | [
"python",
"syntax"
] |
What is the purpose of the colon before a block in Python? | 215,581 | <p>What is the purpose of the colon before a block in Python?</p>
<p>Example:</p>
<pre><code>if n == 0:
print "The end"
</code></pre>
| 44 | 2008-10-18T21:18:46Z | 216,060 | <p>Three reasons:</p>
<ol>
<li>To increase readability. The colon helps the code flow into the following indented block.</li>
<li>To help text editors/IDEs, they can automatically indent the next line if the previous line ended with a colon.</li>
<li>To make parsing by python slightly easier.</li>
</ol>
| 12 | 2008-10-19T05:40:07Z | [
"python",
"syntax"
] |
What is the purpose of the colon before a block in Python? | 215,581 | <p>What is the purpose of the colon before a block in Python?</p>
<p>Example:</p>
<pre><code>if n == 0:
print "The end"
</code></pre>
| 44 | 2008-10-18T21:18:46Z | 1,464,645 | <p>Consider the following list of things to buy from the grocery store, written in Pewprikanese.</p>
<pre><code>pewkah
lalala
chunkykachoo
pewpewpew
skunkybacon
</code></pre>
<p>When I read that, I'm confused, Are chunkykachoo and pewpewpew a kind of lalala? Or what if chunkykachoo and pewpewpew are indented just because they are special items?</p>
<p>Now see what happens when my Pewprikanese friend add a colon to help me parse the list better: (<-- like this)</p>
<pre><code>pewkah
lalala: (<-- see this colon)
chunkykachoo
pewpewpew
skunkybacon
</code></pre>
<p>Now it's clear that chunkykachoo and pewpewpew are a kind of lalala.</p>
<p>Let's say there is a person who's starting to learn Python, which happens to be her first programming language to learn. Without colons, there's a considerable probability that she's going to keep thinking "this lines are indented because this lines are like special items.", and it could take a while to realize that that's not the best way to think about indentation.</p>
| 15 | 2009-09-23T08:13:16Z | [
"python",
"syntax"
] |
What is the purpose of the colon before a block in Python? | 215,581 | <p>What is the purpose of the colon before a block in Python?</p>
<p>Example:</p>
<pre><code>if n == 0:
print "The end"
</code></pre>
| 44 | 2008-10-18T21:18:46Z | 3,075,389 | <p>As far as I know, it's an intentional design to make it more obvious, that the reader should expect an indentation after the colon.</p>
<p>It also makes constructs like this possible:</p>
<pre><code>if expression: action()
code_continues()
</code></pre>
<p>Note (as a commenter did) that this is not exactly the shining gold standard of good Python style. It would be far better to have a blank, there:</p>
<pre><code>if expression: action()
code_continues()
</code></pre>
<p>to avoid confusion. I just wanted to make it clear, with the first example, that it's possible to write like that, since having the code for the <code>if</code> immediately following the colon makes it possible for the compiler to understand that the next line should <em>not</em> be indented.</p>
| 4 | 2010-06-19T12:00:59Z | [
"python",
"syntax"
] |
How do I find all cells with a particular attribute in BeautifulSoup? | 215,667 | <p>Hi
I am trying to develop a script to pull some data from a large number of html tables. One problem is that the number of rows that contain the information to create the column headings is indeterminate. I have discovered that the last row of the set of header rows has the attribute border-bottom for each cell with a value. Thus I decided to find those cells with the attribute border-bottom. As you can see I initialized a list. I intended to find the parent of each of the cells that end up in the borderCells list. However, when I run this code only one cell, that is the first cell in allCells with the attribute border-bottom is added to the list borderCells. For your information allCells has 193 cells, 9 of them have the attr border-bottom. Thus I was expecting nine members in the borderCells list. Any help is appreciated.</p>
<pre><code>borderCells=[]
for each in allCells:
if each.find(attrs={"style": re.compile("border-bottom")}):
borderCells.append(each)
</code></pre>
| 2 | 2008-10-18T22:37:05Z | 215,720 | <p>Is there any reason </p>
<blockquote>
<p><code>borderCells = soup.findAll("td", style=re.compile("border-bottom")})</code></p>
</blockquote>
<p>wouldn't work? It's kind of hard to figure out exactly what you're asking for, since your description of the original tables is pretty ambiguous, and it's not really clear what allCells is supposed to be either.</p>
<p>I would suggest giving a representative sample of the HTML you're working with, along with the "correct" results pulled from that table.</p>
| 2 | 2008-10-18T23:35:32Z | [
"python",
"parsing",
"beautifulsoup"
] |
How do I find all cells with a particular attribute in BeautifulSoup? | 215,667 | <p>Hi
I am trying to develop a script to pull some data from a large number of html tables. One problem is that the number of rows that contain the information to create the column headings is indeterminate. I have discovered that the last row of the set of header rows has the attribute border-bottom for each cell with a value. Thus I decided to find those cells with the attribute border-bottom. As you can see I initialized a list. I intended to find the parent of each of the cells that end up in the borderCells list. However, when I run this code only one cell, that is the first cell in allCells with the attribute border-bottom is added to the list borderCells. For your information allCells has 193 cells, 9 of them have the attr border-bottom. Thus I was expecting nine members in the borderCells list. Any help is appreciated.</p>
<pre><code>borderCells=[]
for each in allCells:
if each.find(attrs={"style": re.compile("border-bottom")}):
borderCells.append(each)
</code></pre>
| 2 | 2008-10-18T22:37:05Z | 215,727 | <p>Well you know computers are always right. The answer is that the attrs are on different things in the html. What I was modeling on what some html that looked like this:</p>
<pre><code><TD nowrap align="left" valign="bottom">
<DIV style="border-bottom: 1px solid #000000; width: 1%; padding-bottom: 1px">
<B>Name</B>
</DIV>
</TD>
</code></pre>
<p>The other places in the file where style="border-bottom etc look like:</p>
<pre><code><TD colspan="2" nowrap align="center" valign="bottom" style="border-bottom: 1px solid 00000">
<B>Location</B>
</TD>
</code></pre>
<p>so now I have to modify the question to figure out how identify those cells where the attr is at the td level not the div level</p>
| 0 | 2008-10-18T23:36:05Z | [
"python",
"parsing",
"beautifulsoup"
] |
How do I find all cells with a particular attribute in BeautifulSoup? | 215,667 | <p>Hi
I am trying to develop a script to pull some data from a large number of html tables. One problem is that the number of rows that contain the information to create the column headings is indeterminate. I have discovered that the last row of the set of header rows has the attribute border-bottom for each cell with a value. Thus I decided to find those cells with the attribute border-bottom. As you can see I initialized a list. I intended to find the parent of each of the cells that end up in the borderCells list. However, when I run this code only one cell, that is the first cell in allCells with the attribute border-bottom is added to the list borderCells. For your information allCells has 193 cells, 9 of them have the attr border-bottom. Thus I was expecting nine members in the borderCells list. Any help is appreciated.</p>
<pre><code>borderCells=[]
for each in allCells:
if each.find(attrs={"style": re.compile("border-bottom")}):
borderCells.append(each)
</code></pre>
| 2 | 2008-10-18T22:37:05Z | 215,737 | <p>Someone took away one of their answers though I tested it and it worked for me. Thanks for the help. Both answers worked and I learned a little bit more about how to post questions and after I stare at the code for a while I might learn more about Python and BeautifulSoup</p>
| 0 | 2008-10-18T23:45:51Z | [
"python",
"parsing",
"beautifulsoup"
] |
Why Python decorators rather than closures? | 215,689 | <p>I still haven't got my head around decorators in Python.</p>
<p>I've already started using a lot of closures to do things like customize functions and classes in my coding.</p>
<p>Eg.</p>
<pre><code>class Node :
def __init__(self,val,children) :
self.val = val
self.children = children
def makeRunner(f) :
def run(node) :
f(node)
for x in node.children :
run(x)
return run
tree=Node(1,[Node(2,[]),Node(3,[Node(4,[]),Node(5,[])])])
def pp(n) : print "%s," % n.val
printTree = makeRunner(pp)
printTree(tree)
</code></pre>
<p>As far as I can see, decorators are just a different syntax for doing something similar. </p>
<p>Instead of </p>
<pre><code>def pp(n) : print "%s," % n.val
printTree = makeRunner(pp)
</code></pre>
<p>I would write :</p>
<pre><code>@makeRunner
def printTree(n) : print "%s," % n.val
</code></pre>
<p>Is this all there is to decorators? Or is there a fundamental difference that I've missed? </p>
| 13 | 2008-10-18T23:07:28Z | 215,782 | <p>Are your examples real code, or just examples?</p>
<p>If they're real code, I think you overuse decorators, probably because of your background (i.e. you are used to other programming languages)</p>
<h3>Stage 1: avoiding decorators</h3>
<pre><code>def run(rootnode, func):
def _run(node): # recursive internal function
func(node)
for x in node.children:
_run(x) # recurse
_run(rootnode) # initial run
</code></pre>
<p>This run method obsoletes makeRunner. Your example turns to:</p>
<pre><code>def pp(n): print "%s," % n.val
run(tree, pp)
</code></pre>
<p>However, this ignores completely generators, soâ¦</p>
<h3>Stage 2: using generators</h3>
<pre><code>class Node :
def __init__(self,val,children) :
self.val = val
self.children = children
def __iter__(self): # recursive
yield self
for child in self.children:
for item in child: # recurse
yield item
def run(rootnode, func):
for node in rootnode:
func(node)
</code></pre>
<p>Your example remains</p>
<pre><code>def pp(n): print "%s," % n.val
run(tree, pp)
</code></pre>
<p>Note that the special method <code>__iter__</code> allows us to use the <code>for node in rootnode:</code> construct. If you don't like it, just rename the <code>__iter__</code> method to e.g. <code>walker</code>, and change the <code>run</code> loop into: <code>for node in rootnode.walker():</code><br />
Obviously, the <code>run</code> function could be a method of <code>class Node</code> instead.</p>
<p>As you see, I suggest you use directly <code>run(tree, func)</code> instead of binding them to the name <code>printTree</code>, but you can use them in a decorator, or you can make use of the <code>functools.partial</code> function:</p>
<pre><code>printTree= functools.partial(run, func=pp)
</code></pre>
<p>and from then on, you would just</p>
<pre><code>printTree(tree)
</code></pre>
| 7 | 2008-10-19T00:34:16Z | [
"python",
"decorator"
] |
Why Python decorators rather than closures? | 215,689 | <p>I still haven't got my head around decorators in Python.</p>
<p>I've already started using a lot of closures to do things like customize functions and classes in my coding.</p>
<p>Eg.</p>
<pre><code>class Node :
def __init__(self,val,children) :
self.val = val
self.children = children
def makeRunner(f) :
def run(node) :
f(node)
for x in node.children :
run(x)
return run
tree=Node(1,[Node(2,[]),Node(3,[Node(4,[]),Node(5,[])])])
def pp(n) : print "%s," % n.val
printTree = makeRunner(pp)
printTree(tree)
</code></pre>
<p>As far as I can see, decorators are just a different syntax for doing something similar. </p>
<p>Instead of </p>
<pre><code>def pp(n) : print "%s," % n.val
printTree = makeRunner(pp)
</code></pre>
<p>I would write :</p>
<pre><code>@makeRunner
def printTree(n) : print "%s," % n.val
</code></pre>
<p>Is this all there is to decorators? Or is there a fundamental difference that I've missed? </p>
| 13 | 2008-10-18T23:07:28Z | 335,442 | <p>While it is true that syntactically, decorators are just "sugar", that is not the best way to think about them.</p>
<p>Decorators allow you to weave functionality into your existing code without actually modifying it. And they allow you to do it in a way that is declarative.</p>
<p>This allows you to use decorators to do <em>aspect-oriented programming</em> (AOP). So you want to use a decorator when you have a cross-cutting concern that you want to encapsulate in one place. </p>
<p>The quintessential example would probably be logging, where you want to log the entry or exit of a function, or both. Using a decorator is equivalent to applying advice (log this!) to a joinpoint (during method entry or exit).</p>
<p>Method decoration is a concept like OOP or list comprehensions. As you point out, it is not always appropriate, and <strong>can</strong> be overused. But in the right place, it can be useful for making code more modular and decoupled.</p>
| 13 | 2008-12-02T21:03:22Z | [
"python",
"decorator"
] |
Why Python decorators rather than closures? | 215,689 | <p>I still haven't got my head around decorators in Python.</p>
<p>I've already started using a lot of closures to do things like customize functions and classes in my coding.</p>
<p>Eg.</p>
<pre><code>class Node :
def __init__(self,val,children) :
self.val = val
self.children = children
def makeRunner(f) :
def run(node) :
f(node)
for x in node.children :
run(x)
return run
tree=Node(1,[Node(2,[]),Node(3,[Node(4,[]),Node(5,[])])])
def pp(n) : print "%s," % n.val
printTree = makeRunner(pp)
printTree(tree)
</code></pre>
<p>As far as I can see, decorators are just a different syntax for doing something similar. </p>
<p>Instead of </p>
<pre><code>def pp(n) : print "%s," % n.val
printTree = makeRunner(pp)
</code></pre>
<p>I would write :</p>
<pre><code>@makeRunner
def printTree(n) : print "%s," % n.val
</code></pre>
<p>Is this all there is to decorators? Or is there a fundamental difference that I've missed? </p>
| 13 | 2008-10-18T23:07:28Z | 26,626,194 | <p>Following up Dutch Master's AOP reference, you'll find that using decorators becomes especially useful when you start <strong>adding parameters</strong> to modify the behaviour of the decorated function/method, and reading that above the function definition is so much easier.</p>
<p>In one project I recall, we needed to supervise tons of celery tasks and so we came up with the idea of using a decorator to plug-and-tweak as required, which was something like:</p>
<pre><code>class tracked_with(object):
"""
Method decorator used to track the results of celery tasks.
"""
def __init__(self, model, unique=False, id_attr='results_id',
log_error=False, raise_error=False):
self.model = model
self.unique = unique
self.id_attr = id_attr
self.log_error = log_error
self.raise_error = raise_error
def __call__(self, fn):
def wrapped(*args, **kwargs):
# Unique passed by parameter has priority above the decorator def
unique = kwargs.get('unique', None)
if unique is not None:
self.unique = unique
if self.unique:
caller = args[0]
pending = self.model.objects.filter(
state=self.model.Running,
task_type=caller.__class__.__name__
)
if pending.exists():
raise AssertionError('Another {} task is already running'
''.format(caller.__class__.__name__))
results_id = kwargs.get(self.id_attr)
try:
result = fn(*args, **kwargs)
except Retry:
# Retry must always be raised to retry a task
raise
except Exception as e:
# Error, update stats, log/raise/return depending on values
if results_id:
self.model.update_stats(results_id, error=e)
if self.log_error:
logger.error(e)
if self.raise_error:
raise
else:
return e
else:
# No error, save results in refresh object and return
if results_id:
self.model.update_stats(results_id, **result)
return result
return wrapped
</code></pre>
<p>Then we simply decorated the <code>run</code> method on the tasks with the params required for each case, like:</p>
<pre><code>class SomeTask(Task):
@tracked_with(RefreshResults, unique=True, log_error=False)
def run(self, *args, **kwargs)...
</code></pre>
<p>Then changing the behaviour of the task (or removing the tracking altogether) meant tweaking one param, or commenting out the decorated line. Super easy to implement, but more importantly, <strong>super easy to understand</strong> on inspection.</p>
| 0 | 2014-10-29T09:01:05Z | [
"python",
"decorator"
] |
How can you use BeautifulSoup to get colindex numbers? | 215,702 | <p>I had a problem a week or so ago. Since I think the solution was cool I am sharing it here while I am waiting for an answer to the question I posted earlier. I need to know the relative position for the column headings in a table so I know how to match the column heading up with the data in the rows below. I found some of my tables had the following row as the first row in the table</p>
<pre><code><!-- Table Width Row -->
<TR style="font-size: 1pt" valign="bottom">
<TD width="60%">&nbsp;</TD> <!-- colindex=01 type=maindata -->
<TD width="1%">&nbsp;</TD> <!-- colindex=02 type=gutter -->
<TD width="1%" align="right">&nbsp;</TD> <!-- colindex=02 type=lead -->
<TD width="9%" align="right">&nbsp;</TD> <!-- colindex=02 type=body -->
<TD width="1%" align="left">&nbsp;</TD> <!-- colindex=02 type=hang1 -->
<TD width="3%">&nbsp;</TD> <!-- colindex=03 type=gutter -->
<TD width="1%" align="right">&nbsp;</TD> <!-- colindex=03 type=lead -->
<TD width="4%" align="right">&nbsp;</TD> <!-- colindex=03 type=body -->
<TD width="1%" align="left">&nbsp;</TD> <!-- colindex=03 type=hang1 -->
<TD width="3%">&nbsp;</TD> <!-- colindex=04 type=gutter -->
<TD width="1%" align="right">&nbsp;</TD> <!-- colindex=04 type=lead -->
<TD width="4%" align="right">&nbsp;</TD> <!-- colindex=04 type=body -->
<TD width="1%" align="left">&nbsp;</TD> <!-- colindex=04 type=hang1 -->
<TD width="3%">&nbsp;</TD> <!-- colindex=05 type=gutter -->
<TD width="1%" align="right">&nbsp;</TD> <!-- colindex=05 type=lead -->
<TD width="5%" align="right">&nbsp;</TD> <!-- colindex=05 type=body -->
<TD width="1%" align="left">&nbsp;</TD> <!-- colindex=05 type=hang1 -->
</TR>
</code></pre>
<p>I thought wow, this will be easy because the data is in the column below type=body. Counting down I knew that in the data rows I would need to get the values in columns [3, 7, 11, 15]. So I set out to accomplish that using this code:</p>
<pre><code>indexComment = souptoGetColIndex.findAll(text=re.compile("type=body"))
indexRow=indexComment[0].findParent()
indexCells=indexRow.findAll(text=re.compile("type=body"))
for each in range(len(indexCells)):
collist.append(tdlist.index(indexCells[each].previousSibling.previousSibling))
</code></pre>
<p>what I got back was collist=[0, 3, 7, 7, 15]</p>
<p>It turns out I think that because cells in the 7th and 11th position looked exactly alike the same index position was returned. I was trying to figure out how to deal with this, clearly I had to make them look different. So what I did was make them look different by first using a readlines to read each line of the file in and change the blank spaces to a random integer.</p>
<pre><code>for each in toGetColIndex:
newlt.append(each.replace(r"&nbsp;",str(random.randint(1,14567))))
</code></pre>
<p>a friend pointed out that I could lower overhead by using this instead</p>
<pre><code>for each in toGetColIndex:
newlt.append(each.replace(r"&nbsp;",str(toGetColIndex.index(each))))
</code></pre>
<p>Nonetheless, each of these approaches gets me a list with the colindex for the location of my headers for each column and to use on the data rows. Note that replace function is missing the blank space since I guess the html is causing it to disappear the actual code uses r"&.n.b.s.p;" without the periods</p>
| 1 | 2008-10-18T23:17:38Z | 219,000 | <p>The code below produces [3, 7, 11, 15] which is what I understand you seek</p>
<pre><code>from BeautifulSoup import BeautifulSoup
from re import compile
soup = BeautifulSoup(
'''<HTML><BODY>
<TABLE>
<TR style="font-size: 1pt" valign="bottom">
<TD width="60%"> </TD> <!-- colindex=01 type=maindata -->
<TD width="1%"> </TD> <!-- colindex=02 type=gutter -->
<TD width="1%" align="right"> </TD> <!-- colindex=02 type=lead -->
<TD width="9%" align="right"> </TD> <!-- colindex=02 type=body -->
<TD width="1%" align="left"> </TD> <!-- colindex=02 type=hang1 -->
<TD width="3%"> </TD> <!-- colindex=03 type=gutter -->
<TD width="1%" align="right"> </TD> <!-- colindex=03 type=lead -->
<TD width="4%" align="right"> </TD> <!-- colindex=03 type=body -->
<TD width="1%" align="left"> </TD> <!-- colindex=03 type=hang1 -->
<TD width="3%"> </TD> <!-- colindex=04 type=gutter -->
<TD width="1%" align="right"> </TD> <!-- colindex=04 type=lead -->
<TD width="4%" align="right"> </TD> <!-- colindex=04 type=body -->
<TD width="1%" align="left"> </TD> <!-- colindex=04 type=hang1 -->
<TD width="3%"> </TD> <!-- colindex=05 type=gutter -->
<TD width="1%" align="right"> </TD> <!-- colindex=05 type=lead -->
<TD width="5%" align="right"> </TD> <!-- colindex=05 type=body -->
<TD width="1%" align="left"> </TD> <!-- colindex=05 type=hang1 -->
</TR>
</TABLE> </BODY></HTML>'''
)
tables = soup.findAll('table')
matcher = compile('colindex')
def body_cols(row):
for i, comment in enumerate(row.findAll(text=matcher)):
if 'type=body' in comment:
yield i
for table in soup.findAll('table'):
index_row = table.find('tr')
print list(body_cols(index_row))
</code></pre>
| 1 | 2008-10-20T16:13:14Z | [
"python",
"html",
"parsing",
"beautifulsoup"
] |
Python embedded in CPP: how to get data back to CPP | 215,752 | <p>While working on a C++ project, I was looking for a third party library for something that is not my core business. I found a really good library, doing exactly what's needed, but it is written in Python. I decided to experiment with embedding Python code in C++, using the Boost.Python library.</p>
<p>The C++ code looks something like this:</p>
<pre><code>#include <string>
#include <iostream>
#include <boost/python.hpp>
using namespace boost::python;
int main(int, char **)
{
Py_Initialize();
try
{
object module((handle<>(borrowed(PyImport_AddModule("__main__")))));
object name_space = module.attr("__dict__");
object ignored = exec("from myModule import MyFunc\n"
"MyFunc(\"some_arg\")\n",
name_space);
std::string res = extract<std::string>(name_space["result"]);
}
catch (error_already_set)
{
PyErr_Print();
}
Py_Finalize();
return 0;
}
</code></pre>
<p>A (very) simplified version of the Python code looks like this:</p>
<pre><code>import thirdparty
def MyFunc(some_arg):
result = thirdparty.go()
print result
</code></pre>
<p>Now the problem is this:
'MyFunc' executes fine, i can see the print of 'result'.
What i cannot do is read 'result' back from the C++ code. The extract command never finds 'result' in any namespace.
I tried defining 'result' as a global, i even tried returning a tuple, but i cannot get it to work.</p>
| 11 | 2008-10-18T23:59:37Z | 215,772 | <p>You should be able to return the result from MyFunc, which would then end up in the variable you are currently calling "ignored". This eliminates the need to access it in any other way.</p>
| 0 | 2008-10-19T00:19:55Z | [
"c++",
"python",
"boost-python"
] |
Python embedded in CPP: how to get data back to CPP | 215,752 | <p>While working on a C++ project, I was looking for a third party library for something that is not my core business. I found a really good library, doing exactly what's needed, but it is written in Python. I decided to experiment with embedding Python code in C++, using the Boost.Python library.</p>
<p>The C++ code looks something like this:</p>
<pre><code>#include <string>
#include <iostream>
#include <boost/python.hpp>
using namespace boost::python;
int main(int, char **)
{
Py_Initialize();
try
{
object module((handle<>(borrowed(PyImport_AddModule("__main__")))));
object name_space = module.attr("__dict__");
object ignored = exec("from myModule import MyFunc\n"
"MyFunc(\"some_arg\")\n",
name_space);
std::string res = extract<std::string>(name_space["result"]);
}
catch (error_already_set)
{
PyErr_Print();
}
Py_Finalize();
return 0;
}
</code></pre>
<p>A (very) simplified version of the Python code looks like this:</p>
<pre><code>import thirdparty
def MyFunc(some_arg):
result = thirdparty.go()
print result
</code></pre>
<p>Now the problem is this:
'MyFunc' executes fine, i can see the print of 'result'.
What i cannot do is read 'result' back from the C++ code. The extract command never finds 'result' in any namespace.
I tried defining 'result' as a global, i even tried returning a tuple, but i cannot get it to work.</p>
| 11 | 2008-10-18T23:59:37Z | 215,843 | <p>I think what you need is either <code>PyObject_CallObject(<py function>, <args>)</code>, which returns the return value of the function you call as a PyObject, or <code>PyRun_String(<expression>, Py_eval_input, <globals>, <locals>)</code> which evaluates a single expression and returns its result.</p>
| 1 | 2008-10-19T01:20:35Z | [
"c++",
"python",
"boost-python"
] |
Python embedded in CPP: how to get data back to CPP | 215,752 | <p>While working on a C++ project, I was looking for a third party library for something that is not my core business. I found a really good library, doing exactly what's needed, but it is written in Python. I decided to experiment with embedding Python code in C++, using the Boost.Python library.</p>
<p>The C++ code looks something like this:</p>
<pre><code>#include <string>
#include <iostream>
#include <boost/python.hpp>
using namespace boost::python;
int main(int, char **)
{
Py_Initialize();
try
{
object module((handle<>(borrowed(PyImport_AddModule("__main__")))));
object name_space = module.attr("__dict__");
object ignored = exec("from myModule import MyFunc\n"
"MyFunc(\"some_arg\")\n",
name_space);
std::string res = extract<std::string>(name_space["result"]);
}
catch (error_already_set)
{
PyErr_Print();
}
Py_Finalize();
return 0;
}
</code></pre>
<p>A (very) simplified version of the Python code looks like this:</p>
<pre><code>import thirdparty
def MyFunc(some_arg):
result = thirdparty.go()
print result
</code></pre>
<p>Now the problem is this:
'MyFunc' executes fine, i can see the print of 'result'.
What i cannot do is read 'result' back from the C++ code. The extract command never finds 'result' in any namespace.
I tried defining 'result' as a global, i even tried returning a tuple, but i cannot get it to work.</p>
| 11 | 2008-10-18T23:59:37Z | 215,874 | <p>First of all, change your function to <code>return</code> the value. <code>print</code>ing it will complicate things since you want to get the value back. Suppose your <code>MyModule.py</code> looks like this:</p>
<pre><code>import thirdparty
def MyFunc(some_arg):
result = thirdparty.go()
return result
</code></pre>
<p>Now, to do what you want, you have to go beyond basic embedding, as the <a href="http://docs.python.org/extending/embedding.html">documentation says</a>. Here is the full code to run your function:</p>
<pre><code>#include <Python.h>
int
main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pFunc;
PyObject *pArgs, *pArg, *pResult;
int i;
Py_Initialize();
pName = PyString_FromString("MyModule.py");
/* Error checking of pName left out as exercise */
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, "MyFunc");
/* pFunc is a new reference */
if (pFunc) {
pArgs = PyTuple_New(0);
pArg = PyString_FromString("some parameter")
/* pArg reference stolen here: */
PyTuple_SetItem(pArgs, 0, pArg);
pResult = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pResult != NULL) {
printf("Result of call: %s\n", PyString_AsString(pResult));
Py_DECREF(pResult);
}
else {
Py_DECREF(pFunc);
Py_DECREF(pModule);
PyErr_Print();
fprintf(stderr,"Call failed\n");
return 1;
}
}
else {
if (PyErr_Occurred())
PyErr_Print();
fprintf(stderr, "Cannot find function");
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
else {
PyErr_Print();
fprintf(stderr, "Failed to load module");
return 1;
}
Py_Finalize();
return 0;
}
</code></pre>
| 6 | 2008-10-19T01:53:32Z | [
"c++",
"python",
"boost-python"
] |
Python embedded in CPP: how to get data back to CPP | 215,752 | <p>While working on a C++ project, I was looking for a third party library for something that is not my core business. I found a really good library, doing exactly what's needed, but it is written in Python. I decided to experiment with embedding Python code in C++, using the Boost.Python library.</p>
<p>The C++ code looks something like this:</p>
<pre><code>#include <string>
#include <iostream>
#include <boost/python.hpp>
using namespace boost::python;
int main(int, char **)
{
Py_Initialize();
try
{
object module((handle<>(borrowed(PyImport_AddModule("__main__")))));
object name_space = module.attr("__dict__");
object ignored = exec("from myModule import MyFunc\n"
"MyFunc(\"some_arg\")\n",
name_space);
std::string res = extract<std::string>(name_space["result"]);
}
catch (error_already_set)
{
PyErr_Print();
}
Py_Finalize();
return 0;
}
</code></pre>
<p>A (very) simplified version of the Python code looks like this:</p>
<pre><code>import thirdparty
def MyFunc(some_arg):
result = thirdparty.go()
print result
</code></pre>
<p>Now the problem is this:
'MyFunc' executes fine, i can see the print of 'result'.
What i cannot do is read 'result' back from the C++ code. The extract command never finds 'result' in any namespace.
I tried defining 'result' as a global, i even tried returning a tuple, but i cannot get it to work.</p>
| 11 | 2008-10-18T23:59:37Z | 216,224 | <p>Based on ΤÎΩΤÎÎÎÎ¥, Josh and Nosklo's answers i finally got it work using boost.python:</p>
<p>Python:</p>
<pre><code>import thirdparty
def MyFunc(some_arg):
result = thirdparty.go()
return result
</code></pre>
<p>C++:</p>
<pre><code>#include <string>
#include <iostream>
#include <boost/python.hpp>
using namespace boost::python;
int main(int, char **)
{
Py_Initialize();
try
{
object module = import("__main__");
object name_space = module.attr("__dict__");
exec_file("MyModule.py", name_space, name_space);
object MyFunc = name_space["MyFunc"];
object result = MyFunc("some_args");
// result is a dictionary
std::string val = extract<std::string>(result["val"]);
}
catch (error_already_set)
{
PyErr_Print();
}
Py_Finalize();
return 0;
}
</code></pre>
<p>Some important points:</p>
<ol>
<li>I changed 'exec' to 'exec_file' out of
convenience, it also works with
plain 'exec'. </li>
<li>The main reason it failed is that <strong>i
did not pass a "local" name_sapce to
'exec' or 'exec_file'</strong> - this is now
fixed by passing name_space twice.</li>
<li>If the python function returns
unicode strings, they are not
convertible to 'std::string', so i
had to suffix all python strings
with '.encode('ASCII', 'ignore')'.</li>
</ol>
| 3 | 2008-10-19T09:47:47Z | [
"c++",
"python",
"boost-python"
] |
How do I coherently organize modules for a PyGTK desktop application? | 216,093 | <p>I am working on a desktop application in PyGTK and seem to be bumping up against some limitations of my file organization. Thus far I've structured my project this way:</p>
<ul>
<li>application.py - holds the primary application class (most functional routines)</li>
<li>gui.py - holds a loosely coupled GTK gui implementation. Handles signal callbacks, etc.</li>
<li>command.py - holds command line automation functions not dependent on data in the application class</li>
<li>state.py - holds the state data persistence class</li>
</ul>
<p>This has served fairly well so far, but at this point application.py is starting to get rather long. I have looked at numerous other PyGTK applications and they seem to have similar structural issues. At a certain point the primary module starts to get very long and there is not obvious way of breaking the code out into narrower modules without sacrificing clarity and object orientation.</p>
<p>I have considered making the GUI the primary module and having seperate modules for the toolbar routines, the menus routines, etc, but at that point I believe I will lose most of the benefits of OOP and end up with an everything-references-everything scenario.</p>
<p>Should I just deal with having a very long central module or is there a better way of structuring the project so that I don't have to rely on the class browser so much?</p>
<p><strong>EDIT I</strong></p>
<p>Ok, so point taken regarding all the MVC stuff. I do have a rough approximation of MVC in my code, but admittedly I could probably gain some mileage by further segregating the model and controller. However, I am reading over python-gtkmvc's documentation (which is a great find by the way, thank you for referencing it) and my impression is that its not going to solve my problem so much as just formalize it. My application is a single glade file, generally a single window. So no matter how tightly I define the MVC roles of the modules I'm still going to have one controller module doing most everything, which is pretty much what I have now. Admittedly I'm a little fuzzy on proper MVC implementation and I'm going to keep researching, but it doesn't look to me like this architecture is going to get any more stuff out of my main file, its just going to rename that file to controller.py.</p>
<p>Should I be thinking about separate Controller/View pairs for seperate sections of the window (the toolbar, the menus, etc)? Perhaps that is what I'm missing here. It seems that this is what S. Lott is referring to in his second bullet point.</p>
<p>Thanks for the responses so far.</p>
| 7 | 2008-10-19T06:07:28Z | 216,098 | <p>This has likely nothing to do with PyGTK, but rather a general code organization issue. You would probably benefit from applying some MVC (Model-View-Controller) design patterns. See <a href="http://en.wikipedia.org/wiki/Design_Patterns" rel="nofollow">Design Patterns</a>, for example.</p>
| 2 | 2008-10-19T06:15:00Z | [
"python",
"gtk",
"module",
"pygtk",
"organization"
] |
How do I coherently organize modules for a PyGTK desktop application? | 216,093 | <p>I am working on a desktop application in PyGTK and seem to be bumping up against some limitations of my file organization. Thus far I've structured my project this way:</p>
<ul>
<li>application.py - holds the primary application class (most functional routines)</li>
<li>gui.py - holds a loosely coupled GTK gui implementation. Handles signal callbacks, etc.</li>
<li>command.py - holds command line automation functions not dependent on data in the application class</li>
<li>state.py - holds the state data persistence class</li>
</ul>
<p>This has served fairly well so far, but at this point application.py is starting to get rather long. I have looked at numerous other PyGTK applications and they seem to have similar structural issues. At a certain point the primary module starts to get very long and there is not obvious way of breaking the code out into narrower modules without sacrificing clarity and object orientation.</p>
<p>I have considered making the GUI the primary module and having seperate modules for the toolbar routines, the menus routines, etc, but at that point I believe I will lose most of the benefits of OOP and end up with an everything-references-everything scenario.</p>
<p>Should I just deal with having a very long central module or is there a better way of structuring the project so that I don't have to rely on the class browser so much?</p>
<p><strong>EDIT I</strong></p>
<p>Ok, so point taken regarding all the MVC stuff. I do have a rough approximation of MVC in my code, but admittedly I could probably gain some mileage by further segregating the model and controller. However, I am reading over python-gtkmvc's documentation (which is a great find by the way, thank you for referencing it) and my impression is that its not going to solve my problem so much as just formalize it. My application is a single glade file, generally a single window. So no matter how tightly I define the MVC roles of the modules I'm still going to have one controller module doing most everything, which is pretty much what I have now. Admittedly I'm a little fuzzy on proper MVC implementation and I'm going to keep researching, but it doesn't look to me like this architecture is going to get any more stuff out of my main file, its just going to rename that file to controller.py.</p>
<p>Should I be thinking about separate Controller/View pairs for seperate sections of the window (the toolbar, the menus, etc)? Perhaps that is what I'm missing here. It seems that this is what S. Lott is referring to in his second bullet point.</p>
<p>Thanks for the responses so far.</p>
| 7 | 2008-10-19T06:07:28Z | 216,113 | <p>Python 2.6 supports <a href="http://docs.python.org/whatsnew/2.6.html#pep-366-explicit-relative-imports-from-a-main-module" rel="nofollow">explicit relative imports</a>, which make using packages even easier than previous versions.
I suggest you look into breaking your app into smaller modules inside a package.
You can organize your application like this:</p>
<pre><code>myapp/
application/
gui/
command/
state/
</code></pre>
<p>Where each directory has its own <code>__init__.py</code>. You can have a look at any python app or even standard library modules for examples.</p>
| 0 | 2008-10-19T06:41:46Z | [
"python",
"gtk",
"module",
"pygtk",
"organization"
] |
How do I coherently organize modules for a PyGTK desktop application? | 216,093 | <p>I am working on a desktop application in PyGTK and seem to be bumping up against some limitations of my file organization. Thus far I've structured my project this way:</p>
<ul>
<li>application.py - holds the primary application class (most functional routines)</li>
<li>gui.py - holds a loosely coupled GTK gui implementation. Handles signal callbacks, etc.</li>
<li>command.py - holds command line automation functions not dependent on data in the application class</li>
<li>state.py - holds the state data persistence class</li>
</ul>
<p>This has served fairly well so far, but at this point application.py is starting to get rather long. I have looked at numerous other PyGTK applications and they seem to have similar structural issues. At a certain point the primary module starts to get very long and there is not obvious way of breaking the code out into narrower modules without sacrificing clarity and object orientation.</p>
<p>I have considered making the GUI the primary module and having seperate modules for the toolbar routines, the menus routines, etc, but at that point I believe I will lose most of the benefits of OOP and end up with an everything-references-everything scenario.</p>
<p>Should I just deal with having a very long central module or is there a better way of structuring the project so that I don't have to rely on the class browser so much?</p>
<p><strong>EDIT I</strong></p>
<p>Ok, so point taken regarding all the MVC stuff. I do have a rough approximation of MVC in my code, but admittedly I could probably gain some mileage by further segregating the model and controller. However, I am reading over python-gtkmvc's documentation (which is a great find by the way, thank you for referencing it) and my impression is that its not going to solve my problem so much as just formalize it. My application is a single glade file, generally a single window. So no matter how tightly I define the MVC roles of the modules I'm still going to have one controller module doing most everything, which is pretty much what I have now. Admittedly I'm a little fuzzy on proper MVC implementation and I'm going to keep researching, but it doesn't look to me like this architecture is going to get any more stuff out of my main file, its just going to rename that file to controller.py.</p>
<p>Should I be thinking about separate Controller/View pairs for seperate sections of the window (the toolbar, the menus, etc)? Perhaps that is what I'm missing here. It seems that this is what S. Lott is referring to in his second bullet point.</p>
<p>Thanks for the responses so far.</p>
| 7 | 2008-10-19T06:07:28Z | 216,145 | <p>In the project <a href="http://wader-project.org">Wader</a> we use <a href="http://pygtkmvc.sourceforge.net/">python gtkmvc</a>, that makes much easier to apply the MVC patterns when using pygtk and glade, you can see the file organization of our project in the <a href="http://trac.wader-project.org/browser/trunk/wader">svn repository</a>:</p>
<pre><code>wader/
cli/
common/
contrib/
gtk/
controllers/
models/
views/
test/
utils/
</code></pre>
| 7 | 2008-10-19T07:39:33Z | [
"python",
"gtk",
"module",
"pygtk",
"organization"
] |
How do I coherently organize modules for a PyGTK desktop application? | 216,093 | <p>I am working on a desktop application in PyGTK and seem to be bumping up against some limitations of my file organization. Thus far I've structured my project this way:</p>
<ul>
<li>application.py - holds the primary application class (most functional routines)</li>
<li>gui.py - holds a loosely coupled GTK gui implementation. Handles signal callbacks, etc.</li>
<li>command.py - holds command line automation functions not dependent on data in the application class</li>
<li>state.py - holds the state data persistence class</li>
</ul>
<p>This has served fairly well so far, but at this point application.py is starting to get rather long. I have looked at numerous other PyGTK applications and they seem to have similar structural issues. At a certain point the primary module starts to get very long and there is not obvious way of breaking the code out into narrower modules without sacrificing clarity and object orientation.</p>
<p>I have considered making the GUI the primary module and having seperate modules for the toolbar routines, the menus routines, etc, but at that point I believe I will lose most of the benefits of OOP and end up with an everything-references-everything scenario.</p>
<p>Should I just deal with having a very long central module or is there a better way of structuring the project so that I don't have to rely on the class browser so much?</p>
<p><strong>EDIT I</strong></p>
<p>Ok, so point taken regarding all the MVC stuff. I do have a rough approximation of MVC in my code, but admittedly I could probably gain some mileage by further segregating the model and controller. However, I am reading over python-gtkmvc's documentation (which is a great find by the way, thank you for referencing it) and my impression is that its not going to solve my problem so much as just formalize it. My application is a single glade file, generally a single window. So no matter how tightly I define the MVC roles of the modules I'm still going to have one controller module doing most everything, which is pretty much what I have now. Admittedly I'm a little fuzzy on proper MVC implementation and I'm going to keep researching, but it doesn't look to me like this architecture is going to get any more stuff out of my main file, its just going to rename that file to controller.py.</p>
<p>Should I be thinking about separate Controller/View pairs for seperate sections of the window (the toolbar, the menus, etc)? Perhaps that is what I'm missing here. It seems that this is what S. Lott is referring to in his second bullet point.</p>
<p>Thanks for the responses so far.</p>
| 7 | 2008-10-19T06:07:28Z | 216,386 | <p>"holds the primary application class (most functional routines)"</p>
<p>As in singular -- one class?</p>
<p>I'm not surprised that the <strong>One Class Does Everything</strong> design isn't working. It might not be what I'd call object-oriented. It doesn't sound like it follows the typical MVC design pattern if your functionality is piling up in a single class.</p>
<p>What's in this massive class? I suggest that you can probably refactor this into pieces. You have two candidate dimensions for refactoring your application class -- if, indeed, I've guessed right that you've put everything into a single class.</p>
<ol>
<li><p>Before doing anything else, refactor into components that parallel the Real World Entities. It's not clear what's in your "state.py" -- wether this is a proper model of real-world entities, or just mappings between persistent storage and some murky data structure in the application. Most likely you'd move processing out of your application and into your model (possibly state.py, possibly a new module that is a proper model.)</p>
<p>Break your model into pieces. It will help organize the control and view elements. The most common MVC mistake is to put too much in control and nothing in the model.</p></li>
<li><p>Later, once your model is doing most of the work, you can look at refactor into components that parallel the GUI presentation. Various top-level frames, for example, should probably have separate cotrol objects. It's not clear what's in "GUI.py" -- this might be a proper view. What appears to be missing is a Control component.</p></li>
</ol>
| 2 | 2008-10-19T12:53:42Z | [
"python",
"gtk",
"module",
"pygtk",
"organization"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.