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
list
Extending python - to swig, not to swig or Cython
456,884
<p>I found the bottleneck in my python code, played around with psycho etc. Then decided to write a c/c++ extension for performance.</p> <p>With the help of swig you almost don't need to care about arguments etc. Everything works fine.</p> <p>Now my question: swig creates a quite large py-file which does a lot of 'checkings' and 'PySwigObject' before calling the actual .pyd or .so code.</p> <p>Does anyone of you have any experience whether there is some more performance to gain if you hand-write this file or let swig do it. </p>
55
2009-01-19T08:32:06Z
457,099
<p>Using <a href="http://cython.org/">Cython</a> is pretty good. You can write your C extension with a Python-like syntax and have it generate C code. Boilerplate included. Since you have the code already in python, you have to do just a few changes to your bottleneck code and C code will be generated from it.</p> <p>Example. <code>hello.pyx</code>:</p> <pre><code>cdef int hello(int a, int b): return a + b </code></pre> <p>That generates <strong>601 lines</strong> of boilerplate code:</p> <pre><code>/* Generated by Cython 0.10.3 on Mon Jan 19 08:24:44 2009 */ #define PY_SSIZE_T_CLEAN #include "Python.h" #include "structmember.h" #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif #if PY_VERSION_HEX &lt; 0x02040000 #define METH_COEXIST 0 #endif #if PY_VERSION_HEX &lt; 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PyInt_FromSsize_t(z) PyInt_FromLong(z) #define PyInt_AsSsize_t(o) PyInt_AsLong(o) #define PyNumber_Index(o) PyNumber_Int(o) #define PyIndex_Check(o) PyNumber_Check(o) #endif #if PY_VERSION_HEX &lt; 0x02060000 #define Py_REFCNT(ob) (((PyObject*)(ob))-&gt;ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))-&gt;ob_type) #define Py_SIZE(ob) (((PyVarObject*)(ob))-&gt;ob_size) #define PyVarObject_HEAD_INIT(type, size) \ PyObject_HEAD_INIT(type) size, #define PyType_Modified(t) typedef struct { void *buf; PyObject *obj; Py_ssize_t len; Py_ssize_t itemsize; int readonly; int ndim; char *format; Py_ssize_t *shape; Py_ssize_t *strides; Py_ssize_t *suboffsets; void *internal; } Py_buffer; #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 #define PyBUF_LOCK 0x0002 #define PyBUF_FORMAT 0x0004 #define PyBUF_ND 0x0008 #define PyBUF_STRIDES (0x0010 | PyBUF_ND) #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) #endif #if PY_MAJOR_VERSION &lt; 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #endif #if PY_MAJOR_VERSION &gt;= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif #if (PY_VERSION_HEX &lt; 0x02060000) || (PY_MAJOR_VERSION &gt;= 3) #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #if PY_MAJOR_VERSION &gt;= 3 #define PyBaseString_Type PyUnicode_Type #define PyString_Type PyBytes_Type #define PyInt_Type PyLong_Type #define PyInt_Check(op) PyLong_Check(op) #define PyInt_CheckExact(op) PyLong_CheckExact(op) #define PyInt_FromString PyLong_FromString #define PyInt_FromUnicode PyLong_FromUnicode #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyInt_FromSsize_t PyLong_FromSsize_t #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #else #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) #define PyBytes_Type PyString_Type #endif #if PY_MAJOR_VERSION &gt;= 3 #define PyMethod_New(func, self, klass) PyInstanceMethod_New(func) #endif #if !defined(WIN32) &amp;&amp; !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall #endif #ifndef __cdecl #define __cdecl #endif #else #define _USE_MATH_DEFINES #endif #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #include &lt;math.h&gt; #define __PYX_HAVE_API__helloworld #ifdef __GNUC__ #define INLINE __inline__ #elif _WIN32 #define INLINE __inline #else #define INLINE #endif typedef struct {PyObject **p; char *s; long n; char is_unicode; char intern; char is_identifier;} __Pyx_StringTabEntry; /*proto*/ static int __pyx_skip_dispatch = 0; /* Type Conversion Predeclarations */ #if PY_MAJOR_VERSION &lt; 3 #define __Pyx_PyBytes_FromString PyString_FromString #define __Pyx_PyBytes_AsString PyString_AsString #else #define __Pyx_PyBytes_FromString PyBytes_FromString #define __Pyx_PyBytes_AsString PyBytes_AsString #endif #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static INLINE int __Pyx_PyObject_IsTrue(PyObject* x); static INLINE PY_LONG_LONG __pyx_PyInt_AsLongLong(PyObject* x); static INLINE unsigned PY_LONG_LONG __pyx_PyInt_AsUnsignedLongLong(PyObject* x); static INLINE Py_ssize_t __pyx_PyIndex_AsSsize_t(PyObject* b); #define __pyx_PyInt_AsLong(x) (PyInt_CheckExact(x) ? PyInt_AS_LONG(x) : PyInt_AsLong(x)) #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) static INLINE unsigned char __pyx_PyInt_unsigned_char(PyObject* x); static INLINE unsigned short __pyx_PyInt_unsigned_short(PyObject* x); static INLINE char __pyx_PyInt_char(PyObject* x); static INLINE short __pyx_PyInt_short(PyObject* x); static INLINE int __pyx_PyInt_int(PyObject* x); static INLINE long __pyx_PyInt_long(PyObject* x); static INLINE signed char __pyx_PyInt_signed_char(PyObject* x); static INLINE signed short __pyx_PyInt_signed_short(PyObject* x); static INLINE signed int __pyx_PyInt_signed_int(PyObject* x); static INLINE signed long __pyx_PyInt_signed_long(PyObject* x); static INLINE long double __pyx_PyInt_long_double(PyObject* x); #ifdef __GNUC__ /* Test for GCC &gt; 2.95 */ #if __GNUC__ &gt; 2 || (__GNUC__ == 2 &amp;&amp; (__GNUC_MINOR__ &gt; 95)) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else /* __GNUC__ &gt; 2 ... */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ &gt; 2 ... */ #else /* __GNUC__ */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ static PyObject *__pyx_m; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; static const char **__pyx_f; static void __Pyx_AddTraceback(const char *funcname); /*proto*/ /* Type declarations */ /* Module declarations from helloworld */ static int __pyx_f_10helloworld_hello(int, int); /*proto*/ /* Implementation of helloworld */ /* "/home/nosklo/devel/ctest/hello.pyx":1 * cdef int hello(int a, int b): # &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; * return a + b * */ static int __pyx_f_10helloworld_hello(int __pyx_v_a, int __pyx_v_b) { int __pyx_r; /* "/home/nosklo/devel/ctest/hello.pyx":2 * cdef int hello(int a, int b): * return a + b # &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; * */ __pyx_r = (__pyx_v_a + __pyx_v_b); goto __pyx_L0; __pyx_r = 0; __pyx_L0:; return __pyx_r; } static struct PyMethodDef __pyx_methods[] = { {0, 0, 0, 0} }; static void __pyx_init_filenames(void); /*proto*/ #if PY_MAJOR_VERSION &gt;= 3 static struct PyModuleDef __pyx_moduledef = { PyModuleDef_HEAD_INIT, "helloworld", 0, /* m_doc */ -1, /* m_size */ __pyx_methods /* m_methods */, NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ }; #endif static int __Pyx_InitCachedBuiltins(void) { return 0; return -1; } static int __Pyx_InitGlobals(void) { return 0; return -1; } #if PY_MAJOR_VERSION &lt; 3 PyMODINIT_FUNC inithelloworld(void); /*proto*/ PyMODINIT_FUNC inithelloworld(void) #else PyMODINIT_FUNC PyInit_helloworld(void); /*proto*/ PyMODINIT_FUNC PyInit_helloworld(void) #endif { __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Library function declarations ---*/ __pyx_init_filenames(); /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() &lt; 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Module creation code ---*/ #if PY_MAJOR_VERSION &lt; 3 __pyx_m = Py_InitModule4("helloworld", __pyx_methods, 0, 0, PYTHON_API_VERSION); #else __pyx_m = PyModule_Create(&amp;__pyx_moduledef); #endif if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; #if PY_MAJOR_VERSION &lt; 3 Py_INCREF(__pyx_m); #endif __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) &lt; 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Builtin init code ---*/ if (unlikely(__Pyx_InitCachedBuiltins() &lt; 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_skip_dispatch = 0; /*--- Global init code ---*/ /*--- Function export code ---*/ /*--- Type init code ---*/ /*--- Type import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ /* "/home/nosklo/devel/ctest/hello.pyx":1 * cdef int hello(int a, int b): # &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; * return a + b * */ #if PY_MAJOR_VERSION &lt; 3 return; #else return __pyx_m; #endif __pyx_L1_error:; __Pyx_AddTraceback("helloworld"); #if PY_MAJOR_VERSION &gt;= 3 return NULL; #endif } static const char *__pyx_filenames[] = { "hello.pyx", }; /* Runtime support code */ static void __pyx_init_filenames(void) { __pyx_f = __pyx_filenames; } #include "compile.h" #include "frameobject.h" #include "traceback.h" static void __Pyx_AddTraceback(const char *funcname) { PyObject *py_srcfile = 0; PyObject *py_funcname = 0; PyObject *py_globals = 0; PyObject *empty_string = 0; PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; #if PY_MAJOR_VERSION &lt; 3 py_srcfile = PyString_FromString(__pyx_filename); #else py_srcfile = PyUnicode_FromString(__pyx_filename); #endif if (!py_srcfile) goto bad; if (__pyx_clineno) { #if PY_MAJOR_VERSION &lt; 3 py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); #else py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); #endif } else { #if PY_MAJOR_VERSION &lt; 3 py_funcname = PyString_FromString(funcname); #else py_funcname = PyUnicode_FromString(funcname); #endif } if (!py_funcname) goto bad; py_globals = PyModule_GetDict(__pyx_m); if (!py_globals) goto bad; #if PY_MAJOR_VERSION &lt; 3 empty_string = PyString_FromStringAndSize("", 0); #else empty_string = PyBytes_FromStringAndSize("", 0); #endif if (!empty_string) goto bad; py_code = PyCode_New( 0, /*int argcount,*/ #if PY_MAJOR_VERSION &gt;= 3 0, /*int kwonlyargcount,*/ #endif 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ empty_string, /*PyObject *code,*/ __pyx_empty_tuple, /*PyObject *consts,*/ __pyx_empty_tuple, /*PyObject *names,*/ __pyx_empty_tuple, /*PyObject *varnames,*/ __pyx_empty_tuple, /*PyObject *freevars,*/ __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ __pyx_lineno, /*int firstlineno,*/ empty_string /*PyObject *lnotab*/ ); if (!py_code) goto bad; py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ py_globals, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; py_frame-&gt;f_lineno = __pyx_lineno; PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); Py_XDECREF(empty_string); Py_XDECREF(py_code); Py_XDECREF(py_frame); } /* Type Conversion Functions */ static INLINE Py_ssize_t __pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject* x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } static INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { if (x == Py_True) return 1; else if (x == Py_False) return 0; else return PyObject_IsTrue(x); } static INLINE PY_LONG_LONG __pyx_PyInt_AsLongLong(PyObject* x) { if (PyInt_CheckExact(x)) { return PyInt_AS_LONG(x); } else if (PyLong_CheckExact(x)) { return PyLong_AsLongLong(x); } else { PY_LONG_LONG val; PyObject* tmp = PyNumber_Int(x); if (!tmp) return (PY_LONG_LONG)-1; val = __pyx_PyInt_AsLongLong(tmp); Py_DECREF(tmp); return val; } } static INLINE unsigned PY_LONG_LONG __pyx_PyInt_AsUnsignedLongLong(PyObject* x) { if (PyInt_CheckExact(x)) { long val = PyInt_AS_LONG(x); if (unlikely(val &lt; 0)) { PyErr_SetString(PyExc_TypeError, "Negative assignment to unsigned type."); return (unsigned PY_LONG_LONG)-1; } return val; } else if (PyLong_CheckExact(x)) { return PyLong_AsUnsignedLongLong(x); } else { PY_LONG_LONG val; PyObject* tmp = PyNumber_Int(x); if (!tmp) return (PY_LONG_LONG)-1; val = __pyx_PyInt_AsUnsignedLongLong(tmp); Py_DECREF(tmp); return val; } } static INLINE unsigned char __pyx_PyInt_unsigned_char(PyObject* x) { if (sizeof(unsigned char) &lt; sizeof(long)) { long long_val = __pyx_PyInt_AsLong(x); unsigned char val = (unsigned char)long_val; if (unlikely((val != long_val) || (long_val &lt; 0))) { PyErr_SetString(PyExc_OverflowError, "value too large to convert to unsigned char"); return (unsigned char)-1; } return val; } else { return __pyx_PyInt_AsLong(x); } } static INLINE unsigned short __pyx_PyInt_unsigned_short(PyObject* x) { if (sizeof(unsigned short) &lt; sizeof(long)) { long long_val = __pyx_PyInt_AsLong(x); unsigned short val = (unsigned short)long_val; if (unlikely((val != long_val) || (long_val &lt; 0))) { PyErr_SetString(PyExc_OverflowError, "value too large to convert to unsigned short"); return (unsigned short)-1; } return val; } else { return __pyx_PyInt_AsLong(x); } } static INLINE char __pyx_PyInt_char(PyObject* x) { if (sizeof(char) &lt; sizeof(long)) { long long_val = __pyx_PyInt_AsLong(x); char val = (char)long_val; if (unlikely((val != long_val) )) { PyErr_SetString(PyExc_OverflowError, "value too large to convert to char"); return (char)-1; } return val; } else { return __pyx_PyInt_AsLong(x); } } static INLINE short __pyx_PyInt_short(PyObject* x) { if (sizeof(short) &lt; sizeof(long)) { long long_val = __pyx_PyInt_AsLong(x); short val = (short)long_val; if (unlikely((val != long_val) )) { PyErr_SetString(PyExc_OverflowError, "value too large to convert to short"); return (short)-1; } return val; } else { return __pyx_PyInt_AsLong(x); } } static INLINE int __pyx_PyInt_int(PyObject* x) { if (sizeof(int) &lt; sizeof(long)) { long long_val = __pyx_PyInt_AsLong(x); int val = (int)long_val; if (unlikely((val != long_val) )) { PyErr_SetString(PyExc_OverflowError, "value too large to convert to int"); return (int)-1; } return val; } else { return __pyx_PyInt_AsLong(x); } } static INLINE long __pyx_PyInt_long(PyObject* x) { if (sizeof(long) &lt; sizeof(long)) { long long_val = __pyx_PyInt_AsLong(x); long val = (long)long_val; if (unlikely((val != long_val) )) { PyErr_SetString(PyExc_OverflowError, "value too large to convert to long"); return (long)-1; } return val; } else { return __pyx_PyInt_AsLong(x); } } static INLINE signed char __pyx_PyInt_signed_char(PyObject* x) { if (sizeof(signed char) &lt; sizeof(long)) { long long_val = __pyx_PyInt_AsLong(x); signed char val = (signed char)long_val; if (unlikely((val != long_val) )) { PyErr_SetString(PyExc_OverflowError, "value too large to convert to signed char"); return (signed char)-1; } return val; } else { return __pyx_PyInt_AsLong(x); } } static INLINE signed short __pyx_PyInt_signed_short(PyObject* x) { if (sizeof(signed short) &lt; sizeof(long)) { long long_val = __pyx_PyInt_AsLong(x); signed short val = (signed short)long_val; if (unlikely((val != long_val) )) { PyErr_SetString(PyExc_OverflowError, "value too large to convert to signed short"); return (signed short)-1; } return val; } else { return __pyx_PyInt_AsLong(x); } } static INLINE signed int __pyx_PyInt_signed_int(PyObject* x) { if (sizeof(signed int) &lt; sizeof(long)) { long long_val = __pyx_PyInt_AsLong(x); signed int val = (signed int)long_val; if (unlikely((val != long_val) )) { PyErr_SetString(PyExc_OverflowError, "value too large to convert to signed int"); return (signed int)-1; } return val; } else { return __pyx_PyInt_AsLong(x); } } static INLINE signed long __pyx_PyInt_signed_long(PyObject* x) { if (sizeof(signed long) &lt; sizeof(long)) { long long_val = __pyx_PyInt_AsLong(x); signed long val = (signed long)long_val; if (unlikely((val != long_val) )) { PyErr_SetString(PyExc_OverflowError, "value too large to convert to signed long"); return (signed long)-1; } return val; } else { return __pyx_PyInt_AsLong(x); } } static INLINE long double __pyx_PyInt_long_double(PyObject* x) { if (sizeof(long double) &lt; sizeof(long)) { long long_val = __pyx_PyInt_AsLong(x); long double val = (long double)long_val; if (unlikely((val != long_val) )) { PyErr_SetString(PyExc_OverflowError, "value too large to convert to long double"); return (long double)-1; } return val; } else { return __pyx_PyInt_AsLong(x); } } </code></pre>
16
2009-01-19T10:05:52Z
[ "python", "c++", "c", "swig", "cython" ]
Extending python - to swig, not to swig or Cython
456,884
<p>I found the bottleneck in my python code, played around with psycho etc. Then decided to write a c/c++ extension for performance.</p> <p>With the help of swig you almost don't need to care about arguments etc. Everything works fine.</p> <p>Now my question: swig creates a quite large py-file which does a lot of 'checkings' and 'PySwigObject' before calling the actual .pyd or .so code.</p> <p>Does anyone of you have any experience whether there is some more performance to gain if you hand-write this file or let swig do it. </p>
55
2009-01-19T08:32:06Z
461,364
<p>There be dragons here. Don't swig, don't boost. For any complicated project the code you have to fill in yourself to make them work becomes unmanageable quickly. If it's a plain C API to your library (no classes), you can just use ctypes. It will be easy and painless, and you won't have to spend hours trawling through the documentation for these labyrinthine wrapper projects trying to find the one tiny note about the feature you need.</p>
4
2009-01-20T13:56:30Z
[ "python", "c++", "c", "swig", "cython" ]
Extending python - to swig, not to swig or Cython
456,884
<p>I found the bottleneck in my python code, played around with psycho etc. Then decided to write a c/c++ extension for performance.</p> <p>With the help of swig you almost don't need to care about arguments etc. Everything works fine.</p> <p>Now my question: swig creates a quite large py-file which does a lot of 'checkings' and 'PySwigObject' before calling the actual .pyd or .so code.</p> <p>Does anyone of you have any experience whether there is some more performance to gain if you hand-write this file or let swig do it. </p>
55
2009-01-19T08:32:06Z
478,892
<p>Since you are concerned with speed and overhead, I suggest considering <a href="http://code.google.com/p/pybindgen/">PyBindGen </a>. </p> <p>I have experience using it to wrap a large internal C++ library. After trying SWIG, SIP, and Boost.Python I prefer PyBindGen for the following reasons:</p> <ol> <li>A PyBindGen wrapper is pure-Python, no need to learn another file format</li> <li>PyBindGen generates Python C API calls directly, there is no speed-robbing indirection layer like SWIG. </li> <li>The generated C code is clean and simple to understand. I like Cython too, but trying to read its C output can be difficult at times.</li> <li>STL sequence containers are supported (we use a lot of std::vector's)</li> </ol>
5
2009-01-26T05:07:53Z
[ "python", "c++", "c", "swig", "cython" ]
Extending python - to swig, not to swig or Cython
456,884
<p>I found the bottleneck in my python code, played around with psycho etc. Then decided to write a c/c++ extension for performance.</p> <p>With the help of swig you almost don't need to care about arguments etc. Everything works fine.</p> <p>Now my question: swig creates a quite large py-file which does a lot of 'checkings' and 'PySwigObject' before calling the actual .pyd or .so code.</p> <p>Does anyone of you have any experience whether there is some more performance to gain if you hand-write this file or let swig do it. </p>
55
2009-01-19T08:32:06Z
3,167,276
<p>An observation: Based on the benchmarking conducted by the pybindgen developers, there is no significant difference between boost.python and swig. I haven't done my own benchmarking to verify how much of this depends on the proper use of the boost.python functionality. </p> <p>Note also that there may be a reason that pybindgen seems to be in general quite a bit faster than swig and boost.python: it <em>may</em> not produce as versatile a binding as the other two. For instance, exception propagation, call argument type checking, etc. I haven't had a chance to use pybindgen yet but I intend to. </p> <p>Boost is in general quite big package to install, and last I saw you can't just install boost python you pretty much need the whole Boost library. As others have mentioned compilation will be slow due to heavy use of template programming, which also means typically rather cryptic error messages at compile time. </p> <p>Summary: given how easy SWIG is to install and use, that it generates decent binding that is robust and versatile, and that one interface file allows your C++ DLL to be available from several other languages like LUA, C#, and Java, I would favor it over boost.python. But unless you really need multi-language support I would take a close look at PyBindGen because of its purported speed, and pay close attention to robustness and versatility of binding it generates. </p>
7
2010-07-02T15:58:44Z
[ "python", "c++", "c", "swig", "cython" ]
Extending python - to swig, not to swig or Cython
456,884
<p>I found the bottleneck in my python code, played around with psycho etc. Then decided to write a c/c++ extension for performance.</p> <p>With the help of swig you almost don't need to care about arguments etc. Everything works fine.</p> <p>Now my question: swig creates a quite large py-file which does a lot of 'checkings' and 'PySwigObject' before calling the actual .pyd or .so code.</p> <p>Does anyone of you have any experience whether there is some more performance to gain if you hand-write this file or let swig do it. </p>
55
2009-01-19T08:32:06Z
6,580,735
<p>SWIG 2.0.4 has introduced a new -builtin option that improves performance. I did some benchmarking using an example program that does a lot of fast calls to a C++ extension. I built the extension using boost.python, PyBindGen, SIP and SWIG with and without the -builtin option. Here are the results (average of 100 runs):</p> <pre><code>SWIG with -builtin 2.67s SIP 2.70s PyBindGen 2.74s boost.python 3.07s SWIG without -builtin 4.65s </code></pre> <p>SWIG used to be slowest. With the new -builtin option, SWIG seems to be fastest.</p>
26
2011-07-05T09:47:58Z
[ "python", "c++", "c", "swig", "cython" ]
Code to utilize memory more than 70%
456,926
<p>Please tell me C++/Java code which utilize memory more than 70% .</p> <p>For Example we have 3 Virtual machine and in memory resources we want to test the<br /> memory utilization as per memory resources allocated by user.</p>
1
2009-01-19T08:52:11Z
456,943
<pre><code>#include malloc.h #DEFINE MB 512 void main(int argc, char **argv) { int i; for (i = 0; i &lt; MB; i++) { malloc(1024* 1024); } getchar(); } </code></pre> <p>Hit enter to release the memory, set the MB constant to how much memory you want your program to take.</p> <p>My C is a little rusty so if someone comes here and walks all over me, 1000 apologies, my forte is C#.</p>
3
2009-01-19T08:58:28Z
[ "java", "c++", "python", "c" ]
Code to utilize memory more than 70%
456,926
<p>Please tell me C++/Java code which utilize memory more than 70% .</p> <p>For Example we have 3 Virtual machine and in memory resources we want to test the<br /> memory utilization as per memory resources allocated by user.</p>
1
2009-01-19T08:52:11Z
456,948
<p>Which memory? On a 64 bit platform, a 64 bit process can use far more than 4GB. You'd be filling swap for hours before you hit those limits.</p> <p>If you want to test "70% of physical RAM", you might discover that you cannot allocate 70% of the 32 bits address space. A significant amount is already claimed by the OS.</p>
4
2009-01-19T09:00:13Z
[ "java", "c++", "python", "c" ]
Code to utilize memory more than 70%
456,926
<p>Please tell me C++/Java code which utilize memory more than 70% .</p> <p>For Example we have 3 Virtual machine and in memory resources we want to test the<br /> memory utilization as per memory resources allocated by user.</p>
1
2009-01-19T08:52:11Z
460,265
<p>I want to test the Memory utilization but after executing the code i am unable to test the same.</p> <p>As i am new to this so help me more on this.</p> <p>Let we have 3 Virtual machine V1,V2,V3</p> <p>For V1 - Set shared resource as High</p> <p>For V2 - Set shared resources as Normal </p> <p>For V3 - Set shared resources as Normal </p> <p>So it means total is 2 GB then V1 get 1 GB and V2,V3 gets 512 MB each . So i want to test using programming if some one changes the Shared or reservation or Limit then how it works.</p>
0
2009-01-20T06:24:40Z
[ "java", "c++", "python", "c" ]
Cropping pages of a .pdf file
457,207
<p>I was wondering if anyone had any experience in working programmatically with .pdf files. I have a .pdf file and I need to crop every page down to a certain size.</p> <p>After a quick Google search I found the pyPdf library for python but my experiments with it failed. When I changed the cropBox and trimBox attributes on a page object the results were not what I had expected and appeared to be quite random.</p> <p>Has anyone had any experience with this? Code examples would be well appreciated, preferably in python.</p>
9
2009-01-19T10:43:23Z
458,189
<p>You are probably looking for a free solution, but if you have money to spend, <a href="http://pdflib.com" rel="nofollow">PDFlib</a> is a fabulous library. It has never disappointed me. </p>
0
2009-01-19T16:24:51Z
[ "python", "pdf" ]
Cropping pages of a .pdf file
457,207
<p>I was wondering if anyone had any experience in working programmatically with .pdf files. I have a .pdf file and I need to crop every page down to a certain size.</p> <p>After a quick Google search I found the pyPdf library for python but my experiments with it failed. When I changed the cropBox and trimBox attributes on a page object the results were not what I had expected and appeared to be quite random.</p> <p>Has anyone had any experience with this? Code examples would be well appreciated, preferably in python.</p>
9
2009-01-19T10:43:23Z
459,523
<p>You can convert the PDF to Postscript (pstopdf or ps2pdf) and than use text processing on the Postscript file. After that you can convert the output back to PDF.</p> <p>This works nicely if the PDFs you want to process are all generated by the same application and are somewhat similar. If they come from different sources it is usually to hard to process the Postscript files - the structure is varying to much. But even than you migt be able to fix page sizes and the like with a few regular expressions.</p>
0
2009-01-19T22:54:55Z
[ "python", "pdf" ]
Cropping pages of a .pdf file
457,207
<p>I was wondering if anyone had any experience in working programmatically with .pdf files. I have a .pdf file and I need to crop every page down to a certain size.</p> <p>After a quick Google search I found the pyPdf library for python but my experiments with it failed. When I changed the cropBox and trimBox attributes on a page object the results were not what I had expected and appeared to be quite random.</p> <p>Has anyone had any experience with this? Code examples would be well appreciated, preferably in python.</p>
9
2009-01-19T10:43:23Z
459,639
<p>Acrobat Javascript API has a setPageBoxes method, but Adobe doesn't provide any Python code samples. Only C++, C# and VB.</p>
0
2009-01-19T23:39:01Z
[ "python", "pdf" ]
Cropping pages of a .pdf file
457,207
<p>I was wondering if anyone had any experience in working programmatically with .pdf files. I have a .pdf file and I need to crop every page down to a certain size.</p> <p>After a quick Google search I found the pyPdf library for python but my experiments with it failed. When I changed the cropBox and trimBox attributes on a page object the results were not what I had expected and appeared to be quite random.</p> <p>Has anyone had any experience with this? Code examples would be well appreciated, preferably in python.</p>
9
2009-01-19T10:43:23Z
465,901
<p>pypdf does what I expect in this area. Using the following script:</p> <pre><code>#!/usr/bin/python # from pyPdf import PdfFileWriter, PdfFileReader input1 = PdfFileReader(file("in.pdf", "rb")) output = PdfFileWriter() numPages = input1.getNumPages() print "document has %s pages." % numPages for i in range(numPages): page = input1.getPage(i) print page.mediaBox.getUpperRight_x(), page.mediaBox.getUpperRight_y() page.trimBox.lowerLeft = (25, 25) page.trimBox.upperRight = (225, 225) page.cropBox.lowerLeft = (50, 50) page.cropBox.upperRight = (200, 200) output.addPage(page) outputStream = file("out.pdf", "wb") output.write(outputStream) outputStream.close() </code></pre> <p>The resulting document has a trim box that is 200x200 points and starts at 25,25 points inside the media box. The crop box is 25 points inside the trim box.</p> <p>Here is how my sample document looks in acrobat professional after processing with the above code: <img src="http://i40.tinypic.com/fkqn2t.png" alt="crop pages screenshot"> This document will appear blank when loaded in acrobat reader.</p>
14
2009-01-21T16:12:44Z
[ "python", "pdf" ]
What is the best real time plotting widget for wxPython?
457,246
<p>I would like to show a read time graph with one or two curves an up to 50 samples per second using Python and wxPython. The widget should support both Win32 and Linux platforms.</p> <p>Any hints are welcome.</p> <p>Edited to add:</p> <p>I don't need to update the display at 50 fps, but up need to show up to 50 samples of data on both curves, with a reasonable update rate for the display (5..10 fps should be okay).</p> <p>Edited to add:</p> <p>I have used mathplotlib in a project with good success. I have then settled for wx.lib.plot for other projects, which I found to be simpler, but somewhat easier to use and consuming less CPU cycles. As wx.lib comes as part of the standard wxPython distribution is is particularly easy to use.</p>
12
2009-01-19T11:00:38Z
457,310
<p>Maybe <a href="http://code.enthought.com/chaco/" rel="nofollow">Chaco</a>? I don't know if it can do 50 frames per second, but I saw in a demonstration how it did very smooth realtime plotting. It should definitely be faster than matplotlib.</p>
1
2009-01-19T11:27:17Z
[ "python", "wxpython", "wxwidgets" ]
What is the best real time plotting widget for wxPython?
457,246
<p>I would like to show a read time graph with one or two curves an up to 50 samples per second using Python and wxPython. The widget should support both Win32 and Linux platforms.</p> <p>Any hints are welcome.</p> <p>Edited to add:</p> <p>I don't need to update the display at 50 fps, but up need to show up to 50 samples of data on both curves, with a reasonable update rate for the display (5..10 fps should be okay).</p> <p>Edited to add:</p> <p>I have used mathplotlib in a project with good success. I have then settled for wx.lib.plot for other projects, which I found to be simpler, but somewhat easier to use and consuming less CPU cycles. As wx.lib comes as part of the standard wxPython distribution is is particularly easy to use.</p>
12
2009-01-19T11:00:38Z
457,505
<p>If you want really something fast with 50 frames per second, I think you need something like PyGame and kind of talk directly to the display, not a plotting module.</p> <p>Check the related threads:</p> <ul> <li><a href="http://stackoverflow.com/questions/434583/what-is-the-fastest-way-to-draw-an-image-from-discrete-pixel-values-in-python#434801">http://stackoverflow.com/questions/434583/what-is-the-fastest-way-to-draw-an-image-from-discrete-pixel-values-in-python#434801</a></li> <li><a href="http://stackoverflow.com/search?q=python+pygame">http://stackoverflow.com/search?q=python+pygame</a></li> </ul>
1
2009-01-19T12:57:15Z
[ "python", "wxpython", "wxwidgets" ]
What is the best real time plotting widget for wxPython?
457,246
<p>I would like to show a read time graph with one or two curves an up to 50 samples per second using Python and wxPython. The widget should support both Win32 and Linux platforms.</p> <p>Any hints are welcome.</p> <p>Edited to add:</p> <p>I don't need to update the display at 50 fps, but up need to show up to 50 samples of data on both curves, with a reasonable update rate for the display (5..10 fps should be okay).</p> <p>Edited to add:</p> <p>I have used mathplotlib in a project with good success. I have then settled for wx.lib.plot for other projects, which I found to be simpler, but somewhat easier to use and consuming less CPU cycles. As wx.lib comes as part of the standard wxPython distribution is is particularly easy to use.</p>
12
2009-01-19T11:00:38Z
457,524
<p>Here's a sample of a dynamic plotter with wxPython and matplotlib. While not 50 FPS, it draws smoothly and quickly enough for most real-time data views:</p> <p><a href="http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/">http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/</a></p> <p>Here's just the code paste: <a href="http://paste.pocoo.org/show/100358/">http://paste.pocoo.org/show/100358/</a></p>
10
2009-01-19T13:04:57Z
[ "python", "wxpython", "wxwidgets" ]
What is the best real time plotting widget for wxPython?
457,246
<p>I would like to show a read time graph with one or two curves an up to 50 samples per second using Python and wxPython. The widget should support both Win32 and Linux platforms.</p> <p>Any hints are welcome.</p> <p>Edited to add:</p> <p>I don't need to update the display at 50 fps, but up need to show up to 50 samples of data on both curves, with a reasonable update rate for the display (5..10 fps should be okay).</p> <p>Edited to add:</p> <p>I have used mathplotlib in a project with good success. I have then settled for wx.lib.plot for other projects, which I found to be simpler, but somewhat easier to use and consuming less CPU cycles. As wx.lib comes as part of the standard wxPython distribution is is particularly easy to use.</p>
12
2009-01-19T11:00:38Z
457,781
<p>It's not difficult to create a C++ widget that would read from your data source, and truly update at 50 FPS. The beautiful thing about this approach is that very little (if any) Python code would be executing at 50FPS, it would all be in the C++, depending on how you hand your updated data to the widget.</p> <p>You could even push an event handler into the custom real-time data viewer from the Python side, to handle all the mouse events and user interaction, and leave just the rendering in C++.</p> <p>It would be a small C++ class that extends wxWidget's wxWindow class</p> <p>class RealtimeDataViewer: public wxWindow { ...</p> <p>and override OnPaint</p> <p>void OnPaint(wxPaintEvent &amp;WXUNUSED(event)) { ....</p> <p>Then it would get a device context, and start drawing lines and shapes...</p> <p>You would then have to take the .h file, and copy it to .i, and tweak it just a bit to make it a definition that SWIG could use to extend wxPython.</p> <p>The build process could be handled by Python's own distutils using the following parameter to setup:</p> <pre><code> ext_modules=[Extension('myextension', sources, include_dirs=includeDirs library_dirs=usual_libs, )], </code></pre> <p>It would be a few days work to get it looking great and working well... But it's probably the one option that would really accelerate your project into the future.</p> <p>And all of this works well on Mac, Windows, and Linux.</p> <p>wxPython is really a hidden Gem that would really take over the world with more professionally supported IDE / designer tools.</p> <p>That said, try matplotlib first, it has lots of beautiful optimized rendering, and can do updates in real time too.</p>
5
2009-01-19T14:40:50Z
[ "python", "wxpython", "wxwidgets" ]
What is the best real time plotting widget for wxPython?
457,246
<p>I would like to show a read time graph with one or two curves an up to 50 samples per second using Python and wxPython. The widget should support both Win32 and Linux platforms.</p> <p>Any hints are welcome.</p> <p>Edited to add:</p> <p>I don't need to update the display at 50 fps, but up need to show up to 50 samples of data on both curves, with a reasonable update rate for the display (5..10 fps should be okay).</p> <p>Edited to add:</p> <p>I have used mathplotlib in a project with good success. I have then settled for wx.lib.plot for other projects, which I found to be simpler, but somewhat easier to use and consuming less CPU cycles. As wx.lib comes as part of the standard wxPython distribution is is particularly easy to use.</p>
12
2009-01-19T11:00:38Z
7,605,072
<p>If you want high performance with a minimal code footprint, look no farther than Python's built-in plotting library tkinter. No need to write special C / C++ code or use a large plotting package to get performance much better than 50 fps.</p> <p><img src="http://i.stack.imgur.com/CGK8y.png" alt="Screenshot"></p> <p>The following code scrolls a 1000x200 strip chart at 400 fps on a 2.2 GHz Core 2 duo, 1000 fps on a 3.4 GHz Core i3. The central routine "scrollstrip" plots a set of data points and corresponding colors at the right edge along with an optional vertical grid bar, then scrolls the stripchart to the left by 1. To plot horizontal grid bars just include them in the data and color arrays as constants along with your variable data points.</p> <pre><code>from tkinter import * import math, random, threading, time class StripChart: def __init__(self, root): self.gf = self.makeGraph(root) self.cf = self.makeControls(root) self.gf.pack() self.cf.pack() self.Reset() def makeGraph(self, frame): self.sw = 1000 self.h = 200 self.top = 2 gf = Canvas(frame, width=self.sw, height=self.h+10, bg="#002", bd=0, highlightthickness=0) gf.p = PhotoImage(width=2*self.sw, height=self.h) self.item = gf.create_image(0, self.top, image=gf.p, anchor=NW) return(gf) def makeControls(self, frame): cf = Frame(frame, borderwidth=1, relief="raised") Button(cf, text="Run", command=self.Run).grid(column=2, row=2) Button(cf, text="Stop", command=self.Stop).grid(column=4, row=2) Button(cf, text="Reset", command=self.Reset).grid(column=6, row=2) self.fps = Label(cf, text="0 fps") self.fps.grid(column=2, row=4, columnspan=5) return(cf) def Run(self): self.go = 1 for t in threading.enumerate(): if t.name == "_gen_": print("already running") return threading.Thread(target=self.do_start, name="_gen_").start() def Stop(self): self.go = 0 for t in threading.enumerate(): if t.name == "_gen_": t.join() def Reset(self): self.Stop() self.clearstrip(self.gf.p, '#345') def do_start(self): t = 0 y2 = 0 tx = time.time() while self.go: y1 = 0.2*math.sin(0.02*math.pi*t) y2 = 0.9*y2 + 0.1*(random.random()-0.5) self.scrollstrip(self.gf.p, (0.25+y1, 0.25, 0.7+y2, 0.6, 0.7, 0.8), ( '#ff4', '#f40', '#4af', '#080', '#0f0', '#080'), "" if t % 65 else "#088") t += 1 if not t % 100: tx2 = time.time() self.fps.config(text='%d fps' % int(100/(tx2 - tx))) tx = tx2 # time.sleep(0.001) def clearstrip(self, p, color): # Fill strip with background color self.bg = color # save background color for scroll self.data = None # clear previous data self.x = 0 p.tk.call(p, 'put', color, '-to', 0, 0, p['width'], p['height']) def scrollstrip(self, p, data, colors, bar=""): # Scroll the strip, add new data self.x = (self.x + 1) % self.sw # x = double buffer position bg = bar if bar else self.bg p.tk.call(p, 'put', bg, '-to', self.x, 0, self.x+1, self.h) p.tk.call(p, 'put', bg, '-to', self.x+self.sw, 0, self.x+self.sw+1, self.h) self.gf.coords(self.item, -1-self.x, self.top) # scroll to just-written column if not self.data: self.data = data for d in range(len(data)): y0 = int((self.h-1) * (1.0-self.data[d])) # plot all the data points y1 = int((self.h-1) * (1.0-data[d])) ya, yb = sorted((y0, y1)) for y in range(ya, yb+1): # connect the dots p.put(colors[d], (self.x,y)) p.put(colors[d], (self.x+self.sw,y)) self.data = data # save for next call def main(): root = Tk() root.title("StripChart") app = StripChart(root) root.mainloop() main() </code></pre>
8
2011-09-30T01:24:00Z
[ "python", "wxpython", "wxwidgets" ]
What is the best real time plotting widget for wxPython?
457,246
<p>I would like to show a read time graph with one or two curves an up to 50 samples per second using Python and wxPython. The widget should support both Win32 and Linux platforms.</p> <p>Any hints are welcome.</p> <p>Edited to add:</p> <p>I don't need to update the display at 50 fps, but up need to show up to 50 samples of data on both curves, with a reasonable update rate for the display (5..10 fps should be okay).</p> <p>Edited to add:</p> <p>I have used mathplotlib in a project with good success. I have then settled for wx.lib.plot for other projects, which I found to be simpler, but somewhat easier to use and consuming less CPU cycles. As wx.lib comes as part of the standard wxPython distribution is is particularly easy to use.</p>
12
2009-01-19T11:00:38Z
39,784,200
<p>I use <a href="http://www.pyqtgraph.org/" rel="nofollow">PyQtGraph</a> for this kind of thing. It is much faster than Matplotlib for realtime plotting and has lots of nice convenience features like a context menu in the plotting canvas with auto-scaling and scrolling without any extra work.</p>
0
2016-09-30T05:21:06Z
[ "python", "wxpython", "wxwidgets" ]
Is there an easily available implementation of erf() for Python?
457,408
<p>I can implement the error function, erf, myself, but I'd prefer not to. Is there a python package with no external dependencies that contains an implementation of this function? I have found http://pylab.sourceforge.net/packages/included_functions.html>this but this seems to be part of some much larger package (and it's not even clear which one!).</p> <p>I'm sorry if this is a naive question - I'm totally new to Python.</p>
36
2009-01-19T12:10:58Z
457,475
<p>I would recommend you download <a href="http://sourceforge.net/project/showfiles.php?group_id=1369&amp;package_id=175103">numpy</a> (to have efficiant matrix in python) and <a href="http://www.scipy.org/">scipy</a> (a Matlab toolbox substitute, which uses numpy). The erf function lies in scipy.</p> <pre><code>&gt;&gt;&gt;from scipy.special import erf &gt;&gt;&gt;help(erf) </code></pre> <p>You can also use the erf function defined in pylab, but this is more intended at plotting the results of the things you compute with numpy and scipy. If you want an all-in-one installation of these software you can use directly the <a href="http://www.enthought.com/products/epd.php">Python Enthought distribution</a>.</p>
20
2009-01-19T12:47:09Z
[ "python", "math" ]
Is there an easily available implementation of erf() for Python?
457,408
<p>I can implement the error function, erf, myself, but I'd prefer not to. Is there a python package with no external dependencies that contains an implementation of this function? I have found http://pylab.sourceforge.net/packages/included_functions.html>this but this seems to be part of some much larger package (and it's not even clear which one!).</p> <p>I'm sorry if this is a naive question - I'm totally new to Python.</p>
36
2009-01-19T12:10:58Z
457,805
<p>I recommend SciPy for numerical functions in Python, but if you want something with no dependencies, here is a function with an error error is less than 1.5 * 10<sup>-7</sup> for all inputs.</p> <pre><code>def erf(x): # save the sign of x sign = 1 if x &gt;= 0 else -1 x = abs(x) # constants a1 = 0.254829592 a2 = -0.284496736 a3 = 1.421413741 a4 = -1.453152027 a5 = 1.061405429 p = 0.3275911 # A&amp;S formula 7.1.26 t = 1.0/(1.0 + p*x) y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*math.exp(-x*x) return sign*y # erf(-x) = -erf(x) </code></pre> <p>The algorithm comes from <a href="http://rads.stackoverflow.com/amzn/click/0486612724">Handbook of Mathematical Functions</a>, formula 7.1.26.</p>
39
2009-01-19T14:46:13Z
[ "python", "math" ]
Is there an easily available implementation of erf() for Python?
457,408
<p>I can implement the error function, erf, myself, but I'd prefer not to. Is there a python package with no external dependencies that contains an implementation of this function? I have found http://pylab.sourceforge.net/packages/included_functions.html>this but this seems to be part of some much larger package (and it's not even clear which one!).</p> <p>I'm sorry if this is a naive question - I'm totally new to Python.</p>
36
2009-01-19T12:10:58Z
458,069
<p>To answer my own question, I have ended up using the following code, adapted from a Java version I found elsewhere on the web:</p> <pre><code># from: http://www.cs.princeton.edu/introcs/21function/ErrorFunction.java.html # Implements the Gauss error function. # erf(z) = 2 / sqrt(pi) * integral(exp(-t*t), t = 0..z) # # fractional error in math formula less than 1.2 * 10 ^ -7. # although subject to catastrophic cancellation when z in very close to 0 # from Chebyshev fitting formula for erf(z) from Numerical Recipes, 6.2 def erf(z): t = 1.0 / (1.0 + 0.5 * abs(z)) # use Horner's method ans = 1 - t * math.exp( -z*z - 1.26551223 + t * ( 1.00002368 + t * ( 0.37409196 + t * ( 0.09678418 + t * (-0.18628806 + t * ( 0.27886807 + t * (-1.13520398 + t * ( 1.48851587 + t * (-0.82215223 + t * ( 0.17087277)))))))))) if z &gt;= 0.0: return ans else: return -ans </code></pre>
6
2009-01-19T15:54:40Z
[ "python", "math" ]
Is there an easily available implementation of erf() for Python?
457,408
<p>I can implement the error function, erf, myself, but I'd prefer not to. Is there a python package with no external dependencies that contains an implementation of this function? I have found http://pylab.sourceforge.net/packages/included_functions.html>this but this seems to be part of some much larger package (and it's not even clear which one!).</p> <p>I'm sorry if this is a naive question - I'm totally new to Python.</p>
36
2009-01-19T12:10:58Z
463,261
<p>A pure python implementation can be found in the mpmath module (http://code.google.com/p/mpmath/)</p> <p>From the doc string:</p> <pre><code>&gt;&gt;&gt; from mpmath import * &gt;&gt;&gt; mp.dps = 15 &gt;&gt;&gt; print erf(0) 0.0 &gt;&gt;&gt; print erf(1) 0.842700792949715 &gt;&gt;&gt; print erf(-1) -0.842700792949715 &gt;&gt;&gt; print erf(inf) 1.0 &gt;&gt;&gt; print erf(-inf) -1.0 </code></pre> <p>For large real <code>x</code>, <code>\mathrm{erf}(x)</code> approaches 1 very rapidly::</p> <pre><code>&gt;&gt;&gt; print erf(3) 0.999977909503001 &gt;&gt;&gt; print erf(5) 0.999999999998463 </code></pre> <p>The error function is an odd function::</p> <pre><code>&gt;&gt;&gt; nprint(chop(taylor(erf, 0, 5))) [0.0, 1.12838, 0.0, -0.376126, 0.0, 0.112838] </code></pre> <p>:func:<code>erf</code> implements arbitrary-precision evaluation and supports complex numbers::</p> <pre><code>&gt;&gt;&gt; mp.dps = 50 &gt;&gt;&gt; print erf(0.5) 0.52049987781304653768274665389196452873645157575796 &gt;&gt;&gt; mp.dps = 25 &gt;&gt;&gt; print erf(1+j) (1.316151281697947644880271 + 0.1904534692378346862841089j) </code></pre> <p><strong>Related functions</strong></p> <p>See also :func:<code>erfc</code>, which is more accurate for large <code>x</code>, and :func:<code>erfi</code> which gives the antiderivative of <code>\exp(t^2)</code>.</p> <p>The Fresnel integrals :func:<code>fresnels</code> and :func:<code>fresnelc</code> are also related to the error function.</p>
7
2009-01-20T21:44:09Z
[ "python", "math" ]
Is there an easily available implementation of erf() for Python?
457,408
<p>I can implement the error function, erf, myself, but I'd prefer not to. Is there a python package with no external dependencies that contains an implementation of this function? I have found http://pylab.sourceforge.net/packages/included_functions.html>this but this seems to be part of some much larger package (and it's not even clear which one!).</p> <p>I'm sorry if this is a naive question - I'm totally new to Python.</p>
36
2009-01-19T12:10:58Z
4,021,276
<p>I have a function which does 10^5 erf calls. On my machine...</p> <p>scipy.special.erf makes it time at 6.1s</p> <p>erf Handbook of Mathematical Functions takes 8.3s</p> <p>erf Numerical Recipes 6.2 takes 9.5s</p> <p>(three-run averages, code taken from above posters).</p>
6
2010-10-26T06:41:50Z
[ "python", "math" ]
Is there an easily available implementation of erf() for Python?
457,408
<p>I can implement the error function, erf, myself, but I'd prefer not to. Is there a python package with no external dependencies that contains an implementation of this function? I have found http://pylab.sourceforge.net/packages/included_functions.html>this but this seems to be part of some much larger package (and it's not even clear which one!).</p> <p>I'm sorry if this is a naive question - I'm totally new to Python.</p>
36
2009-01-19T12:10:58Z
6,662,057
<p>Since v.2.7. the standard <em>math</em> module contains <em>erf</em> function. This should be the easiest way.</p> <p><a href="http://docs.python.org/2/library/math.html#math.erf">http://docs.python.org/2/library/math.html#math.erf</a></p>
44
2011-07-12T09:31:08Z
[ "python", "math" ]
Is there an easily available implementation of erf() for Python?
457,408
<p>I can implement the error function, erf, myself, but I'd prefer not to. Is there a python package with no external dependencies that contains an implementation of this function? I have found http://pylab.sourceforge.net/packages/included_functions.html>this but this seems to be part of some much larger package (and it's not even clear which one!).</p> <p>I'm sorry if this is a naive question - I'm totally new to Python.</p>
36
2009-01-19T12:10:58Z
20,745,660
<p>One note for those aiming for higher performance: vectorize, if possible.</p> <pre><code>import numpy as np from scipy.special import erf def vectorized(n): x = np.random.randn(n) return erf(x) def loopstyle(n): x = np.random.randn(n) return [erf(v) for v in x] %timeit vectorized(10e5) %timeit loopstyle(10e5) </code></pre> <p>gives results</p> <pre><code># vectorized 10 loops, best of 3: 108 ms per loop # loops 1 loops, best of 3: 2.34 s per loop </code></pre>
3
2013-12-23T14:37:14Z
[ "python", "math" ]
How to copy a picture from canvas to clipboard?
457,514
<p>I have some Tkinter canvas and some picture of lines and text on it. Is there an easy way to copy it to a clipboard?</p>
3
2009-01-19T12:59:53Z
458,236
<p>To use windows clipboard you must convert the image data to a format accepted by win api. Then, just use this function:</p> <pre><code>import win32clipboard def send_to_clibboard(clip_type, data): win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardData(clip_type, data) win32clipboard.CloseClipboard() </code></pre> <p>Where <code>clip_type</code> can be <code>win32clipboard.CF_BITMAP</code>, <code>win32clipboard.CF_TIFF</code> or many others.</p>
3
2009-01-19T16:38:14Z
[ "python", "clipboard", "tkinter" ]
How to copy a picture from canvas to clipboard?
457,514
<p>I have some Tkinter canvas and some picture of lines and text on it. Is there an easy way to copy it to a clipboard?</p>
3
2009-01-19T12:59:53Z
488,541
<p>You could use <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/canvas-methods.html" rel="nofollow"><code>.postscript</code></a> method of the canvas to get an Encapsulated PostScript (EPS) representation of the contents. Then, use `<a href="http://www.imagemagick.org" rel="nofollow">ImageMagick</a>'s Python bindings (<a href="http://www.imagemagick.org/download/python/" rel="nofollow">PythonMagick</a> or <a href="http://www.procoders.net/?p=39" rel="nofollow">PythonMagickWand</a>) to convert the EPS to a Windows Enhanced Metafile (EMF). Finally, copy it to the clipboard (e.g. using <a href="http://stackoverflow.com/questions/457514/how-to-copy-a-picture-from-canvas-to-clipboard#458236">nosklo's solution</a>) with the <a href="http://msdn.microsoft.com/en-us/library/ms649013(VS.85).aspx" rel="nofollow">CF_ENHMETAFILE</a> clipboard format.</p>
4
2009-01-28T17:27:01Z
[ "python", "clipboard", "tkinter" ]
What is the correct procedure to store a utf-16 encoded rss stream into sqlite3 using python
457,641
<p>I have a python sgi script that attempts to extract an rss items that is posted to it and store the rss in a sqlite3 db. I am using flup as the WSGIServer.<br> To obtain the posted content: postData = environ["wsgi.input"].read(int(environ["CONTENT_LENGTH"]))</p> <p>To attempt to store in the db:</p> <pre><code>from pysqlite2 import dbapi2 as sqlite ldb = sqlite.connect("/var/vhost/mysite.com/db/rssharvested.db") lcursor = ldb.cursor() lcursor.execute("INSERT into rss(data) VALUES(?)", (postData,)) </code></pre> <p>This results in only the first few characters of the rss being stored in the record: ÿþ&lt; I believe the initial chars are the BOM of the rss.</p> <p>I have tried every permutation I could think of including first encoding rss as utf-8 and then attempting to store but the results were the same. I could not decode because some characters could not be represented as unicode.</p> <p>Running python 2.5.2 sqlite 3.5.7</p> <p>Thanks in advance for any insight into this problem.</p> <hr> <p>Here is a sample of the initial data contained in postData as modified by the repr function, written to a file and viewed with less:</p> <p>'\xef\xbb\xbf</p> <p>Thanks for the all the replies! Very helpful. </p> <hr> <p>The sample I submitted didn't make it through the stackoverflow html filters will try again, converting less and greater than to entities (preview indicates this works).</p> <p>\xef\xbb\xbf&lt;?xml version="1.0" encoding="utf-16"?&gt;&lt;rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;&lt;channel&gt;&lt;item d3p1:size="0" xsi:type="tFileItem" xmlns:d3p1="http://htinc.com/opensearch-ex/1.0/"&gt;</p>
1
2009-01-19T13:57:37Z
457,663
<p>Regarding the insertion encoding - in any decent database API, you should insert <code>unicode</code> strings and <code>unicode</code> strings only.</p> <p>For the reading and parsing bit, I'd recommend Mark Pilgrim's <a href="http://www.feedparser.org/" rel="nofollow">Feed Parser</a>. It properly handles BOM, and the license allows commercial use. <em>This may be a bit too heavy handed if you are not doing any actual parsing on the RSS data.</em></p>
1
2009-01-19T14:04:45Z
[ "python", "sqlite", "wsgi" ]
What is the correct procedure to store a utf-16 encoded rss stream into sqlite3 using python
457,641
<p>I have a python sgi script that attempts to extract an rss items that is posted to it and store the rss in a sqlite3 db. I am using flup as the WSGIServer.<br> To obtain the posted content: postData = environ["wsgi.input"].read(int(environ["CONTENT_LENGTH"]))</p> <p>To attempt to store in the db:</p> <pre><code>from pysqlite2 import dbapi2 as sqlite ldb = sqlite.connect("/var/vhost/mysite.com/db/rssharvested.db") lcursor = ldb.cursor() lcursor.execute("INSERT into rss(data) VALUES(?)", (postData,)) </code></pre> <p>This results in only the first few characters of the rss being stored in the record: ÿþ&lt; I believe the initial chars are the BOM of the rss.</p> <p>I have tried every permutation I could think of including first encoding rss as utf-8 and then attempting to store but the results were the same. I could not decode because some characters could not be represented as unicode.</p> <p>Running python 2.5.2 sqlite 3.5.7</p> <p>Thanks in advance for any insight into this problem.</p> <hr> <p>Here is a sample of the initial data contained in postData as modified by the repr function, written to a file and viewed with less:</p> <p>'\xef\xbb\xbf</p> <p>Thanks for the all the replies! Very helpful. </p> <hr> <p>The sample I submitted didn't make it through the stackoverflow html filters will try again, converting less and greater than to entities (preview indicates this works).</p> <p>\xef\xbb\xbf&lt;?xml version="1.0" encoding="utf-16"?&gt;&lt;rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;&lt;channel&gt;&lt;item d3p1:size="0" xsi:type="tFileItem" xmlns:d3p1="http://htinc.com/opensearch-ex/1.0/"&gt;</p>
1
2009-01-19T13:57:37Z
457,769
<p>Before the SQL insertion you should to convert the string to unicode compatible strings. If you raise an UnicodeError exception, then encode the string.encode("utf-8").</p> <p>Or , you can autodetect encoding and encode it , on his encode schema. <a href="http://code.activestate.com/recipes/52257" rel="nofollow">Auto detect encoding</a></p>
0
2009-01-19T14:36:03Z
[ "python", "sqlite", "wsgi" ]
What is the correct procedure to store a utf-16 encoded rss stream into sqlite3 using python
457,641
<p>I have a python sgi script that attempts to extract an rss items that is posted to it and store the rss in a sqlite3 db. I am using flup as the WSGIServer.<br> To obtain the posted content: postData = environ["wsgi.input"].read(int(environ["CONTENT_LENGTH"]))</p> <p>To attempt to store in the db:</p> <pre><code>from pysqlite2 import dbapi2 as sqlite ldb = sqlite.connect("/var/vhost/mysite.com/db/rssharvested.db") lcursor = ldb.cursor() lcursor.execute("INSERT into rss(data) VALUES(?)", (postData,)) </code></pre> <p>This results in only the first few characters of the rss being stored in the record: ÿþ&lt; I believe the initial chars are the BOM of the rss.</p> <p>I have tried every permutation I could think of including first encoding rss as utf-8 and then attempting to store but the results were the same. I could not decode because some characters could not be represented as unicode.</p> <p>Running python 2.5.2 sqlite 3.5.7</p> <p>Thanks in advance for any insight into this problem.</p> <hr> <p>Here is a sample of the initial data contained in postData as modified by the repr function, written to a file and viewed with less:</p> <p>'\xef\xbb\xbf</p> <p>Thanks for the all the replies! Very helpful. </p> <hr> <p>The sample I submitted didn't make it through the stackoverflow html filters will try again, converting less and greater than to entities (preview indicates this works).</p> <p>\xef\xbb\xbf&lt;?xml version="1.0" encoding="utf-16"?&gt;&lt;rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;&lt;channel&gt;&lt;item d3p1:size="0" xsi:type="tFileItem" xmlns:d3p1="http://htinc.com/opensearch-ex/1.0/"&gt;</p>
1
2009-01-19T13:57:37Z
458,637
<p>Are you sure your incoming data are encoded as UTF-16 (otherwise known as UCS-2)?</p> <p>UTF-16 encoded unicode strings typically include lots of NUL characters (surely for all characters existing in ASCII too), so UTF-16 data hardly can be stored in environment variables (env vars in POSIX are NUL terminated).</p> <p>Please provide samples of the <code>postData</code> variable contents. Output them using <code>repr()</code>.</p> <p>Until then, the solid advice is: in all DB interactions, your strings on the Python side should be unicode strings; the DB interface should take care of all translations/encodings/decodings necessary.</p>
1
2009-01-19T18:34:14Z
[ "python", "sqlite", "wsgi" ]
Is there a way to detach matplotlib plots so that the computation can continue?
458,209
<p>After these instructions in the Python interpreter one gets a window with a plot:</p> <pre><code>from matplotlib.pyplot import * plot([1,2,3]) show() # other code </code></pre> <p>Unfortunately, I don't know how to continue to interactively explore the figure created by <code>show()</code> while the program does further calculations.</p> <p>Is it possible at all? Sometimes calculations are long and it would help if they would proceed during examination of intermediate results.</p>
122
2009-01-19T16:30:57Z
458,246
<p>It is better to always check with the library you are using if it supports usage in a <strong>non-blocking</strong> way.</p> <p>But if you want a more generic solution, or if there is no other way, you can run anything that blocks in a separated process by using the <a href="http://docs.python.org/library/multiprocessing.html"><code>multprocessing</code></a> module included in python. Computation will continue:</p> <pre><code>from multiprocessing import Process from matplotlib.pyplot import plot, show def plot_graph(*args): for data in args: plot(data) show() p = Process(target=plot_graph, args=([1, 2, 3],)) p.start() print 'yay' print 'computation continues...' print 'that rocks.' print 'Now lets wait for the graph be closed to continue...:' p.join() </code></pre> <p>That has the overhead of launching a new process, and is sometimes harder to debug on complex scenarios, so I'd prefer the other solution (using <code>matplotlib</code>'s <a href="http://stackoverflow.com/questions/458209/is-there-a-way-to-detach-matplotlib-plots-so-that-the-computation-can-continue#458295">nonblocking API calls</a>)</p>
19
2009-01-19T16:40:24Z
[ "python", "matplotlib", "plot" ]
Is there a way to detach matplotlib plots so that the computation can continue?
458,209
<p>After these instructions in the Python interpreter one gets a window with a plot:</p> <pre><code>from matplotlib.pyplot import * plot([1,2,3]) show() # other code </code></pre> <p>Unfortunately, I don't know how to continue to interactively explore the figure created by <code>show()</code> while the program does further calculations.</p> <p>Is it possible at all? Sometimes calculations are long and it would help if they would proceed during examination of intermediate results.</p>
122
2009-01-19T16:30:57Z
458,295
<p>Use <code>matplotlib</code>'s calls that won't block:</p> <p>Using <code>draw()</code>:</p> <pre><code>from matplotlib.pyplot import plot, draw, show plot([1,2,3]) draw() print 'continue computation' # at the end call show to ensure window won't close. show() </code></pre> <p>Using interactive mode:</p> <pre><code>from matplotlib.pyplot import plot, ion, show ion() # enables interactive mode plot([1,2,3]) # result shows immediatelly (implicit draw()) print 'continue computation' # at the end call show to ensure window won't close. show() </code></pre>
112
2009-01-19T16:52:17Z
[ "python", "matplotlib", "plot" ]
Is there a way to detach matplotlib plots so that the computation can continue?
458,209
<p>After these instructions in the Python interpreter one gets a window with a plot:</p> <pre><code>from matplotlib.pyplot import * plot([1,2,3]) show() # other code </code></pre> <p>Unfortunately, I don't know how to continue to interactively explore the figure created by <code>show()</code> while the program does further calculations.</p> <p>Is it possible at all? Sometimes calculations are long and it would help if they would proceed during examination of intermediate results.</p>
122
2009-01-19T16:30:57Z
458,321
<p>You may want to read this document in <code>matplotlib</code>'s documentation, titled:</p> <p><a href="http://matplotlib.sourceforge.net/users/shell.html#using-matplotlib-in-a-python-shell">Using matplotlib in a python shell</a></p>
8
2009-01-19T17:00:04Z
[ "python", "matplotlib", "plot" ]
Is there a way to detach matplotlib plots so that the computation can continue?
458,209
<p>After these instructions in the Python interpreter one gets a window with a plot:</p> <pre><code>from matplotlib.pyplot import * plot([1,2,3]) show() # other code </code></pre> <p>Unfortunately, I don't know how to continue to interactively explore the figure created by <code>show()</code> while the program does further calculations.</p> <p>Is it possible at all? Sometimes calculations are long and it would help if they would proceed during examination of intermediate results.</p>
122
2009-01-19T16:30:57Z
465,439
<p>In my case, I wanted to have several windows pop up as they are being computed. For reference, this is the way:</p> <pre><code>from matplotlib.pyplot import draw, figure, show f1, f2 = figure(), figure() af1 = f1.add_subplot(111) af2 = f2.add_subplot(111) af1.plot([1,2,3]) af2.plot([6,5,4]) draw() print 'continuing computation' show() </code></pre> <p>PS. A quite useful <a href="https://github.com/ericliang/matplotlib/blob/master/branches/unit_support/htdocs/leftwich_tut.txt" rel="nofollow">guide to matplotlib's OO interface</a>.</p>
6
2009-01-21T14:05:30Z
[ "python", "matplotlib", "plot" ]
Is there a way to detach matplotlib plots so that the computation can continue?
458,209
<p>After these instructions in the Python interpreter one gets a window with a plot:</p> <pre><code>from matplotlib.pyplot import * plot([1,2,3]) show() # other code </code></pre> <p>Unfortunately, I don't know how to continue to interactively explore the figure created by <code>show()</code> while the program does further calculations.</p> <p>Is it possible at all? Sometimes calculations are long and it would help if they would proceed during examination of intermediate results.</p>
122
2009-01-19T16:30:57Z
4,149,491
<p>Well, I had great trouble figuring out the non-blocking commands... But finally, I managed to rework the "<a href="http://www.scipy.org/Cookbook/Matplotlib/Animations#head-3d51654b8306b1585664e7fe060a60fc76e5aa08" rel="nofollow">Cookbook/Matplotlib/Animations - Animating selected plot elements</a>" example, so it works with threads (<em>and passes data between threads either via global variables, or through a multiprocess <code>Pipe</code></em>) on Python 2.6.5 on Ubuntu 10.04. </p> <p>The script can be found here: <a href="http://sdaaubckp.svn.sourceforge.net/viewvc/sdaaubckp/single-scripts/Animating_selected_plot_elements-thread.py?revision=101&amp;content-type=text%2Fplain" rel="nofollow">Animating_selected_plot_elements-thread.py</a> - otherwise pasted below (<em>with fewer comments</em>) for reference: </p> <pre><code>import sys import gtk, gobject import matplotlib matplotlib.use('GTKAgg') import pylab as p import numpy as nx import time import threading ax = p.subplot(111) canvas = ax.figure.canvas # for profiling tstart = time.time() # create the initial line x = nx.arange(0,2*nx.pi,0.01) line, = ax.plot(x, nx.sin(x), animated=True) # save the clean slate background -- everything but the animated line # is drawn and saved in the pixel buffer background background = canvas.copy_from_bbox(ax.bbox) # just a plain global var to pass data (from main, to plot update thread) global mypass # http://docs.python.org/library/multiprocessing.html#pipes-and-queues from multiprocessing import Pipe global pipe1main, pipe1upd pipe1main, pipe1upd = Pipe() # the kind of processing we might want to do in a main() function, # will now be done in a "main thread" - so it can run in # parallel with gobject.idle_add(update_line) def threadMainTest(): global mypass global runthread global pipe1main print "tt" interncount = 1 while runthread: mypass += 1 if mypass &gt; 100: # start "speeding up" animation, only after 100 counts have passed interncount *= 1.03 pipe1main.send(interncount) time.sleep(0.01) return # main plot / GUI update def update_line(*args): global mypass global t0 global runthread global pipe1upd if not runthread: return False if pipe1upd.poll(): # check first if there is anything to receive myinterncount = pipe1upd.recv() update_line.cnt = mypass # restore the clean slate background canvas.restore_region(background) # update the data line.set_ydata(nx.sin(x+(update_line.cnt+myinterncount)/10.0)) # just draw the animated artist ax.draw_artist(line) # just redraw the axes rectangle canvas.blit(ax.bbox) if update_line.cnt&gt;=500: # print the timing info and quit print 'FPS:' , update_line.cnt/(time.time()-tstart) runthread=0 t0.join(1) print "exiting" sys.exit(0) return True global runthread update_line.cnt = 0 mypass = 0 runthread=1 gobject.idle_add(update_line) global t0 t0 = threading.Thread(target=threadMainTest) t0.start() # start the graphics update thread p.show() print "out" # will never print - show() blocks indefinitely! </code></pre> <p>Hope this helps someone,<br> Cheers!</p>
4
2010-11-10T21:55:48Z
[ "python", "matplotlib", "plot" ]
Is there a way to detach matplotlib plots so that the computation can continue?
458,209
<p>After these instructions in the Python interpreter one gets a window with a plot:</p> <pre><code>from matplotlib.pyplot import * plot([1,2,3]) show() # other code </code></pre> <p>Unfortunately, I don't know how to continue to interactively explore the figure created by <code>show()</code> while the program does further calculations.</p> <p>Is it possible at all? Sometimes calculations are long and it would help if they would proceed during examination of intermediate results.</p>
122
2009-01-19T16:30:57Z
5,335,087
<p>On my system show() does not block, although I wanted the script to wait for the user to interact with the graph (and collect data using 'pick_event' callbacks) before continuing.</p> <p>In order to block execution until the plot window is closed, I used the following:</p> <pre><code>fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot(x,y) # set processing to continue when window closed def onclose(event): fig.canvas.stop_event_loop() fig.canvas.mpl_connect('close_event', onclose) fig.show() # this call does not block on my system fig.canvas.start_event_loop_default() # block here until window closed # continue with further processing, perhaps using result from callbacks </code></pre> <p>Note, however, that canvas.start_event_loop_default() produced the following warning:</p> <pre><code>C:\Python26\lib\site-packages\matplotlib\backend_bases.py:2051: DeprecationWarning: Using default event loop until function specific to this GUI is implemented warnings.warn(str,DeprecationWarning) </code></pre> <p>although the script still ran.</p>
2
2011-03-17T05:06:56Z
[ "python", "matplotlib", "plot" ]
Is there a way to detach matplotlib plots so that the computation can continue?
458,209
<p>After these instructions in the Python interpreter one gets a window with a plot:</p> <pre><code>from matplotlib.pyplot import * plot([1,2,3]) show() # other code </code></pre> <p>Unfortunately, I don't know how to continue to interactively explore the figure created by <code>show()</code> while the program does further calculations.</p> <p>Is it possible at all? Sometimes calculations are long and it would help if they would proceed during examination of intermediate results.</p>
122
2009-01-19T16:30:57Z
10,731,085
<p>If I understand the question properly, using Ipython (or Ipython QT or Ipython notebook) would allow you to work interactively with the chart while calculations go one in the background. <a href="http://ipython.org/" rel="nofollow">http://ipython.org/</a></p>
0
2012-05-24T04:18:42Z
[ "python", "matplotlib", "plot" ]
Is there a way to detach matplotlib plots so that the computation can continue?
458,209
<p>After these instructions in the Python interpreter one gets a window with a plot:</p> <pre><code>from matplotlib.pyplot import * plot([1,2,3]) show() # other code </code></pre> <p>Unfortunately, I don't know how to continue to interactively explore the figure created by <code>show()</code> while the program does further calculations.</p> <p>Is it possible at all? Sometimes calculations are long and it would help if they would proceed during examination of intermediate results.</p>
122
2009-01-19T16:30:57Z
13,361,748
<p>Use the keyword 'block' to override the blocking behavior, e.g. </p> <pre><code>from matplotlib.pyplot import show, plot plot(1) show(block=False) # your code </code></pre> <p>to continue your code.</p>
67
2012-11-13T13:40:54Z
[ "python", "matplotlib", "plot" ]
Is there a way to detach matplotlib plots so that the computation can continue?
458,209
<p>After these instructions in the Python interpreter one gets a window with a plot:</p> <pre><code>from matplotlib.pyplot import * plot([1,2,3]) show() # other code </code></pre> <p>Unfortunately, I don't know how to continue to interactively explore the figure created by <code>show()</code> while the program does further calculations.</p> <p>Is it possible at all? Sometimes calculations are long and it would help if they would proceed during examination of intermediate results.</p>
122
2009-01-19T16:30:57Z
14,398,396
<p>Try</p> <pre class="lang-py prettyprint-override"><code>from matplotlib.pyplot import * plot([1,2,3]) show(block=False) # other code # [...] # Put show() # at the very end of your script # to make sure Python doesn't bail out # before you finished examining. </code></pre> <p>The <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.show" rel="nofollow"><code>show()</code> documentation</a> says:</p> <blockquote> <p>In non-interactive mode, display all figures and block until the figures have been closed; in interactive mode it has no effect unless figures were created prior to a change from non-interactive to interactive mode (not recommended). In that case it displays the figures but does not block.</p> <p>A single experimental keyword argument, <code>block</code>, may be set to <code>True</code> or <code>False</code> to override the blocking behavior described above.</p> </blockquote>
13
2013-01-18T11:53:33Z
[ "python", "matplotlib", "plot" ]
Is there a way to detach matplotlib plots so that the computation can continue?
458,209
<p>After these instructions in the Python interpreter one gets a window with a plot:</p> <pre><code>from matplotlib.pyplot import * plot([1,2,3]) show() # other code </code></pre> <p>Unfortunately, I don't know how to continue to interactively explore the figure created by <code>show()</code> while the program does further calculations.</p> <p>Is it possible at all? Sometimes calculations are long and it would help if they would proceed during examination of intermediate results.</p>
122
2009-01-19T16:30:57Z
20,665,576
<p>In many cases it is <strong>more convenient til save the image</strong> as a .png file on the hard drive. Here is why:</p> <p><strong>Advantages:</strong></p> <ul> <li>You can open it, have a look at it and close it down any time in the process. This is particularly convenient when your application is running for a long time.</li> <li>Nothing pops up and you are not forced to have the windows open. This is particularly convenient when you are dealing with many figures.</li> <li>Your image is accessible for later reference and is not lost when closing the figure window.</li> </ul> <p><strong>Drawback:</strong></p> <ul> <li>The only thing I can think of is that you will have to go and finder the folder and open the image yourself.</li> </ul>
2
2013-12-18T18:21:54Z
[ "python", "matplotlib", "plot" ]
Is there a way to detach matplotlib plots so that the computation can continue?
458,209
<p>After these instructions in the Python interpreter one gets a window with a plot:</p> <pre><code>from matplotlib.pyplot import * plot([1,2,3]) show() # other code </code></pre> <p>Unfortunately, I don't know how to continue to interactively explore the figure created by <code>show()</code> while the program does further calculations.</p> <p>Is it possible at all? Sometimes calculations are long and it would help if they would proceed during examination of intermediate results.</p>
122
2009-01-19T16:30:57Z
26,734,905
<p>I also wanted my plots to display run the rest of the code (and then keep on displaying) even if there is an error (I sometimes use plots for debugging). I coded up this little hack so that any plots inside this <code>with</code> statement behave as such.</p> <p>This is probably a bit too non-standard and not advisable for production code. There is probably a lot of hidden "gotchas" in this code.</p> <pre><code>from contextlib import contextmanager @contextmanager def keep_plots_open(keep_show_open_on_exit=True, even_when_error=True): ''' To continue excecuting code when plt.show() is called and keep the plot on displaying before this contex manager exits (even if an error caused the exit). ''' import matplotlib.pyplot show_original = matplotlib.pyplot.show def show_replacement(*args, **kwargs): kwargs['block'] = False show_original(*args, **kwargs) matplotlib.pyplot.show = show_replacement pylab_exists = True try: import pylab except ImportError: pylab_exists = False if pylab_exists: pylab.show = show_replacement try: yield except Exception, err: if keep_show_open_on_exit and even_when_error: print "*********************************************" print "Error early edition while waiting for show():" print "*********************************************" import traceback print traceback.format_exc() show_original() print "*********************************************" raise finally: matplotlib.pyplot.show = show_original if pylab_exists: pylab.show = show_original if keep_show_open_on_exit: show_original() # *********************** # Running example # *********************** import pylab as pl import time if __name__ == '__main__': with keep_plots_open(): pl.figure('a') pl.plot([1,2,3], [4,5,6]) pl.plot([3,2,1], [4,5,6]) pl.show() pl.figure('b') pl.plot([1,2,3], [4,5,6]) pl.show() time.sleep(1) print '...' time.sleep(1) print '...' time.sleep(1) print '...' this_will_surely_cause_an_error </code></pre> <p>If/when I implement a proper "keep the plots open (even if an error occurs) and allow new plots to be shown", I would want the script to properly exit if no user interference tells it otherwise (for batch execution purposes).</p> <p>I may use something like a time-out-question "End of script! \nPress p if you want the plotting output to be paused (you have 5 seconds): " from <a href="http://stackoverflow.com/questions/26704840/corner-cases-for-my-wait-for-user-input-interruption-implementation">Corner cases for my wait for user input interruption implementation</a>.</p>
2
2014-11-04T12:14:28Z
[ "python", "matplotlib", "plot" ]
Is there a way to detach matplotlib plots so that the computation can continue?
458,209
<p>After these instructions in the Python interpreter one gets a window with a plot:</p> <pre><code>from matplotlib.pyplot import * plot([1,2,3]) show() # other code </code></pre> <p>Unfortunately, I don't know how to continue to interactively explore the figure created by <code>show()</code> while the program does further calculations.</p> <p>Is it possible at all? Sometimes calculations are long and it would help if they would proceed during examination of intermediate results.</p>
122
2009-01-19T16:30:57Z
34,478,093
<p>In my opinion, the answers in this thread provide methods which don't work for every systems and in more complex situations like animations. I suggest to have a look at the answer of MikeTex in the following thread, where a robust method has been found: <a href="http://stackoverflow.com/questions/34432353/how-to-wait-until-matplotlib-animation-ends/34475657#34475657">How to wait until matplotlib animation ends?</a></p>
0
2015-12-27T06:17:15Z
[ "python", "matplotlib", "plot" ]
Is there a way to detach matplotlib plots so that the computation can continue?
458,209
<p>After these instructions in the Python interpreter one gets a window with a plot:</p> <pre><code>from matplotlib.pyplot import * plot([1,2,3]) show() # other code </code></pre> <p>Unfortunately, I don't know how to continue to interactively explore the figure created by <code>show()</code> while the program does further calculations.</p> <p>Is it possible at all? Sometimes calculations are long and it would help if they would proceed during examination of intermediate results.</p>
122
2009-01-19T16:30:57Z
34,853,314
<p>If you are working in console, i.e. <code>IPython</code> you could use <code>plt.show(block=False)</code> as pointed out in the other answers. But if you're lazy you could just type:</p> <pre><code>plt.show(0) </code></pre> <p>Which will be the same.</p>
2
2016-01-18T11:11:44Z
[ "python", "matplotlib", "plot" ]
Is there a way to detach matplotlib plots so that the computation can continue?
458,209
<p>After these instructions in the Python interpreter one gets a window with a plot:</p> <pre><code>from matplotlib.pyplot import * plot([1,2,3]) show() # other code </code></pre> <p>Unfortunately, I don't know how to continue to interactively explore the figure created by <code>show()</code> while the program does further calculations.</p> <p>Is it possible at all? Sometimes calculations are long and it would help if they would proceed during examination of intermediate results.</p>
122
2009-01-19T16:30:57Z
39,534,832
<p>If you want to open multiple figures, while keeping them all opened, this code worked for me:</p> <pre><code>show(block=False) draw() </code></pre>
-1
2016-09-16T15:11:08Z
[ "python", "matplotlib", "plot" ]
How do I install an .egg file without easy_install in Windows?
458,311
<p>I have Python 2.6 and I want to install easy _ install module. The problem is that the only available installation package of easy _ install for Python 2.6 is an .egg file! What should I do?</p>
14
2009-01-19T16:58:10Z
458,339
<p>You could try <a href="http://peak.telecommunity.com/dist/ez_setup.py" rel="nofollow">this script</a>.</p> <pre><code>#!python """Bootstrap setuptools installation If you want to use setuptools in your package's setup.py, just include this file in the same directory with it, and add this to the top of your setup.py::     from ez_setup import use_setuptools     use_setuptools() If you want to require a specific version of setuptools, set a download mirror, or use an alternate download directory, you can do so by supplying the appropriate options to ``use_setuptools()``. This file can also be run as a script to install or upgrade setuptools. """ import sys DEFAULT_VERSION = "0.6c11" DEFAULT_URL     = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3] md5_data = {     'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca',     'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb',     'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b',     'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a',     'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618',     'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac',     'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5',     'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4',     'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c',     'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b',     'setuptools-0.6c10-py2.3.egg': 'ce1e2ab5d3a0256456d9fc13800a7090',     'setuptools-0.6c10-py2.4.egg': '57d6d9d6e9b80772c59a53a8433a5dd4',     'setuptools-0.6c10-py2.5.egg': 'de46ac8b1c97c895572e5e8596aeb8c7',     'setuptools-0.6c10-py2.6.egg': '58ea40aef06da02ce641495523a0b7f5',     'setuptools-0.6c11-py2.3.egg': '2baeac6e13d414a9d28e7ba5b5a596de',     'setuptools-0.6c11-py2.4.egg': 'bd639f9b0eac4c42497034dec2ec0c2b',     'setuptools-0.6c11-py2.5.egg': '64c94f3bf7a72a13ec83e0b24f2749b2',     'setuptools-0.6c11-py2.6.egg': 'bfa92100bd772d5a213eedd356d64086',     'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27',     'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277',     'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa',     'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e',     'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e',     'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f',     'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2',     'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc',     'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167',     'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64',     'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d',     'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20',     'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab',     'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53',     'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2',     'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e',     'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372',     'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902',     'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de',     'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b',     'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03',     'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a',     'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6',     'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a', } import sys, os try: from hashlib import md5 except ImportError: from md5 import md5 def _validate_md5(egg_name, data):     if egg_name in md5_data:         digest = md5(data).hexdigest()         if digest != md5_data[egg_name]:             print &gt;&gt;sys.stderr, (                 "md5 validation of %s failed!  (Possible download problem?)"                 % egg_name             )             sys.exit(2)     return data def use_setuptools(     version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,     download_delay=15 ):     """Automatically find/download setuptools and make it available on sys.path     `version` should be a valid setuptools version number that is available     as an egg for download under the `download_base` URL (which should end with     a '/').  `to_dir` is the directory where setuptools will be downloaded, if     it is not already available.  If `download_delay` is specified, it should     be the number of seconds that will be paused before initiating a download,     should one be required.  If an older version of setuptools is installed,     this routine will print a message to ``sys.stderr`` and raise SystemExit in     an attempt to abort the calling script.     """     was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules     def do_download():         egg = download_setuptools(version, download_base, to_dir, download_delay)         sys.path.insert(0, egg)         import setuptools; setuptools.bootstrap_install_from = egg     try:         import pkg_resources     except ImportError:         return do_download()            try:         pkg_resources.require("setuptools&gt;="+version); return     except pkg_resources.VersionConflict, e:         if was_imported:             print &gt;&gt;sys.stderr, (             "The required version of setuptools (&gt;=%s) is not available, and\n"             "can't be installed while this script is running. Please install\n"             " a more recent version first, using 'easy_install -U setuptools'."             "\n\n(Currently using %r)"             ) % (version, e.args[0])             sys.exit(2)     except pkg_resources.DistributionNotFound:         pass     del pkg_resources, sys.modules['pkg_resources']    # reload ok     return do_download() def download_setuptools(     version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,     delay = 15 ):     """Download setuptools from a specified location and return its filename     `version` should be a valid setuptools version number that is available     as an egg for download under the `download_base` URL (which should end     with a '/'). `to_dir` is the directory where the egg will be downloaded.     `delay` is the number of seconds to pause before an actual download attempt.     """     import urllib2, shutil     egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])     url = download_base + egg_name     saveto = os.path.join(to_dir, egg_name)     src = dst = None     if not os.path.exists(saveto):  # Avoid repeated downloads         try:             from distutils import log             if delay:                 log.warn(""" --------------------------------------------------------------------------- This script requires setuptools version %s to run (even to display help).  I will attempt to download it for you (from %s), but you may need to enable firewall access for this script first. I will start the download in %d seconds. (Note: if this machine does not have network access, please obtain the file    %s and place it in this directory before rerunning this script.) ---------------------------------------------------------------------------""",                     version, download_base, delay, url                 ); from time import sleep; sleep(delay)             log.warn("Downloading %s", url)             src = urllib2.urlopen(url)             # Read/write all in one block, so we don't create a corrupt file             # if the download is interrupted.             data = _validate_md5(egg_name, src.read())             dst = open(saveto,"wb"); dst.write(data)         finally:             if src: src.close()             if dst: dst.close()     return os.path.realpath(saveto) def main(argv, version=DEFAULT_VERSION):     """Install or upgrade setuptools and EasyInstall"""     try:         import setuptools     except ImportError:         egg = None         try:             egg = download_setuptools(version, delay=0)             sys.path.insert(0,egg)             from setuptools.command.easy_install import main             return main(list(argv)+[egg])   # we're done here         finally:             if egg and os.path.exists(egg):                 os.unlink(egg)     else:         if setuptools.__version__ == '0.0.1':             print &gt;&gt;sys.stderr, (             "You have an obsolete version of setuptools installed.  Please\n"             "remove it from your system entirely before rerunning this script."             )             sys.exit(2)     req = "setuptools&gt;="+version     import pkg_resources     try:         pkg_resources.require(req)     except pkg_resources.VersionConflict:         try:             from setuptools.command.easy_install import main         except ImportError:             from easy_install import main         main(list(argv)+[download_setuptools(delay=0)])         sys.exit(0) # try to force an exit     else:         if argv:             from setuptools.command.easy_install import main             main(argv)         else:             print "Setuptools version",version,"or greater has been installed."             print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)' def update_md5(filenames):     """Update our built-in md5 registry"""     import re     for name in filenames:         base = os.path.basename(name)         f = open(name,'rb')         md5_data[base] = md5(f.read()).hexdigest()         f.close()     data = ["    %r: %r,\n" % it for it in md5_data.items()]     data.sort()     repl = "".join(data)     import inspect     srcfile = inspect.getsourcefile(sys.modules[__name__])     f = open(srcfile, 'rb'); src = f.read(); f.close()     match = re.search("\nmd5_data = {\n([^}]+)}", src)     if not match:         print &gt;&gt;sys.stderr, "Internal error!"         sys.exit(2)     src = src[:match.start(1)] + repl + src[match.end(1):]     f = open(srcfile,'w')     f.write(src)     f.close() if __name__=='__main__':     if len(sys.argv)&gt;2 and sys.argv[1]=='--md5update':         update_md5(sys.argv[2:])     else:         main(sys.argv[1:]) </code></pre>
12
2009-01-19T17:05:36Z
[ "python", "easy-install", "egg" ]
How do I install an .egg file without easy_install in Windows?
458,311
<p>I have Python 2.6 and I want to install easy _ install module. The problem is that the only available installation package of easy _ install for Python 2.6 is an .egg file! What should I do?</p>
14
2009-01-19T16:58:10Z
458,342
<p>Maybe you need to bootstrap setup tools like it's shown here:</p> <p><a href="http://www.ibm.com/developerworks/library/l-cppeak3.html" rel="nofollow">http://www.ibm.com/developerworks/library/l-cppeak3.html</a></p>
2
2009-01-19T17:06:09Z
[ "python", "easy-install", "egg" ]
How do I install an .egg file without easy_install in Windows?
458,311
<p>I have Python 2.6 and I want to install easy _ install module. The problem is that the only available installation package of easy _ install for Python 2.6 is an .egg file! What should I do?</p>
14
2009-01-19T16:58:10Z
1,878,505
<p>sh setuptools-0.6c9-py2.5.egg</p>
5
2009-12-10T03:43:06Z
[ "python", "easy-install", "egg" ]
How do I install an .egg file without easy_install in Windows?
458,311
<p>I have Python 2.6 and I want to install easy _ install module. The problem is that the only available installation package of easy _ install for Python 2.6 is an .egg file! What should I do?</p>
14
2009-01-19T16:58:10Z
10,000,462
<p>MS Windows installer (.exe) <a href="http://pypi.python.org/pypi/setuptools#files" rel="nofollow">http://pypi.python.org/pypi/setuptools#files</a></p>
2
2012-04-03T20:01:06Z
[ "python", "easy-install", "egg" ]
Adding folders to a zip file using python
458,436
<p>I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder.</p> <p>So I want to end up with a zip file with a single folder with files in.</p> <p>I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject.</p> <p>I started out with this:</p> <pre><code>def addFolderToZip(myZipFile,folder): folder = folder.encode('ascii') #convert path to ascii for ZipFile Method for file in glob.glob(folder+"/*"): if os.path.isfile(file): print file myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) elif os.path.isdir(file): addFolderToZip(myZipFile,file) def createZipFile(filename,files,folders): curTime=strftime("__%Y_%m_%d", time.localtime()) filename=filename+curTime; print filename zipFilename=utils.getFileName("files", filename+".zip") myZipFile = zipfile.ZipFile( zipFilename, "w" ) # Open the zip file for writing for file in files: file = file.encode('ascii') #convert path to ascii for ZipFile Method if os.path.isfile(file): (filepath, filename) = os.path.split(file) myZipFile.write( file, filename, zipfile.ZIP_DEFLATED ) for folder in folders: addFolderToZip(myZipFile,folder) myZipFile.close() return (1,zipFilename) (success,filename)=createZipFile(planName,files,folders); </code></pre> <p>Taken from: <a href="http://mail.python.org/pipermail/python-list/2006-August/396166.html">http://mail.python.org/pipermail/python-list/2006-August/396166.html</a></p> <p>Which gets rid of all folders and puts all files in the target folder (and its subfolders) into a single zip file. I couldnt get it to add an entire folder.</p> <p>If I feed the path to a folder in myZipFile.write, I get</p> <blockquote> <p>IOError: [Errno 13] Permission denied: '..\packed\bin'</p> </blockquote> <p>Any help is much welcome.</p> <p>Related question: <a href="http://stackoverflow.com/questions/296499/how-do-i-zip-the-contents-of-a-folder-using-python-version-2-5">How do I zip the contents of a folder using python (version 2.5)?</a></p>
31
2009-01-19T17:33:17Z
458,478
<p>after adding some imports your code runs fine for me, how do you call the script, maybe you could tell us the folder structure of the '..\packed\bin' directory. </p> <p>I called your code with the following arguments:</p> <pre><code>planName='test.zip' files=['z.py',] folders=['c:\\temp'] (success,filename)=createZipFile(planName,files,folders) </code></pre> <p>`</p>
2
2009-01-19T17:47:34Z
[ "python", "file", "zip", "folder", "zipfile" ]
Adding folders to a zip file using python
458,436
<p>I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder.</p> <p>So I want to end up with a zip file with a single folder with files in.</p> <p>I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject.</p> <p>I started out with this:</p> <pre><code>def addFolderToZip(myZipFile,folder): folder = folder.encode('ascii') #convert path to ascii for ZipFile Method for file in glob.glob(folder+"/*"): if os.path.isfile(file): print file myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) elif os.path.isdir(file): addFolderToZip(myZipFile,file) def createZipFile(filename,files,folders): curTime=strftime("__%Y_%m_%d", time.localtime()) filename=filename+curTime; print filename zipFilename=utils.getFileName("files", filename+".zip") myZipFile = zipfile.ZipFile( zipFilename, "w" ) # Open the zip file for writing for file in files: file = file.encode('ascii') #convert path to ascii for ZipFile Method if os.path.isfile(file): (filepath, filename) = os.path.split(file) myZipFile.write( file, filename, zipfile.ZIP_DEFLATED ) for folder in folders: addFolderToZip(myZipFile,folder) myZipFile.close() return (1,zipFilename) (success,filename)=createZipFile(planName,files,folders); </code></pre> <p>Taken from: <a href="http://mail.python.org/pipermail/python-list/2006-August/396166.html">http://mail.python.org/pipermail/python-list/2006-August/396166.html</a></p> <p>Which gets rid of all folders and puts all files in the target folder (and its subfolders) into a single zip file. I couldnt get it to add an entire folder.</p> <p>If I feed the path to a folder in myZipFile.write, I get</p> <blockquote> <p>IOError: [Errno 13] Permission denied: '..\packed\bin'</p> </blockquote> <p>Any help is much welcome.</p> <p>Related question: <a href="http://stackoverflow.com/questions/296499/how-do-i-zip-the-contents-of-a-folder-using-python-version-2-5">How do I zip the contents of a folder using python (version 2.5)?</a></p>
31
2009-01-19T17:33:17Z
459,242
<p>A zip file has no directory structure, it just has a bunch of pathnames and their contents. These pathnames should be relative to an imaginary root folder (the ZIP file itself). "../" prefixes have no defined meaning in a zip file.</p> <p>Consider you have a file, <code>a</code> and you want to store it in a "folder" inside a zip file. All you have to do is prefix the filename with a folder name when storing the file in the zipfile:</p> <pre><code>zipi= zipfile.ZipInfo() zipi.filename= "folder/a" # this is what you want zipi.date_time= time.localtime(os.path.getmtime("a"))[:6] zipi.compress_type= zipfile.ZIP_DEFLATED filedata= open("a", "rb").read() zipfile1.writestr(zipi, filedata) # zipfile1 is a zipfile.ZipFile instance </code></pre> <p>I don't know of any ZIP implementations allowing the inclusion of an <em>empty</em> folder in a ZIP file. I can think of a workaround (storing a <em>dummy</em> filename in the zip "folder" which should be ignored on extraction), but not portable across implementations.</p>
10
2009-01-19T21:34:13Z
[ "python", "file", "zip", "folder", "zipfile" ]
Adding folders to a zip file using python
458,436
<p>I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder.</p> <p>So I want to end up with a zip file with a single folder with files in.</p> <p>I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject.</p> <p>I started out with this:</p> <pre><code>def addFolderToZip(myZipFile,folder): folder = folder.encode('ascii') #convert path to ascii for ZipFile Method for file in glob.glob(folder+"/*"): if os.path.isfile(file): print file myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) elif os.path.isdir(file): addFolderToZip(myZipFile,file) def createZipFile(filename,files,folders): curTime=strftime("__%Y_%m_%d", time.localtime()) filename=filename+curTime; print filename zipFilename=utils.getFileName("files", filename+".zip") myZipFile = zipfile.ZipFile( zipFilename, "w" ) # Open the zip file for writing for file in files: file = file.encode('ascii') #convert path to ascii for ZipFile Method if os.path.isfile(file): (filepath, filename) = os.path.split(file) myZipFile.write( file, filename, zipfile.ZIP_DEFLATED ) for folder in folders: addFolderToZip(myZipFile,folder) myZipFile.close() return (1,zipFilename) (success,filename)=createZipFile(planName,files,folders); </code></pre> <p>Taken from: <a href="http://mail.python.org/pipermail/python-list/2006-August/396166.html">http://mail.python.org/pipermail/python-list/2006-August/396166.html</a></p> <p>Which gets rid of all folders and puts all files in the target folder (and its subfolders) into a single zip file. I couldnt get it to add an entire folder.</p> <p>If I feed the path to a folder in myZipFile.write, I get</p> <blockquote> <p>IOError: [Errno 13] Permission denied: '..\packed\bin'</p> </blockquote> <p>Any help is much welcome.</p> <p>Related question: <a href="http://stackoverflow.com/questions/296499/how-do-i-zip-the-contents-of-a-folder-using-python-version-2-5">How do I zip the contents of a folder using python (version 2.5)?</a></p>
31
2009-01-19T17:33:17Z
459,419
<p>Ok, after i understood what you want, it is as simple as using the second argument of <code>zipfile.write</code>, where you can use whatever you want:</p> <pre><code>import zipfile myZipFile = zipfile.ZipFile("zip.zip", "w" ) myZipFile.write("test.py", "dir\\test.py", zipfile.ZIP_DEFLATED ) </code></pre> <p>creates a zipfile where <code>test.py</code> would be extracted to a directory called <code>dir</code> </p> <p>EDIT: I once had to create an empty directory in a zip file: it is possible. after the code above just delete the file test.py from the zipfile, the file is gone, but the empty directory stays.</p>
30
2009-01-19T22:21:46Z
[ "python", "file", "zip", "folder", "zipfile" ]
Adding folders to a zip file using python
458,436
<p>I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder.</p> <p>So I want to end up with a zip file with a single folder with files in.</p> <p>I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject.</p> <p>I started out with this:</p> <pre><code>def addFolderToZip(myZipFile,folder): folder = folder.encode('ascii') #convert path to ascii for ZipFile Method for file in glob.glob(folder+"/*"): if os.path.isfile(file): print file myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) elif os.path.isdir(file): addFolderToZip(myZipFile,file) def createZipFile(filename,files,folders): curTime=strftime("__%Y_%m_%d", time.localtime()) filename=filename+curTime; print filename zipFilename=utils.getFileName("files", filename+".zip") myZipFile = zipfile.ZipFile( zipFilename, "w" ) # Open the zip file for writing for file in files: file = file.encode('ascii') #convert path to ascii for ZipFile Method if os.path.isfile(file): (filepath, filename) = os.path.split(file) myZipFile.write( file, filename, zipfile.ZIP_DEFLATED ) for folder in folders: addFolderToZip(myZipFile,folder) myZipFile.close() return (1,zipFilename) (success,filename)=createZipFile(planName,files,folders); </code></pre> <p>Taken from: <a href="http://mail.python.org/pipermail/python-list/2006-August/396166.html">http://mail.python.org/pipermail/python-list/2006-August/396166.html</a></p> <p>Which gets rid of all folders and puts all files in the target folder (and its subfolders) into a single zip file. I couldnt get it to add an entire folder.</p> <p>If I feed the path to a folder in myZipFile.write, I get</p> <blockquote> <p>IOError: [Errno 13] Permission denied: '..\packed\bin'</p> </blockquote> <p>Any help is much welcome.</p> <p>Related question: <a href="http://stackoverflow.com/questions/296499/how-do-i-zip-the-contents-of-a-folder-using-python-version-2-5">How do I zip the contents of a folder using python (version 2.5)?</a></p>
31
2009-01-19T17:33:17Z
459,430
<p>Heres the edited code I ran. Its based on the code above, taken from the mailing list. I added the imports and made a main routine. I also cut out the fiddling with the output filename to make the code shorter.</p> <pre><code>#!/usr/bin/env python import os, zipfile, glob, sys def addFolderToZip(myZipFile,folder): folder = folder.encode('ascii') #convert path to ascii for ZipFile Method for file in glob.glob(folder+"/*"): if os.path.isfile(file): print file myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) elif os.path.isdir(file): addFolderToZip(myZipFile,file) def createZipFile(filename,files,folders): myZipFile = zipfile.ZipFile( filename, "w" ) # Open the zip file for writing for file in files: file = file.encode('ascii') #convert path to ascii for ZipFile Method if os.path.isfile(file): (filepath, filename) = os.path.split(file) myZipFile.write( file, filename, zipfile.ZIP_DEFLATED ) for folder in folders: addFolderToZip(myZipFile,folder) myZipFile.close() return (1,filename) if __name__=="__main__": #put everything in sys.argv[1] in out.zip, skip files print createZipFile("out.zip", [], sys.argv[1]) </code></pre> <p>At work, on my Windows box, this code ran fine but didnt create any "folders" in the zipfile. At least I recall it did. Now at home, on my Linux box, the zip file created seems to be bad:</p> <pre><code>$ unzip -l out.zip Archive: out.zip End-of-central-directory signature not found. Either this file is not a zipfile, or it constitutes one disk of a multi-part archive. In the latter case the central directory and zipfile comment will be found on the last disk(s) of this archive. unzip: cannot find zipfile directory in one of out.zip or out.zip.zip, and cannot find out.zip.ZIP, period. </code></pre> <p>I dont know if I accidently broke the code, I think its the same. Crossplatform issues? Either way, its not related to my original question; getting folders in the zip file. Just wanted to post the code I actually ran, not the code I based my code on.</p>
0
2009-01-19T22:26:04Z
[ "python", "file", "zip", "folder", "zipfile" ]
Adding folders to a zip file using python
458,436
<p>I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder.</p> <p>So I want to end up with a zip file with a single folder with files in.</p> <p>I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject.</p> <p>I started out with this:</p> <pre><code>def addFolderToZip(myZipFile,folder): folder = folder.encode('ascii') #convert path to ascii for ZipFile Method for file in glob.glob(folder+"/*"): if os.path.isfile(file): print file myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) elif os.path.isdir(file): addFolderToZip(myZipFile,file) def createZipFile(filename,files,folders): curTime=strftime("__%Y_%m_%d", time.localtime()) filename=filename+curTime; print filename zipFilename=utils.getFileName("files", filename+".zip") myZipFile = zipfile.ZipFile( zipFilename, "w" ) # Open the zip file for writing for file in files: file = file.encode('ascii') #convert path to ascii for ZipFile Method if os.path.isfile(file): (filepath, filename) = os.path.split(file) myZipFile.write( file, filename, zipfile.ZIP_DEFLATED ) for folder in folders: addFolderToZip(myZipFile,folder) myZipFile.close() return (1,zipFilename) (success,filename)=createZipFile(planName,files,folders); </code></pre> <p>Taken from: <a href="http://mail.python.org/pipermail/python-list/2006-August/396166.html">http://mail.python.org/pipermail/python-list/2006-August/396166.html</a></p> <p>Which gets rid of all folders and puts all files in the target folder (and its subfolders) into a single zip file. I couldnt get it to add an entire folder.</p> <p>If I feed the path to a folder in myZipFile.write, I get</p> <blockquote> <p>IOError: [Errno 13] Permission denied: '..\packed\bin'</p> </blockquote> <p>Any help is much welcome.</p> <p>Related question: <a href="http://stackoverflow.com/questions/296499/how-do-i-zip-the-contents-of-a-folder-using-python-version-2-5">How do I zip the contents of a folder using python (version 2.5)?</a></p>
31
2009-01-19T17:33:17Z
670,635
<pre><code>import zipfile import os class ZipUtilities: def toZip(self, file, filename): zip_file = zipfile.ZipFile(filename, 'w') if os.path.isfile(file): zip_file.write(file) else: self.addFolderToZip(zip_file, file) zip_file.close() def addFolderToZip(self, zip_file, folder): for file in os.listdir(folder): full_path = os.path.join(folder, file) if os.path.isfile(full_path): print 'File added: ' + str(full_path) zip_file.write(full_path) elif os.path.isdir(full_path): print 'Entering folder: ' + str(full_path) self.addFolderToZip(zip_file, full_path) def main(): utilities = ZipUtilities() filename = 'TEMP.zip' directory = 'TEMP' utilities.toZip(directory, filename) main() </code></pre> <p>I'm running:</p> <pre><code>python tozip.py </code></pre> <p>This is the log:</p> <pre><code>havok@fireshield:~$ python tozip.py File added: TEMP/NARF (7ª copia) Entering folder: TEMP/TEMP2 File added: TEMP/TEMP2/NERF (otra copia) File added: TEMP/TEMP2/NERF (copia) File added: TEMP/TEMP2/NARF File added: TEMP/TEMP2/NARF (copia) File added: TEMP/TEMP2/NARF (otra copia) Entering folder: TEMP/TEMP2/TEMP3 File added: TEMP/TEMP2/TEMP3/DOCUMENTO DEL FINAL File added: TEMP/TEMP2/TEMP3/DOCUMENTO DEL FINAL (copia) File added: TEMP/TEMP2/NERF File added: TEMP/NARF (copia) (otra copia) File added: TEMP/NARF (copia) (copia) File added: TEMP/NARF (6ª copia) File added: TEMP/NERF (copia) (otra copia) File added: TEMP/NERF (4ª copia) File added: TEMP/NERF (otra copia) File added: TEMP/NERF (3ª copia) File added: TEMP/NERF (6ª copia) File added: TEMP/NERF (copia) File added: TEMP/NERF (5ª copia) File added: TEMP/NARF (8ª copia) File added: TEMP/NARF (3ª copia) File added: TEMP/NARF (5ª copia) File added: TEMP/NERF (copia) (3ª copia) File added: TEMP/NARF File added: TEMP/NERF (copia) (copia) File added: TEMP/NERF (8ª copia) File added: TEMP/NERF (7ª copia) File added: TEMP/NARF (copia) File added: TEMP/NARF (otra copia) File added: TEMP/NARF (4ª copia) File added: TEMP/NERF File added: TEMP/NARF (copia) (3ª copia) </code></pre> <p>As you can see, it work, the archive is ok too. This is a recursive function that can zip an entire folder. The only problem is that it doesn't create a empty folder.</p> <p>Cheers.</p>
4
2009-03-22T07:03:11Z
[ "python", "file", "zip", "folder", "zipfile" ]
Adding folders to a zip file using python
458,436
<p>I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder.</p> <p>So I want to end up with a zip file with a single folder with files in.</p> <p>I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject.</p> <p>I started out with this:</p> <pre><code>def addFolderToZip(myZipFile,folder): folder = folder.encode('ascii') #convert path to ascii for ZipFile Method for file in glob.glob(folder+"/*"): if os.path.isfile(file): print file myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) elif os.path.isdir(file): addFolderToZip(myZipFile,file) def createZipFile(filename,files,folders): curTime=strftime("__%Y_%m_%d", time.localtime()) filename=filename+curTime; print filename zipFilename=utils.getFileName("files", filename+".zip") myZipFile = zipfile.ZipFile( zipFilename, "w" ) # Open the zip file for writing for file in files: file = file.encode('ascii') #convert path to ascii for ZipFile Method if os.path.isfile(file): (filepath, filename) = os.path.split(file) myZipFile.write( file, filename, zipfile.ZIP_DEFLATED ) for folder in folders: addFolderToZip(myZipFile,folder) myZipFile.close() return (1,zipFilename) (success,filename)=createZipFile(planName,files,folders); </code></pre> <p>Taken from: <a href="http://mail.python.org/pipermail/python-list/2006-August/396166.html">http://mail.python.org/pipermail/python-list/2006-August/396166.html</a></p> <p>Which gets rid of all folders and puts all files in the target folder (and its subfolders) into a single zip file. I couldnt get it to add an entire folder.</p> <p>If I feed the path to a folder in myZipFile.write, I get</p> <blockquote> <p>IOError: [Errno 13] Permission denied: '..\packed\bin'</p> </blockquote> <p>Any help is much welcome.</p> <p>Related question: <a href="http://stackoverflow.com/questions/296499/how-do-i-zip-the-contents-of-a-folder-using-python-version-2-5">How do I zip the contents of a folder using python (version 2.5)?</a></p>
31
2009-01-19T17:33:17Z
676,492
<p>When you wanna create an empty folder, you can do it like this: </p> <pre><code> storage = api.Storage.open("empty_folder.zip","w") res = storage.open_resource("hannu//","w") storage.close() </code></pre> <p>Folder not showe in winextractor, but when you extract it it is showed.</p>
-2
2009-03-24T08:06:09Z
[ "python", "file", "zip", "folder", "zipfile" ]
Adding folders to a zip file using python
458,436
<p>I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder.</p> <p>So I want to end up with a zip file with a single folder with files in.</p> <p>I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject.</p> <p>I started out with this:</p> <pre><code>def addFolderToZip(myZipFile,folder): folder = folder.encode('ascii') #convert path to ascii for ZipFile Method for file in glob.glob(folder+"/*"): if os.path.isfile(file): print file myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) elif os.path.isdir(file): addFolderToZip(myZipFile,file) def createZipFile(filename,files,folders): curTime=strftime("__%Y_%m_%d", time.localtime()) filename=filename+curTime; print filename zipFilename=utils.getFileName("files", filename+".zip") myZipFile = zipfile.ZipFile( zipFilename, "w" ) # Open the zip file for writing for file in files: file = file.encode('ascii') #convert path to ascii for ZipFile Method if os.path.isfile(file): (filepath, filename) = os.path.split(file) myZipFile.write( file, filename, zipfile.ZIP_DEFLATED ) for folder in folders: addFolderToZip(myZipFile,folder) myZipFile.close() return (1,zipFilename) (success,filename)=createZipFile(planName,files,folders); </code></pre> <p>Taken from: <a href="http://mail.python.org/pipermail/python-list/2006-August/396166.html">http://mail.python.org/pipermail/python-list/2006-August/396166.html</a></p> <p>Which gets rid of all folders and puts all files in the target folder (and its subfolders) into a single zip file. I couldnt get it to add an entire folder.</p> <p>If I feed the path to a folder in myZipFile.write, I get</p> <blockquote> <p>IOError: [Errno 13] Permission denied: '..\packed\bin'</p> </blockquote> <p>Any help is much welcome.</p> <p>Related question: <a href="http://stackoverflow.com/questions/296499/how-do-i-zip-the-contents-of-a-folder-using-python-version-2-5">How do I zip the contents of a folder using python (version 2.5)?</a></p>
31
2009-01-19T17:33:17Z
792,199
<p>Below is some code for zipping an entire directory into a zipfile.</p> <p>This seems to work OK creating zip files on both windows and linux. The output files seem to extract properly on windows (built-in Compressed Folders feature, WinZip, and 7-Zip) and linux. However, empty directories in a zip file appear to be a thorny issue. The solution below seems to work but the output of "zipinfo" on linux is concerning. Also the directory permissions are not set correctly for empty directories in the zip archive. This appears to require some more in depth research.</p> <p>I got some info from <a href="http://www.velocityreviews.com/forums/t318840-add-empty-directory-using-zipfile.html" rel="nofollow">this velocity reviews thread</a> and <a href="http://mail.python.org/pipermail/python-list/2006-January/535240.html" rel="nofollow">this python mailing list thread</a>.</p> <p>Note that this function is designed to put files in the zip archive with either no parent directory or just one parent directory, so it will trim any leading directories in the filesystem paths and not include them inside the zip archive paths. This is generally the case when you want to just take a directory and make it into a zip file that can be extracted in different locations. </p> <p>Keyword arguments:</p> <p>dirPath -- string path to the directory to archive. This is the only required argument. It can be absolute or relative, but only one or zero leading directories will be included in the zip archive.</p> <p>zipFilePath -- string path to the output zip file. This can be an absolute or relative path. If the zip file already exists, it will be updated. If not, it will be created. If you want to replace it from scratch, delete it prior to calling this function. (default is computed as dirPath + ".zip")</p> <p>includeDirInZip -- boolean indicating whether the top level directory should be included in the archive or omitted. (default True)</p> <p>(Note that StackOverflow seems to be failing to pretty print my python with triple quoted strings, so I just converted my doc strings to the post text here)</p> <pre><code>#!/usr/bin/python import os import zipfile def zipdir(dirPath=None, zipFilePath=None, includeDirInZip=True): if not zipFilePath: zipFilePath = dirPath + ".zip" if not os.path.isdir(dirPath): raise OSError("dirPath argument must point to a directory. " "'%s' does not." % dirPath) parentDir, dirToZip = os.path.split(dirPath) #Little nested function to prepare the proper archive path def trimPath(path): archivePath = path.replace(parentDir, "", 1) if parentDir: archivePath = archivePath.replace(os.path.sep, "", 1) if not includeDirInZip: archivePath = archivePath.replace(dirToZip + os.path.sep, "", 1) return os.path.normcase(archivePath) outFile = zipfile.ZipFile(zipFilePath, "w", compression=zipfile.ZIP_DEFLATED) for (archiveDirPath, dirNames, fileNames) in os.walk(dirPath): for fileName in fileNames: filePath = os.path.join(archiveDirPath, fileName) outFile.write(filePath, trimPath(filePath)) #Make sure we get empty directories as well if not fileNames and not dirNames: zipInfo = zipfile.ZipInfo(trimPath(archiveDirPath) + "/") #some web sites suggest doing #zipInfo.external_attr = 16 #or #zipInfo.external_attr = 48 #Here to allow for inserting an empty directory. Still TBD/TODO. outFile.writestr(zipInfo, "") outFile.close() </code></pre> <p>Here's some sample usages. Note that if your dirPath argument has several leading directories, only the LAST one will be included by default. Pass includeDirInZip=False to omit all leading directories.</p> <pre><code>zipdir("foo") #Just give it a dir and get a .zip file zipdir("foo", "foo2.zip") #Get a .zip file with a specific file name zipdir("foo", "foo3nodir.zip", False) #Omit the top level directory zipdir("../test1/foo", "foo4nopardirs.zip") </code></pre>
4
2009-04-27T03:53:45Z
[ "python", "file", "zip", "folder", "zipfile" ]
Adding folders to a zip file using python
458,436
<p>I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder.</p> <p>So I want to end up with a zip file with a single folder with files in.</p> <p>I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject.</p> <p>I started out with this:</p> <pre><code>def addFolderToZip(myZipFile,folder): folder = folder.encode('ascii') #convert path to ascii for ZipFile Method for file in glob.glob(folder+"/*"): if os.path.isfile(file): print file myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) elif os.path.isdir(file): addFolderToZip(myZipFile,file) def createZipFile(filename,files,folders): curTime=strftime("__%Y_%m_%d", time.localtime()) filename=filename+curTime; print filename zipFilename=utils.getFileName("files", filename+".zip") myZipFile = zipfile.ZipFile( zipFilename, "w" ) # Open the zip file for writing for file in files: file = file.encode('ascii') #convert path to ascii for ZipFile Method if os.path.isfile(file): (filepath, filename) = os.path.split(file) myZipFile.write( file, filename, zipfile.ZIP_DEFLATED ) for folder in folders: addFolderToZip(myZipFile,folder) myZipFile.close() return (1,zipFilename) (success,filename)=createZipFile(planName,files,folders); </code></pre> <p>Taken from: <a href="http://mail.python.org/pipermail/python-list/2006-August/396166.html">http://mail.python.org/pipermail/python-list/2006-August/396166.html</a></p> <p>Which gets rid of all folders and puts all files in the target folder (and its subfolders) into a single zip file. I couldnt get it to add an entire folder.</p> <p>If I feed the path to a folder in myZipFile.write, I get</p> <blockquote> <p>IOError: [Errno 13] Permission denied: '..\packed\bin'</p> </blockquote> <p>Any help is much welcome.</p> <p>Related question: <a href="http://stackoverflow.com/questions/296499/how-do-i-zip-the-contents-of-a-folder-using-python-version-2-5">How do I zip the contents of a folder using python (version 2.5)?</a></p>
31
2009-01-19T17:33:17Z
1,544,983
<p>here is my function i use to zip a folder:</p> <pre><code>import os import os.path import zipfile def zip_dir(dirpath, zippath): fzip = zipfile.ZipFile(zippath, 'w', zipfile.ZIP_DEFLATED) basedir = os.path.dirname(dirpath) + '/' for root, dirs, files in os.walk(dirpath): if os.path.basename(root)[0] == '.': continue #skip hidden directories dirname = root.replace(basedir, '') for f in files: if f[-1] == '~' or (f[0] == '.' and f != '.htaccess'): #skip backup files and all hidden files except .htaccess continue fzip.write(root + '/' + f, dirname + '/' + f) fzip.close() </code></pre>
2
2009-10-09T17:04:44Z
[ "python", "file", "zip", "folder", "zipfile" ]
Adding folders to a zip file using python
458,436
<p>I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder.</p> <p>So I want to end up with a zip file with a single folder with files in.</p> <p>I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject.</p> <p>I started out with this:</p> <pre><code>def addFolderToZip(myZipFile,folder): folder = folder.encode('ascii') #convert path to ascii for ZipFile Method for file in glob.glob(folder+"/*"): if os.path.isfile(file): print file myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) elif os.path.isdir(file): addFolderToZip(myZipFile,file) def createZipFile(filename,files,folders): curTime=strftime("__%Y_%m_%d", time.localtime()) filename=filename+curTime; print filename zipFilename=utils.getFileName("files", filename+".zip") myZipFile = zipfile.ZipFile( zipFilename, "w" ) # Open the zip file for writing for file in files: file = file.encode('ascii') #convert path to ascii for ZipFile Method if os.path.isfile(file): (filepath, filename) = os.path.split(file) myZipFile.write( file, filename, zipfile.ZIP_DEFLATED ) for folder in folders: addFolderToZip(myZipFile,folder) myZipFile.close() return (1,zipFilename) (success,filename)=createZipFile(planName,files,folders); </code></pre> <p>Taken from: <a href="http://mail.python.org/pipermail/python-list/2006-August/396166.html">http://mail.python.org/pipermail/python-list/2006-August/396166.html</a></p> <p>Which gets rid of all folders and puts all files in the target folder (and its subfolders) into a single zip file. I couldnt get it to add an entire folder.</p> <p>If I feed the path to a folder in myZipFile.write, I get</p> <blockquote> <p>IOError: [Errno 13] Permission denied: '..\packed\bin'</p> </blockquote> <p>Any help is much welcome.</p> <p>Related question: <a href="http://stackoverflow.com/questions/296499/how-do-i-zip-the-contents-of-a-folder-using-python-version-2-5">How do I zip the contents of a folder using python (version 2.5)?</a></p>
31
2009-01-19T17:33:17Z
1,906,438
<p>Thank you wery much for this useful function! I found it very useful as I was also searching for help. However, maybe it would be useful to change it a little bit so that </p> <pre><code>basedir = os.path.dirname(dirpath) + '/' </code></pre> <p>would be </p> <pre><code>basedir = os.path.dirname(dirpath + '/') </code></pre> <p>Because found that if I want to zip folder 'Example' which is located at 'C:\folder\path\notWanted\to\zip\Example',</p> <p>I got in Windows:</p> <pre><code>dirpath = 'C:\folder\path\notWanted\to\zip\Example' basedir = 'C:\folder\path\notWanted\to\zip\Example/' dirname = 'C:\folder\path\notWanted\to\zip\Example\Example\Subfolder_etc' </code></pre> <p>But I suppose your code should give</p> <pre><code>dirpath = 'C:\folder\path\notWanted\to\zip\Example' basedir = 'C:\folder\path\notWanted\to\zip\Example\' dirname = '\Subfolder_etc' </code></pre>
0
2009-12-15T10:17:30Z
[ "python", "file", "zip", "folder", "zipfile" ]
Adding folders to a zip file using python
458,436
<p>I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder.</p> <p>So I want to end up with a zip file with a single folder with files in.</p> <p>I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject.</p> <p>I started out with this:</p> <pre><code>def addFolderToZip(myZipFile,folder): folder = folder.encode('ascii') #convert path to ascii for ZipFile Method for file in glob.glob(folder+"/*"): if os.path.isfile(file): print file myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) elif os.path.isdir(file): addFolderToZip(myZipFile,file) def createZipFile(filename,files,folders): curTime=strftime("__%Y_%m_%d", time.localtime()) filename=filename+curTime; print filename zipFilename=utils.getFileName("files", filename+".zip") myZipFile = zipfile.ZipFile( zipFilename, "w" ) # Open the zip file for writing for file in files: file = file.encode('ascii') #convert path to ascii for ZipFile Method if os.path.isfile(file): (filepath, filename) = os.path.split(file) myZipFile.write( file, filename, zipfile.ZIP_DEFLATED ) for folder in folders: addFolderToZip(myZipFile,folder) myZipFile.close() return (1,zipFilename) (success,filename)=createZipFile(planName,files,folders); </code></pre> <p>Taken from: <a href="http://mail.python.org/pipermail/python-list/2006-August/396166.html">http://mail.python.org/pipermail/python-list/2006-August/396166.html</a></p> <p>Which gets rid of all folders and puts all files in the target folder (and its subfolders) into a single zip file. I couldnt get it to add an entire folder.</p> <p>If I feed the path to a folder in myZipFile.write, I get</p> <blockquote> <p>IOError: [Errno 13] Permission denied: '..\packed\bin'</p> </blockquote> <p>Any help is much welcome.</p> <p>Related question: <a href="http://stackoverflow.com/questions/296499/how-do-i-zip-the-contents-of-a-folder-using-python-version-2-5">How do I zip the contents of a folder using python (version 2.5)?</a></p>
31
2009-01-19T17:33:17Z
6,511,788
<p>You can also use shutil</p> <pre><code>import shutil shutil.make_archive("desired_zipfile_name_no", "zip", "name_of_the_folder_you_want_to_zip") </code></pre> <p>This will put the whole folder in the zip.</p>
44
2011-06-28T19:05:19Z
[ "python", "file", "zip", "folder", "zipfile" ]
Adding folders to a zip file using python
458,436
<p>I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder.</p> <p>So I want to end up with a zip file with a single folder with files in.</p> <p>I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject.</p> <p>I started out with this:</p> <pre><code>def addFolderToZip(myZipFile,folder): folder = folder.encode('ascii') #convert path to ascii for ZipFile Method for file in glob.glob(folder+"/*"): if os.path.isfile(file): print file myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) elif os.path.isdir(file): addFolderToZip(myZipFile,file) def createZipFile(filename,files,folders): curTime=strftime("__%Y_%m_%d", time.localtime()) filename=filename+curTime; print filename zipFilename=utils.getFileName("files", filename+".zip") myZipFile = zipfile.ZipFile( zipFilename, "w" ) # Open the zip file for writing for file in files: file = file.encode('ascii') #convert path to ascii for ZipFile Method if os.path.isfile(file): (filepath, filename) = os.path.split(file) myZipFile.write( file, filename, zipfile.ZIP_DEFLATED ) for folder in folders: addFolderToZip(myZipFile,folder) myZipFile.close() return (1,zipFilename) (success,filename)=createZipFile(planName,files,folders); </code></pre> <p>Taken from: <a href="http://mail.python.org/pipermail/python-list/2006-August/396166.html">http://mail.python.org/pipermail/python-list/2006-August/396166.html</a></p> <p>Which gets rid of all folders and puts all files in the target folder (and its subfolders) into a single zip file. I couldnt get it to add an entire folder.</p> <p>If I feed the path to a folder in myZipFile.write, I get</p> <blockquote> <p>IOError: [Errno 13] Permission denied: '..\packed\bin'</p> </blockquote> <p>Any help is much welcome.</p> <p>Related question: <a href="http://stackoverflow.com/questions/296499/how-do-i-zip-the-contents-of-a-folder-using-python-version-2-5">How do I zip the contents of a folder using python (version 2.5)?</a></p>
31
2009-01-19T17:33:17Z
18,295,769
<p>If you look at a zip file created with Info-ZIP, you'll see that directories are indeed listed:</p> <pre><code>$ zip foo.zip -r foo adding: foo/ (stored 0%) adding: foo/foo.jpg (deflated 84%) $ less foo.zip Archive: foo.zip Length Method Size Cmpr Date Time CRC-32 Name -------- ------ ------- ---- ---------- ----- -------- ---- 0 Stored 0 0% 2013-08-18 14:32 00000000 foo/ 476320 Defl:N 77941 84% 2013-08-18 14:31 55a52268 foo/foo.jpg -------- ------- --- ------- 476320 77941 84% 2 files </code></pre> <p>Notice that the directory entry has zero length and is not compressed. It seems you can achieve the same thing with Python by writing the directory by name, but forcing it to not use compression.</p> <pre><code>if os.path.isdir(name): zf.write(name, arcname=arcname, compress_type=zipfile.ZIP_STORED) else: zf.write(name, arcname=arcname, compress_type=zipfile.ZIP_DEFLATED) </code></pre> <p>It might be worth making sure <code>arcname</code> ends in a <code>/</code>.</p>
1
2013-08-18T04:41:39Z
[ "python", "file", "zip", "folder", "zipfile" ]
Adding folders to a zip file using python
458,436
<p>I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder.</p> <p>So I want to end up with a zip file with a single folder with files in.</p> <p>I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject.</p> <p>I started out with this:</p> <pre><code>def addFolderToZip(myZipFile,folder): folder = folder.encode('ascii') #convert path to ascii for ZipFile Method for file in glob.glob(folder+"/*"): if os.path.isfile(file): print file myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) elif os.path.isdir(file): addFolderToZip(myZipFile,file) def createZipFile(filename,files,folders): curTime=strftime("__%Y_%m_%d", time.localtime()) filename=filename+curTime; print filename zipFilename=utils.getFileName("files", filename+".zip") myZipFile = zipfile.ZipFile( zipFilename, "w" ) # Open the zip file for writing for file in files: file = file.encode('ascii') #convert path to ascii for ZipFile Method if os.path.isfile(file): (filepath, filename) = os.path.split(file) myZipFile.write( file, filename, zipfile.ZIP_DEFLATED ) for folder in folders: addFolderToZip(myZipFile,folder) myZipFile.close() return (1,zipFilename) (success,filename)=createZipFile(planName,files,folders); </code></pre> <p>Taken from: <a href="http://mail.python.org/pipermail/python-list/2006-August/396166.html">http://mail.python.org/pipermail/python-list/2006-August/396166.html</a></p> <p>Which gets rid of all folders and puts all files in the target folder (and its subfolders) into a single zip file. I couldnt get it to add an entire folder.</p> <p>If I feed the path to a folder in myZipFile.write, I get</p> <blockquote> <p>IOError: [Errno 13] Permission denied: '..\packed\bin'</p> </blockquote> <p>Any help is much welcome.</p> <p>Related question: <a href="http://stackoverflow.com/questions/296499/how-do-i-zip-the-contents-of-a-folder-using-python-version-2-5">How do I zip the contents of a folder using python (version 2.5)?</a></p>
31
2009-01-19T17:33:17Z
25,898,859
<pre><code>import os import zipfile zf = zipfile.ZipFile("file.zip", "w") for file in os.listdir(os.curdir): if not file.endswith('.zip') and os.path.isfile(os.curdir+'/'+file): print file zf.write(file) elif os.path.isdir(os.curdir+'/'+file): print f for f in os.listdir(os.curdir+'/'+file): zf.write(file+'\\'+f) zf.close() </code></pre>
0
2014-09-17T19:32:24Z
[ "python", "file", "zip", "folder", "zipfile" ]
Standard way to embed version into python package?
458,550
<p>Is there a standard way to associate version string with a python package in such way that I could do the following?</p> <pre><code>import foo print foo.version </code></pre> <p>I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in <code>setup.py</code> already. Alternative solution that I found was to have <code>import __version__</code> in my <code>foo/__init__.py</code> and then have <code>__version__.py</code> generated by <code>setup.py</code>.</p>
126
2009-01-19T18:05:54Z
458,658
<p>For what it's worth, if you're using NumPy distutils, <code>numpy.distutils.misc_util.Configuration</code> has a <a href="http://docs.scipy.org/doc/numpy/reference/distutils.html#numpy.distutils.misc_util.Configuration.make_svn_version_py" rel="nofollow"><code>make_svn_version_py()</code></a> method that embeds the revision number inside <code>package.__svn_version__</code> in the variable <code>version</code> .</p>
0
2009-01-19T18:42:23Z
[ "python", "string", "package" ]
Standard way to embed version into python package?
458,550
<p>Is there a standard way to associate version string with a python package in such way that I could do the following?</p> <pre><code>import foo print foo.version </code></pre> <p>I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in <code>setup.py</code> already. Alternative solution that I found was to have <code>import __version__</code> in my <code>foo/__init__.py</code> and then have <code>__version__.py</code> generated by <code>setup.py</code>.</p>
126
2009-01-19T18:05:54Z
458,684
<p>There doesn't seem to be a standard way to embed a version string in a python package. Most packages I've seen use some variant of your solution, i.e. eitner</p> <ol> <li><p>Embed the version in <code>setup.py</code> and have <code>setup.py</code> generate a module (e.g. <code>version.py</code>) containing only version info, that's imported by your package, or</p></li> <li><p>The reverse: put the version info in your package itself, and import <em>that</em> to set the version in <code>setup.py</code> </p></li> </ol>
5
2009-01-19T18:49:58Z
[ "python", "string", "package" ]
Standard way to embed version into python package?
458,550
<p>Is there a standard way to associate version string with a python package in such way that I could do the following?</p> <pre><code>import foo print foo.version </code></pre> <p>I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in <code>setup.py</code> already. Alternative solution that I found was to have <code>import __version__</code> in my <code>foo/__init__.py</code> and then have <code>__version__.py</code> generated by <code>setup.py</code>.</p>
126
2009-01-19T18:05:54Z
459,185
<p>Not directly an answer to your question, but you should consider naming it <code>__version__</code>, not <code>version</code>.</p> <p>This is almost a quasi-standard. Many modules in the standard library use <code>__version__</code>, and this is also used in <a href="http://www.google.com/codesearch?as_q=__version__&amp;btnG=Search+Code&amp;hl=en&amp;as_lang=python&amp;as_license_restrict=i&amp;as_license=&amp;as_package=&amp;as_filename=&amp;as_case=">lots</a> of 3rd-party modules, so it's the quasi-standard.</p> <p>Usually, <code>__version__</code> is a string, but sometimes it's also a float or tuple.</p> <p>Edit: as mentioned by S.Lott (Thank you!), <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> says it explicitly:</p> <blockquote> <p>Version Bookkeeping</p> <p>If you have to have Subversion, CVS, or RCS crud in your source file, do it as follows.</p> <pre><code> __version__ = "$Revision: 63990 $" # $Source$ </code></pre> <p>These lines should be included after the module's docstring, before any other code, separated by a blank line above and below.</p> </blockquote> <p>You should also make sure that the version number conforms to the format described in <a href="http://www.python.org/dev/peps/pep-0440/">PEP 440</a> (<a href="http://www.python.org/dev/peps/pep-0386/">PEP 386</a> a previous version of this standard).</p>
64
2009-01-19T21:13:57Z
[ "python", "string", "package" ]
Standard way to embed version into python package?
458,550
<p>Is there a standard way to associate version string with a python package in such way that I could do the following?</p> <pre><code>import foo print foo.version </code></pre> <p>I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in <code>setup.py</code> already. Alternative solution that I found was to have <code>import __version__</code> in my <code>foo/__init__.py</code> and then have <code>__version__.py</code> generated by <code>setup.py</code>.</p>
126
2009-01-19T18:05:54Z
466,694
<p>Also worth noting is that as well as <code>__version__</code> being a semi-std. in python so is <code>__version_info__</code> which is a tuple, in the simple cases you can just do something like:</p> <pre><code>__version__ = '1.2.3' __version_info__ = tuple([ int(num) for num in __version__.split('.')]) </code></pre> <p>...and you can get the <code>__version__</code> string from a file, or whatever.</p>
3
2009-01-21T19:44:24Z
[ "python", "string", "package" ]
Standard way to embed version into python package?
458,550
<p>Is there a standard way to associate version string with a python package in such way that I could do the following?</p> <pre><code>import foo print foo.version </code></pre> <p>I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in <code>setup.py</code> already. Alternative solution that I found was to have <code>import __version__</code> in my <code>foo/__init__.py</code> and then have <code>__version__.py</code> generated by <code>setup.py</code>.</p>
126
2009-01-19T18:05:54Z
1,131,751
<p>Though this is probably far too late, there is a slightly simpler alternative to the previous answer:</p> <pre><code>__version_info__ = ('1', '2', '3') __version__ = '.'.join(__version_info__) </code></pre> <p>(And it would be fairly simple to convert auto-incrementing portions of version numbers to a string using <code>str()</code>.)</p> <p>Of course, from what I've seen, people tend to use something like the previously-mentioned version when using <code>__version_info__</code>, and as such store it as a tuple of ints; however, I don't quite see the point in doing so, as I doubt there are situations where you would perform mathematical operations such as addition and subtraction on portions of version numbers for any purpose besides curiosity or auto-incrementation (and even then, <code>int()</code> and <code>str()</code> can be used fairly easily). (On the other hand, there is the possibility of someone else's code expecting a numerical tuple rather than a string tuple and thus failing.)</p> <p>This is, of course, my own view, and I would gladly like others' input on using a numerical tuple.</p> <hr> <p>As shezi reminded me, (lexical) comparisons of number strings do not necessarily have the same result as direct numerical comparisons; leading zeroes would be required to provide for that. So in the end, storing <code>__version_info__</code> (or whatever it would be called) as a tuple of integer values would allow for more efficient version comparisons.</p>
17
2009-07-15T14:29:04Z
[ "python", "string", "package" ]
Standard way to embed version into python package?
458,550
<p>Is there a standard way to associate version string with a python package in such way that I could do the following?</p> <pre><code>import foo print foo.version </code></pre> <p>I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in <code>setup.py</code> already. Alternative solution that I found was to have <code>import __version__</code> in my <code>foo/__init__.py</code> and then have <code>__version__.py</code> generated by <code>setup.py</code>.</p>
126
2009-01-19T18:05:54Z
1,551,226
<p>I also saw another style:</p> <pre><code>&gt;&gt;&gt; django.VERSION (1, 1, 0, 'final', 0) </code></pre>
5
2009-10-11T17:32:47Z
[ "python", "string", "package" ]
Standard way to embed version into python package?
458,550
<p>Is there a standard way to associate version string with a python package in such way that I could do the following?</p> <pre><code>import foo print foo.version </code></pre> <p>I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in <code>setup.py</code> already. Alternative solution that I found was to have <code>import __version__</code> in my <code>foo/__init__.py</code> and then have <code>__version__.py</code> generated by <code>setup.py</code>.</p>
126
2009-01-19T18:05:54Z
7,071,358
<p>Here is how I do this. Advantages of the following method:</p> <ol> <li><p>It provides a <code>__version__</code> attribute.</p></li> <li><p>It provides the standard metadata version. Therefore it will be detected by <code>pkg_resources</code> or other tools that parse the package metadata (EGG-INFO and/or PKG-INFO, PEP 0345).</p></li> <li><p>It doesn't import your package (or anything else) when building your package, which can cause problems in some situations. (See the comments below about what problems this can cause.)</p></li> <li><p>There is only one place that the version number is written down, so there is only one place to change it when the version number changes, and there is less chance of inconsistent versions.</p></li> </ol> <p>Here is how it works: the "one canonical place" to store the version number is a .py file, named "_version.py" which is in your Python package, for example in <code>myniftyapp/_version.py</code>. This file is a Python module, but your setup.py doesn't import it! (That would defeat feature 3.) Instead your setup.py knows that the contents of this file is very simple, something like:</p> <pre><code>__version__ = "3.6.5" </code></pre> <p>And so your setup.py opens the file and parses it, with code like:</p> <pre><code>import re VERSIONFILE="myniftyapp/_version.py" verstrline = open(VERSIONFILE, "rt").read() VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]" mo = re.search(VSRE, verstrline, re.M) if mo: verstr = mo.group(1) else: raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE,)) </code></pre> <p>Then your setup.py passes that string as the value of the "version" argument to <code>setup()</code>, thus satisfying feature 2.</p> <p>To satisfy feature 1, you can have your package (at run-time, not at setup time!) import the _version file from <code>myniftyapp/__init__.py</code> like this:</p> <pre><code>from _version import __version__ </code></pre> <p>Here is <a href="https://tahoe-lafs.org/trac/zfec/browser/trunk/zfec/setup.py?rev=390#L84">an example of this technique</a> that I've been using for years.</p> <p>The code in that example is a bit more complicated, but the simplified example that I wrote into this comment should be a complete implementation.</p> <p>Here is <a href="https://tahoe-lafs.org/trac/zfec/browser/trunk/zfec/zfec/__init__.py?rev=363">example code of importing the version</a>.</p> <p>If you see anything wrong with this approach, please let me know: zooko at zooko dot com. If you don't see anything wrong with this approach then use it! Because the more packages come with their version numbers in the expected places the better!</p>
67
2011-08-15T22:04:35Z
[ "python", "string", "package" ]
Standard way to embed version into python package?
458,550
<p>Is there a standard way to associate version string with a python package in such way that I could do the following?</p> <pre><code>import foo print foo.version </code></pre> <p>I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in <code>setup.py</code> already. Alternative solution that I found was to have <code>import __version__</code> in my <code>foo/__init__.py</code> and then have <code>__version__.py</code> generated by <code>setup.py</code>.</p>
126
2009-01-19T18:05:54Z
15,952,533
<p>Many of the existing answers argue that "There doesn't seem to be a standard way" or that a style "is almost a quasi-standard."</p> <p>In fact <em>there is a standard way</em> to do this<sup>*</sup>:</p> <ul> <li><strong><a href="http://www.python.org/dev/peps/pep-0396/">PEP 396</a>: Module Version Numbers</strong></li> </ul> <p>This describes, with rationale, an (admittedly optional) standard for modules to follow. Here's a snippet: </p> <blockquote> <p>3) When a module (or package) includes a version number, the version SHOULD be available in the <code>__version__</code> attribute.</p> <p>4) For modules which live inside a namespace package, the module SHOULD include the <code>__version__</code> attribute. The namespace package itself SHOULD NOT include its own <code>__version__</code> attribute.</p> <p>5) The <code>__version__</code> attribute's value SHOULD be a string.</p> </blockquote> <p><sup>*</sup> Edited to add: As per the comments, this actually is <strong>not</strong> an accepted standard; it was deferred.</p>
19
2013-04-11T15:16:03Z
[ "python", "string", "package" ]
Standard way to embed version into python package?
458,550
<p>Is there a standard way to associate version string with a python package in such way that I could do the following?</p> <pre><code>import foo print foo.version </code></pre> <p>I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in <code>setup.py</code> already. Alternative solution that I found was to have <code>import __version__</code> in my <code>foo/__init__.py</code> and then have <code>__version__.py</code> generated by <code>setup.py</code>.</p>
126
2009-01-19T18:05:54Z
16,084,844
<p>Here is the best solution I've seen so far and it also explains why:</p> <p>Inside <code>yourpackage/version.py</code>:</p> <pre><code># Store the version here so: # 1) we don't load dependencies by storing it in __init__.py # 2) we can import it in setup.py for the same reason # 3) we can import it into your module module __version__ = '0.12' </code></pre> <p>Inside <code>yourpackage/__init__.py</code>:</p> <pre><code>from .version import __version__ </code></pre> <p>Inside <code>setup.py</code>:</p> <pre><code>exec(open('yourpackage/version.py').read()) setup( ... version=__version__, ... </code></pre> <p>If you know another approach that seems to be better let me know.</p>
44
2013-04-18T13:50:57Z
[ "python", "string", "package" ]
Standard way to embed version into python package?
458,550
<p>Is there a standard way to associate version string with a python package in such way that I could do the following?</p> <pre><code>import foo print foo.version </code></pre> <p>I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in <code>setup.py</code> already. Alternative solution that I found was to have <code>import __version__</code> in my <code>foo/__init__.py</code> and then have <code>__version__.py</code> generated by <code>setup.py</code>.</p>
126
2009-01-19T18:05:54Z
21,356,350
<p>I use a JSON file in the package dir. This fits Zooko's requirements.</p> <p>Inside <code>pkg_dir/pkg_info.json</code>:</p> <pre><code>{"version": "0.1.0"} </code></pre> <p>Inside <code>setup.py</code>:</p> <pre><code>from distutils.core import setup import json with open('pkg_dir/pkg_info.json') as fp: _info = json.load(fp) setup( version=_info['version'], ... ) </code></pre> <p>Inside <code>pkg_dir/__init__.py</code>:</p> <pre><code>import json from os.path import dirname with open(dirname(__file__) + '/pkg_info.json') as fp: _info = json.load(fp) __version__ = _info['version'] </code></pre> <p>I also put other information in <code>pkg_info.json</code>, like author. I like to use JSON because I can automate management of metadata.</p>
6
2014-01-25T21:15:36Z
[ "python", "string", "package" ]
wxPython is not throwing exceptions when it should, instead giving raw error messages
458,943
<p>I'm coding the menu for an application I'm writing in python, using wxPython libraries for the user interface, and I'm attempting to add icons to some of the menu items. Because I'm trying to be conscientious about it, I'm trying to limit the damage done if one of the image files referenced doesn't exist, and the most simple method (in my mind) is to use exceptions.</p> <p>The trouble is, when I link to a file that doesn't exist, an exception isn't thrown. Instead I get a horrific message box stating:</p> <p><code>Can't load image from &lt;path&gt;: Image does not exist.</code></p> <p>This message is exactly the type of thing I'm trying to stop, but even with the broadest exception catching statement nothing works.</p> <p>This is a cut down version, taking what seems to be relevant, from what I've written:</p> <pre><code>NewProject = wx.MenuItem(File, -1, "&amp;New Project\tCtrl+N", "Create a new project") try: # raises an error message but not an exception NewProject.SetBitmap(wx.Image( &lt;path&gt; ), wx.BITMAP_TYPE_PNG).ConvertToBitmap()) except Exception: pass </code></pre> <p>So these are my questions: What am I doing wrong? Am I approaching this in the wrong direction, putting too much emphasis on exceptions, when there are other ways around it (though non that seem in my head to be as simple)? Is this a bug in the wxPython library, since I'm pretty sure it should be throwing an exception even if it's not the best way around it?</p> <p>p.s. The best a Google search could do was recommend I converted all the images to python code using the <code>img2py</code> module that comes with wxPython, but I would prefer to keep the images in image format for what I'm doing.</p>
3
2009-01-19T19:56:09Z
459,013
<p>That is a known issue. <a href="http://alldunn.com/robin/" rel="nofollow">Robin Dunn</a> answered it a couple of times: just create your Logging method eg.:</p> <pre><code>dummy_log=wx.LogNull() </code></pre> <p>when the variable <code>dummy_log</code> runs out of scope, normal logging is enabled again.</p>
3
2009-01-19T20:13:41Z
[ "python", "exception", "wxpython" ]
How do you run your own code alongside Tkinter's event loop?
459,083
<p>My little brother is just getting into programming, and for his Science Fair project, he's doing a simulation of a flock of birds in the sky. He's gotten most of his code written, and it works nicely, but the birds need to move <em>every moment</em>.</p> <p>Tkinter, however, hogs the time for its own event loop, and so his code won't run. Doing <code>root.mainloop()</code> runs, runs, and keeps running, and the only thing it runs is the event handlers.</p> <p>Is there a way to have his code run alongside the mainloop (without multithreading, it's confusing and this should be kept simple), and if so, what is it?</p> <p>Right now, he came up with an ugly hack, tying his <code>move()</code> function to <code>&lt;b1-motion&gt;</code>, so that as long as he holds the button down and wiggles the mouse, it works. But there's got to be a better way.</p>
64
2009-01-19T20:40:39Z
459,131
<p>Use the <code>after</code> method on the <code>Tk</code> object:</p> <pre><code>from tkinter import * root = Tk() def task(): print("hello") root.after(2000, task) # reschedule event in 2 seconds root.after(2000, task) root.mainloop() </code></pre> <p>Here's the declaration and documentation for the <code>after</code> method:</p> <pre><code>def after(self, ms, func=None, *args): """Call function once after given time. MS specifies the time in milliseconds. FUNC gives the function which shall be called. Additional parameters are given as parameters to the function call. Return identifier to cancel scheduling with after_cancel.""" </code></pre>
79
2009-01-19T20:55:36Z
[ "python", "events", "tkinter" ]
How do you run your own code alongside Tkinter's event loop?
459,083
<p>My little brother is just getting into programming, and for his Science Fair project, he's doing a simulation of a flock of birds in the sky. He's gotten most of his code written, and it works nicely, but the birds need to move <em>every moment</em>.</p> <p>Tkinter, however, hogs the time for its own event loop, and so his code won't run. Doing <code>root.mainloop()</code> runs, runs, and keeps running, and the only thing it runs is the event handlers.</p> <p>Is there a way to have his code run alongside the mainloop (without multithreading, it's confusing and this should be kept simple), and if so, what is it?</p> <p>Right now, he came up with an ugly hack, tying his <code>move()</code> function to <code>&lt;b1-motion&gt;</code>, so that as long as he holds the button down and wiggles the mouse, it works. But there's got to be a better way.</p>
64
2009-01-19T20:40:39Z
538,559
<p>Another option is to let tkinter execute on a separate thread. One way of doing it is like this:</p> <pre><code>import Tkinter import threading class MyTkApp(threading.Thread): def __init__(self): self.root=Tkinter.Tk() self.s = Tkinter.StringVar() self.s.set('Foo') l = Tkinter.Label(self.root,textvariable=self.s) l.pack() threading.Thread.__init__(self) def run(self): self.root.mainloop() app = MyTkApp() app.start() # Now the app should be running and the value shown on the label # can be changed by changing the member variable s. # Like this: # app.s.set('Bar') </code></pre> <p>Be careful though, multithreaded programming is hard and it is really easy to shoot your self in the foot. For example you have to be careful when you change member variables of the sample class above so you don't interrupt with the event loop of Tkinter.</p>
0
2009-02-11T20:14:55Z
[ "python", "events", "tkinter" ]
How do you run your own code alongside Tkinter's event loop?
459,083
<p>My little brother is just getting into programming, and for his Science Fair project, he's doing a simulation of a flock of birds in the sky. He's gotten most of his code written, and it works nicely, but the birds need to move <em>every moment</em>.</p> <p>Tkinter, however, hogs the time for its own event loop, and so his code won't run. Doing <code>root.mainloop()</code> runs, runs, and keeps running, and the only thing it runs is the event handlers.</p> <p>Is there a way to have his code run alongside the mainloop (without multithreading, it's confusing and this should be kept simple), and if so, what is it?</p> <p>Right now, he came up with an ugly hack, tying his <code>move()</code> function to <code>&lt;b1-motion&gt;</code>, so that as long as he holds the button down and wiggles the mouse, it works. But there's got to be a better way.</p>
64
2009-01-19T20:40:39Z
1,835,036
<p>The solution posted by Bjorn results in a "RuntimeError: Calling Tcl from different appartment" message on my computer (RedHat Enterprise 5, python 2.6.1). Bjorn might not have gotten this message, since, according to <a href="http://www.mail-archive.com/[email protected]/msg01808.html">one place I checked</a>, mishandling threading with Tkinter is unpredictable and platform-dependent.</p> <p>The problem seems to be that <code>app.start()</code> counts as a reference to Tk, since app contains Tk elements. I fixed this by replacing <code>app.start()</code> with a <code>self.start()</code> inside <code>__init__</code>. I also made it so that all Tk references are either inside the <em>function that calls <code>mainloop()</code></em> or are inside <em>functions that are called by</em> the function that calls <code>mainloop()</code> (this is apparently critical to avoid the "different apartment" error). </p> <p>Finally, I added a protocol handler with a callback, since without this the program exits with an error when the Tk window is closed by the user. </p> <p>The revised code is as follows:</p> <pre><code># Run tkinter code in another thread import tkinter as tk import threading class App(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.start() def callback(self): self.root.quit() def run(self): self.root = tk.Tk() self.root.protocol("WM_DELETE_WINDOW", self.callback) label = tk.Label(self.root, text="Hello World") label.pack() self.root.mainloop() app = App() print('Now we can continue running code while mainloop runs!') for i in range(100000): print(i) </code></pre>
26
2009-12-02T18:55:46Z
[ "python", "events", "tkinter" ]
How do you run your own code alongside Tkinter's event loop?
459,083
<p>My little brother is just getting into programming, and for his Science Fair project, he's doing a simulation of a flock of birds in the sky. He's gotten most of his code written, and it works nicely, but the birds need to move <em>every moment</em>.</p> <p>Tkinter, however, hogs the time for its own event loop, and so his code won't run. Doing <code>root.mainloop()</code> runs, runs, and keeps running, and the only thing it runs is the event handlers.</p> <p>Is there a way to have his code run alongside the mainloop (without multithreading, it's confusing and this should be kept simple), and if so, what is it?</p> <p>Right now, he came up with an ugly hack, tying his <code>move()</code> function to <code>&lt;b1-motion&gt;</code>, so that as long as he holds the button down and wiggles the mouse, it works. But there's got to be a better way.</p>
64
2009-01-19T20:40:39Z
4,836,121
<p>When writing your own loop, as in the simulation (I assume), you need to call the <code>update</code> function which does what the <code>mainloop</code> does: updates the window with your changes, but you do it in your loop.</p> <pre><code>def task(): # do something root.update() while 1: task() </code></pre>
8
2011-01-29T09:35:20Z
[ "python", "events", "tkinter" ]
Filtering by relation count in SQLAlchemy
459,125
<p>I'm using the SQLAlchemy Python ORM in a Pylons project. I have a class "Project" which has a one to many relationship with another class "Entry". I want to do a query in SQLAlchemy that gives me all of the projects which have one or more entries associated with them. At the moment I'm doing:</p> <pre><code>[project for project in Session.query(Project) if len(project.entries)&gt;0] </code></pre> <p>which I know isn't ideal, but I can't figure out how to do a filter that does what I require (e.g. Session.query(Project).filter(Project.entries.exists())).</p> <p>Any ideas?</p>
6
2009-01-19T20:53:54Z
459,313
<p>Project.entries.any() should work.</p>
11
2009-01-19T21:48:24Z
[ "python", "sql", "database", "sqlalchemy", "pylons" ]
BeautifulSoup 3.1 parser breaks far too easily
459,552
<p><em>I was having trouble parsing some dodgy HTML with BeautifulSoup. Turns out that the HTMLParser used in newer versions is less tolerant than the SGMLParser used previously.</em></p> <p><hr /></p> <p>Does BeautifulSoup have some kind of debug mode? I'm trying to figure out how to stop it borking on some nasty HTML I'm loading from a crabby website:</p> <pre><code>&lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;Title&lt;/TITLE&gt; &lt;HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"&gt; &lt;/HEAD&gt; &lt;BODY&gt; ... ... &lt;/BODY&gt; &lt;/HTML&gt; </code></pre> <p>BeautifulSoup gives up after the <code>&lt;HTTP-EQUIV...&gt;</code> tag</p> <pre><code>In [1]: print BeautifulSoup(c).prettify() &lt;html&gt; &lt;head&gt; &lt;title&gt; Title &lt;/title&gt; &lt;/head&gt; &lt;/html&gt; </code></pre> <p>The problem is clearly the HTTP-EQUIV tag, which is really a <em>very</em> malformed <code>&lt;META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"&gt;</code> tag. Evidently, I need to specify this as self-closing, but no matter what I specify I can't fix it:</p> <pre><code>In [2]: print BeautifulSoup(c,selfClosingTags=['http-equiv', 'http-equiv="pragma"']).prettify() &lt;html&gt; &lt;head&gt; &lt;title&gt; Title &lt;/title&gt; &lt;/head&gt; &lt;/html&gt; </code></pre> <p>Is there a verbose debug mode in which BeautifulSoup will tell me what it is doing, so I can figure out what it is treating as the tag name in this case?</p>
3
2009-01-19T23:07:02Z
459,642
<p>Your problem must be something else; it works fine for me: </p> <pre><code>In [1]: import BeautifulSoup In [2]: c = """&lt;HTML&gt; ...: &lt;HEAD&gt; ...: &lt;TITLE&gt;Title&lt;/TITLE&gt; ...: &lt;HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"&gt; ...: &lt;/HEAD&gt; ...: &lt;BODY&gt; ...: ... ...: ... ...: &lt;/BODY&gt; ...: &lt;/HTML&gt; ...: """ In [3]: print BeautifulSoup.BeautifulSoup(c).prettify() &lt;html&gt; &lt;head&gt; &lt;title&gt; Title &lt;/title&gt; &lt;http-equiv&gt; &lt;/http-equiv&gt; &lt;/head&gt; &lt;body&gt; ... ... &lt;/body&gt; &lt;/html&gt; In [4]: </code></pre> <p>This is Python 2.5.2 with BeautifulSoup 3.0.7a — maybe it's different in older/newer versions? This is exactly the kind of soup BeautifulSoup handles so beautifully, so I doubt it's been changed at some point… Is there something else to the structure that you haven't mentioned in the problem?</p>
2
2009-01-19T23:40:08Z
[ "python", "html", "parsing", "beautifulsoup" ]
BeautifulSoup 3.1 parser breaks far too easily
459,552
<p><em>I was having trouble parsing some dodgy HTML with BeautifulSoup. Turns out that the HTMLParser used in newer versions is less tolerant than the SGMLParser used previously.</em></p> <p><hr /></p> <p>Does BeautifulSoup have some kind of debug mode? I'm trying to figure out how to stop it borking on some nasty HTML I'm loading from a crabby website:</p> <pre><code>&lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;Title&lt;/TITLE&gt; &lt;HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"&gt; &lt;/HEAD&gt; &lt;BODY&gt; ... ... &lt;/BODY&gt; &lt;/HTML&gt; </code></pre> <p>BeautifulSoup gives up after the <code>&lt;HTTP-EQUIV...&gt;</code> tag</p> <pre><code>In [1]: print BeautifulSoup(c).prettify() &lt;html&gt; &lt;head&gt; &lt;title&gt; Title &lt;/title&gt; &lt;/head&gt; &lt;/html&gt; </code></pre> <p>The problem is clearly the HTTP-EQUIV tag, which is really a <em>very</em> malformed <code>&lt;META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"&gt;</code> tag. Evidently, I need to specify this as self-closing, but no matter what I specify I can't fix it:</p> <pre><code>In [2]: print BeautifulSoup(c,selfClosingTags=['http-equiv', 'http-equiv="pragma"']).prettify() &lt;html&gt; &lt;head&gt; &lt;title&gt; Title &lt;/title&gt; &lt;/head&gt; &lt;/html&gt; </code></pre> <p>Is there a verbose debug mode in which BeautifulSoup will tell me what it is doing, so I can figure out what it is treating as the tag name in this case?</p>
3
2009-01-19T23:07:02Z
638,597
<p><a href="http://www.crummy.com/software/BeautifulSoup/3.1-problems.html" rel="nofollow">Having problems with Beautiful Soup 3.1.0?</a> recommends to use <a href="http://code.google.com/p/html5lib/" rel="nofollow">html5lib</a>'s parser as one of workarounds.</p> <pre><code>#!/usr/bin/env python from html5lib import HTMLParser, treebuilders parser = HTMLParser(tree=treebuilders.getTreeBuilder("beautifulsoup")) c = """&lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;Title&lt;/TITLE&gt; &lt;HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"&gt; &lt;/HEAD&gt; &lt;BODY&gt; ... ... &lt;/BODY&gt; &lt;/HTML&gt;""" soup = parser.parse(c) print soup.prettify() </code></pre> <p>Output:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt; Title &lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;http-equiv="pragma" content="NO-CACHE"&gt; ... ... &lt;/http-equiv="pragma"&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The output shows that html5lib hasn't fixed the problem in this case though.</p>
6
2009-03-12T13:20:25Z
[ "python", "html", "parsing", "beautifulsoup" ]
BeautifulSoup 3.1 parser breaks far too easily
459,552
<p><em>I was having trouble parsing some dodgy HTML with BeautifulSoup. Turns out that the HTMLParser used in newer versions is less tolerant than the SGMLParser used previously.</em></p> <p><hr /></p> <p>Does BeautifulSoup have some kind of debug mode? I'm trying to figure out how to stop it borking on some nasty HTML I'm loading from a crabby website:</p> <pre><code>&lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;Title&lt;/TITLE&gt; &lt;HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"&gt; &lt;/HEAD&gt; &lt;BODY&gt; ... ... &lt;/BODY&gt; &lt;/HTML&gt; </code></pre> <p>BeautifulSoup gives up after the <code>&lt;HTTP-EQUIV...&gt;</code> tag</p> <pre><code>In [1]: print BeautifulSoup(c).prettify() &lt;html&gt; &lt;head&gt; &lt;title&gt; Title &lt;/title&gt; &lt;/head&gt; &lt;/html&gt; </code></pre> <p>The problem is clearly the HTTP-EQUIV tag, which is really a <em>very</em> malformed <code>&lt;META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"&gt;</code> tag. Evidently, I need to specify this as self-closing, but no matter what I specify I can't fix it:</p> <pre><code>In [2]: print BeautifulSoup(c,selfClosingTags=['http-equiv', 'http-equiv="pragma"']).prettify() &lt;html&gt; &lt;head&gt; &lt;title&gt; Title &lt;/title&gt; &lt;/head&gt; &lt;/html&gt; </code></pre> <p>Is there a verbose debug mode in which BeautifulSoup will tell me what it is doing, so I can figure out what it is treating as the tag name in this case?</p>
3
2009-01-19T23:07:02Z
1,223,045
<p>Try <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a> (and its html module). Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles "broken" HTML better than BeautifulSoup. It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.</p> <p><a href="http://blog.ianbicking.org/2008/12/10/lxml-an-underappreciated-web-scraping-library/" rel="nofollow">Ian Blicking agrees</a>.</p> <p>There's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed.</p>
3
2009-08-03T15:40:41Z
[ "python", "html", "parsing", "beautifulsoup" ]
Thread specific data with webpy
459,608
<p>I'm writing a little web app with webpy, and I'm wondering if anyone has any information on a little problem I'm having.</p> <p>I've written a little ORM system, and it seems to be working pretty well. Ideally I'd like to stitch it in with webpy, but it appears that just using it as is causes thread issues (DB connection is instantiated/accessed across thread boundaries, or so the exception states).</p> <p>Does anyone know how I can (within the webpy) create my DB connection on the same thread as the rest of the page handling code will be?</p>
2
2009-01-19T23:26:18Z
460,713
<p>I'll give this one a try. Disclaimer: I have no experience with the web.py framework.</p> <p>I suggest you try the following:</p> <p>(1) Create a global threading.local instance to keep track of your thread local objects (in your case, it will keep track of only one object, a database session).</p> <pre><code>import threading serving = threading.local() </code></pre> <p>(2) At the start of each request, create a db connection/session and save it in the threading.local instance. If I understand the <a href="http://webpy.org/cookbook/application_processors" rel="nofollow">web.py documentation</a> correctly, you can do the following:</p> <pre><code>def setup_dbconnection(handler): serving.dbconnection = create_dbconnection(...) try: return handler() finally: serving.dbconnection.close() # or similar app.add_processor(setup_dbconnection) </code></pre> <p>(3) In your controller methods (if they're called that in web.py?), whenever you need a db connection, use serving.dbconnection.</p>
2
2009-01-20T10:17:25Z
[ "python", "database", "multithreading", "web.py" ]
Thread specific data with webpy
459,608
<p>I'm writing a little web app with webpy, and I'm wondering if anyone has any information on a little problem I'm having.</p> <p>I've written a little ORM system, and it seems to be working pretty well. Ideally I'd like to stitch it in with webpy, but it appears that just using it as is causes thread issues (DB connection is instantiated/accessed across thread boundaries, or so the exception states).</p> <p>Does anyone know how I can (within the webpy) create my DB connection on the same thread as the rest of the page handling code will be?</p>
2
2009-01-19T23:26:18Z
519,493
<p>We use SQLAlchemy with web.py and use hooks to create and close db connections per request. SQLAlchemy handles pooling, so not every connection is a tcp connection.</p> <p>The thread local storage you want to use is web.ctx ie. any time you access web.ctx you only see properties set by that thread.</p> <p>Our code looks something like this:</p> <pre><code>def sa_load_hook(): web.ctx.sadb = Session() def sa_unload_hook(): web.ctx.sadb.close() web.loadhooks['sasession'] = sa_load_hook web.unloadhooks['sasession'] = sa_unload_hook </code></pre> <p>Replace Session with your db connection function and it should work fine for you.</p>
4
2009-02-06T07:59:19Z
[ "python", "database", "multithreading", "web.py" ]
BeautifulSoup - modifying all links in a piece of HTML?
459,981
<p>I need to be able to modify every single link in an HTML document. I know that I need to use the <code>SoupStrainer</code> but I'm not 100% positive on how to implement it. If someone could direct me to a good resource or provide a code example, it'd be very much appreciated.</p> <p>Thanks.</p>
13
2009-01-20T02:52:19Z
459,991
<p>Maybe something like this would work? (I don't have a Python interpreter in front of me, unfortunately)</p> <pre><code>from BeautifulSoup import BeautifulSoup soup = BeautifulSoup('&lt;p&gt;Blah blah blah &lt;a href="http://google.com"&gt;Google&lt;/a&gt;&lt;/p&gt;') for a in soup.findAll('a'): a['href'] = a['href'].replace("google", "mysite") result = str(soup) </code></pre>
29
2009-01-20T03:02:34Z
[ "python", "beautifulsoup" ]
BeautifulSoup - modifying all links in a piece of HTML?
459,981
<p>I need to be able to modify every single link in an HTML document. I know that I need to use the <code>SoupStrainer</code> but I'm not 100% positive on how to implement it. If someone could direct me to a good resource or provide a code example, it'd be very much appreciated.</p> <p>Thanks.</p>
13
2009-01-20T02:52:19Z
460,002
<pre><code>from BeautifulSoup import BeautifulSoup soup = BeautifulSoup('&lt;p&gt;Blah blah blah &lt;a href="http://google.com"&gt;Google&lt;/a&gt;&lt;/p&gt;') for a in soup.findAll('a'): a['href'] = a['href'].replace("google", "mysite") print str(soup) </code></pre> <p>This is Lusid's solution, but since he didn't have a Python interpreter in front of him, he wasn't able to test it and it had a few errors. I just wanted to post the working condition. Thank's Lusid!</p>
22
2009-01-20T03:09:49Z
[ "python", "beautifulsoup" ]
BeautifulSoup - modifying all links in a piece of HTML?
459,981
<p>I need to be able to modify every single link in an HTML document. I know that I need to use the <code>SoupStrainer</code> but I'm not 100% positive on how to implement it. If someone could direct me to a good resource or provide a code example, it'd be very much appreciated.</p> <p>Thanks.</p>
13
2009-01-20T02:52:19Z
22,571,633
<p>I tried this and it worked, it's easier to avoid using regexp for matching each <code>'href'</code>:</p> <pre><code>from bs4 import BeautifulSoup as bs soup = bs(htmltext) for a in soup.findAll('a'): a['href'] = "mysite" </code></pre> <p>Check it out, on <a href="http://beautiful-soup-4.readthedocs.org/en/latest/#modifying-the-tree" rel="nofollow">bs4 docs</a>.</p>
1
2014-03-22T00:03:17Z
[ "python", "beautifulsoup" ]
Python/Twisted - Sending to a specific socket object?
460,068
<p>I have a "manager" process on a node, and several worker processes. The manager is the actual server who holds all of the connections to the clients. The manager accepts all incoming packets and puts them into a queue, and then the worker processes pull the packets out of the queue, process them, and generate a result. They send the result back to the manager (by putting them into another queue which is read by the manager), but here is where I get stuck: how do I send the result to a specific socket? When dealing with the processing of the packets on a single process, it's easy, because when you receive a packet you can reply to it by just grabbing the "transport" object in-context. But how would I do this with the method I'm using?</p>
1
2009-01-20T03:43:14Z
460,245
<p>It sounds like you might need to keep a reference to the transport (or protocol) along with the bytes the just came in on that protocol in your 'event' object. That way responses that came in on a connection go out on the same connection. </p> <p>If things don't need to be processed serially perhaps you should think about setting up functors that can handle the data in parallel to remove the need for queueing. Just keep in mind that you will need to protect critical sections of your code.</p> <p>Edit: Judging from your other question about evaluating your server design it would seem that processing in parallel may not be possible for your situation, so my first suggestion stands.</p>
3
2009-01-20T06:00:42Z
[ "python", "sockets", "twisted", "multiprocess" ]
Python/Twisted - TCP packet fragmentation?
460,144
<p>In Twisted when implementing the dataReceived method, there doesn't seem to be any examples which refer to packets being fragmented. In every other language this is something you manually implement, so I was just wondering if this is done for you in twisted already or what? If so, do I need to prefix my packets with a length header? Or do I have to do this manually? If so, what way would that be?</p>
5
2009-01-20T04:38:17Z
460,224
<p>In the dataReceived method you get back the data as a string of indeterminate length meaning that it may be a whole message in your protocol or it may only be part of the message that some 'client' sent to you. You will have to inspect the data to see if it comprises a whole message in your protocol.</p> <p>I'm currently using Twisted on one of my projects to implement a protocol and decided to use the struct module to pack/unpack my data. The protocol I am implementing has a fixed header size so I don't construct any messages until I've read at least HEADER_SIZE amount of bytes. The total message size is declared in this header data portion.</p> <p>I guess you don't really need to define a message length as part of your protocol but it helps. If you didn't define one you would have to have a special delimiter that determines when a message begins/ends. Sort of how the FIX protocol uses the SOH byte to delimit fields. Though it does have a required field that tells you how long a message is (just not how many fields are in a message).</p>
6
2009-01-20T05:47:42Z
[ "python", "tcp", "twisted", "packet" ]
Python/Twisted - TCP packet fragmentation?
460,144
<p>In Twisted when implementing the dataReceived method, there doesn't seem to be any examples which refer to packets being fragmented. In every other language this is something you manually implement, so I was just wondering if this is done for you in twisted already or what? If so, do I need to prefix my packets with a length header? Or do I have to do this manually? If so, what way would that be?</p>
5
2009-01-20T04:38:17Z
461,477
<p>When dealing with TCP, you should really forget all notion of 'packets'. TCP is a stream protocol - you stream data in and data streams out the other side. Once the data is sent, it is allowed to arrive in as many or as few blocks as it wants, as long as the data all arrives in the right order. You'll have to manually do the delimitation as with other languages, with a length field, or a message type field, or a special delimiter character, etc.</p>
5
2009-01-20T14:20:12Z
[ "python", "tcp", "twisted", "packet" ]
Python/Twisted - TCP packet fragmentation?
460,144
<p>In Twisted when implementing the dataReceived method, there doesn't seem to be any examples which refer to packets being fragmented. In every other language this is something you manually implement, so I was just wondering if this is done for you in twisted already or what? If so, do I need to prefix my packets with a length header? Or do I have to do this manually? If so, what way would that be?</p>
5
2009-01-20T04:38:17Z
817,378
<p>You can also use a LineReceiver protocol</p>
1
2009-05-03T16:01:47Z
[ "python", "tcp", "twisted", "packet" ]
Algorithm to generate spanning set
460,479
<p>Given this input: [1,2,3,4]</p> <p>I'd like to generate the set of spanning sets:</p> <pre><code>[1] [2] [3] [4] [1] [2] [3,4] [1] [2,3] [4] [1] [3] [2,4] [1,2] [3] [4] [1,3] [2] [4] [1,4] [2] [3] [1,2] [3,4] [1,3] [2,4] [1,4] [2,3] [1,2,3] [4] [1,2,4] [3] [1,3,4] [2] [2,3,4] [1] [1,2,3,4] </code></pre> <p>Every set has all the elements of the original set, permuted to appear in unique subsets. What is the algorithm that produces these sets? I've tried Python generator functions using choose, permutation, combination, power set, and so on, but can't get the right combination.</p> <p>20 Jan 2009</p> <p>This is not a homework question. This is an improved answer I was working on for www.projecteuler.net problem # 118. I already had a slow solution but came up with a better way -- except I could not figure out how to do the spanning set.</p> <p>I'll post my code when I get back from an Inauguration Party.</p> <p>21 Jan 2009</p> <p>This is the eventual algorithm I used:</p> <pre><code>def spanningsets(items): if len(items) == 1: yield [items] else: left_set, last = items[:-1], [items[-1]] for cc in spanningsets(left_set): yield cc + [last] for i,elem in enumerate(cc): yield cc[:i] + [elem + last] + cc[i+1:] </code></pre> <p>@Yuval F: I know how to do a powerset. Here's a straightforward implementation:</p> <pre><code>def powerset(s) : length = len(s) for i in xrange(0, 2**length) : yield [c for j, c in enumerate(s) if (1 &lt;&lt; j) &amp; i] return </code></pre>
10
2009-01-20T08:38:46Z
460,514
<p>What about this? I haven't tested it yet, but I'll try it later…</p> <p>I think this technique is called Dynamic Programming:</p> <ol> <li><p>Take the first element <code>[1]</code><br /> What can you create with it? Only <code>[1]</code></p></li> <li><p>Take the second one <code>[2]</code><br /> Now you've got two possibilities: <code>[1,2]</code> and <code>[1] [2]</code></p></li> <li><p>Take the third one <code>[3]</code><br /> With the first of number 2 <code>[1,2]</code> one can create <code>[1,2,3]</code> and <code>[1,2] [3]</code><br /> With the second of number 2 <code>[1] [2]</code> one can create <code>[1,3] [2]</code> and <code>[1] [2,3]</code> and <code>[1] [2] [3]</code></p></li> </ol> <p>I hope it is clear enough what I tried to show. (If not, drop a comment!)</p>
6
2009-01-20T08:55:20Z
[ "python", "algorithm" ]
Algorithm to generate spanning set
460,479
<p>Given this input: [1,2,3,4]</p> <p>I'd like to generate the set of spanning sets:</p> <pre><code>[1] [2] [3] [4] [1] [2] [3,4] [1] [2,3] [4] [1] [3] [2,4] [1,2] [3] [4] [1,3] [2] [4] [1,4] [2] [3] [1,2] [3,4] [1,3] [2,4] [1,4] [2,3] [1,2,3] [4] [1,2,4] [3] [1,3,4] [2] [2,3,4] [1] [1,2,3,4] </code></pre> <p>Every set has all the elements of the original set, permuted to appear in unique subsets. What is the algorithm that produces these sets? I've tried Python generator functions using choose, permutation, combination, power set, and so on, but can't get the right combination.</p> <p>20 Jan 2009</p> <p>This is not a homework question. This is an improved answer I was working on for www.projecteuler.net problem # 118. I already had a slow solution but came up with a better way -- except I could not figure out how to do the spanning set.</p> <p>I'll post my code when I get back from an Inauguration Party.</p> <p>21 Jan 2009</p> <p>This is the eventual algorithm I used:</p> <pre><code>def spanningsets(items): if len(items) == 1: yield [items] else: left_set, last = items[:-1], [items[-1]] for cc in spanningsets(left_set): yield cc + [last] for i,elem in enumerate(cc): yield cc[:i] + [elem + last] + cc[i+1:] </code></pre> <p>@Yuval F: I know how to do a powerset. Here's a straightforward implementation:</p> <pre><code>def powerset(s) : length = len(s) for i in xrange(0, 2**length) : yield [c for j, c in enumerate(s) if (1 &lt;&lt; j) &amp; i] return </code></pre>
10
2009-01-20T08:38:46Z
460,529
<p>This should work, though I haven't tested it enough.</p> <pre><code>def spanningsets(items): if not items: return if len(items) == 1: yield [[items[-1]]] else: for cc in spanningsets(items[:-1]): yield cc + [[items[-1]]] for i in range(len(cc)): yield cc[:i] + [cc[i] + [items[-1]]] + cc[i+1:] for sset in spanningsets([1, 2, 3, 4]): print ' '.join(map(str, sset)) </code></pre> <p>Output:</p> <pre><code>[1] [2] [3] [4] [1, 4] [2] [3] [1] [2, 4] [3] [1] [2] [3, 4] [1, 3] [2] [4] [1, 3, 4] [2] [1, 3] [2, 4] [1] [2, 3] [4] [1, 4] [2, 3] [1] [2, 3, 4] [1, 2] [3] [4] [1, 2, 4] [3] [1, 2] [3, 4] [1, 2, 3] [4] [1, 2, 3, 4] </code></pre>
11
2009-01-20T09:02:54Z
[ "python", "algorithm" ]
Algorithm to generate spanning set
460,479
<p>Given this input: [1,2,3,4]</p> <p>I'd like to generate the set of spanning sets:</p> <pre><code>[1] [2] [3] [4] [1] [2] [3,4] [1] [2,3] [4] [1] [3] [2,4] [1,2] [3] [4] [1,3] [2] [4] [1,4] [2] [3] [1,2] [3,4] [1,3] [2,4] [1,4] [2,3] [1,2,3] [4] [1,2,4] [3] [1,3,4] [2] [2,3,4] [1] [1,2,3,4] </code></pre> <p>Every set has all the elements of the original set, permuted to appear in unique subsets. What is the algorithm that produces these sets? I've tried Python generator functions using choose, permutation, combination, power set, and so on, but can't get the right combination.</p> <p>20 Jan 2009</p> <p>This is not a homework question. This is an improved answer I was working on for www.projecteuler.net problem # 118. I already had a slow solution but came up with a better way -- except I could not figure out how to do the spanning set.</p> <p>I'll post my code when I get back from an Inauguration Party.</p> <p>21 Jan 2009</p> <p>This is the eventual algorithm I used:</p> <pre><code>def spanningsets(items): if len(items) == 1: yield [items] else: left_set, last = items[:-1], [items[-1]] for cc in spanningsets(left_set): yield cc + [last] for i,elem in enumerate(cc): yield cc[:i] + [elem + last] + cc[i+1:] </code></pre> <p>@Yuval F: I know how to do a powerset. Here's a straightforward implementation:</p> <pre><code>def powerset(s) : length = len(s) for i in xrange(0, 2**length) : yield [c for j, c in enumerate(s) if (1 &lt;&lt; j) &amp; i] return </code></pre>
10
2009-01-20T08:38:46Z
460,565
<p>Here's <a href="http://www.cs.sunysb.edu/~algorith/files/generating-subsets.shtml" rel="nofollow">The SUNY algorithm repository</a> page on the problem. Maybe you can translate one of the code references to python.</p> <p>Edit: This was a similar problem. <a href="http://www.cs.sunysb.edu/~algorith/files/generating-partitions.shtml" rel="nofollow">Here</a> is the SUNY repository page about generating partitions, which I believe is the correct problem.</p>
0
2009-01-20T09:23:06Z
[ "python", "algorithm" ]
Algorithm to generate spanning set
460,479
<p>Given this input: [1,2,3,4]</p> <p>I'd like to generate the set of spanning sets:</p> <pre><code>[1] [2] [3] [4] [1] [2] [3,4] [1] [2,3] [4] [1] [3] [2,4] [1,2] [3] [4] [1,3] [2] [4] [1,4] [2] [3] [1,2] [3,4] [1,3] [2,4] [1,4] [2,3] [1,2,3] [4] [1,2,4] [3] [1,3,4] [2] [2,3,4] [1] [1,2,3,4] </code></pre> <p>Every set has all the elements of the original set, permuted to appear in unique subsets. What is the algorithm that produces these sets? I've tried Python generator functions using choose, permutation, combination, power set, and so on, but can't get the right combination.</p> <p>20 Jan 2009</p> <p>This is not a homework question. This is an improved answer I was working on for www.projecteuler.net problem # 118. I already had a slow solution but came up with a better way -- except I could not figure out how to do the spanning set.</p> <p>I'll post my code when I get back from an Inauguration Party.</p> <p>21 Jan 2009</p> <p>This is the eventual algorithm I used:</p> <pre><code>def spanningsets(items): if len(items) == 1: yield [items] else: left_set, last = items[:-1], [items[-1]] for cc in spanningsets(left_set): yield cc + [last] for i,elem in enumerate(cc): yield cc[:i] + [elem + last] + cc[i+1:] </code></pre> <p>@Yuval F: I know how to do a powerset. Here's a straightforward implementation:</p> <pre><code>def powerset(s) : length = len(s) for i in xrange(0, 2**length) : yield [c for j, c in enumerate(s) if (1 &lt;&lt; j) &amp; i] return </code></pre>
10
2009-01-20T08:38:46Z
461,219
<p>The result sets together with the empty set {} looks like the results of the <a href="http://en.wikipedia.org/wiki/Power_set" rel="nofollow">powerset</a> (or power set), but it is not the same thing.</p> <p>I started a post about a similar problem which has a few implementations (although in C#) and geared more for speed than clarity in some cases. The first example should be easy to translate. Maybe it will give a few ideas anyway.</p> <p>They work on the principle that emmumerating the combinations is similar to counting in binary (imagine counting from 0 to 16). You do not state if the order is important, or just generating all the combinations, so a quick tidy up may be in order afterwards.</p> <p>Have a <a href="http://stackoverflow.com/questions/343654/c-data-structure-to-mimic-cs-listlistint">look</a> here (ignore the odd title, the discussion took another direction)</p>
-1
2009-01-20T13:03:18Z
[ "python", "algorithm" ]
Algorithm to generate spanning set
460,479
<p>Given this input: [1,2,3,4]</p> <p>I'd like to generate the set of spanning sets:</p> <pre><code>[1] [2] [3] [4] [1] [2] [3,4] [1] [2,3] [4] [1] [3] [2,4] [1,2] [3] [4] [1,3] [2] [4] [1,4] [2] [3] [1,2] [3,4] [1,3] [2,4] [1,4] [2,3] [1,2,3] [4] [1,2,4] [3] [1,3,4] [2] [2,3,4] [1] [1,2,3,4] </code></pre> <p>Every set has all the elements of the original set, permuted to appear in unique subsets. What is the algorithm that produces these sets? I've tried Python generator functions using choose, permutation, combination, power set, and so on, but can't get the right combination.</p> <p>20 Jan 2009</p> <p>This is not a homework question. This is an improved answer I was working on for www.projecteuler.net problem # 118. I already had a slow solution but came up with a better way -- except I could not figure out how to do the spanning set.</p> <p>I'll post my code when I get back from an Inauguration Party.</p> <p>21 Jan 2009</p> <p>This is the eventual algorithm I used:</p> <pre><code>def spanningsets(items): if len(items) == 1: yield [items] else: left_set, last = items[:-1], [items[-1]] for cc in spanningsets(left_set): yield cc + [last] for i,elem in enumerate(cc): yield cc[:i] + [elem + last] + cc[i+1:] </code></pre> <p>@Yuval F: I know how to do a powerset. Here's a straightforward implementation:</p> <pre><code>def powerset(s) : length = len(s) for i in xrange(0, 2**length) : yield [c for j, c in enumerate(s) if (1 &lt;&lt; j) &amp; i] return </code></pre>
10
2009-01-20T08:38:46Z
463,586
<p>I think the following method is the best way to generate them for the euler problem, as you can replace the return value with the number of prime spanning subsets, and it will be trivial to do the multiplication (especially with memoization):</p> <pre><code>GenerateSubsets(list) partitions = { x | x is subset of list and x contains the lowest element of list } foreach (parition in partitions) if set == list yield { partition } else yield { partition } x GenerateSubsets(list - part) </code></pre> <p>The key part is to make sure that the recursive side always has the leftmost element, this way, you don't get duplicates.</p> <p>I have some messy C# code that does this:</p> <pre><code> IEnumerable&lt;IEnumerable&lt;List&lt;int&gt;&gt;&gt; GenerateSubsets(List&lt;int&gt; list) { int p = (1 &lt;&lt; (list.Count)) - 2; List&lt;int&gt; lhs = new List&lt;int&gt;(); List&lt;int&gt; rhs = new List&lt;int&gt;(); while (p &gt;= 0) { for (int i = 0; i &lt; list.Count; i++) if ((p &amp; (1 &lt;&lt; i)) == 0) lhs.Add(list[i]); else rhs.Add(list[i]); if (rhs.Count &gt; 0) foreach (var rhsSubset in GenerateSubsets(rhs)) yield return Combine(lhs, rhsSubset); else yield return Combine(lhs, null); lhs.Clear(); rhs.Clear(); p -= 2; } } IEnumerable&lt;List&lt;int&gt;&gt; Combine(List&lt;int&gt; list, IEnumerable&lt;List&lt;int&gt;&gt; rest) { yield return list; if (rest != null) foreach (List&lt;int&gt; x in rest) yield return x; } </code></pre>
0
2009-01-20T23:46:59Z
[ "python", "algorithm" ]
Simulating a 'local static' variable in python
460,586
<p>Consider the following code: </p> <pre><code>def CalcSomething(a): if CalcSomething._cache.has_key(a): return CalcSomething._cache[a] CalcSomething._cache[a] = ReallyCalc(a) return CalcSomething._cache[a] CalcSomething._cache = { } </code></pre> <p>This is the easiest way I can think of for simulating a 'local static' variable in python.<br /> What bothers me is that CalcSomething._cache is mentioned outside the function's definition, but the alternative would be something like that: </p> <pre><code>if not hasattr(CalcSomething, "_cache"): setattr(CalcSomething, "_cache", { } ) </code></pre> <p>inside the function's definition, which is really cumbersome. </p> <p>Is there a more elegant way? </p> <p>[EDIT]<br /> Just to clarify, this question is not about local function caches, as the example above might suggest. Here is another short example where a 'static local' might be handy: </p> <pre><code>def ParseString(s): return ParseString._parser.parse(s) # Create a Parser object once, which will be used for all parsings. # Assuming a Parser object is heave on resources, for the sake of this example. ParseString._parser = Parser() </code></pre>
23
2009-01-20T09:32:42Z
460,601
<p>Turn it into a decorator.</p> <pre><code>def static_var(var_name, initial_value): def _set_var(obj): setattr(obj, var_name, initial_value) return obj return _set_var @static_var("_cache", {}) def CalcSomething(a): ... </code></pre>
15
2009-01-20T09:39:21Z
[ "python" ]
Simulating a 'local static' variable in python
460,586
<p>Consider the following code: </p> <pre><code>def CalcSomething(a): if CalcSomething._cache.has_key(a): return CalcSomething._cache[a] CalcSomething._cache[a] = ReallyCalc(a) return CalcSomething._cache[a] CalcSomething._cache = { } </code></pre> <p>This is the easiest way I can think of for simulating a 'local static' variable in python.<br /> What bothers me is that CalcSomething._cache is mentioned outside the function's definition, but the alternative would be something like that: </p> <pre><code>if not hasattr(CalcSomething, "_cache"): setattr(CalcSomething, "_cache", { } ) </code></pre> <p>inside the function's definition, which is really cumbersome. </p> <p>Is there a more elegant way? </p> <p>[EDIT]<br /> Just to clarify, this question is not about local function caches, as the example above might suggest. Here is another short example where a 'static local' might be handy: </p> <pre><code>def ParseString(s): return ParseString._parser.parse(s) # Create a Parser object once, which will be used for all parsings. # Assuming a Parser object is heave on resources, for the sake of this example. ParseString._parser = Parser() </code></pre>
23
2009-01-20T09:32:42Z
460,691
<p>Consider writing decorator that will maintain cache and your function won't be contaminated by caching code:</p> <pre><code>def cacheResults(aFunc): '''This decorator funcion binds a map between the tuple of arguments and results computed by aFunc for those arguments''' def cachedFunc(*args): if not hasattr(aFunc, '_cache'): aFunc._cache = {} if args in aFunc._cache: return aFunc._cache[args] newVal = aFunc(*args) aFunc._cache[args] = newVal return newVal return cachedFunc @cacheResults def ReallyCalc(a): '''This function does only actual computation''' return pow(a, 42) </code></pre> <p>Maybe it doesn't look great at first, but you can use <code>cacheResults()</code> anywhere you don't need keyword parameters. It is possible to create similar decorator that would work also for keyword params, but that didn't seem necessary this time.</p>
10
2009-01-20T10:10:57Z
[ "python" ]
Simulating a 'local static' variable in python
460,586
<p>Consider the following code: </p> <pre><code>def CalcSomething(a): if CalcSomething._cache.has_key(a): return CalcSomething._cache[a] CalcSomething._cache[a] = ReallyCalc(a) return CalcSomething._cache[a] CalcSomething._cache = { } </code></pre> <p>This is the easiest way I can think of for simulating a 'local static' variable in python.<br /> What bothers me is that CalcSomething._cache is mentioned outside the function's definition, but the alternative would be something like that: </p> <pre><code>if not hasattr(CalcSomething, "_cache"): setattr(CalcSomething, "_cache", { } ) </code></pre> <p>inside the function's definition, which is really cumbersome. </p> <p>Is there a more elegant way? </p> <p>[EDIT]<br /> Just to clarify, this question is not about local function caches, as the example above might suggest. Here is another short example where a 'static local' might be handy: </p> <pre><code>def ParseString(s): return ParseString._parser.parse(s) # Create a Parser object once, which will be used for all parsings. # Assuming a Parser object is heave on resources, for the sake of this example. ParseString._parser = Parser() </code></pre>
23
2009-01-20T09:32:42Z
460,811
<p>Turn it into a callable object (since that's what it really is.)</p> <pre><code>class CalcSomething(object): def __init__(self): self._cache = {} def __call__(self, a): if a not in self._cache: self._cache[a] = self.reallyCalc(a) return self._cache[a] def reallyCalc(self, a): return # a real answer calcSomething = CalcSomething() </code></pre> <p>Now you can use <code>calcSomething</code> as if it were a function. But it remains tidy and self-contained. </p>
44
2009-01-20T10:57:30Z
[ "python" ]
Simulating a 'local static' variable in python
460,586
<p>Consider the following code: </p> <pre><code>def CalcSomething(a): if CalcSomething._cache.has_key(a): return CalcSomething._cache[a] CalcSomething._cache[a] = ReallyCalc(a) return CalcSomething._cache[a] CalcSomething._cache = { } </code></pre> <p>This is the easiest way I can think of for simulating a 'local static' variable in python.<br /> What bothers me is that CalcSomething._cache is mentioned outside the function's definition, but the alternative would be something like that: </p> <pre><code>if not hasattr(CalcSomething, "_cache"): setattr(CalcSomething, "_cache", { } ) </code></pre> <p>inside the function's definition, which is really cumbersome. </p> <p>Is there a more elegant way? </p> <p>[EDIT]<br /> Just to clarify, this question is not about local function caches, as the example above might suggest. Here is another short example where a 'static local' might be handy: </p> <pre><code>def ParseString(s): return ParseString._parser.parse(s) # Create a Parser object once, which will be used for all parsings. # Assuming a Parser object is heave on resources, for the sake of this example. ParseString._parser = Parser() </code></pre>
23
2009-01-20T09:32:42Z
460,924
<p>One option is to abuse default parameters. ie:</p> <pre><code>def CalcSomething(a, _cache={}): if _cache.has_key(a): </code></pre> <p>This has the advantage that you don't need to qualify the name, and will get fast local access to the variables rather than doing two slow dict lookups. However it still has the problem that it is mentioned outside the function (in fact it's worse since its now in the function signature.)</p> <p>To prevent this, a better solution would be to wrap the function in a closure containing your statics:</p> <pre><code>@apply def CalcSomething(): cache = {} # statics go here def CalcSomething(a): if cache.has_key(a): return cache[a] cache[a] = ReallyCalc(a) return cache[a] return CalcSomething </code></pre>
3
2009-01-20T11:34:50Z
[ "python" ]
Simulating a 'local static' variable in python
460,586
<p>Consider the following code: </p> <pre><code>def CalcSomething(a): if CalcSomething._cache.has_key(a): return CalcSomething._cache[a] CalcSomething._cache[a] = ReallyCalc(a) return CalcSomething._cache[a] CalcSomething._cache = { } </code></pre> <p>This is the easiest way I can think of for simulating a 'local static' variable in python.<br /> What bothers me is that CalcSomething._cache is mentioned outside the function's definition, but the alternative would be something like that: </p> <pre><code>if not hasattr(CalcSomething, "_cache"): setattr(CalcSomething, "_cache", { } ) </code></pre> <p>inside the function's definition, which is really cumbersome. </p> <p>Is there a more elegant way? </p> <p>[EDIT]<br /> Just to clarify, this question is not about local function caches, as the example above might suggest. Here is another short example where a 'static local' might be handy: </p> <pre><code>def ParseString(s): return ParseString._parser.parse(s) # Create a Parser object once, which will be used for all parsings. # Assuming a Parser object is heave on resources, for the sake of this example. ParseString._parser = Parser() </code></pre>
23
2009-01-20T09:32:42Z
461,557
<p>The solution proposed by S.Lott is the solution I would propose too.</p> <p>There are useful "memoize" decorators around, too, like:</p> <ul> <li><a href="http://code.activestate.com/recipes/496879/" rel="nofollow">Memoize decorator function with cache size limit</a></li> <li><a href="http://code.activestate.com/recipes/498110/" rel="nofollow">Memoize decorator with O(1) length-limited LRU cache, supports mutable types </a></li> </ul> <p>Given all that, I'm providing an alternative for your initial attempt at a function and a "static local", which is standalone:</p> <pre><code>def calc_something(a): try: return calc_something._cache[a] except AttributeError: # _cache is not there calc_something._cache= {} except KeyError: # the result is not there pass # compute result here calc_something._cache[a]= result return result </code></pre>
4
2009-01-20T14:37:35Z
[ "python" ]
XML-RPC and Continuum from Python / Perl
462,038
<p>Has anyone had any success with getting data via Xml-rpc using Python or Perl...?</p> <p>I'm using the continuum.py library:</p> <pre><code>#!/usr/bin/env python from continuum import * c = Continuum( "http://localhost:8080/continuum/xmlrpc" ) </code></pre> <p>or:</p> <pre><code>#!/usr/bin/perl use Frontier::Client; my $url = "http://dev.server.com:8080/continuum/xmlrpc"; my $client = RPC::XML::Client-&gt;new($url); my $res = $client-&gt;send_request('system.listMethods'); print " Response class = ".(ref $res)."\n"; print " Response type = ".$res-&gt;type."\n"; print " Response string = ".$res-&gt;as_string."\n"; print " Response value = ".$res-&gt;value."\n"; </code></pre> <p>Gives: <code>No such handler: system.listMethods</code></p> <p>Anyone fared any better...?</p>
2
2009-01-20T16:27:39Z
464,646
<p>Yes... with Perl. </p> <p>I've used <a href="http://search.cpan.org/dist/XML-RPC/" rel="nofollow">XML::RPC</a>. In fact I wrote the CPAN module <a href="http://search.cpan.org/dist/WWW-FreshMeat-API/" rel="nofollow">WWW::FreshMeat::API</a> using it to access Freshmeats XML-RPC API so I know it does work well!</p> <p>Using XML::RPC with Freshmeat the "system.*" calls work for me....</p> <pre><code>use XML::RPC; use Data::Dumper; my $fm = XML::RPC-&gt;new( 'http://freshmeat.net/xmlrpc/' ); # need to put in your Freshmeat username/password here my $session = $fm-&gt;call( 'login', { username =&gt; 'user', password =&gt; 'pass' }); my $x = $fm-&gt;call('system.listMethods'); say Dumper( $x ); </code></pre> <p>Gives me....</p> <pre><code>$VAR1 = [ 'system.listMethods', 'system.methodHelp', 'system.methodSignature', 'system.describeMethods', 'system.multiCall', 'system.getCapabilities', 'publish_release', 'fetch_branch_list', 'fetch_project_list', 'fetch_available_licenses', 'fetch_available_release_foci', 'fetch_release', 'login', 'logout', 'withdraw_release' ]; </code></pre> <p>Hope that helps.</p> <p>/I3az/</p>
1
2009-01-21T09:59:57Z
[ "python", "perl", "xml-rpc", "continuum" ]
XML-RPC and Continuum from Python / Perl
462,038
<p>Has anyone had any success with getting data via Xml-rpc using Python or Perl...?</p> <p>I'm using the continuum.py library:</p> <pre><code>#!/usr/bin/env python from continuum import * c = Continuum( "http://localhost:8080/continuum/xmlrpc" ) </code></pre> <p>or:</p> <pre><code>#!/usr/bin/perl use Frontier::Client; my $url = "http://dev.server.com:8080/continuum/xmlrpc"; my $client = RPC::XML::Client-&gt;new($url); my $res = $client-&gt;send_request('system.listMethods'); print " Response class = ".(ref $res)."\n"; print " Response type = ".$res-&gt;type."\n"; print " Response string = ".$res-&gt;as_string."\n"; print " Response value = ".$res-&gt;value."\n"; </code></pre> <p>Gives: <code>No such handler: system.listMethods</code></p> <p>Anyone fared any better...?</p>
2
2009-01-20T16:27:39Z
498,602
<p>What you describe is not part of the client-side library-- it's a matter of whether the server implements these methods.</p> <p>I'm the author of the <a href="http://search.cpan.org/dist/RPC-XML" rel="nofollow">RPC::XML</a> Perl module, and in the server class I provide I also provide implementation of the basic "introspection" API that has become a sort of semi-standard in the XML-RPC arena. But even then, users of the server class may choose to not have the introspection API activate.</p> <p>Of course, I can't speak to other XML-RPC implementations.</p>
1
2009-01-31T10:11:11Z
[ "python", "perl", "xml-rpc", "continuum" ]