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 |
---|---|---|---|---|---|---|---|---|---|
How to import a python file in python script more than once | 276,679 | <p>Is it possible to import a python file more than once in a python script because i run a loop back to my driver file in a function by using the import command but it only works once? thanks</p>
<p><strong>edit:</strong> Resolved myself thanks</p>
| 1 | 2008-11-09T23:40:27Z | 276,696 | <p>You most probably should not use import for what you are trying to do.</p>
<p>Without further information I can only guess, but you should move the code in the module you import from the top level into a function, do the import once and than simply call the function from you loop.</p>
| 7 | 2008-11-09T23:51:56Z | [
"python"
] |
How to import a python file in python script more than once | 276,679 | <p>Is it possible to import a python file more than once in a python script because i run a loop back to my driver file in a function by using the import command but it only works once? thanks</p>
<p><strong>edit:</strong> Resolved myself thanks</p>
| 1 | 2008-11-09T23:40:27Z | 277,463 | <p>While Tom Ley's answer is the correct approach, it <em>is</em> possible to import a module more than once, using the reload built-in.</p>
<pre><code>module.py:
print "imported!"
>>> import module
imported!
>>> reload(module)
imported!
<module 'module' from 'module.pyc'>
</code></pre>
<p>Note that reload returns the module, allowing you to rebind it if necessary.</p>
| 1 | 2008-11-10T09:53:09Z | [
"python"
] |
Exposing a C++ API to Python | 276,761 | <p>I'm currently working on a project were I had to wrap the C++ classes with Python to be able to script the program. So my specific experience also involved embedding the Python interpreter in our program.</p>
<p>The alternatives I tried were:</p>
<ul>
<li><p>Boost.Python</p>
<p>I liked the cleaner API produced by Boost.Python, but the fact that it would have required that users install an additional dependency made us switch to SWIG.</p></li>
<li><p>SWIG</p>
<p>SWIG's main advantage for us was that it doesn't require end users to install it to use the final program.</p></li>
</ul>
<p>What have you used to do this, and what has been your experience with it?</p>
| 34 | 2008-11-10T00:34:50Z | 277,306 | <p>I've used both (for the same project): Boost is better integrated with the STL, and especially C++ exceptions. Also, its memory management mechanism (which tries to bridge C++ memory management and Python GC) is way more flexible than SWIG's. However, SWIG has <em>much</em> better documentation, no external dependencies, and if you get the library wrapped in SWIG for Python you're more than half-way there to getting a Java/Perl/Ruby wrapper as well.</p>
<p>I don't think there's a clear-cut choice: for smaller projects, I'd go with Boost.Python again, for larger long-lived projects, the extra investment in SWIG is worth it.</p>
| 19 | 2008-11-10T07:41:53Z | [
"c++",
"python",
"boost",
"swig"
] |
Exposing a C++ API to Python | 276,761 | <p>I'm currently working on a project were I had to wrap the C++ classes with Python to be able to script the program. So my specific experience also involved embedding the Python interpreter in our program.</p>
<p>The alternatives I tried were:</p>
<ul>
<li><p>Boost.Python</p>
<p>I liked the cleaner API produced by Boost.Python, but the fact that it would have required that users install an additional dependency made us switch to SWIG.</p></li>
<li><p>SWIG</p>
<p>SWIG's main advantage for us was that it doesn't require end users to install it to use the final program.</p></li>
</ul>
<p>What have you used to do this, and what has been your experience with it?</p>
| 34 | 2008-11-10T00:34:50Z | 277,308 | <p><a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/" rel="nofollow">pyrex</a> or <a href="http://cython.org/" rel="nofollow">cython</a> are also good and easy ways for mixing the two worlds.</p>
<p>Wrapping C++ using these tools is a bit trickier then wrapping C but it can be done. <a href="http://wiki.cython.org/WrappingCPlusPlus" rel="nofollow">Here</a> is the wiki page about it.</p>
| 5 | 2008-11-10T07:42:23Z | [
"c++",
"python",
"boost",
"swig"
] |
Exposing a C++ API to Python | 276,761 | <p>I'm currently working on a project were I had to wrap the C++ classes with Python to be able to script the program. So my specific experience also involved embedding the Python interpreter in our program.</p>
<p>The alternatives I tried were:</p>
<ul>
<li><p>Boost.Python</p>
<p>I liked the cleaner API produced by Boost.Python, but the fact that it would have required that users install an additional dependency made us switch to SWIG.</p></li>
<li><p>SWIG</p>
<p>SWIG's main advantage for us was that it doesn't require end users to install it to use the final program.</p></li>
</ul>
<p>What have you used to do this, and what has been your experience with it?</p>
| 34 | 2008-11-10T00:34:50Z | 287,114 | <p>I suggest <a href="http://www.riverbankcomputing.co.uk/software/sip/intro">SIP</a>. SIP is better than SWIG due to the following reasons:</p>
<ol>
<li><p>For a given set of files, swig generates more duplicate (overhead) code than SIP. SIP manages to generate less duplicate (overhead) code by using a library file which can be statically or dynamically linked. In other words SIP has better scalability.</p></li>
<li><p>Execution time of SIP is much less than that of SWIG. Refer <a href="http://people.web.psi.ch/geus/talks/europython2004_geus.pdf">Python Wrapper Tools: A Performance Study</a>. Unfortunately link appears broken. I have a personal copy which can be shared on request.</p></li>
</ol>
| 6 | 2008-11-13T14:45:33Z | [
"c++",
"python",
"boost",
"swig"
] |
Exposing a C++ API to Python | 276,761 | <p>I'm currently working on a project were I had to wrap the C++ classes with Python to be able to script the program. So my specific experience also involved embedding the Python interpreter in our program.</p>
<p>The alternatives I tried were:</p>
<ul>
<li><p>Boost.Python</p>
<p>I liked the cleaner API produced by Boost.Python, but the fact that it would have required that users install an additional dependency made us switch to SWIG.</p></li>
<li><p>SWIG</p>
<p>SWIG's main advantage for us was that it doesn't require end users to install it to use the final program.</p></li>
</ul>
<p>What have you used to do this, and what has been your experience with it?</p>
| 34 | 2008-11-10T00:34:50Z | 288,689 | <p>I've used <a href="http://code.google.com/p/robin/">Robin</a> with great success. </p>
<p><strong>Great</strong> integration with C++ types, and creates a single .cpp file to compile and include in your shared object.</p>
| 18 | 2008-11-13T23:03:19Z | [
"c++",
"python",
"boost",
"swig"
] |
Exposing a C++ API to Python | 276,761 | <p>I'm currently working on a project were I had to wrap the C++ classes with Python to be able to script the program. So my specific experience also involved embedding the Python interpreter in our program.</p>
<p>The alternatives I tried were:</p>
<ul>
<li><p>Boost.Python</p>
<p>I liked the cleaner API produced by Boost.Python, but the fact that it would have required that users install an additional dependency made us switch to SWIG.</p></li>
<li><p>SWIG</p>
<p>SWIG's main advantage for us was that it doesn't require end users to install it to use the final program.</p></li>
</ul>
<p>What have you used to do this, and what has been your experience with it?</p>
| 34 | 2008-11-10T00:34:50Z | 847,688 | <p>A big plus for Boost::Python is that it allows for tab completion in the ipython shell: You import a C++ class, exposed by Boost directly, or you subclass it, and from then on, it really behaves like a pure Python class.</p>
<p>The downside: It takes so long to install and use Boost that all the Tab-completion time-saving won't ever amortize ;-(</p>
<p>So I prefer Swig: No bells and whistles, but works reliably after a short introductory example.</p>
| 2 | 2009-05-11T11:27:15Z | [
"c++",
"python",
"boost",
"swig"
] |
How to expose std::vector<int> as a Python list using SWIG? | 276,769 | <p>I'm trying to expose this function to Python using SWIG:</p>
<pre><code>std::vector<int> get_match_stats();
</code></pre>
<p>And I want SWIG to generate wrapping code for Python so I can see it as a list of integers.</p>
<p>Adding this to the .i file:</p>
<pre>
%include "typemaps.i"
%include "std_vector.i"
namespace std
{
%template(IntVector) vector<int>;
}
</pre>
<p>I'm running <code>SWIG Version 1.3.36</code> and calling swig with <code>-Wall</code> and I get no warnings.</p>
<p>I'm able to get access to a list but I get a bunch of warnings when compiling with <code>-Wall</code> (with <code>g++ (GCC) 4.2.4</code> ) the generated C++ code that say:</p>
<pre>
warning: dereferencing type-punned pointer will break strict-aliasing rules
</pre>
<p>Am I exposing the function correctly? If so, what does the warning mean?</p>
<hr>
<p>These are the lines before the offending line in the same function:</p>
<pre>
SWIGINTERN PyObject *_wrap_IntVector_erase__SWIG_0(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
PyObject *resultobj = 0;
std::vector *arg1 = (std::vector *) 0 ;
std::vector::iterator arg2 ;
std::vector::iterator result;
void *argp1 = 0 ;
int res1 = 0 ;
swig::PySwigIterator *iter2 = 0 ;
int res2 ;
PyObject * obj0 = 0 ;
PyObject * obj1 = 0 ;
if (!PyArg_ParseTuple(args,(char *)"OO:IntVector_erase",&obj0,&obj1)) SWIG_fail;
res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_std__vectorT_int_std__allocatorT_int_t_t, 0 | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "IntVector_erase" "', argument " "1"" of type '" "std::vector *""'");
}
arg1 = reinterpret_cast * >(argp1);
</pre>
<p>And this is the offending line:</p>
<pre>
res2 = SWIG_ConvertPtr(obj1, SWIG_as_voidptrptr(&iter2), swig::PySwigIterator::descriptor(), 0);
</pre>
<p>More code follows that.</p>
<p>The warning generated when compiling with g++ 4.2.4 is:</p>
<pre>
swig_iss_wrap.cxx: In function âPyObject* _wrap_IntVector_erase__SWIG_0(PyObject*, PyObject*)â:
swig_iss_wrap.cxx:5885: warning: dereferencing type-punned pointer will break strict-aliasing rules
</pre>
| 14 | 2008-11-10T00:38:59Z | 277,687 | <pre><code>%template(IntVector) vector<int>;
</code></pre>
| 14 | 2008-11-10T11:44:15Z | [
"c++",
"python",
"stl",
"swig"
] |
How to expose std::vector<int> as a Python list using SWIG? | 276,769 | <p>I'm trying to expose this function to Python using SWIG:</p>
<pre><code>std::vector<int> get_match_stats();
</code></pre>
<p>And I want SWIG to generate wrapping code for Python so I can see it as a list of integers.</p>
<p>Adding this to the .i file:</p>
<pre>
%include "typemaps.i"
%include "std_vector.i"
namespace std
{
%template(IntVector) vector<int>;
}
</pre>
<p>I'm running <code>SWIG Version 1.3.36</code> and calling swig with <code>-Wall</code> and I get no warnings.</p>
<p>I'm able to get access to a list but I get a bunch of warnings when compiling with <code>-Wall</code> (with <code>g++ (GCC) 4.2.4</code> ) the generated C++ code that say:</p>
<pre>
warning: dereferencing type-punned pointer will break strict-aliasing rules
</pre>
<p>Am I exposing the function correctly? If so, what does the warning mean?</p>
<hr>
<p>These are the lines before the offending line in the same function:</p>
<pre>
SWIGINTERN PyObject *_wrap_IntVector_erase__SWIG_0(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
PyObject *resultobj = 0;
std::vector *arg1 = (std::vector *) 0 ;
std::vector::iterator arg2 ;
std::vector::iterator result;
void *argp1 = 0 ;
int res1 = 0 ;
swig::PySwigIterator *iter2 = 0 ;
int res2 ;
PyObject * obj0 = 0 ;
PyObject * obj1 = 0 ;
if (!PyArg_ParseTuple(args,(char *)"OO:IntVector_erase",&obj0,&obj1)) SWIG_fail;
res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_std__vectorT_int_std__allocatorT_int_t_t, 0 | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "IntVector_erase" "', argument " "1"" of type '" "std::vector *""'");
}
arg1 = reinterpret_cast * >(argp1);
</pre>
<p>And this is the offending line:</p>
<pre>
res2 = SWIG_ConvertPtr(obj1, SWIG_as_voidptrptr(&iter2), swig::PySwigIterator::descriptor(), 0);
</pre>
<p>More code follows that.</p>
<p>The warning generated when compiling with g++ 4.2.4 is:</p>
<pre>
swig_iss_wrap.cxx: In function âPyObject* _wrap_IntVector_erase__SWIG_0(PyObject*, PyObject*)â:
swig_iss_wrap.cxx:5885: warning: dereferencing type-punned pointer will break strict-aliasing rules
</pre>
| 14 | 2008-11-10T00:38:59Z | 368,961 | <p>I don't have much experience with Swig, but are you #including your C++ header file in your .i file? Try one (or both) of</p>
<pre><code>%include "myvector.h"
%{
# include "myvector.h"
%}
</code></pre>
| 0 | 2008-12-15T16:40:34Z | [
"c++",
"python",
"stl",
"swig"
] |
Is there a good Python GUI shell? | 277,170 | <p>I saw this the other day (scroll <em>all the way</em> down to see some of the clever stuff): </p>
<blockquote>
<p><a href="http://www.mono-project.com/docs/tools+libraries/tools/repl/" rel="nofollow">http://www.mono-project.com/docs/tools+libraries/tools/repl/</a></p>
</blockquote>
<p>And wondered whether something like this exists for Python.</p>
<p>So, is there a good Python GUI shell that can do stuff like that C# shell can do?</p>
<p>Edit: Here are links to screenshots from the article, showing what I'm interested in doing.</p>
<p>An example of the type of things I'm interested: </p>
<p><a href="http://www.mono-project.com/archived/images/7/75/GSharpPlot.png" rel="nofollow">http://www.mono-project.com/archived/images/7/75/GSharpPlot.png</a></p>
<p>They are able to add hooks to produce GUI elements like the plot, or even do silly things like:</p>
<p><a href="http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png" rel="nofollow">http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png</a></p>
<p>I don't think this is possible with any of the console shells I've tried (the regular python shell, ipython).</p>
<p>Edit: I'm not looking for an IDE. If you look at the link, you'll get an idea of what I want.</p>
| 12 | 2008-11-10T06:02:59Z | 277,191 | <p>As far as I know there is nothing out there that offers the sort of whiz-bang features that the Mono guys have implemented in their new shell, but that is not to say that the "basic" python interactive shell isn't a feature-complete and powerful application. I could see something like the C# shell being developed at some point, but I think as of today those features you're pointing to are reasonably unique. One might argue that this is because nobody thought of them or, alternatively, because nobody has really had a need for them. I tend to subscribe to the latter, although I suppose both are plausible.</p>
| 6 | 2008-11-10T06:21:04Z | [
"python",
"shell",
"user-interface"
] |
Is there a good Python GUI shell? | 277,170 | <p>I saw this the other day (scroll <em>all the way</em> down to see some of the clever stuff): </p>
<blockquote>
<p><a href="http://www.mono-project.com/docs/tools+libraries/tools/repl/" rel="nofollow">http://www.mono-project.com/docs/tools+libraries/tools/repl/</a></p>
</blockquote>
<p>And wondered whether something like this exists for Python.</p>
<p>So, is there a good Python GUI shell that can do stuff like that C# shell can do?</p>
<p>Edit: Here are links to screenshots from the article, showing what I'm interested in doing.</p>
<p>An example of the type of things I'm interested: </p>
<p><a href="http://www.mono-project.com/archived/images/7/75/GSharpPlot.png" rel="nofollow">http://www.mono-project.com/archived/images/7/75/GSharpPlot.png</a></p>
<p>They are able to add hooks to produce GUI elements like the plot, or even do silly things like:</p>
<p><a href="http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png" rel="nofollow">http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png</a></p>
<p>I don't think this is possible with any of the console shells I've tried (the regular python shell, ipython).</p>
<p>Edit: I'm not looking for an IDE. If you look at the link, you'll get an idea of what I want.</p>
| 12 | 2008-11-10T06:02:59Z | 277,234 | <p>Have you looked at <a href="http://ipython.scipy.org/moin/">ipython</a>? It's not quite as "gui". No smileys, sorry. ;-) It is a pretty good interactive shell for python though. </p>
<p>edit: I see you revised your question to emphasize the importance <strong>GUI</strong>. In that case, IPython wouldn't be a good match. </p>
<p>Might as well save you another blind alley: I went looking at DrPython hoping it would be similar to PLT's DrScheme, which looks comparable to example you've linked too. Unfortunately DrPython isn't all that much like DrScheme. </p>
| 7 | 2008-11-10T06:49:18Z | [
"python",
"shell",
"user-interface"
] |
Is there a good Python GUI shell? | 277,170 | <p>I saw this the other day (scroll <em>all the way</em> down to see some of the clever stuff): </p>
<blockquote>
<p><a href="http://www.mono-project.com/docs/tools+libraries/tools/repl/" rel="nofollow">http://www.mono-project.com/docs/tools+libraries/tools/repl/</a></p>
</blockquote>
<p>And wondered whether something like this exists for Python.</p>
<p>So, is there a good Python GUI shell that can do stuff like that C# shell can do?</p>
<p>Edit: Here are links to screenshots from the article, showing what I'm interested in doing.</p>
<p>An example of the type of things I'm interested: </p>
<p><a href="http://www.mono-project.com/archived/images/7/75/GSharpPlot.png" rel="nofollow">http://www.mono-project.com/archived/images/7/75/GSharpPlot.png</a></p>
<p>They are able to add hooks to produce GUI elements like the plot, or even do silly things like:</p>
<p><a href="http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png" rel="nofollow">http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png</a></p>
<p>I don't think this is possible with any of the console shells I've tried (the regular python shell, ipython).</p>
<p>Edit: I'm not looking for an IDE. If you look at the link, you'll get an idea of what I want.</p>
| 12 | 2008-11-10T06:02:59Z | 277,531 | <p>One project I'm aware of that provides similar features (inline plotting, customisable rendering) is <a href="http://fishsoup.net/software/reinteract/">Reinteract</a>. Another (though possibly a bit heavyweight for general usage) is <a href="http://www.sagemath.org/">SAGE</a> which provides functionality for web-based <a href="http://www.sagenb.org">notebooks</a>.</p>
<p>These aren't quite shells - they're designed more as a mathematical notebook (so for instance, you can modify an earlier result and have the change propogate to later calculations), but they're close to what you're looking for, and could probably be modified to be used as such.</p>
| 13 | 2008-11-10T10:23:00Z | [
"python",
"shell",
"user-interface"
] |
Is there a good Python GUI shell? | 277,170 | <p>I saw this the other day (scroll <em>all the way</em> down to see some of the clever stuff): </p>
<blockquote>
<p><a href="http://www.mono-project.com/docs/tools+libraries/tools/repl/" rel="nofollow">http://www.mono-project.com/docs/tools+libraries/tools/repl/</a></p>
</blockquote>
<p>And wondered whether something like this exists for Python.</p>
<p>So, is there a good Python GUI shell that can do stuff like that C# shell can do?</p>
<p>Edit: Here are links to screenshots from the article, showing what I'm interested in doing.</p>
<p>An example of the type of things I'm interested: </p>
<p><a href="http://www.mono-project.com/archived/images/7/75/GSharpPlot.png" rel="nofollow">http://www.mono-project.com/archived/images/7/75/GSharpPlot.png</a></p>
<p>They are able to add hooks to produce GUI elements like the plot, or even do silly things like:</p>
<p><a href="http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png" rel="nofollow">http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png</a></p>
<p>I don't think this is possible with any of the console shells I've tried (the regular python shell, ipython).</p>
<p>Edit: I'm not looking for an IDE. If you look at the link, you'll get an idea of what I want.</p>
| 12 | 2008-11-10T06:02:59Z | 278,322 | <p><a href="http://www.loria.fr/~rougier/pub/Software/pylab" rel="nofollow">Interactive pylab console</a>.</p>
| 3 | 2008-11-10T16:21:31Z | [
"python",
"shell",
"user-interface"
] |
Is there a good Python GUI shell? | 277,170 | <p>I saw this the other day (scroll <em>all the way</em> down to see some of the clever stuff): </p>
<blockquote>
<p><a href="http://www.mono-project.com/docs/tools+libraries/tools/repl/" rel="nofollow">http://www.mono-project.com/docs/tools+libraries/tools/repl/</a></p>
</blockquote>
<p>And wondered whether something like this exists for Python.</p>
<p>So, is there a good Python GUI shell that can do stuff like that C# shell can do?</p>
<p>Edit: Here are links to screenshots from the article, showing what I'm interested in doing.</p>
<p>An example of the type of things I'm interested: </p>
<p><a href="http://www.mono-project.com/archived/images/7/75/GSharpPlot.png" rel="nofollow">http://www.mono-project.com/archived/images/7/75/GSharpPlot.png</a></p>
<p>They are able to add hooks to produce GUI elements like the plot, or even do silly things like:</p>
<p><a href="http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png" rel="nofollow">http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png</a></p>
<p>I don't think this is possible with any of the console shells I've tried (the regular python shell, ipython).</p>
<p>Edit: I'm not looking for an IDE. If you look at the link, you'll get an idea of what I want.</p>
| 12 | 2008-11-10T06:02:59Z | 278,404 | <p>I think that a combination of Pycrust with matplotlib can do exactly what you need. Pycrust is part of the wxPython installation, and matplotlib should be insalled separately. Both are simple to install in about 5 minutes.</p>
<p>Read <a href="http://eli.thegreenplace.net/2008/07/26/matplotlib-plotting-with-python/" rel="nofollow">this</a> about integrating matplotlib with Pycrust to produce dynamic plots like the ones in the link you posted.</p>
| 2 | 2008-11-10T16:41:18Z | [
"python",
"shell",
"user-interface"
] |
Is there a good Python GUI shell? | 277,170 | <p>I saw this the other day (scroll <em>all the way</em> down to see some of the clever stuff): </p>
<blockquote>
<p><a href="http://www.mono-project.com/docs/tools+libraries/tools/repl/" rel="nofollow">http://www.mono-project.com/docs/tools+libraries/tools/repl/</a></p>
</blockquote>
<p>And wondered whether something like this exists for Python.</p>
<p>So, is there a good Python GUI shell that can do stuff like that C# shell can do?</p>
<p>Edit: Here are links to screenshots from the article, showing what I'm interested in doing.</p>
<p>An example of the type of things I'm interested: </p>
<p><a href="http://www.mono-project.com/archived/images/7/75/GSharpPlot.png" rel="nofollow">http://www.mono-project.com/archived/images/7/75/GSharpPlot.png</a></p>
<p>They are able to add hooks to produce GUI elements like the plot, or even do silly things like:</p>
<p><a href="http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png" rel="nofollow">http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png</a></p>
<p>I don't think this is possible with any of the console shells I've tried (the regular python shell, ipython).</p>
<p>Edit: I'm not looking for an IDE. If you look at the link, you'll get an idea of what I want.</p>
| 12 | 2008-11-10T06:02:59Z | 280,287 | <p>You're looking for <a href="http://www.reinteract.org/" rel="nofollow">Reinteract</a>, which is a Python-based shell that <a href="http://tirania.org/blog/archive/2008/Nov-02.html" rel="nofollow">at least partially inspired</a> the C# shell you found. It's definitely still in-development, but already very useful.</p>
| 3 | 2008-11-11T07:55:39Z | [
"python",
"shell",
"user-interface"
] |
Is there a good Python GUI shell? | 277,170 | <p>I saw this the other day (scroll <em>all the way</em> down to see some of the clever stuff): </p>
<blockquote>
<p><a href="http://www.mono-project.com/docs/tools+libraries/tools/repl/" rel="nofollow">http://www.mono-project.com/docs/tools+libraries/tools/repl/</a></p>
</blockquote>
<p>And wondered whether something like this exists for Python.</p>
<p>So, is there a good Python GUI shell that can do stuff like that C# shell can do?</p>
<p>Edit: Here are links to screenshots from the article, showing what I'm interested in doing.</p>
<p>An example of the type of things I'm interested: </p>
<p><a href="http://www.mono-project.com/archived/images/7/75/GSharpPlot.png" rel="nofollow">http://www.mono-project.com/archived/images/7/75/GSharpPlot.png</a></p>
<p>They are able to add hooks to produce GUI elements like the plot, or even do silly things like:</p>
<p><a href="http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png" rel="nofollow">http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png</a></p>
<p>I don't think this is possible with any of the console shells I've tried (the regular python shell, ipython).</p>
<p>Edit: I'm not looking for an IDE. If you look at the link, you'll get an idea of what I want.</p>
| 12 | 2008-11-10T06:02:59Z | 2,364,228 | <p>(Sorry for thread necromancy, but this page still comes up highly in a Google search and I assume there must be some interest in the subject.)</p>
<p>One GUI shell for Python which I believe is quite new is <a href="http://dreampie.sourceforge.net/">DreamPie</a>. It doesn't quite go as far as the screenshots in the question, but it might be the closest available. They do at least highlight interactive graph plotting in their list of useful features.</p>
| 6 | 2010-03-02T15:23:54Z | [
"python",
"shell",
"user-interface"
] |
Is there a good Python GUI shell? | 277,170 | <p>I saw this the other day (scroll <em>all the way</em> down to see some of the clever stuff): </p>
<blockquote>
<p><a href="http://www.mono-project.com/docs/tools+libraries/tools/repl/" rel="nofollow">http://www.mono-project.com/docs/tools+libraries/tools/repl/</a></p>
</blockquote>
<p>And wondered whether something like this exists for Python.</p>
<p>So, is there a good Python GUI shell that can do stuff like that C# shell can do?</p>
<p>Edit: Here are links to screenshots from the article, showing what I'm interested in doing.</p>
<p>An example of the type of things I'm interested: </p>
<p><a href="http://www.mono-project.com/archived/images/7/75/GSharpPlot.png" rel="nofollow">http://www.mono-project.com/archived/images/7/75/GSharpPlot.png</a></p>
<p>They are able to add hooks to produce GUI elements like the plot, or even do silly things like:</p>
<p><a href="http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png" rel="nofollow">http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png</a></p>
<p>I don't think this is possible with any of the console shells I've tried (the regular python shell, ipython).</p>
<p>Edit: I'm not looking for an IDE. If you look at the link, you'll get an idea of what I want.</p>
| 12 | 2008-11-10T06:02:59Z | 6,101,558 | <p><a href="http://www.dreampie.org/" rel="nofollow">DreamPie</a> is my personal favorite. It doesn't appear to be any more restrictive than CSharpRepl. For example, the graph drawing example can be done if matplotlib is installed. There is an example screenshot to this effect on DreamPie's web site (<a href="http://dreampie.sourceforge.net/" rel="nofollow">http://dreampie.sourceforge.net/</a>). </p>
<p>Bpython is similar, and I like it better. But it is only available on Linux as binary. </p>
| 1 | 2011-05-23T18:53:17Z | [
"python",
"shell",
"user-interface"
] |
Is there a good Python GUI shell? | 277,170 | <p>I saw this the other day (scroll <em>all the way</em> down to see some of the clever stuff): </p>
<blockquote>
<p><a href="http://www.mono-project.com/docs/tools+libraries/tools/repl/" rel="nofollow">http://www.mono-project.com/docs/tools+libraries/tools/repl/</a></p>
</blockquote>
<p>And wondered whether something like this exists for Python.</p>
<p>So, is there a good Python GUI shell that can do stuff like that C# shell can do?</p>
<p>Edit: Here are links to screenshots from the article, showing what I'm interested in doing.</p>
<p>An example of the type of things I'm interested: </p>
<p><a href="http://www.mono-project.com/archived/images/7/75/GSharpPlot.png" rel="nofollow">http://www.mono-project.com/archived/images/7/75/GSharpPlot.png</a></p>
<p>They are able to add hooks to produce GUI elements like the plot, or even do silly things like:</p>
<p><a href="http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png" rel="nofollow">http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png</a></p>
<p>I don't think this is possible with any of the console shells I've tried (the regular python shell, ipython).</p>
<p>Edit: I'm not looking for an IDE. If you look at the link, you'll get an idea of what I want.</p>
| 12 | 2008-11-10T06:02:59Z | 16,783,547 | <p><a href="http://www.lighttable.com/" rel="nofollow">Light Table</a> is working on this. The IDE is simultaneously a REPL -- it has in-line plotting with iPython.</p>
| 0 | 2013-05-28T03:45:37Z | [
"python",
"shell",
"user-interface"
] |
Is there a more Pythonic way to merge two HTML header rows with colspans? | 277,187 | <p>I am using BeautifulSoup in Python to parse some HTML. One of the problems I am dealing with is that I have situations where the colspans are different across header rows. (Header rows are the rows that need to be combined to get the column headings in my jargon) That is one column may span a number of columns above or below it and the words need to be appended or prepended based on the spanning. Below is a routine to do this. I use BeautifulSoup to pull the colspans and to pull the contents of each cell in each row. longHeader is the contents of the header row with the most items, spanLong is a list with the colspans of each item in the row. This works but it is not looking very Pythonic. </p>
<p>Alos-it is not going to work if the diff is <0, I can fix that with the same approach I used to get this to work. But before I do I wonder if anyone can quickly look at this and suggest a more Pythonic approach. I am a long time SAS programmer and so I struggle to break the mold-well I will write code as if I am writing a SAS macro.</p>
<pre><code>longHeader=['','','bananas','','','','','','','','','','trains','','planes','','','','']
shortHeader=['','','bunches','','cars','','trucks','','freight','','cargo','','all other','','']
spanShort=[1,1,3,1,3,1,3,1,3,1,3,1,3,1,3]
spanLong=[1,1,3,1,1,1,1,1,1,1,1,1,3,1,3,1,3,1,3]
combinedHeader=[]
sumSpanLong=0
sumSpanShort=0
spanDiff=0
longHeaderCount=0
for each in range(len(shortHeader)):
sumSpanLong=sumSpanLong+spanLong[longHeaderCount]
sumSpanShort=sumSpanShort+spanShort[each]
spanDiff=sumSpanShort-sumSpanLong
if spanDiff==0:
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
continue
for i in range(0,spanDiff):
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
sumSpanLong=sumSpanLong+spanLong[longHeaderCount]
spanDiff=sumSpanShort-sumSpanLong
if spanDiff==0:
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
break
print combinedHeader
</code></pre>
| 1 | 2008-11-10T06:17:39Z | 277,280 | <p>Maybe look at the zip function for parts of the problem:</p>
<pre><code>>>> execfile('so_ques.py')
[[' '], [' '], ['bananas bunches'], [' '], [' cars'], [' cars'], [' cars'], [' '], [' trucks'], [' trucks'], [' trucks'], [' '], ['trains freight'], [' '], ['planes cargo'], [' '], [' all other'], [' '], [' ']]
>>> zip(long_header, short_header)
[('', ''), ('', ''), ('bananas', 'bunches'), ('', ''), ('', 'cars'), ('', ''), ('', 'trucks'), ('', ''), ('', 'freight'), ('', ''), ('', 'cargo'), ('', ''), ('trains', 'all other'), ('', ''), ('planes', '')]
>>>
</code></pre>
<p><code>enumerate</code> can help avoid some of the complex indexing with counters:</p>
<pre><code>>>> diff_list = []
>>> for place, header in enumerate(short_header):
diff_list.append(abs(span_short[place] - span_long[place]))
>>> for place, num in enumerate(diff_list):
if num:
new_shortlist.extend(short_header[place] for item in range(num+1))
else:
new_shortlist.append(short_header[place])
>>> new_shortlist
['', '', 'bunches', '', 'cars', 'cars', 'cars', '', 'trucks', 'trucks', 'trucks', '',...
>>> z = zip(new_shortlist, long_header)
>>> z
[('', ''), ('', ''), ('bunches', 'bananas'), ('', ''), ('cars', ''), ('cars', ''), ('cars', '')...
</code></pre>
<p>Also more pythonic naming may add clarity:</p>
<pre><code> for each in range(len(short_header)):
sum_span_long += span_long[long_header_count]
sum_span_short += span_short[each]
span_diff = sum_span_short - sum_span_long
if not span_diff:
combined_header.append...
</code></pre>
| 1 | 2008-11-10T07:25:44Z | [
"python",
"beautifulsoup"
] |
Is there a more Pythonic way to merge two HTML header rows with colspans? | 277,187 | <p>I am using BeautifulSoup in Python to parse some HTML. One of the problems I am dealing with is that I have situations where the colspans are different across header rows. (Header rows are the rows that need to be combined to get the column headings in my jargon) That is one column may span a number of columns above or below it and the words need to be appended or prepended based on the spanning. Below is a routine to do this. I use BeautifulSoup to pull the colspans and to pull the contents of each cell in each row. longHeader is the contents of the header row with the most items, spanLong is a list with the colspans of each item in the row. This works but it is not looking very Pythonic. </p>
<p>Alos-it is not going to work if the diff is <0, I can fix that with the same approach I used to get this to work. But before I do I wonder if anyone can quickly look at this and suggest a more Pythonic approach. I am a long time SAS programmer and so I struggle to break the mold-well I will write code as if I am writing a SAS macro.</p>
<pre><code>longHeader=['','','bananas','','','','','','','','','','trains','','planes','','','','']
shortHeader=['','','bunches','','cars','','trucks','','freight','','cargo','','all other','','']
spanShort=[1,1,3,1,3,1,3,1,3,1,3,1,3,1,3]
spanLong=[1,1,3,1,1,1,1,1,1,1,1,1,3,1,3,1,3,1,3]
combinedHeader=[]
sumSpanLong=0
sumSpanShort=0
spanDiff=0
longHeaderCount=0
for each in range(len(shortHeader)):
sumSpanLong=sumSpanLong+spanLong[longHeaderCount]
sumSpanShort=sumSpanShort+spanShort[each]
spanDiff=sumSpanShort-sumSpanLong
if spanDiff==0:
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
continue
for i in range(0,spanDiff):
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
sumSpanLong=sumSpanLong+spanLong[longHeaderCount]
spanDiff=sumSpanShort-sumSpanLong
if spanDiff==0:
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
break
print combinedHeader
</code></pre>
| 1 | 2008-11-10T06:17:39Z | 277,390 | <p>Here is a modified version of your algorithm. <em>zip</em> is used to iterate over <strong>short</strong> lengths and headers and a <em>class object</em> is used to count and iterate the <strong>long</strong> items, as well as combine the headers. <em>while</em> is more appropriate for the inner loop.
(forgive the too short names).</p>
<pre><code>class collector(object):
def __init__(self, header):
self.longHeader = header
self.combinedHeader = []
self.longHeaderCount = 0
def combine(self, shortValue):
self.combinedHeader.append(
[self.longHeader[self.longHeaderCount]+' '+shortValue] )
self.longHeaderCount += 1
return self.longHeaderCount
def main():
longHeader = [
'','','bananas','','','','','','','','','','trains','','planes','','','','']
shortHeader = [
'','','bunches','','cars','','trucks','','freight','','cargo','','all other','','']
spanShort=[1,1,3,1,3,1,3,1,3,1,3,1,3,1,3]
spanLong=[1,1,3,1,1,1,1,1,1,1,1,1,3,1,3,1,3,1,3]
sumSpanLong=0
sumSpanShort=0
combiner = collector(longHeader)
for sLen,sHead in zip(spanShort,shortHeader):
sumSpanLong += spanLong[combiner.longHeaderCount]
sumSpanShort += sLen
while sumSpanShort - sumSpanLong > 0:
combiner.combine(sHead)
sumSpanLong += spanLong[combiner.longHeaderCount]
combiner.combine(sHead)
return combiner.combinedHeader
</code></pre>
| 3 | 2008-11-10T09:05:10Z | [
"python",
"beautifulsoup"
] |
Is there a more Pythonic way to merge two HTML header rows with colspans? | 277,187 | <p>I am using BeautifulSoup in Python to parse some HTML. One of the problems I am dealing with is that I have situations where the colspans are different across header rows. (Header rows are the rows that need to be combined to get the column headings in my jargon) That is one column may span a number of columns above or below it and the words need to be appended or prepended based on the spanning. Below is a routine to do this. I use BeautifulSoup to pull the colspans and to pull the contents of each cell in each row. longHeader is the contents of the header row with the most items, spanLong is a list with the colspans of each item in the row. This works but it is not looking very Pythonic. </p>
<p>Alos-it is not going to work if the diff is <0, I can fix that with the same approach I used to get this to work. But before I do I wonder if anyone can quickly look at this and suggest a more Pythonic approach. I am a long time SAS programmer and so I struggle to break the mold-well I will write code as if I am writing a SAS macro.</p>
<pre><code>longHeader=['','','bananas','','','','','','','','','','trains','','planes','','','','']
shortHeader=['','','bunches','','cars','','trucks','','freight','','cargo','','all other','','']
spanShort=[1,1,3,1,3,1,3,1,3,1,3,1,3,1,3]
spanLong=[1,1,3,1,1,1,1,1,1,1,1,1,3,1,3,1,3,1,3]
combinedHeader=[]
sumSpanLong=0
sumSpanShort=0
spanDiff=0
longHeaderCount=0
for each in range(len(shortHeader)):
sumSpanLong=sumSpanLong+spanLong[longHeaderCount]
sumSpanShort=sumSpanShort+spanShort[each]
spanDiff=sumSpanShort-sumSpanLong
if spanDiff==0:
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
continue
for i in range(0,spanDiff):
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
sumSpanLong=sumSpanLong+spanLong[longHeaderCount]
spanDiff=sumSpanShort-sumSpanLong
if spanDiff==0:
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
break
print combinedHeader
</code></pre>
| 1 | 2008-11-10T06:17:39Z | 277,837 | <p>You've actually got a lot going on in this example.</p>
<ol>
<li><p>You've "over-processed" the Beautiful Soup Tag objects to make lists. Leave them as Tags.</p></li>
<li><p>All of these kinds of merge algorithms are hard. It helps to treat the two things being merged symmetrically.</p></li>
</ol>
<p>Here's a version that should work directly with the Beautiful Soup Tag objects. Also, this version doesn't assume anything about the lengths of the two rows.</p>
<pre><code>def merge3( row1, row2 ):
i1= 0
i2= 0
result= []
while i1 != len(row1) or i2 != len(row2):
if i1 == len(row1):
result.append( ' '.join(row1[i1].contents) )
i2 += 1
elif i2 == len(row2):
result.append( ' '.join(row2[i2].contents) )
i1 += 1
else:
if row1[i1]['colspan'] < row2[i2]['colspan']:
# Fill extra cols from row1
c1= row1[i1]['colspan']
while c1 != row2[i2]['colspan']:
result.append( ' '.join(row2[i2].contents) )
c1 += 1
elif row1[i1]['colspan'] > row2[i2]['colspan']:
# Fill extra cols from row2
c2= row2[i2]['colspan']
while row1[i1]['colspan'] != c2:
result.append( ' '.join(row1[i1].contents) )
c2 += 1
else:
assert row1[i1]['colspan'] == row2[i2]['colspan']
pass
txt1= ' '.join(row1[i1].contents)
txt2= ' '.join(row2[i2].contents)
result.append( txt1 + " " + txt2 )
i1 += 1
i2 += 1
return result
</code></pre>
| 2 | 2008-11-10T13:20:02Z | [
"python",
"beautifulsoup"
] |
Is there a more Pythonic way to merge two HTML header rows with colspans? | 277,187 | <p>I am using BeautifulSoup in Python to parse some HTML. One of the problems I am dealing with is that I have situations where the colspans are different across header rows. (Header rows are the rows that need to be combined to get the column headings in my jargon) That is one column may span a number of columns above or below it and the words need to be appended or prepended based on the spanning. Below is a routine to do this. I use BeautifulSoup to pull the colspans and to pull the contents of each cell in each row. longHeader is the contents of the header row with the most items, spanLong is a list with the colspans of each item in the row. This works but it is not looking very Pythonic. </p>
<p>Alos-it is not going to work if the diff is <0, I can fix that with the same approach I used to get this to work. But before I do I wonder if anyone can quickly look at this and suggest a more Pythonic approach. I am a long time SAS programmer and so I struggle to break the mold-well I will write code as if I am writing a SAS macro.</p>
<pre><code>longHeader=['','','bananas','','','','','','','','','','trains','','planes','','','','']
shortHeader=['','','bunches','','cars','','trucks','','freight','','cargo','','all other','','']
spanShort=[1,1,3,1,3,1,3,1,3,1,3,1,3,1,3]
spanLong=[1,1,3,1,1,1,1,1,1,1,1,1,3,1,3,1,3,1,3]
combinedHeader=[]
sumSpanLong=0
sumSpanShort=0
spanDiff=0
longHeaderCount=0
for each in range(len(shortHeader)):
sumSpanLong=sumSpanLong+spanLong[longHeaderCount]
sumSpanShort=sumSpanShort+spanShort[each]
spanDiff=sumSpanShort-sumSpanLong
if spanDiff==0:
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
continue
for i in range(0,spanDiff):
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
sumSpanLong=sumSpanLong+spanLong[longHeaderCount]
spanDiff=sumSpanShort-sumSpanLong
if spanDiff==0:
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
break
print combinedHeader
</code></pre>
| 1 | 2008-11-10T06:17:39Z | 280,181 | <p>I guess I am going to answer my own question but I did receive a lot of help. Thanks for all of the help. I made S.LOTT's answer work after a few small corrections. (They may be so small as to not be visible (inside joke)). So now the question is why is this more Pythonic? I think I see that it is less denser / works with the raw inputs instead of derivations / I cannot judge if it is easier to read ---> though it is easy to read</p>
<h2>S.LOTT's Answer Corrected</h2>
<pre><code>row1=headerCells[0]
row2=headerCells[1]
i1= 0
i2= 0
result= []
while i1 != len(row1) or i2 != len(row2):
if i1 == len(row1):
result.append( ' '.join(row1[i1]) )
i2 += 1
elif i2 == len(row2):
result.append( ' '.join(row2[i2]) )
i1 += 1
else:
if int(row1[i1].get("colspan","1")) < int(row2[i2].get("colspan","1")):
c1= int(row1[i1].get("colspan","1"))
while c1 != int(row2[i2].get("colspan","1")):
txt1= ' '.join(row1[i1]) # needed to add when working adjust opposing case
txt2= ' '.join(row2[i2]) # needed to add when working adjust opposing case
result.append( txt1 + " " + txt2 ) # needed to add when working adjust opposing case
print 'stayed in middle', 'i1=',i1,'i2=',i2, ' c1=',c1
c1 += 1
i1 += 1 # Is this the problem it
elif int(row1[i1].get("colspan","1"))> int(row2[i2].get("colspan","1")):
# Fill extra cols from row2 Make same adjustment as above
c2= int(row2[i2].get("colspan","1"))
while int(row1[i1].get("colspan","1")) != c2:
result.append( ' '.join(row1[i1]) )
c2 += 1
i2 += 1
else:
assert int(row1[i1].get("colspan","1")) == int(row2[i2].get("colspan","1"))
pass
txt1= ' '.join(row1[i1])
txt2= ' '.join(row2[i2])
result.append( txt1 + " " + txt2 )
print 'went to bottom', 'i1=',i1,'i2=',i2
i1 += 1
i2 += 1
print result
</code></pre>
| 0 | 2008-11-11T06:41:52Z | [
"python",
"beautifulsoup"
] |
Is there a more Pythonic way to merge two HTML header rows with colspans? | 277,187 | <p>I am using BeautifulSoup in Python to parse some HTML. One of the problems I am dealing with is that I have situations where the colspans are different across header rows. (Header rows are the rows that need to be combined to get the column headings in my jargon) That is one column may span a number of columns above or below it and the words need to be appended or prepended based on the spanning. Below is a routine to do this. I use BeautifulSoup to pull the colspans and to pull the contents of each cell in each row. longHeader is the contents of the header row with the most items, spanLong is a list with the colspans of each item in the row. This works but it is not looking very Pythonic. </p>
<p>Alos-it is not going to work if the diff is <0, I can fix that with the same approach I used to get this to work. But before I do I wonder if anyone can quickly look at this and suggest a more Pythonic approach. I am a long time SAS programmer and so I struggle to break the mold-well I will write code as if I am writing a SAS macro.</p>
<pre><code>longHeader=['','','bananas','','','','','','','','','','trains','','planes','','','','']
shortHeader=['','','bunches','','cars','','trucks','','freight','','cargo','','all other','','']
spanShort=[1,1,3,1,3,1,3,1,3,1,3,1,3,1,3]
spanLong=[1,1,3,1,1,1,1,1,1,1,1,1,3,1,3,1,3,1,3]
combinedHeader=[]
sumSpanLong=0
sumSpanShort=0
spanDiff=0
longHeaderCount=0
for each in range(len(shortHeader)):
sumSpanLong=sumSpanLong+spanLong[longHeaderCount]
sumSpanShort=sumSpanShort+spanShort[each]
spanDiff=sumSpanShort-sumSpanLong
if spanDiff==0:
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
continue
for i in range(0,spanDiff):
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
sumSpanLong=sumSpanLong+spanLong[longHeaderCount]
spanDiff=sumSpanShort-sumSpanLong
if spanDiff==0:
combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]])
longHeaderCount=longHeaderCount+1
break
print combinedHeader
</code></pre>
| 1 | 2008-11-10T06:17:39Z | 283,026 | <p>Well I have an answer now. I was thinking through this and decided that I needed to use parts of every answer. I still need to figure out if I want a class or a function. But I have the algorithm that I think is probably more Pythonic than any of the others. But, it borrows heavily from the answers that some very generous people provided. I appreciate those a lot because I have learned quite a bit.</p>
<p>To save the time of having to make test cases I am going to paste the the complete code I have been banging away with in IDLE and follow that with an HTML sample file. Other than making a decision about class/function (and I need to think about how I am using this code in my program) I would be happy to see any improvements that make the code more Pythonic.</p>
<pre><code>from BeautifulSoup import BeautifulSoup
original=file(r"C:\testheaders.htm").read()
soupOriginal=BeautifulSoup(original)
all_Rows=soupOriginal.findAll('tr')
header_Rows=[]
for each in range(len(all_Rows)):
header_Rows.append(all_Rows[each])
header_Cells=[]
for each in header_Rows:
header_Cells.append(each.findAll('td'))
temp_Header_Row=[]
header=[]
for row in range(len(header_Cells)):
for column in range(len(header_Cells[row])):
x=int(header_Cells[row][column].get("colspan","1"))
if x==1:
temp_Header_Row.append( ' '.join(header_Cells[row][column]) )
else:
for item in range(x):
temp_Header_Row.append( ''.join(header_Cells[row][column]) )
header.append(temp_Header_Row)
temp_Header_Row=[]
combined_Header=zip(*header)
for each in combined_Header:
print each
</code></pre>
<p>Okay test file contents are below Sorry I tried to attach these but couldn't make it happen:</p>
<pre><code> <TABLE style="font-size: 10pt" cellspacing="0" border="0" cellpadding="0" width="100%">
<TR valign="bottom">
<TD width="40%">&nbsp;</TD>
<TD width="5%">&nbsp;</TD>
<TD width="3%">&nbsp;</TD>
<TD width="3%">&nbsp;</TD>
<TD width="1%">&nbsp;</TD>
<TD width="5%">&nbsp;</TD>
<TD width="3%">&nbsp;</TD>
<TD width="3%">&nbsp;</TD>
<TD width="1%">&nbsp;</TD>
<TD width="5%">&nbsp;</TD>
<TD width="3%">&nbsp;</TD>
<TD width="1%">&nbsp;</TD>
<TD width="1%">&nbsp;</TD>
<TD width="5%">&nbsp;</TD>
<TD width="3%">&nbsp;</TD>
<TD width="1%">&nbsp;</TD>
<TD width="1%">&nbsp;</TD>
<TD width="5%">&nbsp;</TD>
<TD width="3%">&nbsp;</TD>
<TD width="3%">&nbsp;</TD>
<TD width="1%">&nbsp;</TD>
</TR>
<TR style="font-size: 10pt" valign="bottom">
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD nowrap align="right" colspan="2">FOODS WE LIKE</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD nowrap align="right" colspan="2">&nbsp;</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD nowrap align="right" colspan="2">&nbsp;</TD>
<TD>&nbsp;</TD>
</TR>
<TR style="font-size: 10pt" valign="bottom">
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD nowrap align="CENTER" colspan="6">SILLY STUFF</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD nowrap align="right" colspan="2">OTHER THAN</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD nowrap align="CENTER" colspan="6">FAVORITE PEOPLE</TD>
<TD>&nbsp;</TD>
</TR>
<TR style="font-size: 10pt" valign="bottom">
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD nowrap align="right" colspan="2">MONTY PYTHON</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD nowrap align="right" colspan="2">CHERRYPY</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD nowrap align="right" colspan="2">APPLE PIE</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD nowrap align="right" colspan="2">MOTHERS</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD nowrap align="right" colspan="2">FATHERS</TD>
<TD>&nbsp;</TD>
</TR>
<TR style="font-size: 10pt" valign="bottom">
<TD nowrap align="left">Name</TD>
<TD>&nbsp;</TD>
<TD nowrap align="right" colspan="2">SHOWS</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD nowrap align="right" colspan="2">PROGRAMS</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD nowrap align="right" colspan="2">BANANAS</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD nowrap align="right" colspan="2">PERFUME</TD>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
<TD nowrap align="right" colspan="2">TOOLS</TD>
<TD>&nbsp;</TD>
</TR>
</TABLE>
</code></pre>
| 0 | 2008-11-12T04:20:19Z | [
"python",
"beautifulsoup"
] |
Python Argument Binders | 277,922 | <p>How can I bind arguments to a Python method to store a nullary functor for later invocation? Similar to C++'s <code>boost::bind</code>.</p>
| 39 | 2008-11-10T14:01:22Z | 277,932 | <p><a href="http://docs.python.org/2/library/functools.html#functools.partial"><code>functools.partial</code></a> returns a callable wrapping a function with some or all of the arguments frozen.</p>
<pre class="lang-py prettyprint-override"><code>import sys
import functools
print_hello = functools.partial(sys.stdout.write, "Hello world\n")
print_hello()
</code></pre>
<pre class="lang-none prettyprint-override"><code>Hello world
</code></pre>
<p>The above usage is equivalent to the following <code>lambda</code>.</p>
<pre><code>print_hello = lambda *a, **kw: sys.stdout.write("Hello world\n", *a, **kw)
</code></pre>
| 55 | 2008-11-10T14:06:47Z | [
"python"
] |
Python Argument Binders | 277,922 | <p>How can I bind arguments to a Python method to store a nullary functor for later invocation? Similar to C++'s <code>boost::bind</code>.</p>
| 39 | 2008-11-10T14:01:22Z | 277,933 | <p>I'm not overly familiar with boost::bind, but the <code>partial</code> function from <code>functools</code> may be a good start:</p>
<pre><code>>>> from functools import partial
>>> def f(a, b):
... return a+b
>>> p = partial(f, 1, 2)
>>> p()
3
>>> p2 = partial(f, 1)
>>> p2(7)
8
</code></pre>
| 20 | 2008-11-10T14:07:14Z | [
"python"
] |
Python Argument Binders | 277,922 | <p>How can I bind arguments to a Python method to store a nullary functor for later invocation? Similar to C++'s <code>boost::bind</code>.</p>
| 39 | 2008-11-10T14:01:22Z | 278,056 | <p>Functors can be defined this way in Python. They're callable objects. The "binding" merely sets argument values.</p>
<pre><code>class SomeFunctor( object ):
def __init__( self, arg1, arg2=None ):
self.arg1= arg1
self.arg2= arg2
def __call___( self, arg1=None, arg2=None ):
a1= arg1 or self.arg1
a2= arg2 or self.arg2
# do something
return
</code></pre>
<p>You can do things like</p>
<pre><code>x= SomeFunctor( 3.456 )
x( arg2=123 )
y= SomeFunctor( 3.456, 123 )
y()
</code></pre>
| 0 | 2008-11-10T14:57:19Z | [
"python"
] |
Python Argument Binders | 277,922 | <p>How can I bind arguments to a Python method to store a nullary functor for later invocation? Similar to C++'s <code>boost::bind</code>.</p>
| 39 | 2008-11-10T14:01:22Z | 278,217 | <p>If <code>functools.partial</code> is not available then it can be easily emulated:</p>
<pre><code>>>> make_printer = lambda s: lambda: sys.stdout.write("%s\n" % s)
>>> import sys
>>> print_hello = make_printer("hello")
>>> print_hello()
hello
</code></pre>
<p>Or</p>
<pre><code>def partial(func, *args, **kwargs):
def f(*args_rest, **kwargs_rest):
kw = kwargs.copy()
kw.update(kwargs_rest)
return func(*(args + args_rest), **kw)
return f
def f(a, b):
return a + b
p = partial(f, 1, 2)
print p() # -> 3
p2 = partial(f, 1)
print p2(7) # -> 8
d = dict(a=2, b=3)
p3 = partial(f, **d)
print p3(), p3(a=3), p3() # -> 5 6 5
</code></pre>
| 9 | 2008-11-10T15:50:43Z | [
"python"
] |
Python Argument Binders | 277,922 | <p>How can I bind arguments to a Python method to store a nullary functor for later invocation? Similar to C++'s <code>boost::bind</code>.</p>
| 39 | 2008-11-10T14:01:22Z | 279,892 | <p>This would work, too:</p>
<pre><code>def curry(func, *args):
def curried(*innerargs):
return func(*(args+innerargs))
curried.__name__ = "%s(%s, ...)" % (func.__name__, ", ".join(map(str, args)))
return curried
>>> w=curry(sys.stdout.write, "Hey there")
>>> w()
Hey there
</code></pre>
| 7 | 2008-11-11T03:03:27Z | [
"python"
] |
Python Argument Binders | 277,922 | <p>How can I bind arguments to a Python method to store a nullary functor for later invocation? Similar to C++'s <code>boost::bind</code>.</p>
| 39 | 2008-11-10T14:01:22Z | 15,003,681 | <p>lambdas allow you to create a new unnamed function with less arguments and call the function!</p>
<pre><code>>>> def foobar(x,y,z):
... print "%d, %d, %d" % (x,y,z)
>>> foobar(1,2,3) # call normal function
>>> bind = lambda x: foobar(x, 10, 20) # bind 10 and 20 to foobar
>>> bind(1) # print 1, 10, 20
>>> bind = lambda: foobar(1,2,3) # bind all elements
>>> bind() # print 1, 2, 3
</code></pre>
<h3>edit</h3>
<p><a href="https://docs.python.org/2/library/functools.html#functools.partial" rel="nofollow">https://docs.python.org/2/library/functools.html#functools.partial</a></p>
<p>if you are planning to use named argument binding in the function call this is also applicable:</p>
<pre><code>>>> from functools import partial
>>> barfoo = partial(foobar, x=10)
>>> barfoo(y=5,z=6)
21
</code></pre>
<p>Note though that </p>
<pre><code>>>> barfoo(5,6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foobar() got multiple values for keyword argument 'x'
>>> f = partial(foobar, z=20)
>>> f(1,1)
22
</code></pre>
| 5 | 2013-02-21T13:37:49Z | [
"python"
] |
Dictionary or If statements, Jython | 277,965 | <p>I am writing a script at the moment that will grab certain information from HTML using dom4j.</p>
<p>Since Python/Jython does not have a native <strong>switch</strong> statement I decided to use a whole bunch of <strong>if</strong> statements that call the appropriate method, like below:</p>
<pre><code>if type == 'extractTitle':
extractTitle(dom)
if type == 'extractMetaTags':
extractMetaTags(dom)
</code></pre>
<p>I will be adding more depending on what information I want to extract from the HTML and thought about taking the dictionary approach which I found elsewhere on this site, example below:</p>
<pre><code>{
'extractTitle': extractTitle,
'extractMetaTags': extractMetaTags
}[type](dom)
</code></pre>
<p>I know that each time I run the script the dictionary will be built, but at the same time if I were to use the <strong>if</strong> statements the script would have to check through all of them until it hits the correct one. What I am really wondering, which one performs better or is generally better practice to use?</p>
<p><strong>Update:</strong> @Brian - Thanks for the great reply. I have a question, if any of the extract methods require more than one object, e.g.</p>
<pre><code>handle_extractTag(self, dom, anotherObject)
# Do something
</code></pre>
<p>How would you make the appropriate changes to the <strong>handle</strong> method to implemented this? Hope you know what I mean :)</p>
<p>Cheers</p>
| 4 | 2008-11-10T14:20:13Z | 277,972 | <p>To avoid specifying the tag and handler in the dict, you could just use a handler class with methods named to match the type. Eg</p>
<pre><code>class MyHandler(object):
def handle_extractTitle(self, dom):
# do something
def handle_extractMetaTags(self, dom):
# do something
def handle(self, type, dom):
func = getattr(self, 'handle_%s' % type, None)
if func is None:
raise Exception("No handler for type %r" % type)
return func(dom)
</code></pre>
<p>Usage:</p>
<pre><code> handler = MyHandler()
handler.handle('extractTitle', dom)
</code></pre>
<p><strong>Update:</strong> </p>
<p>When you have multiple arguments, just change the handle function to take those arguments and pass them through to the function. If you want to make it more generic (so you don't have to change both the handler functions and the handle method when you change the argument signature), you can use the *args and **kwargs syntax to pass through all received arguments. The handle method then becomes:</p>
<pre><code>def handle(self, type, *args, **kwargs):
func = getattr(self, 'handle_%s' % type, None)
if func is None:
raise Exception("No handler for type %r" % type)
return func(*args, **kwargs)
</code></pre>
| 14 | 2008-11-10T14:24:04Z | [
"python",
"switch-statement",
"jython"
] |
Dictionary or If statements, Jython | 277,965 | <p>I am writing a script at the moment that will grab certain information from HTML using dom4j.</p>
<p>Since Python/Jython does not have a native <strong>switch</strong> statement I decided to use a whole bunch of <strong>if</strong> statements that call the appropriate method, like below:</p>
<pre><code>if type == 'extractTitle':
extractTitle(dom)
if type == 'extractMetaTags':
extractMetaTags(dom)
</code></pre>
<p>I will be adding more depending on what information I want to extract from the HTML and thought about taking the dictionary approach which I found elsewhere on this site, example below:</p>
<pre><code>{
'extractTitle': extractTitle,
'extractMetaTags': extractMetaTags
}[type](dom)
</code></pre>
<p>I know that each time I run the script the dictionary will be built, but at the same time if I were to use the <strong>if</strong> statements the script would have to check through all of them until it hits the correct one. What I am really wondering, which one performs better or is generally better practice to use?</p>
<p><strong>Update:</strong> @Brian - Thanks for the great reply. I have a question, if any of the extract methods require more than one object, e.g.</p>
<pre><code>handle_extractTag(self, dom, anotherObject)
# Do something
</code></pre>
<p>How would you make the appropriate changes to the <strong>handle</strong> method to implemented this? Hope you know what I mean :)</p>
<p>Cheers</p>
| 4 | 2008-11-10T14:20:13Z | 277,978 | <p>It depends on how many if statements we're talking about; if it's a very small number, then it will be more efficient than using a dictionary.</p>
<p>However, as always, I strongly advice you to do whatever makes your code look cleaner until experience and profiling tell you that a specific block of code needs to be optimized.</p>
| 1 | 2008-11-10T14:26:14Z | [
"python",
"switch-statement",
"jython"
] |
Dictionary or If statements, Jython | 277,965 | <p>I am writing a script at the moment that will grab certain information from HTML using dom4j.</p>
<p>Since Python/Jython does not have a native <strong>switch</strong> statement I decided to use a whole bunch of <strong>if</strong> statements that call the appropriate method, like below:</p>
<pre><code>if type == 'extractTitle':
extractTitle(dom)
if type == 'extractMetaTags':
extractMetaTags(dom)
</code></pre>
<p>I will be adding more depending on what information I want to extract from the HTML and thought about taking the dictionary approach which I found elsewhere on this site, example below:</p>
<pre><code>{
'extractTitle': extractTitle,
'extractMetaTags': extractMetaTags
}[type](dom)
</code></pre>
<p>I know that each time I run the script the dictionary will be built, but at the same time if I were to use the <strong>if</strong> statements the script would have to check through all of them until it hits the correct one. What I am really wondering, which one performs better or is generally better practice to use?</p>
<p><strong>Update:</strong> @Brian - Thanks for the great reply. I have a question, if any of the extract methods require more than one object, e.g.</p>
<pre><code>handle_extractTag(self, dom, anotherObject)
# Do something
</code></pre>
<p>How would you make the appropriate changes to the <strong>handle</strong> method to implemented this? Hope you know what I mean :)</p>
<p>Cheers</p>
| 4 | 2008-11-10T14:20:13Z | 277,980 | <p>Your use of the dictionary is not quite correct. In your implementation, all methods will be called and all the useless one discarded. What is usually done is more something like:</p>
<pre><code>switch_dict = {'extractTitle': extractTitle,
'extractMetaTags': extractMetaTags}
switch_dict[type](dom)
</code></pre>
<p>And that way is facter and more extensible if you have a large (or variable) number of items.</p>
| 1 | 2008-11-10T14:27:35Z | [
"python",
"switch-statement",
"jython"
] |
Dictionary or If statements, Jython | 277,965 | <p>I am writing a script at the moment that will grab certain information from HTML using dom4j.</p>
<p>Since Python/Jython does not have a native <strong>switch</strong> statement I decided to use a whole bunch of <strong>if</strong> statements that call the appropriate method, like below:</p>
<pre><code>if type == 'extractTitle':
extractTitle(dom)
if type == 'extractMetaTags':
extractMetaTags(dom)
</code></pre>
<p>I will be adding more depending on what information I want to extract from the HTML and thought about taking the dictionary approach which I found elsewhere on this site, example below:</p>
<pre><code>{
'extractTitle': extractTitle,
'extractMetaTags': extractMetaTags
}[type](dom)
</code></pre>
<p>I know that each time I run the script the dictionary will be built, but at the same time if I were to use the <strong>if</strong> statements the script would have to check through all of them until it hits the correct one. What I am really wondering, which one performs better or is generally better practice to use?</p>
<p><strong>Update:</strong> @Brian - Thanks for the great reply. I have a question, if any of the extract methods require more than one object, e.g.</p>
<pre><code>handle_extractTag(self, dom, anotherObject)
# Do something
</code></pre>
<p>How would you make the appropriate changes to the <strong>handle</strong> method to implemented this? Hope you know what I mean :)</p>
<p>Cheers</p>
| 4 | 2008-11-10T14:20:13Z | 277,981 | <p>With your code you're running your functions all get called.</p>
<pre>
handlers = {
'extractTitle': extractTitle,
'extractMetaTags': extractMetaTags
}
handlers[type](dom)
</pre>
<p>Would work like your original <code>if</code> code.</p>
| 2 | 2008-11-10T14:27:44Z | [
"python",
"switch-statement",
"jython"
] |
Dictionary or If statements, Jython | 277,965 | <p>I am writing a script at the moment that will grab certain information from HTML using dom4j.</p>
<p>Since Python/Jython does not have a native <strong>switch</strong> statement I decided to use a whole bunch of <strong>if</strong> statements that call the appropriate method, like below:</p>
<pre><code>if type == 'extractTitle':
extractTitle(dom)
if type == 'extractMetaTags':
extractMetaTags(dom)
</code></pre>
<p>I will be adding more depending on what information I want to extract from the HTML and thought about taking the dictionary approach which I found elsewhere on this site, example below:</p>
<pre><code>{
'extractTitle': extractTitle,
'extractMetaTags': extractMetaTags
}[type](dom)
</code></pre>
<p>I know that each time I run the script the dictionary will be built, but at the same time if I were to use the <strong>if</strong> statements the script would have to check through all of them until it hits the correct one. What I am really wondering, which one performs better or is generally better practice to use?</p>
<p><strong>Update:</strong> @Brian - Thanks for the great reply. I have a question, if any of the extract methods require more than one object, e.g.</p>
<pre><code>handle_extractTag(self, dom, anotherObject)
# Do something
</code></pre>
<p>How would you make the appropriate changes to the <strong>handle</strong> method to implemented this? Hope you know what I mean :)</p>
<p>Cheers</p>
| 4 | 2008-11-10T14:20:13Z | 278,006 | <p>The efficiency question is barely relevant. The dictionary lookup is done with a simple hashing technique, the if-statements have to be evaluated one at a time. Dictionaries tend to be quicker.</p>
<p>I suggest that you actually have polymorphic objects that do extractions from the DOM.</p>
<p>It's not clear how <code>type</code> gets set, but it sure looks like it might be a family of related objects, not a simple string.</p>
<pre><code>class ExtractTitle( object ):
def process( dom ):
return something
class ExtractMetaTags( object ):
def process( dom ):
return something
</code></pre>
<p>Instead of setting type="extractTitle", you'd do this.</p>
<pre><code>type= ExtractTitle() # or ExtractMetaTags() or ExtractWhatever()
type.process( dom )
</code></pre>
<p>Then, you wouldn't be building this particular dictionary or if-statement.</p>
| 1 | 2008-11-10T14:36:53Z | [
"python",
"switch-statement",
"jython"
] |
How do I script an OLE component using Python? | 279,094 | <p>I would like to use Python to script an application that advertises itself as providing an OLE component. How should I get started?</p>
<p>I don't yet know what methods I need to call on the COMponents I will be accessing. Should I use win32com to load those components, and then start pressing 'tab' in IPython?</p>
| 9 | 2008-11-10T20:41:41Z | 279,117 | <p>You need the <a href="http://python.net/crew/mhammond/win32/Downloads.html" rel="nofollow">win32com</a> package. Some examples:</p>
<pre><code>from win32com.client.dynamic import Dispatch
# Excel
excel = Dispatch('Excel.Application')
# Vim
vim = Dispatch('Vim.Application')
</code></pre>
<p>And then call whatever you like on them.</p>
| 2 | 2008-11-10T20:50:47Z | [
"python",
"windows",
"scripting",
"activex",
"ole"
] |
How do I script an OLE component using Python? | 279,094 | <p>I would like to use Python to script an application that advertises itself as providing an OLE component. How should I get started?</p>
<p>I don't yet know what methods I need to call on the COMponents I will be accessing. Should I use win32com to load those components, and then start pressing 'tab' in IPython?</p>
| 9 | 2008-11-10T20:41:41Z | 279,120 | <p>You can find an example on <a href="http://www.boddie.org.uk/python/COM.html" rel="nofollow">this website</a>. OLE and is related to COM and ActiveX so you should look out for those terms. Do you have access this book from O'Reilly - <a href="http://oreilly.com/catalog/9781565926219/" rel="nofollow">Python Programming on Win32</a>?</p>
<p>There is also a <a href="http://mail.python.org/pipermail/python-win32/" rel="nofollow">Python Win32</a> mailing list.</p>
| 3 | 2008-11-10T20:51:43Z | [
"python",
"windows",
"scripting",
"activex",
"ole"
] |
How do I script an OLE component using Python? | 279,094 | <p>I would like to use Python to script an application that advertises itself as providing an OLE component. How should I get started?</p>
<p>I don't yet know what methods I need to call on the COMponents I will be accessing. Should I use win32com to load those components, and then start pressing 'tab' in IPython?</p>
| 9 | 2008-11-10T20:41:41Z | 279,123 | <p>Please take a look at the <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">python-win32</a> package, and, in particular, at its win32com API.</p>
| 0 | 2008-11-10T20:52:07Z | [
"python",
"windows",
"scripting",
"activex",
"ole"
] |
How do I script an OLE component using Python? | 279,094 | <p>I would like to use Python to script an application that advertises itself as providing an OLE component. How should I get started?</p>
<p>I don't yet know what methods I need to call on the COMponents I will be accessing. Should I use win32com to load those components, and then start pressing 'tab' in IPython?</p>
| 9 | 2008-11-10T20:41:41Z | 308,854 | <p>PythonWin (<a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">http://sourceforge.net/projects/pywin32/</a>), bundled with python-win32, comes with its own COM browser as part of its shell and debugging environment.</p>
| 0 | 2008-11-21T13:57:17Z | [
"python",
"windows",
"scripting",
"activex",
"ole"
] |
How do I script an OLE component using Python? | 279,094 | <p>I would like to use Python to script an application that advertises itself as providing an OLE component. How should I get started?</p>
<p>I don't yet know what methods I need to call on the COMponents I will be accessing. Should I use win32com to load those components, and then start pressing 'tab' in IPython?</p>
| 9 | 2008-11-10T20:41:41Z | 363,885 | <p>win32com is a good package to use if you want to use the IDispatch interface to control your objects (slow). comtypes is a better, native python, package that uses the raw COM approach to talking to your controls. WxPython uses comtypes to give you an ActiveX container window from Python ... sweet.</p>
| 2 | 2008-12-12T19:33:01Z | [
"python",
"windows",
"scripting",
"activex",
"ole"
] |
How do I search for unpublished Plone content in an IPython debug shell? | 279,119 | <p>I like to use IPython's zope profile to inspect my Plone instance, but a few annoying permissions differences come up compared to inserting a breakpoint and hitting it with the admin user.</p>
<p>For example, I would like to iterate over the content objects in an unpublished testing folder. This query will return no results in the shell, but works from a breakpoint.</p>
<pre><code>$ bin/instance shell
$ ipython --profile=zope
from Products.CMFPlone.utils import getToolByName
catalog = getToolByName(context, 'portal_catalog')
catalog({'path':'Plone/testing'})
</code></pre>
<p>Can I authenticate as admin or otherwise rejigger the permissions to fully manipulate my site from ipython?</p>
| 2 | 2008-11-10T20:51:35Z | 290,657 | <p>Just use catalog.search({'path':'Plone/testing'}). It performs the same query as catalog() but does not filter the results based on the current user's permissions.</p>
<p>IPython's zope profile does provide a method utils.su('username') to change the current user, but it does not recognize the admin user (defined in /acl_users instead of /Plone/acl_users) and after calling it subsequent calls to catalog() fail with AttributeError: 'module' object has no attribute 'checkPermission'.</p>
| 1 | 2008-11-14T16:29:54Z | [
"python",
"plone"
] |
How do I search for unpublished Plone content in an IPython debug shell? | 279,119 | <p>I like to use IPython's zope profile to inspect my Plone instance, but a few annoying permissions differences come up compared to inserting a breakpoint and hitting it with the admin user.</p>
<p>For example, I would like to iterate over the content objects in an unpublished testing folder. This query will return no results in the shell, but works from a breakpoint.</p>
<pre><code>$ bin/instance shell
$ ipython --profile=zope
from Products.CMFPlone.utils import getToolByName
catalog = getToolByName(context, 'portal_catalog')
catalog({'path':'Plone/testing'})
</code></pre>
<p>Can I authenticate as admin or otherwise rejigger the permissions to fully manipulate my site from ipython?</p>
| 2 | 2008-11-10T20:51:35Z | 427,914 | <p>here's the (<strong>very</strong> dirty) code I use to manage my plone app from the debug shell. It may requires some updates depending on your versions of Zope and Plone.</p>
<pre><code>from sys import stdin, stdout, exit
import base64
from thread import get_ident
from ZPublisher.HTTPRequest import HTTPRequest
from ZPublisher.HTTPResponse import HTTPResponse
from ZPublisher.BaseRequest import RequestContainer
from ZPublisher import Publish
from AccessControl import ClassSecurityInfo, getSecurityManager
from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.User import UnrestrictedUser
def loginAsUnrestrictedUser():
"""Exemple of use :
old_user = loginAsUnrestrictedUser()
# Manager stuff
loginAsUser(old_user)
"""
current_user = getSecurityManager().getUser()
newSecurityManager(None, UnrestrictedUser('manager', '', ['Manager'], []))
return current_user
def loginAsUser(user):
newSecurityManager(None, user)
def makerequest(app, stdout=stdout, query_string=None, user_pass=None):
"""Make a request suitable for CMF sites & Plone
- user_pass = "user:pass"
"""
# copy from Testing.makerequest
resp = HTTPResponse(stdout=stdout)
env = {}
env['SERVER_NAME'] = 'lxtools.makerequest.fr'
env['SERVER_PORT'] = '80'
env['REQUEST_METHOD'] = 'GET'
env['REMOTE_HOST'] = 'a.distant.host'
env['REMOTE_ADDR'] = '77.77.77.77'
env['HTTP_HOST'] = '127.0.0.1'
env['HTTP_USER_AGENT'] = 'LxToolsUserAgent/1.0'
env['HTTP_ACCEPT']='image/gif, image/x-xbitmap, image/jpeg, */* '
if user_pass:
env['HTTP_AUTHORIZATION']="Basic %s" % base64.encodestring(user_pass)
if query_string:
p_q = query_string.split('?')
if len(p_q) == 1:
env['PATH_INFO'] = p_q[0]
elif len(p_q) == 2:
(env['PATH_INFO'], env['QUERY_STRING'])=p_q
else:
raise TypeError, ''
req = HTTPRequest(stdin, env, resp)
req['URL1']=req['URL'] # fix for CMFQuickInstaller
#
# copy/hacked from Localizer __init__ patches
# first put the needed values in the request
req['HTTP_ACCEPT_CHARSET'] = 'latin-9'
#req.other['AcceptCharset'] = AcceptCharset(req['HTTP_ACCEPT_CHARSET'])
#
req['HTTP_ACCEPT_LANGUAGE'] = 'fr'
#accept_language = AcceptLanguage(req['HTTP_ACCEPT_LANGUAGE'])
#req.other['AcceptLanguage'] = accept_language
# XXX For backwards compatibility
#req.other['USER_PREF_LANGUAGES'] = accept_language
#req.other['AcceptLanguage'] = accept_language
#
# Plone stuff
#req['plone_skin'] = 'Plone Default'
#
# then store the request in Publish._requests
# with the thread id
id = get_ident()
if hasattr(Publish, '_requests'):
# we do not have _requests inside ZopeTestCase
Publish._requests[id] = req
# add a brainless session container
req['SESSION'] = {}
#
# ok, let's wrap
return app.__of__(RequestContainer(REQUEST = req))
def debug_init(app):
loginAsUnrestrictedUser()
app = makerequest(app)
return app
</code></pre>
<p>This lives in a wshelpers Zope product. Once the debug shell launched, it's just a matter of;</p>
<pre><code>>> from Products.wshelpers import wsdebug
>> app = wsdebug.debug_init(app)
>> # now you're logged in as admin
</code></pre>
| 2 | 2009-01-09T12:37:52Z | [
"python",
"plone"
] |
Can anyone recommend a decent FOSS PDF generator for Python? | 279,129 | <p>I need a basic pdf generator that'll let me toss some images and text into a pdf file. The ability to have some basic drawing commands (lines and so forth) would also be a plus.</p>
<p>I did read through <a href="http://stackoverflow.com/questions/177799/what-is-a-good-pdf-report-generator-tool-for-python">this question</a>, but I really don't need a report generator and most of the responses there seemed like real overkill for what I'm trying to do. (I don't need templates or LaTeX-grade layout control.)</p>
| 5 | 2008-11-10T20:53:34Z | 279,147 | <p>I think going through Latex is the easiest way, and not overkill at all. Generating a working PDF file is quite a difficult activity, whereas generating a Tex source is much easier. Any other typesetting change would probably work as well, such as going through reStructuredText or troff.</p>
| 1 | 2008-11-10T20:59:04Z | [
"python",
"pdf-generation"
] |
Can anyone recommend a decent FOSS PDF generator for Python? | 279,129 | <p>I need a basic pdf generator that'll let me toss some images and text into a pdf file. The ability to have some basic drawing commands (lines and so forth) would also be a plus.</p>
<p>I did read through <a href="http://stackoverflow.com/questions/177799/what-is-a-good-pdf-report-generator-tool-for-python">this question</a>, but I really don't need a report generator and most of the responses there seemed like real overkill for what I'm trying to do. (I don't need templates or LaTeX-grade layout control.)</p>
| 5 | 2008-11-10T20:53:34Z | 279,165 | <p>For one of my projects, I have tested and/or implemented probably six or seven different methods of going from an image to a PDF in the last six months. Ultimately I ended up coming back to <a href="http://www.reportlab.org/downloads.html" rel="nofollow">ReportLab</a> (which I had initially avoided for reasons similar to those you described) because all of the others had glaring limitations or outright omissions (such as the inability to set document metadata).</p>
<p>ReportLab isn't as difficult to handle as it appears at first glance and it may save you a lot of headache-laden refactoring later on. I would strongly suggest you go ahead and use it and therefore know that if you ever want to be able to do more you will have the ability too rather than do what I did and bounce back and forth between a number of different utilities, libraries, and formats.</p>
<p><strong>EDIT:</strong></p>
<p>It is also worth mentioning that you can bypass the Platypus layout system that comes with ReportLab if all you want to do is put bit a of text and imagery on a page.</p>
| 5 | 2008-11-10T21:04:17Z | [
"python",
"pdf-generation"
] |
Can anyone recommend a decent FOSS PDF generator for Python? | 279,129 | <p>I need a basic pdf generator that'll let me toss some images and text into a pdf file. The ability to have some basic drawing commands (lines and so forth) would also be a plus.</p>
<p>I did read through <a href="http://stackoverflow.com/questions/177799/what-is-a-good-pdf-report-generator-tool-for-python">this question</a>, but I really don't need a report generator and most of the responses there seemed like real overkill for what I'm trying to do. (I don't need templates or LaTeX-grade layout control.)</p>
| 5 | 2008-11-10T20:53:34Z | 279,167 | <p>Is the reportlab code not ok? The reason why using LaTeX might not be overkill is because pdf is a really low-level format. In pdf you do not get line-breaks automatically, you have to calculate line-widths yourself.</p>
| 0 | 2008-11-10T21:04:48Z | [
"python",
"pdf-generation"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 279,253 | <p>Be sure that dirBar has the <code>__init__.py</code> file -- this makes a directory into a Python package.</p>
| 259 | 2008-11-10T21:33:33Z | [
"python",
"relative-path",
"python-import"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 279,287 | <p>(This is from memory so someone edit if I make a typo, please.)</p>
<p>If you structure your project this way:</p>
<pre><code>src\
__init__.py
main.py
dirFoo\
__init__.py
Foo.py
dirBar\
__init__.py
Bar.py
</code></pre>
<p>Then from Foo.py you should be able to do:</p>
<pre><code>import dirFoo.Foo
</code></pre>
<p>Or:</p>
<pre><code>from dirFoo.Foo import FooObject
</code></pre>
<p><strong>EDIT 1:</strong></p>
<p>Per Tom's comment, this does require that the <code>src</code> folder is accessible either via <code>site_packages</code> or your search path. Also, as he mentions, <code>__init__.py</code> is implicitly imported when you first import a module in that package/directory. Typically <code>__init__.py</code> is simply an empty file.</p>
| 64 | 2008-11-10T21:46:04Z | [
"python",
"relative-path",
"python-import"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 279,338 | <p>You could also add the sub directory to your python path so that it imports as a normal script.</p>
<pre><code>import sys
sys.path.append( <path to dirFoo> )
import Bar
</code></pre>
| 186 | 2008-11-10T22:04:27Z | [
"python",
"relative-path",
"python-import"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 279,389 | <p>This is the relevant PEP:</p>
<p><a href="http://www.python.org/dev/peps/pep-0328/">http://www.python.org/dev/peps/pep-0328/</a></p>
<p>In particular, presuming dirFoo is a directory up from dirBar...</p>
<p>In dirFoo\Foo.py:</p>
<pre><code>from ..dirBar import Bar
</code></pre>
| 32 | 2008-11-10T22:22:47Z | [
"python",
"relative-path",
"python-import"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 282,778 | <p>The easiest method is to use sys.path.append().</p>
<p>However, you may be also interested in the <a href="http://docs.python.org/library/imp.html?highlight=imp#module-imp">imp</a> module.
It provides access to internal import functions.</p>
<pre><code># mod_name is the filename without the .py/.pyc extention
py_mod = imp.load_source(mod_name,filename_path) # Loads .py file
py_mod = imp.load_compiled(mod_name,filename_path) # Loads .pyc file
</code></pre>
<p>This can be used to load modules dynamically when you don't know a module's name.</p>
<p>I've used this in the past to create a plugin type interface to an application, where the user would write a script with application specific functions, and just drop thier script in a specific directory.</p>
<p>Also, these functions may be useful:</p>
<pre><code>imp.find_module(name[, path])
imp.load_module(name, file, pathname, description)
</code></pre>
| 41 | 2008-11-12T01:56:51Z | [
"python",
"relative-path",
"python-import"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 2,352,563 | <p>Add an <strong>_<em>init</em>_.py</strong> file:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
__init__.py
Bar.py
</code></pre>
<p>Then add this code to the start of Foo.py:</p>
<pre><code>import sys
sys.path.append('dirBar')
import Bar
</code></pre>
| 5 | 2010-02-28T20:34:59Z | [
"python",
"relative-path",
"python-import"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 3,714,805 | <p>In my opinion the best choice is to put <strong>__ init __.py</strong> in the folder and call the file with</p>
<pre><code>from dirBar.Bar import *
</code></pre>
<p>It is not recommended to use sys.path.append() because something might gone wrong if you use the same file name as the existing python package. I haven't test that but that will be ambiguous.</p>
| 11 | 2010-09-15T05:02:52Z | [
"python",
"relative-path",
"python-import"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 4,284,378 | <pre><code>import os, sys
lib_path = os.path.abspath(os.path.join('..', '..', '..', 'lib'))
sys.path.append(lib_path)
import mymodule
</code></pre>
| 87 | 2010-11-26T10:21:28Z | [
"python",
"relative-path",
"python-import"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 4,397,291 | <p>Just do Simple Things to import py file from different folder-</p>
<p>Let's you have a directory like-</p>
<pre><code>lib/abc.py
</code></pre>
<p>Then just keep a empty file in lib folder as named </p>
<pre><code>__init__.py
</code></pre>
<p>and then use </p>
<pre><code>from lib.abc import <Your Module name>
</code></pre>
<p>Keep <code>__init__.py</code> file in every folder of hierarchy of import module</p>
| 71 | 2010-12-09T10:40:09Z | [
"python",
"relative-path",
"python-import"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 4,946,813 | <p>Look at the pkgutil module from the standard library. It may help you do what you want.</p>
| 2 | 2011-02-09T15:19:55Z | [
"python",
"relative-path",
"python-import"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 6,098,238 | <p>Assuming that both your directories are real python packages (do have the <code>__init__.py</code> file inside them), here is a safe solution for inclusion of modules relatively to the location of the script.</p>
<p>I assume that you want to do this because you need to include a set of modules with your script. I use this in production in several products and works in many special scenarios like: scripts called from another directory or executed with python execute instead of opening a new interpreter.</p>
<pre><code> import os, sys, inspect
# realpath() will make your script run, even if you symlink it :)
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
# use this if you want to include modules from a subfolder
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder")))
if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)
# Info:
# cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!!
# __file__ fails if script is called in different ways on Windows
# __file__ fails if someone does os.chdir() before
# sys.argv[0] also fails because it doesn't not always contains the path
</code></pre>
<p>As a bonus, this approach does let you force Python to use your module instead of the ones installed on the system. </p>
<p>Warning! I don't really know what is happening when current module is inside an <code>egg</code> file. Probably it fails too. Add a comment if you really need a better solution, I may invest few more hours in improving it.</p>
| 255 | 2011-05-23T14:00:43Z | [
"python",
"relative-path",
"python-import"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 7,262,716 | <pre><code>from .dirBar import Bar
</code></pre>
<p>instead of:</p>
<pre><code>from dirBar import Bar
</code></pre>
<p>just in case there could be another dirBar installed and confuse a foo.py reader.</p>
| 8 | 2011-08-31T20:02:15Z | [
"python",
"relative-path",
"python-import"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 7,520,383 | <p>Call me overly cautious but I like to make mine more portable because it's unsafe to assume that files will always be in the same place on every computer. Personally I have the code look up the file path first. I use linux so mine would look like this:</p>
<pre><code>import os, sys
from subprocess import Popen, PIPE
try:
path = Popen("find / -name 'file' -type f", shell=True, stdout=PIPE).stdout.read().splitlines()[0]
if not sys.path.__contains__(path):
sys.path.append(path)
except IndexError:
raise RuntimeError("You must have FILE to run this program!")
</code></pre>
<p>That is of course unless you plan to package these together. But if that's the case you don't really need two separate files anyway.</p>
| -12 | 2011-09-22T19:33:39Z | [
"python",
"relative-path",
"python-import"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 9,037,651 | <p>Here's a way to import a file from one level above, using the relative path.</p>
<p>Basically, just move the working directory up a level (or any relative location), add that to your path, then move the working directory back where it started.</p>
<pre><code>#to import from one level above:
cwd = os.getcwd()
os.chdir("..")
below_path = os.getcwd()
sys.path.append(below_path)
os.chdir(cwd)
</code></pre>
| 1 | 2012-01-27T17:43:59Z | [
"python",
"relative-path",
"python-import"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 13,963,800 | <h2>The quick-and-dirty way for Linux users</h2>
<p>If you are just tinkering around and don't care about deployment issues, you can use a symbolic link (assuming your filesystem supports it) to make the module or package directly visible in the folder of the requesting module.</p>
<pre><code>ln -s (path)/module_name.py
</code></pre>
<p>or</p>
<pre><code>ln -s (path)/package_name
</code></pre>
<hr>
<p><em>Note: A "module" is any file with a .py extension and a "package" is any folder that contains the file <code>__init__.py</code> (which can be an empty file). From a usage standpoint, modules and packages are identical -- both expose their contained "definitions and statements" as requested via the <code>import</code> command.</em></p>
<p>See: <a href="http://docs.python.org/2/tutorial/modules.html">http://docs.python.org/2/tutorial/modules.html</a></p>
| 10 | 2012-12-20T01:07:43Z | [
"python",
"relative-path",
"python-import"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 14,803,823 | <p>The easiest way without any modification to your script is to set PYTHONPATH environment variable. Cause sys.path is initialized from these locations:</p>
<ol>
<li>the directory containing the input script (or the current
directory). </li>
<li>PYTHONPATH (a list of directory names, with the same
syntax as the shell variable PATH). </li>
<li>the installation-dependent default.</li>
</ol>
<p>Just run:</p>
<pre><code>export PYTHONPATH=/absolute/path/to/your/module
</code></pre>
<p>You sys.path will contains above path, as show below:</p>
<p>print sys.path</p>
<pre><code>['', '/absolute/path/to/your/module', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-installer', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol']
</code></pre>
| 14 | 2013-02-10T23:21:51Z | [
"python",
"relative-path",
"python-import"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 25,010,192 | <p>Relative sys.path example:</p>
<pre><code># /lib/my_module.py
# /src/test.py
if __name__ == '__main__' and __package__ is None:
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../lib')))
import my_module
</code></pre>
<p>Based on <a href="http://stackoverflow.com/a/19190695/991267">this</a> answer.</p>
| 4 | 2014-07-29T07:27:39Z | [
"python",
"relative-path",
"python-import"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 26,639,332 | <p>For this case to import Bar.py into Foo.py, first I'd turn these folders into python packages like so:</p>
<pre><code>dirFoo\
__init__.py
Foo.py
dirBar\
__init__.py
Bar.py
</code></pre>
<p>Then I would do it like this in Foo.py:</p>
<pre><code>from .dirBar import Bar
</code></pre>
<p>If I wanted the namespacing to look like Bar.<em>whatever</em>, or</p>
<pre><code>from . import dirBar
</code></pre>
<p>If I wanted the namespacing dirBar.Bar.<em>whatever</em>.
This second case is usefull if you have more modules under the dirBar package.</p>
| 7 | 2014-10-29T19:49:53Z | [
"python",
"relative-path",
"python-import"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 29,401,990 | <p>Well, as you mention, usually you want to have access to a folder with your modules relative to where your main script is run, so you just import them<br>
Solution:<br>
I have the script in <code>D:/Books/MyBooks.py</code> and some modules (like oldies.py) I need to import from subdirectory <code>D:/Books/includes</code></p>
<pre><code>import sys,site
site.addsitedir(sys.path[0]+'\\includes')
print (sys.path) # just verify it is there
import oldies
</code></pre>
<p>Place a <code>print('done')</code> in <code>oldies.py</code> so you verify everything is going ok. This way always works because by python definition <code>sys.path</code> As initialized upon program startup, the first item of this list, <code>path[0]</code>, is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), <code>path[0]</code> is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of <code>PYTHONPATH</code>. </p>
| 2 | 2015-04-01T22:29:39Z | [
"python",
"relative-path",
"python-import"
] |
Import a module from a relative path | 279,237 | <p>How do I import a python module given its relative path?</p>
<p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p>
<p>Here's a visual representation:</p>
<pre><code>dirFoo\
Foo.py
dirBar\
Bar.py
</code></pre>
<p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
| 555 | 2008-11-10T21:28:48Z | 38,808,859 | <p>Another solution would be to install the <a href="https://pypi.python.org/pypi/py-require" rel="nofollow">py-require</a> package and then use the following in <code>Foo.py</code></p>
<pre><code>import require
Bar = require('./dirBar/Bar')
</code></pre>
| 1 | 2016-08-06T21:26:58Z | [
"python",
"relative-path",
"python-import"
] |
Python: How do I generate a keypress? | 279,434 | <p>I am opening a process (with os.popen() ) that, for some commands, detects certain keypresses (e.g. ESC - not the character, the key). Is there a way to send keypress events to the process?</p>
| 1 | 2008-11-10T22:41:30Z | 279,460 | <p>The obvious way would be to start the process in it's own shell.<br />
something like os.popen("sh command") </p>
| 0 | 2008-11-10T22:46:59Z | [
"python",
"keypress",
"popen"
] |
Python: How do I generate a keypress? | 279,434 | <p>I am opening a process (with os.popen() ) that, for some commands, detects certain keypresses (e.g. ESC - not the character, the key). Is there a way to send keypress events to the process?</p>
| 1 | 2008-11-10T22:41:30Z | 279,477 | <p>You probably want something like <a href="http://www.noah.org/wiki/Pexpect" rel="nofollow"><code>Pexpect</code></a>. It's been around a while, and there may be a better alternative, now, but it will let you do what you want. </p>
<p>As far as I know, there is no easy way to do that kind of thing with os.popen or the commands in the <code>subprocess</code> module.</p>
| 1 | 2008-11-10T22:52:35Z | [
"python",
"keypress",
"popen"
] |
Python: How do I generate a keypress? | 279,434 | <p>I am opening a process (with os.popen() ) that, for some commands, detects certain keypresses (e.g. ESC - not the character, the key). Is there a way to send keypress events to the process?</p>
| 1 | 2008-11-10T22:41:30Z | 279,627 | <p>What platform is this on? </p>
<p>You may have to actually feed events into the event loop, if it's running on Win32.</p>
| 0 | 2008-11-11T00:04:58Z | [
"python",
"keypress",
"popen"
] |
What is the Python equivalent of static variables inside a function? | 279,561 | <p>What is the idiomatic Python equivalent of this C/C++ code?</p>
<pre><code>void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
</code></pre>
<p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
| 311 | 2008-11-10T23:33:36Z | 279,568 | <p>Use a generator function to generate an iterator.</p>
<pre><code>def foo_gen():
n = 0
while True:
n+=1
yield n
</code></pre>
<p>Then use it like</p>
<pre><code>foo = foo_gen().next
for i in range(0,10):
print foo()
</code></pre>
<p>If you want an upper limit:</p>
<pre><code>def foo_gen(limit=100000):
n = 0
while n < limit:
n+=1
yield n
</code></pre>
<p>If the iterator terminates (like the example above), you can also loop over it directly, like</p>
<pre><code>for i in foo_gen(20):
print i
</code></pre>
<p>Of course, in these simple cases it's better to use xrange :)</p>
<p>Here is the documentation on the <a href="http://docs.python.org/reference/simple_stmts.html#the-yield-statement">yield statement</a>.</p>
| 8 | 2008-11-10T23:37:00Z | [
"python"
] |
What is the Python equivalent of static variables inside a function? | 279,561 | <p>What is the idiomatic Python equivalent of this C/C++ code?</p>
<pre><code>void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
</code></pre>
<p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
| 311 | 2008-11-10T23:33:36Z | 279,586 | <p>A bit reversed, but this should work:</p>
<pre><code>def foo():
foo.counter += 1
print "Counter is %d" % foo.counter
foo.counter = 0
</code></pre>
<p>If you want the counter initialization code at the top instead of the bottom, you can create a decorator:</p>
<pre><code>def static_var(varname, value):
def decorate(func):
setattr(func, varname, value)
return func
return decorate
</code></pre>
<p>Then use the code like this:</p>
<pre><code>@static_var("counter", 0)
def foo():
foo.counter += 1
print "Counter is %d" % foo.counter
</code></pre>
<p>It'll still require you to use the <code>foo.</code> prefix, unfortunately.</p>
<hr>
<p>EDIT (thanks to <a href="http://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function/279586#comment41067162_279586">ony</a>): This looks even nicer:</p>
<pre><code>def static_vars(**kwargs):
def decorate(func):
for k in kwargs:
setattr(func, k, kwargs[k])
return func
return decorate
@static_vars(counter=0)
def foo():
foo.counter += 1
print "Counter is %d" % foo.counter
</code></pre>
| 376 | 2008-11-10T23:46:00Z | [
"python"
] |
What is the Python equivalent of static variables inside a function? | 279,561 | <p>What is the idiomatic Python equivalent of this C/C++ code?</p>
<pre><code>void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
</code></pre>
<p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
| 311 | 2008-11-10T23:33:36Z | 279,592 | <p>Other answers have demonstrated the way you should do this. Here's a way you shouldn't:</p>
<pre><code>>>> def foo(counter=[0]):
... counter[0] += 1
... print("Counter is %i." % counter[0]);
...
>>> foo()
Counter is 1.
>>> foo()
Counter is 2.
>>>
</code></pre>
<p>Default values are initialized only when the function is first evaluated, not each time it is executed, so you can use a list or any other mutable object to store static values.</p>
| 28 | 2008-11-10T23:47:53Z | [
"python"
] |
What is the Python equivalent of static variables inside a function? | 279,561 | <p>What is the idiomatic Python equivalent of this C/C++ code?</p>
<pre><code>void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
</code></pre>
<p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
| 311 | 2008-11-10T23:33:36Z | 279,596 | <pre>
_counter = 0
def foo():
global _counter
_counter += 1
print 'counter is', _counter
</pre>
<p>Python customarily uses underscores to indicate private variables. The only reason in C to declare the static variable inside the function is to hide it outside the function, which is not really idiomatic Python.</p>
| 5 | 2008-11-10T23:50:14Z | [
"python"
] |
What is the Python equivalent of static variables inside a function? | 279,561 | <p>What is the idiomatic Python equivalent of this C/C++ code?</p>
<pre><code>void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
</code></pre>
<p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
| 311 | 2008-11-10T23:33:36Z | 279,597 | <p>You can add attributes to a function, and use it as a static variable.</p>
<pre><code>def myfunc():
myfunc.counter += 1
print myfunc.counter
# attribute must be initialized
myfunc.counter = 0
</code></pre>
<p>Alternatively, if you don't want to setup the variable outside the function, you can use <code>hasattr()</code> to avoid an <code>AttributeError</code> exception:</p>
<pre><code>def myfunc():
if not hasattr(myfunc, "counter"):
myfunc.counter = 0 # it doesn't exist yet, so initialize it
myfunc.counter += 1
</code></pre>
<p>Anyway static variables are rather rare, and you should find a better place for this variable, most likely inside a class.</p>
| 137 | 2008-11-10T23:53:00Z | [
"python"
] |
What is the Python equivalent of static variables inside a function? | 279,561 | <p>What is the idiomatic Python equivalent of this C/C++ code?</p>
<pre><code>void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
</code></pre>
<p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
| 311 | 2008-11-10T23:33:36Z | 279,598 | <p>Python doesn't have static variables but you can fake it by defining a callable class object and then using it as a function. <a href="http://stackoverflow.com/a/593046/4561887">Also see this answer</a>.</p>
<pre><code>class Foo(object):
# Class variable, shared by all instances of this class
counter = 0
def __call__(self):
Foo.counter += 1
print Foo.counter
# Create an object instance of class "Foo," called "foo"
foo = Foo()
# Make calls to the "__call__" method, via the object's name itself
foo() #prints 1
foo() #prints 2
foo() #prints 3
</code></pre>
<p>Note that <code>__call__</code> makes an instance of a class (object) callable by its own name. That's why calling <code>foo()</code> above calls the class' <code>__call__</code> method. <a href="https://docs.python.org/3/reference/datamodel.html" rel="nofollow">From the documentation</a>:</p>
<blockquote>
<p>Instances of arbitrary classes can be made callable by defining a <code>__call__()</code> method in their class.</p>
</blockquote>
| 16 | 2008-11-10T23:53:12Z | [
"python"
] |
What is the Python equivalent of static variables inside a function? | 279,561 | <p>What is the idiomatic Python equivalent of this C/C++ code?</p>
<pre><code>void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
</code></pre>
<p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
| 311 | 2008-11-10T23:33:36Z | 6,014,360 | <p>The <em>idiomatic</em> way is to use a <em>class</em>, which can have attributes. If you need instances to not be separate, use a singleton.</p>
<p>There are a number of ways you could fake or munge "static" variables into Python (one not mentioned so far is to have a mutable default argument), but this is not the <strong>Pythonic, idiomatic</strong> way to do it. Just use a class.</p>
<p>Or possibly a generator, if your usage pattern fits.</p>
| 0 | 2011-05-16T07:36:30Z | [
"python"
] |
What is the Python equivalent of static variables inside a function? | 279,561 | <p>What is the idiomatic Python equivalent of this C/C++ code?</p>
<pre><code>void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
</code></pre>
<p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
| 311 | 2008-11-10T23:33:36Z | 10,941,940 | <p>I personally prefer the following to decorators. To each their own.</p>
<pre><code>def staticize(name, factory):
"""Makes a pseudo-static variable in calling function.
If name `name` exists in calling function, return it.
Otherwise, saves return value of `factory()` in
name `name` of calling function and return it.
:param name: name to use to store static object
in calling function
:type name: String
:param factory: used to initialize name `name`
in calling function
:type factory: function
:rtype: `type(factory())`
>>> def steveholt(z):
... a = staticize('a', list)
... a.append(z)
>>> steveholt.a
Traceback (most recent call last):
...
AttributeError: 'function' object has no attribute 'a'
>>> steveholt(1)
>>> steveholt.a
[1]
>>> steveholt('a')
>>> steveholt.a
[1, 'a']
>>> steveholt.a = []
>>> steveholt.a
[]
>>> steveholt('zzz')
>>> steveholt.a
['zzz']
"""
from inspect import stack
# get scope enclosing calling function
calling_fn_scope = stack()[2][0]
# get calling function
calling_fn_name = stack()[1][3]
calling_fn = calling_fn_scope.f_locals[calling_fn_name]
if not hasattr(calling_fn, name):
setattr(calling_fn, name, factory())
return getattr(calling_fn, name)
</code></pre>
| 1 | 2012-06-08T01:15:58Z | [
"python"
] |
What is the Python equivalent of static variables inside a function? | 279,561 | <p>What is the idiomatic Python equivalent of this C/C++ code?</p>
<pre><code>void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
</code></pre>
<p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
| 311 | 2008-11-10T23:33:36Z | 12,270,415 | <p>Here is a fully encapsulated version that doesn't require an external initialization call:</p>
<pre><code>def mystaticfun():
if "counter" not in vars(mystaticfun): mystaticfun.counter=-1
mystaticfun.counter+=1
print (mystaticfun.counter)
</code></pre>
<p>In Python, object members are dynamically stored in a special <code>__dict__</code> member, and in Python, functions are objects. The built-in <code>vars()</code> returns this <code>__dict__</code>. </p>
<p>EDIT: Note, unlike the alternative <code>try:except AttributeError</code> answer, with this approach the variable will always be ready for the code logic following initialization. I think the <code>try:except AttributeError</code> alternative to the following will be less DRY and/or have awkward flow: </p>
<pre><code>def Fibonacci(n):
if n<2: return n
if 'memo' not in vars(Fibonacci): Fibonacci.memo={}
return Fibonacci.memo.setdefault(n,Fibonacci(n-1)+Fibonacci(n-2))
</code></pre>
| 19 | 2012-09-04T19:51:35Z | [
"python"
] |
What is the Python equivalent of static variables inside a function? | 279,561 | <p>What is the idiomatic Python equivalent of this C/C++ code?</p>
<pre><code>void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
</code></pre>
<p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
| 311 | 2008-11-10T23:33:36Z | 16,214,510 | <p>One could also consider:</p>
<pre><code>def foo():
try:
foo.counter += 1
except AttributeError:
foo.counter = 1
</code></pre>
<p>Reasoning:</p>
<ul>
<li>much pythonic (<code>ask for forgiveness not permission</code>)</li>
<li>use exception (thrown only once) instead of <code>if</code> branch (think <a href="https://docs.python.org/2/library/exceptions.html#exceptions.StopIteration">StopIteration</a> exception)</li>
</ul>
| 86 | 2013-04-25T12:16:31Z | [
"python"
] |
What is the Python equivalent of static variables inside a function? | 279,561 | <p>What is the idiomatic Python equivalent of this C/C++ code?</p>
<pre><code>void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
</code></pre>
<p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
| 311 | 2008-11-10T23:33:36Z | 19,125,990 | <p>Prompted by <a href="http://stackoverflow.com/questions/19125515/function-instance-variables-inside-a-class/19125964">this question</a>, may I present another alternative which might be a bit nicer to use and will look the same for both methods and functions:</p>
<pre><code>@static_var2('seed',0)
def funccounter(statics, add=1):
statics.seed += add
return statics.seed
print funccounter() #1
print funccounter(add=2) #3
print funccounter() #4
class ACircle(object):
@static_var2('seed',0)
def counter(statics, self, add=1):
statics.seed += add
return statics.seed
c = ACircle()
print c.counter() #1
print c.counter(add=2) #3
print c.counter() #4
d = ACircle()
print d.counter() #5
print d.counter(add=2) #7
print d.counter() #8Â Â Â
</code></pre>
<p>If you like the usage, here's the implementation:</p>
<pre><code>class StaticMan(object):
def __init__(self):
self.__dict__['_d'] = {}
def __getattr__(self, name):
return self.__dict__['_d'][name]
def __getitem__(self, name):
return self.__dict__['_d'][name]
def __setattr__(self, name, val):
self.__dict__['_d'][name] = val
def __setitem__(self, name, val):
self.__dict__['_d'][name] = val
def static_var2(name, val):
def decorator(original):
if not hasattr(original, ':staticman'):
def wrapped(*args, **kwargs):
return original(getattr(wrapped, ':staticman'), *args, **kwargs)
setattr(wrapped, ':staticman', StaticMan())
f = wrapped
else:
f = original #already wrapped
getattr(f, ':staticman')[name] = val
return f
return decorator
</code></pre>
| 2 | 2013-10-01T21:09:43Z | [
"python"
] |
What is the Python equivalent of static variables inside a function? | 279,561 | <p>What is the idiomatic Python equivalent of this C/C++ code?</p>
<pre><code>void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
</code></pre>
<p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
| 311 | 2008-11-10T23:33:36Z | 27,783,657 | <p>Many people have already suggested testing 'hasattr', but there's a simpler answer:</p>
<pre><code>def func():
func.counter = getattr(func, 'counter', 0) + 1
</code></pre>
<p>No try/except, no testing hasattr, just getattr with a default.</p>
| 15 | 2015-01-05T16:24:14Z | [
"python"
] |
What is the Python equivalent of static variables inside a function? | 279,561 | <p>What is the idiomatic Python equivalent of this C/C++ code?</p>
<pre><code>void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
</code></pre>
<p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
| 311 | 2008-11-10T23:33:36Z | 27,914,651 | <p>A static variable inside a Python method</p>
<pre><code>class Count:
def foo(self):
try:
self.foo.__func__.counter += 1
except AttributeError:
self.foo.__func__.counter = 1
print self.foo.__func__.counter
m = Count()
m.foo() # 1
m.foo() # 2
m.foo() # 3
</code></pre>
| 0 | 2015-01-13T03:58:38Z | [
"python"
] |
What is the Python equivalent of static variables inside a function? | 279,561 | <p>What is the idiomatic Python equivalent of this C/C++ code?</p>
<pre><code>void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
</code></pre>
<p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
| 311 | 2008-11-10T23:33:36Z | 28,401,932 | <pre><code>def staticvariables(**variables):
def decorate(function):
for variable in variables:
setattr(function, variable, variables[variable])
return function
return decorate
@staticvariables(counter=0, bar=1)
def foo():
print(foo.counter)
print(foo.bar)
</code></pre>
<p>Much like vicent's code above, this would be used as a function decorator and static variables must be accessed with the function name as a prefix. The advantage of this code (although admittedly anyone might be smart enough to figure it out) is that you can have multiple static variables and initialize them in a more conventional manner.</p>
| 5 | 2015-02-09T02:27:39Z | [
"python"
] |
What is the Python equivalent of static variables inside a function? | 279,561 | <p>What is the idiomatic Python equivalent of this C/C++ code?</p>
<pre><code>void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
</code></pre>
<p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
| 311 | 2008-11-10T23:33:36Z | 31,784,304 | <p>Using an attribute of a function as static variable has some potential drawbacks:</p>
<ul>
<li>Every time you want to access the variable, you have to write out the full name of the function. </li>
<li>Outside code can access the variable easily and mess with the value.</li>
</ul>
<p>Idiomatic python for the second issue would probably be naming the variable with a leading underscore to signal that it is not meant to be accessed, while keeping it accessible after the fact. </p>
<p>An alternative would be a pattern using lexical closures, which are supported with the <code>nonlocal</code> keyword in python 3.</p>
<pre><code>def make_counter():
i = 0
def counter():
nonlocal i
i = i + 1
return i
return counter
counter = make_counter()
</code></pre>
<p>Sadly I know no way to encapsulate this solution into a decorator.</p>
| 4 | 2015-08-03T09:50:37Z | [
"python"
] |
What is the Python equivalent of static variables inside a function? | 279,561 | <p>What is the idiomatic Python equivalent of this C/C++ code?</p>
<pre><code>void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
</code></pre>
<p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
| 311 | 2008-11-10T23:33:36Z | 34,023,168 | <p>Another (not recommended!) twist on the callable object like <a href="http://stackoverflow.com/a/279598/916373">http://stackoverflow.com/a/279598/916373</a>, if you don't mind using a funky call signature, would be to do</p>
<pre><code>class foo(object):
counter = 0;
@staticmethod
def __call__():
foo.counter += 1
print "counter is %i" % foo.counter
</code></pre>
<hr>
<pre><code>>>> foo()()
counter is 1
>>> foo()()
counter is 2
</code></pre>
| 1 | 2015-12-01T14:47:24Z | [
"python"
] |
What is the Python equivalent of static variables inside a function? | 279,561 | <p>What is the idiomatic Python equivalent of this C/C++ code?</p>
<pre><code>void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
</code></pre>
<p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
| 311 | 2008-11-10T23:33:36Z | 35,020,271 | <p>Sure this is an old question but I think I might provide some update.</p>
<p>It seems that the performance argument is obsolete.
The same test suite appears to give similar results for siInt_try and isInt_re2.
Of course results vary, but this is one session on my computer with python 3.4.4 on kernel 4.3.01 with Xeon W3550.
I have run it several times and the results seem to be similar.
I moved the global regex into function static, but the performance difference is negligible. </p>
<pre><code>isInt_try: 0.3690
isInt_str: 0.3981
isInt_re: 0.5870
isInt_re2: 0.3632
</code></pre>
<p>With performance issue out of the way, it seems that try/catch would produce the most future- and cornercase- proof code so maybe just wrap it in function</p>
| 1 | 2016-01-26T17:40:11Z | [
"python"
] |
What is the Python equivalent of static variables inside a function? | 279,561 | <p>What is the idiomatic Python equivalent of this C/C++ code?</p>
<pre><code>void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
</code></pre>
<p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
| 311 | 2008-11-10T23:33:36Z | 38,712,809 | <p>A little bit more readable, but more verbose:</p>
<pre><code>>>> def func(_static={'counter': 0}):
... _static['counter'] += 1
... print _static['counter']
...
>>> func()
1
>>> func()
2
>>>
</code></pre>
| 1 | 2016-08-02T06:02:26Z | [
"python"
] |
How can one get the set of all classes with reverse relationships for a model in Django? | 279,782 | <p>Given:</p>
<pre><code>from django.db import models
class Food(models.Model):
"""Food, by name."""
name = models.CharField(max_length=25)
class Cat(models.Model):
"""A cat eats one type of food"""
food = models.ForeignKey(Food)
class Cow(models.Model):
"""A cow eats one type of food"""
food = models.ForeignKey(Food)
class Human(models.Model):
"""A human may eat lots of types of food"""
food = models.ManyToManyField(Food)
</code></pre>
<p>How can one, given only the class Food, get a set of all classes that it has "reverse relationships" to. I.e. given the class <strong>Food</strong>, how can one get the classes <strong>Cat</strong>, <strong>Cow</strong> and <strong>Human</strong>.</p>
<p>I would think it's possible because Food has the three "reverse relations": <em>Food.cat_set</em>, <em>Food.cow_set</em>, and <em>Food.human_set</em>.</p>
<p>Help's appreciated & thank you!</p>
| 4 | 2008-11-11T01:42:39Z | 279,809 | <p>Some digging in the source code revealed:</p>
<p>django/db/models/options.py:</p>
<pre><code>def get_all_related_objects(self, local_only=False):
def get_all_related_many_to_many_objects(self, local_only=False)
</code></pre>
<p>And, using these functions on the models from above, you hypothetically get:</p>
<pre><code>>>> Food._meta.get_all_related_objects()
[<RelatedObject: app_label:cow related to food>,
<RelatedObject: app_label:cat related to food>,]
>>> Food._meta.get_all_related_many_to_many_objects()
[<RelatedObject: app_label:human related to food>,]
# and, per django/db/models/related.py
# you can retrieve the model with
>>> Food._meta.get_all_related_objects()[0].model
<class 'app_label.models.Cow'>
</code></pre>
<p><em>Note</em>: I hear Model._meta is 'unstable', and perhaps ought not to be relied upon in the post Django-1.0 world.</p>
<p>Thanks for reading. :)</p>
| 14 | 2008-11-11T02:00:20Z | [
"python",
"django",
"django-models",
"django-orm"
] |
How can one get the set of all classes with reverse relationships for a model in Django? | 279,782 | <p>Given:</p>
<pre><code>from django.db import models
class Food(models.Model):
"""Food, by name."""
name = models.CharField(max_length=25)
class Cat(models.Model):
"""A cat eats one type of food"""
food = models.ForeignKey(Food)
class Cow(models.Model):
"""A cow eats one type of food"""
food = models.ForeignKey(Food)
class Human(models.Model):
"""A human may eat lots of types of food"""
food = models.ManyToManyField(Food)
</code></pre>
<p>How can one, given only the class Food, get a set of all classes that it has "reverse relationships" to. I.e. given the class <strong>Food</strong>, how can one get the classes <strong>Cat</strong>, <strong>Cow</strong> and <strong>Human</strong>.</p>
<p>I would think it's possible because Food has the three "reverse relations": <em>Food.cat_set</em>, <em>Food.cow_set</em>, and <em>Food.human_set</em>.</p>
<p>Help's appreciated & thank you!</p>
| 4 | 2008-11-11T01:42:39Z | 279,952 | <p>Either </p>
<p>A) Use <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance" rel="nofollow">multiple table inheritance</a> and create a "Eater" base class, that Cat, Cow and Human inherit from.</p>
<p>B) Use a <a href="http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1" rel="nofollow">Generic Relation</a>, where Food could be linked to any other Model.</p>
<p>Those are well-documented and officially supported features, you'd better stick to them to keep your own code clean, avoid workarounds and be sure it'll be still supported in the future.</p>
<p>-- EDIT ( A.k.a. "how to be a reputation whore" )</p>
<p>So, here is a recipe for that particular case.</p>
<p>Let's assume you absolutely want separate models for Cat, Cow and Human. In a real-world application, you want to ask to yourself why a "category" field wouldn't do the job.</p>
<p>It's easier to get to the "real" class through generic relations, so here is the implementation for B. We can't have that 'food' field in Person, Cat or Cow, or we'll run into the same problems. So we'll create an intermediary "FoodConsumer" model. We'll have to write additional validation tests if we don't want more than one food for an instance.</p>
<pre><code>from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class Food(models.Model):
"""Food, by name."""
name = models.CharField(max_length=25)
# ConsumedFood has a foreign key to Food, and a "eaten_by" generic relation
class ConsumedFood(models.Model):
food = models.ForeignKey(Food, related_name="eaters")
content_type = models.ForeignKey(ContentType, null=True)
object_id = models.PositiveIntegerField(null=True)
eaten_by = generic.GenericForeignKey('content_type', 'object_id')
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
birth_date = models.DateField()
address = models.CharField(max_length=100)
city = models.CharField(max_length=50)
foods = generic.GenericRelation(ConsumedFood)
class Cat(models.Model):
name = models.CharField(max_length=50)
foods = generic.GenericRelation(ConsumedFood)
class Cow(models.Model):
farmer = models.ForeignKey(Person)
foods = generic.GenericRelation(ConsumedFood)
</code></pre>
<p>Now, to demonstrate it let's just write this working <a href="http://docs.djangoproject.com/en/dev/topics/testing/#writing-doctests" rel="nofollow">doctest</a>:</p>
<pre><code>"""
>>> from models import *
Create some food records
>>> weed = Food(name="weed")
>>> weed.save()
>>> burger = Food(name="burger")
>>> burger.save()
>>> pet_food = Food(name="Pet food")
>>> pet_food.save()
John the farmer likes burgers
>>> john = Person(first_name="John", last_name="Farmer", birth_date="1960-10-12")
>>> john.save()
>>> john.foods.create(food=burger)
<ConsumedFood: ConsumedFood object>
Wilma the cow eats weed
>>> wilma = Cow(farmer=john)
>>> wilma.save()
>>> wilma.foods.create(food=weed)
<ConsumedFood: ConsumedFood object>
Felix the cat likes pet food
>>> felix = Cat(name="felix")
>>> felix.save()
>>> pet_food.eaters.create(eaten_by=felix)
<ConsumedFood: ConsumedFood object>
What food john likes again ?
>>> john.foods.all()[0].food.name
u'burger'
Who's getting pet food ?
>>> living_thing = pet_food.eaters.all()[0].eaten_by
>>> isinstance(living_thing,Cow)
False
>>> isinstance(living_thing,Cat)
True
John's farm is in fire ! He looses his cow.
>>> wilma.delete()
John is a lot poorer right now
>>> john.foods.clear()
>>> john.foods.create(food=pet_food)
<ConsumedFood: ConsumedFood object>
Who's eating pet food now ?
>>> for consumed_food in pet_food.eaters.all():
... consumed_food.eaten_by
<Cat: Cat object>
<Person: Person object>
Get the second pet food eater
>>> living_thing = pet_food.eaters.all()[1].eaten_by
Try to find if it's a person and reveal his name
>>> if isinstance(living_thing,Person): living_thing.first_name
u'John'
"""
</code></pre>
| 7 | 2008-11-11T03:48:52Z | [
"python",
"django",
"django-models",
"django-orm"
] |
PyOpenGl or pyglet? | 279,912 | <p>I am looking to do some tinkering with openGL and Python and haven't been able to find good reasons for using PyOpenGl versus pyglet</p>
<p>Which would you recommend and why?</p>
| 24 | 2008-11-11T03:17:03Z | 279,942 | <p>pyglet has a lot of nice extras included with it (like image loading and sound). If you're starting out, I'd try pyglet first, and then switch to PyOpenGL if you feel like you want to get closer to the metal.</p>
<p>The real important question though is: what are you trying to accomplish? </p>
| 3 | 2008-11-11T03:38:00Z | [
"python",
"pyglet",
"pyopengl"
] |
PyOpenGl or pyglet? | 279,912 | <p>I am looking to do some tinkering with openGL and Python and haven't been able to find good reasons for using PyOpenGl versus pyglet</p>
<p>Which would you recommend and why?</p>
| 24 | 2008-11-11T03:17:03Z | 279,970 | <p>As Tony said, this is really going to depend on your goals. If you're "tinkering" to try to learn about OpenGL or 3D rendering in general that I would dispense with all pleasantries and start working with PyOpenGL, which is as close are you're going to get to "raw" 3D programming using Python.</p>
<p>On the other hand, if you're "tinkering" by way of mocking up a game or multimedia application, or trying to learn about programming practices in general than Pyglet will save you lots of up-front development time by providing hooks for input events, sounds, text/billboarding, etc. Often, this up-front investment is what prevents people from completing their projects, so having it done for you is not something to be ignored. (It is also very Pythonic to avoid reinventing the wheel.)</p>
<p>If you are looking to do any sort of heavy-duty lifting (which normally falls outside my definition of "tinkering", but maybe not if you're tinkering with 3D engine design) then you might want to take a look at <a href="http://www.python-ogre.org/">Python-Ogre</a>, which wraps the <em>very</em> full-featured and robust <a href="http://www.ogre3d.org/">OGRE 3D</a> graphics engine.</p>
| 26 | 2008-11-11T04:03:04Z | [
"python",
"pyglet",
"pyopengl"
] |
PyOpenGl or pyglet? | 279,912 | <p>I am looking to do some tinkering with openGL and Python and haven't been able to find good reasons for using PyOpenGl versus pyglet</p>
<p>Which would you recommend and why?</p>
| 24 | 2008-11-11T03:17:03Z | 281,395 | <p>I promote pyglet because it has the nicest API I've yet seen on stuff like this.</p>
<p>Pyglet has opengl API as well. But it's often nicer to use the recently added vertex list support.</p>
<p>pyglet.gl</p>
| 3 | 2008-11-11T16:30:11Z | [
"python",
"pyglet",
"pyopengl"
] |
PyOpenGl or pyglet? | 279,912 | <p>I am looking to do some tinkering with openGL and Python and haven't been able to find good reasons for using PyOpenGl versus pyglet</p>
<p>Which would you recommend and why?</p>
| 24 | 2008-11-11T03:17:03Z | 397,041 | <p>I would recommend Pyglet because it is very easy to get started and have something basic running, and then you can add more advanced techniques at your own pace.</p>
| 2 | 2008-12-29T02:52:47Z | [
"python",
"pyglet",
"pyopengl"
] |
PyOpenGl or pyglet? | 279,912 | <p>I am looking to do some tinkering with openGL and Python and haven't been able to find good reasons for using PyOpenGl versus pyglet</p>
<p>Which would you recommend and why?</p>
| 24 | 2008-11-11T03:17:03Z | 408,981 | <p>I'd say that Pyglet is actually more evolved than PyOpenGL. It has a nice API of it's own, and it has a full wrapper around OpenGL accessed through the pyglet.gl module! PyOpenGL doesn't even wrap all the functions OpenGL has.
Pyglet also has a great library for rendering 2D with hardware acceleration through OpenGL, and it's really well made.</p>
<p>If you want a powerful ready made 3D engine you've got <a href="http://www.ogre3d.org/" rel="nofollow">Ogre</a> and such</p>
| 4 | 2009-01-03T12:25:09Z | [
"python",
"pyglet",
"pyopengl"
] |
PyOpenGl or pyglet? | 279,912 | <p>I am looking to do some tinkering with openGL and Python and haven't been able to find good reasons for using PyOpenGl versus pyglet</p>
<p>Which would you recommend and why?</p>
| 24 | 2008-11-11T03:17:03Z | 2,396,038 | <p>pyglet's GL API is nowhere near as nice as PyOpenGL's - pyglet's is at the raw ctypes layer which means you'll need to learn ctypes as well. If you're planning on doing a bunch of OpenGL programming you'll want to use PyOpenGL. </p>
<p>The nice thing is you can mix the two just fine. Use pyglet to provide the GL context, sounds, events, image loading and texture management, text rendering, etc, etc. Use PyOpenGL for the actual OpenGL programming you need to do.</p>
| 2 | 2010-03-07T11:17:49Z | [
"python",
"pyglet",
"pyopengl"
] |
PyOpenGl or pyglet? | 279,912 | <p>I am looking to do some tinkering with openGL and Python and haven't been able to find good reasons for using PyOpenGl versus pyglet</p>
<p>Which would you recommend and why?</p>
| 24 | 2008-11-11T03:17:03Z | 4,246,325 | <p>Start with pyglet. It contains the best high-level API, which contains all you need to get started, from opening a window to drawing sprites and OpenGL primitives using their friendly and powerful Sprite and Batch classes.</p>
<p>Later, you might also want to write your own lower-level code, that makes calls directly to OpenGL functions such as glDrawArrays, etc. You can do this using pyglet's OpenGL bindings, or using PyOpenGL's. The good news is that whichever you use, you can insert such calls right into the middle of your existing pyglet application, and they will 'just work'. Transitioning your code from Pyglet to PyOpenGL is fairly easy, so this is not a decision you need to worry about too much upfront. The trades-off between the two are:</p>
<p>PyOpenGL's bindings make the OpenGL interface more friendly and pythonic. For example, you can pass vertex arrays in many different forms, ctypes arrays, numpy arrays, plain lists, etc, and PyOpenGL will convert them into something OpenGL can use. Things like this make PyOpenGL really easy and convenient.</p>
<p>pyglet's OpenGL bindings are automatically generated, and are not as friendly to use as PyOpenGL. For example, sometimes you will have to manually create ctypes objects, in order to pass 'C pointer' kinds of args to OpenGL. This can be fiddly. The plus side though, is pyglet's bindings tends to be significantly faster.</p>
<p>This implies that there is an optimal middle ground: Use pyglet for windowing, mouse events, sound, etc. Then use PyOpenGL's friendly API when you want to make direct OpenGL function calls. Then when optimising, replace just the small percentage of performance-critical PyOpenGL calls that lie within your inner render loop with the pyglet equivalents. For me, this gives me between 2 and 4 times faster framerates, with PyOpenGL's convenience for 90% of my code.</p>
| 22 | 2010-11-22T14:21:04Z | [
"python",
"pyglet",
"pyopengl"
] |
PyOpenGl or pyglet? | 279,912 | <p>I am looking to do some tinkering with openGL and Python and haven't been able to find good reasons for using PyOpenGl versus pyglet</p>
<p>Which would you recommend and why?</p>
| 24 | 2008-11-11T03:17:03Z | 13,781,633 | <p>Hmm, i would suggest pyglet, it really provides everything needed by a game or application. </p>
<p>Mind you, you can do a lot of things pyglet does with PyOpenGL, for example to create a window all you need to do is:<br>
glutInitWindow(title)</p>
<p>Although i think glutInitDisplayMode has to be called before that. </p>
<p>Simple summary: if you don't wanna code until you cry, choose pyglet, but if you want to be a master, choose PyOpenGL. Goto <a href="http://pyopengl.sourcefourge.net" rel="nofollow">http://pyopengl.sourcefourge.net</a> to read the docs on PyOpenGL and to <a href="http://pyglet.org" rel="nofollow">http://pyglet.org</a> to read the docs on pyglet. Hope this was helpful!</p>
| 3 | 2012-12-08T20:30:29Z | [
"python",
"pyglet",
"pyopengl"
] |
PyOpenGl or pyglet? | 279,912 | <p>I am looking to do some tinkering with openGL and Python and haven't been able to find good reasons for using PyOpenGl versus pyglet</p>
<p>Which would you recommend and why?</p>
| 24 | 2008-11-11T03:17:03Z | 38,231,267 | <p>Try <a href="https://github.com/cprogrammer1994/ModernGL" rel="nofollow">ModernGL</a></p>
<p>pip install ModernGL</p>
<p>(currently windows only)</p>
<p>In case you are using windows, you should try this module.
I had problems using PyOpenGL, PyGame and PyGlet. These modules are mature but takes a lot of time to make something small. However using ModernGL could speedup the programming part. ModernGL is less error prone.
ModernGL is currently BETA (may have bugs).</p>
<p>PyOpenGL is an auto-generated version of the original OpenGL API (generated with SWIG).
The original OpenGL API is not python friendly.</p>
| 0 | 2016-07-06T18:31:05Z | [
"python",
"pyglet",
"pyopengl"
] |
Set permissions on a compressed file in python | 279,945 | <p>I have a file <code>test.txt</code> that is inside a zip archive <code>test.zip</code>. The permissions on <code>test.txt</code> are out of my control when it's compressed, but now I want them to be group-writeable. I am extracting the file with Python, and don't want to escape out to the shell.</p>
<p><strong>EDIT:</strong>
Here's what I've got so far:</p>
<pre><code>import zipfile
z = zipfile.ZipFile('test.zip', 'w')
zi = zipfile.ZipInfo('test.txt')
zi.external_attr = 0777 << 16L
z.writestr(zi, 'FOO')
z.close()
z = zipfile.ZipFile('test.zip', 'r')
for name in z.namelist():
newFile = open(name, "wb")
newFile.write(z.read(name))
newFile.close()
z.close()
</code></pre>
<p>This works perfectly on OS X using 2.5.1, but it doesn't work on my home box (Debian, Python 2.4 & 2.5) or on RHEL 5 with Python 2.4. On anything but OS X it doesn't error, but doesn't change the permissions either. Any ideas why? Also, how does <code>writestr()</code> work? I know I'm using it incorrectly here.</p>
<p>Is there a way to do this without <code>os.chmod</code> (the user extracting the file doesn't have permissions to use <code>os.chmod</code> after it's extracted)? I have full write access to the zip file.</p>
<p>More info:</p>
<pre><code>> ls -l test.zip
-rwxrwxrwx 1 myuser mygroup 2008-11-11 13:24 test.zip
> unzip test.zip
Archive: test.zip
inflating: test.txt
> ls -l test.txt
-rw-r--r-- 1 myuser mygroup 2008-11-11 13:34 test.txt
</code></pre>
<p>The user extracting is not <code>myuser</code>, but is in <code>mygroup</code>.</p>
| 6 | 2008-11-11T03:40:17Z | 279,975 | <p>Per the documentation, unzip sets the permissions to those stored, under unix. Also, the shell umask is not used. Your best bet is to make sure the perms are set before you zip the file.</p>
<p>Since you can't do that, you will have to try and do what you were trying to do (and get it to work under Debian.)</p>
<p>There have been a number of issues with Pythons zipfile library, including setting the mode of writestr to that of the file being written on some systems, or setting the zip systm to windows instead of unix. So your inconsistent results may mean that nothing has changed.</p>
<p>So you may be completely out of luck.</p>
| 1 | 2008-11-11T04:10:07Z | [
"python",
"zip",
"zipfile"
] |
Set permissions on a compressed file in python | 279,945 | <p>I have a file <code>test.txt</code> that is inside a zip archive <code>test.zip</code>. The permissions on <code>test.txt</code> are out of my control when it's compressed, but now I want them to be group-writeable. I am extracting the file with Python, and don't want to escape out to the shell.</p>
<p><strong>EDIT:</strong>
Here's what I've got so far:</p>
<pre><code>import zipfile
z = zipfile.ZipFile('test.zip', 'w')
zi = zipfile.ZipInfo('test.txt')
zi.external_attr = 0777 << 16L
z.writestr(zi, 'FOO')
z.close()
z = zipfile.ZipFile('test.zip', 'r')
for name in z.namelist():
newFile = open(name, "wb")
newFile.write(z.read(name))
newFile.close()
z.close()
</code></pre>
<p>This works perfectly on OS X using 2.5.1, but it doesn't work on my home box (Debian, Python 2.4 & 2.5) or on RHEL 5 with Python 2.4. On anything but OS X it doesn't error, but doesn't change the permissions either. Any ideas why? Also, how does <code>writestr()</code> work? I know I'm using it incorrectly here.</p>
<p>Is there a way to do this without <code>os.chmod</code> (the user extracting the file doesn't have permissions to use <code>os.chmod</code> after it's extracted)? I have full write access to the zip file.</p>
<p>More info:</p>
<pre><code>> ls -l test.zip
-rwxrwxrwx 1 myuser mygroup 2008-11-11 13:24 test.zip
> unzip test.zip
Archive: test.zip
inflating: test.txt
> ls -l test.txt
-rw-r--r-- 1 myuser mygroup 2008-11-11 13:34 test.txt
</code></pre>
<p>The user extracting is not <code>myuser</code>, but is in <code>mygroup</code>.</p>
| 6 | 2008-11-11T03:40:17Z | 279,985 | <p>Extract to stdout (unzip -p) and redirect to a file? If there's more than one file in the zip, you could list the zip contents, and then extract one at a time.</p>
<pre><code>for n in `unzip -l test.zip | awk 'NR > 3 && NF == 4 { print $4 }'`; do unzip -p test.zip $n > $n; done
</code></pre>
<p>(yeah, I know you tagged this 'python' :-) )</p>
| 0 | 2008-11-11T04:16:56Z | [
"python",
"zip",
"zipfile"
] |
Set permissions on a compressed file in python | 279,945 | <p>I have a file <code>test.txt</code> that is inside a zip archive <code>test.zip</code>. The permissions on <code>test.txt</code> are out of my control when it's compressed, but now I want them to be group-writeable. I am extracting the file with Python, and don't want to escape out to the shell.</p>
<p><strong>EDIT:</strong>
Here's what I've got so far:</p>
<pre><code>import zipfile
z = zipfile.ZipFile('test.zip', 'w')
zi = zipfile.ZipInfo('test.txt')
zi.external_attr = 0777 << 16L
z.writestr(zi, 'FOO')
z.close()
z = zipfile.ZipFile('test.zip', 'r')
for name in z.namelist():
newFile = open(name, "wb")
newFile.write(z.read(name))
newFile.close()
z.close()
</code></pre>
<p>This works perfectly on OS X using 2.5.1, but it doesn't work on my home box (Debian, Python 2.4 & 2.5) or on RHEL 5 with Python 2.4. On anything but OS X it doesn't error, but doesn't change the permissions either. Any ideas why? Also, how does <code>writestr()</code> work? I know I'm using it incorrectly here.</p>
<p>Is there a way to do this without <code>os.chmod</code> (the user extracting the file doesn't have permissions to use <code>os.chmod</code> after it's extracted)? I have full write access to the zip file.</p>
<p>More info:</p>
<pre><code>> ls -l test.zip
-rwxrwxrwx 1 myuser mygroup 2008-11-11 13:24 test.zip
> unzip test.zip
Archive: test.zip
inflating: test.txt
> ls -l test.txt
-rw-r--r-- 1 myuser mygroup 2008-11-11 13:34 test.txt
</code></pre>
<p>The user extracting is not <code>myuser</code>, but is in <code>mygroup</code>.</p>
| 6 | 2008-11-11T03:40:17Z | 596,455 | <p>I had a similar problem to you, so here is the code spinet from my stuff, this I believe should help here.</p>
<pre><code># extract all of the zip
for file in zf.filelist:
name = file.filename
perm = ((file.external_attr >> 16L) & 0777)
if name.endswith('/'):
outfile = os.path.join(dir, name)
os.mkdir(outfile, perm)
else:
outfile = os.path.join(dir, name)
fh = os.open(outfile, os.O_CREAT | os.O_WRONLY , perm)
os.write(fh, zf.read(name))
os.close(fh)
print "Extracting: " + outfile
</code></pre>
<p>You might do something similar, but insert your own logic to calculate your perm value. I should note that I'm using Python 2.5 here, I'm aware of a few incompatibilities with some versions of Python's zipfile support.</p>
| 3 | 2009-02-27T20:12:53Z | [
"python",
"zip",
"zipfile"
] |
email body from a parsed email object in jython | 280,207 | <p>I have an object.</p>
<pre><code> fp = open(self.currentEmailPath, "rb")
p = email.Parser.Parser()
self._currentEmailParsedInstance= p.parse(fp)
fp.close()
</code></pre>
<p>self.currentEmailParsedInstance, from this object I want to get the body of an email, text only no HTML....</p>
<p>How do I do it?</p>
<hr>
<p>something like this? </p>
<pre><code> newmsg=self._currentEmailParsedInstance.get_payload()
body=newmsg[0].get_content....?
</code></pre>
<p>then strip the html from body.
just what is that .... method to return the actual text... maybe I mis-understand you</p>
<pre><code> msg=self._currentEmailParsedInstance.get_payload()
print type(msg)
</code></pre>
<p>output = type 'list'</p>
<hr>
<p>the email </p>
<p>Return-Path: <br>
Received: from xx.xx.net (example) by mxx3.xx.net (xxx)<br>
id 485EF65F08EDX5E12 for [email protected]; Thu, 23 Oct 2008 06:07:51 +0200<br>
Received: from xxxxx2 (ccc) by example.net (ccc) (authenticated as [email protected])
id 48798D4001146189 for [email protected]; Thu, 23 Oct 2008 06:07:51 +0200<br>
From: "example" <br>
To: <br>
Subject: FW: example
Date: Thu, 23 Oct 2008 12:07:45 +0800<br>
Organization: example
Message-ID: <001601c934c4$xxxx30$a9ff460a@xxx><br>
MIME-Version: 1.0<br>
Content-Type: multipart/mixed;<br>
boundary="----=_NextPart_000_0017_01C93507.F6F64E30"<br>
X-Mailer: Microsoft Office Outlook 11<br>
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.3138<br>
Thread-Index: Ack0wLaumqgZo1oXSBuIpUCEg/wfOAABAFEA </p>
<p>This is a multi-part message in MIME format. </p>
<p>------=_NextPart_000_0017_01C93507.F6F64E30<br>
Content-Type: multipart/alternative;<br>
boundary="----=_NextPart_001_0018_01C93507.F6F64E30" </p>
<p>------=_NextPart_001_0018_01C93507.F6F64E30<br>
Content-Type: text/plain;<br>
charset="us-ascii"<br>
Content-Transfer-Encoding: 7bit </p>
<p>From: example.example[mailto:[email protected]]<br>
Sent: Thursday, October 23, 2008 11:37 AM<br>
To: [email protected]<br>
Subject: S/I for example(B/L<br>
No.:4357-0120-810.044) </p>
<p>Please find attached the example.doc), </p>
<p>Thanks. </p>
<p>B.rgds, </p>
<p>xxx xxx </p>
<p>------=_NextPart_001_0018_01C93507.F6F64E30<br>
Content-Type: text/html;<br>
charset="us-ascii"<br>
Content-Transfer-Encoding: quoted-printable </p>
<p>
xmlns:o=3D"urn:schemas-microsoft-com:office:office" =<br>
xmlns:w=3D"urn:schemas-microsoft-com:office:word" =<br>
xmlns:st1=3D"urn:schemas-microsoft-com:office:smarttags" =<br>
xmlns=3D"<a href="http://www.w3.org/TR/REC-html40" rel="nofollow">http://www.w3.org/TR/REC-html40</a>"> </p>
<p>HTML STUFF till </p>
<p>------=_NextPart_001_0018_01C93507.F6F64E30-- </p>
<p>------=_NextPart_000_0017_01C93507.F6F64E30<br>
Content-Type: application/msword;<br>
name="xxxx.doc"<br>
Content-Transfer-Encoding: base64<br>
Content-Disposition: attachment;<br>
filename="xxxx.doc" </p>
<p>0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAAAAABAAAAYAAAAAAAAAAA
EAAAYgAAAAEAAAD+////AAAAAF8AAAD/////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////s
pcEAI2AJBAAA+FK/AAAAAAAAEAAAAAAABgAAnEIAAA4AYmpiaqEVoRUAAAAAAAAAAAAAAAAAAAAA
AAAECBYAMlAAAMN/AADDfwAAQQ4AAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAA
AAAAAAD//w8AAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAKQAAAAAAEYEAAAAAAAARgQAAEYE
AAAAAAAARgQAAAAAAABGBAAAAAAAAEYEAAAAAAAARgQAABQAAAAAAAAAAAAAAFoEAAAAAAAA4hsA
AAAAAADiGwAAAAAAAOIbAAA4AAAAGhwAAHwAAACWHAAARAAAAFoEAAAAAAAABzcAAEgBAADmHAAA
FgAAAPwcAAAAAAAA/BwAAAAAAAD8HAAAAAAAAPwcAAAAAAAA/BwAAAAAAAD8HAAAAAAAAPwcAAAA
AAAAMjYAAAIAAAA0NgAAAAAAADQ2AAAAAAAANDYAAAAAAAA0NgAAAAAAADQ2AAAAAAAANDYAACQA
AABPOAAAaAIAALc6AACOAAAAWDYAAGkAAAAAAAAAAAAAAAAAAAAAAAAARgQAAAAAAABHLAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAD8HAAAAAAAAPwcAAAAAAAARywAAAAAAABHLAAAAAAAAFg2AAAAAAAA</p>
<p>------=_NextPart_000_0017_01C93507.F6F64E30-- </p>
<hr>
<p>I just want to get : </p>
<p>From: xxxx.xxxx [mailto:[email protected]]<br>
Sent: Thursday, October 23, 2008 11:37 AM<br>
To: [email protected]<br>
Subject: S/I for xxxxx (B/L<br>
No.:4357-0120-810.044) </p>
<p>Pls find attached the xxxx.doc), </p>
<p>Thanks. </p>
<p>B.rgds, </p>
<p>xxx xxx </p>
<hr>
<p>not sure if the mail is malformed!
seems if you get an html page you have to do this:</p>
<pre><code> parts=self._currentEmailParsedInstance.get_payload()
print parts[0].get_content_type()
..._multipart/alternative_
textParts=parts[0].get_payload()
print textParts[0].get_content_type()
..._text/plain_
body=textParts[0].get_payload()
print body
...get the text without a problem!!
</code></pre>
<p>thank you so much Vinko.</p>
<p>So its kinda like dealing with xml, recursive in nature.</p>
| 4 | 2008-11-11T07:07:09Z | 280,238 | <p>This will get you the contents of the message</p>
<pre><code>self.currentEmailParsedInstance.get_payload()
</code></pre>
<p>As for the text only part you will have to strip HTML on your own, for example using BeautifulSoup.</p>
<p>Check <a href="http://www.python.org/doc/2.2.3/lib/module-email.Message.html" rel="nofollow">this link</a> for more information about the Message class the Parser returns. If you mean getting the text part of messages containing both HTML and plain text version of themselves, you can specify an index to get_payload() to get the part you want.</p>
<p>I tried with a different MIME email because what you pasted seems malformed, hopefully it got malformed when you edited it.</p>
<pre><code>>>> parser = email.parser.Parser()
>>> message = parser.parse(open('/home/vinko/jlm.txt','r'))
>>> message.is_multipart()
True
>>> parts = message.get_payload()
>>> len(parts)
2
>>> parts[0].get_content_type()
'text/plain'
>>> parts[1].get_content_type()
'message/rfc822'
>>> parts[0].get_payload()
'Message Text'
</code></pre>
<p>parts will contain all parts of the multipart message, you can check their content types as shown and get only the text/plain ones, for instance.</p>
<p>Good luck.</p>
| 4 | 2008-11-11T07:27:54Z | [
"python",
"email",
"jython",
"parsing"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.