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
listlengths
1
5
Prevent python imports compiling
1,331,235
<p>I have have a python file that imports a few frequently changed python files. I have had trouble with the imported files not recompiling when I change them. How do I stop them compiling?</p>
1
2009-08-25T21:52:55Z
1,331,279
<p>There are some modules which might help you:</p> <p>The py_compile module (<a href="http://effbot.org/librarybook/py-compile.htm" rel="nofollow">http://effbot.org/librarybook/py-compile.htm</a>) will allow you to explicitly compile modules (without running them like the 'import' statement does).</p> <pre><code>import py_compile py_compile.compile("my_module.py") </code></pre> <p>Also, the compileall module (<a href="http://effbot.org/librarybook/compileall.htm" rel="nofollow">http://effbot.org/librarybook/compileall.htm</a>) will compile all the modules found in a directory.</p> <pre><code>import compileall compileall.compile_dir(".", force=1) </code></pre>
1
2009-08-25T22:02:59Z
[ "python", "import", "compilation" ]
Prevent python imports compiling
1,331,235
<p>I have have a python file that imports a few frequently changed python files. I have had trouble with the imported files not recompiling when I change them. How do I stop them compiling?</p>
1
2009-08-25T21:52:55Z
1,331,744
<p>You are looking for <a href="http://docs.python.org/library/compileall.html" rel="nofollow">compileall</a></p> <blockquote> <p>compileall.compile_dir(dir[, maxlevels[, ddir[, force[, rx[, quiet]]]]])</p> <p>Recursively descend the directory tree named by dir, compiling all .py files along the way.</p> </blockquote>
0
2009-08-26T00:27:45Z
[ "python", "import", "compilation" ]
Prevent python imports compiling
1,331,235
<p>I have have a python file that imports a few frequently changed python files. I have had trouble with the imported files not recompiling when I change them. How do I stop them compiling?</p>
1
2009-08-25T21:52:55Z
1,331,831
<p>In python 2.6, you should be able to supply the -B option.</p>
1
2009-08-26T00:58:40Z
[ "python", "import", "compilation" ]
iTunes COM interface
1,331,438
<p>I would like to be able to control iTunes with python.</p> <p>I know this is possible and I successfully tested some examples I have seen here at stackoverflow and in other sites, too.</p> <p>However, I would like to read the documentation about this. I have registered in Mac Dev Center, and when try to access the [link] where the docs are, but I am redirected to the Mac Dev Center. </p> <p>Has anyone been able to download the docs, or is it just me?</p> <p>Thanks, nunos</p>
0
2009-08-25T22:45:40Z
1,332,030
<p>Apple has moved things around and failed to update their sites appropriately (trying to download the itunes sdk directly does bounce you back as you've observed), but by faithfully following the instructions found <a href="http://www.paraesthesia.com/archive/2009/05/20/itunes-com-for-windows-sdk-now-in-adc.aspx" rel="nofollow">here</a> I've been able to download the zipfile with the SDK and it appears to be intact and usable.</p>
3
2009-08-26T02:11:24Z
[ "python", "com", "itunes" ]
iTunes COM interface
1,331,438
<p>I would like to be able to control iTunes with python.</p> <p>I know this is possible and I successfully tested some examples I have seen here at stackoverflow and in other sites, too.</p> <p>However, I would like to read the documentation about this. I have registered in Mac Dev Center, and when try to access the [link] where the docs are, but I am redirected to the Mac Dev Center. </p> <p>Has anyone been able to download the docs, or is it just me?</p> <p>Thanks, nunos</p>
0
2009-08-25T22:45:40Z
5,668,626
<p>Pre-Scriptum: I use the COM for Windows, which is usable through Python.</p> <p>I have been able to download (leagaly) both an ActivePython install (<a href="http://www.activestate.com/activepython/downloads" rel="nofollow">here</a>) and the documentation for it (although i can't seem to find the link anymore, I have the file; send me your email if you need it). </p> <p>It is a very good tool, but you will unboutly need the documentation in order to get through.</p> <p>Don't forget <a href="http://www.google.fr/search?sourceid=chrome&amp;ie=UTF-8&amp;q=itunes%20com%20download#sclient=psy&amp;hl=fr&amp;source=hp&amp;q=itunes%20windows%20com%20example&amp;aq=f&amp;aqi=&amp;aql=&amp;oq=&amp;pbx=1&amp;fp=122b790cdd433dfe" rel="nofollow">google</a> if you need examples.</p> <p>Hope I helped.</p>
0
2011-04-14T19:31:18Z
[ "python", "com", "itunes" ]
In-memory size of a Python structure
1,331,471
<p>Is there a reference for the memory size of Python data stucture on 32- and 64-bit platforms?</p> <p>If not, this would be nice to have it on SO. The more exhaustive the better! So how many bytes are used by the following Python structures (depending on the <code>len</code> and the content type when relevant)?</p> <ul> <li><code>int</code></li> <li><code>float</code></li> <li>reference</li> <li><code>str</code></li> <li>unicode string</li> <li><code>tuple</code></li> <li><code>list</code></li> <li><code>dict</code></li> <li><code>set</code></li> <li><code>array.array</code></li> <li><code>numpy.array</code></li> <li><code>deque</code></li> <li>new-style classes object</li> <li>old-style classes object</li> <li>... and everything I am forgetting!</li> </ul> <p>(For containers that keep only references to other objects, we obviously do not want to count the size of the item themselves, since it might be shared.)</p> <p>Furthermore, is there a way to get the memory used by an object at runtime (recursively or not)?</p>
57
2009-08-25T22:56:35Z
1,331,541
<p>The recommendation from <a href="http://stackoverflow.com/questions/449560/how-do-i-determine-the-size-of-an-object-in-python">an earlier question</a> on this was to use <a href="http://docs.python.org/library/sys.html#sys.getsizeof" rel="nofollow">sys.getsizeof()</a>, quoting:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; x = 2 &gt;&gt;&gt; sys.getsizeof(x) 14 &gt;&gt;&gt; sys.getsizeof(sys.getsizeof) 32 &gt;&gt;&gt; sys.getsizeof('this') 38 &gt;&gt;&gt; sys.getsizeof('this also') 48 </code></pre> <p>You could take this approach:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; import decimal &gt;&gt;&gt; &gt;&gt;&gt; d = { ... "int": 0, ... "float": 0.0, ... "dict": dict(), ... "set": set(), ... "tuple": tuple(), ... "list": list(), ... "str": "a", ... "unicode": u"a", ... "decimal": decimal.Decimal(0), ... "object": object(), ... } &gt;&gt;&gt; for k, v in sorted(d.iteritems()): ... print k, sys.getsizeof(v) ... decimal 40 dict 140 float 16 int 12 list 36 object 8 set 116 str 25 tuple 28 unicode 28 </code></pre> <hr> <p>2012-09-30</p> <p>python 2.7 (linux, 32-bit):</p> <pre><code>decimal 36 dict 136 float 16 int 12 list 32 object 8 set 112 str 22 tuple 24 unicode 32 </code></pre> <p>python 3.3 (linux, 32-bit)</p> <pre><code>decimal 52 dict 144 float 16 int 14 list 32 object 8 set 112 str 26 tuple 24 unicode 26 </code></pre> <hr> <p>2016-08-01</p> <p>OSX, Python 2.7.10 (default, Oct 23 2015, 19:19:21) [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin</p> <pre><code>decimal 80 dict 280 float 24 int 24 list 72 object 16 set 232 str 38 tuple 56 unicode 52 </code></pre>
82
2009-08-25T23:13:48Z
[ "python", "memory", "memory-footprint" ]
In-memory size of a Python structure
1,331,471
<p>Is there a reference for the memory size of Python data stucture on 32- and 64-bit platforms?</p> <p>If not, this would be nice to have it on SO. The more exhaustive the better! So how many bytes are used by the following Python structures (depending on the <code>len</code> and the content type when relevant)?</p> <ul> <li><code>int</code></li> <li><code>float</code></li> <li>reference</li> <li><code>str</code></li> <li>unicode string</li> <li><code>tuple</code></li> <li><code>list</code></li> <li><code>dict</code></li> <li><code>set</code></li> <li><code>array.array</code></li> <li><code>numpy.array</code></li> <li><code>deque</code></li> <li>new-style classes object</li> <li>old-style classes object</li> <li>... and everything I am forgetting!</li> </ul> <p>(For containers that keep only references to other objects, we obviously do not want to count the size of the item themselves, since it might be shared.)</p> <p>Furthermore, is there a way to get the memory used by an object at runtime (recursively or not)?</p>
57
2009-08-25T22:56:35Z
1,331,952
<p>I've been happily using <a href="http://code.google.com/p/pympler/">pympler</a> for such tasks. It's compatible with many versions of Python -- the <code>asizeof</code> module in particular goes back to 2.2!</p> <p>For example, using hughdbrown's example but with <code>from pympler import asizeof</code> at the start and <code>print asizeof.asizeof(v)</code> at the end, I see (system Python 2.5 on MacOSX 10.5):</p> <pre><code>$ python pymp.py set 120 unicode 32 tuple 32 int 16 decimal 152 float 16 list 40 object 0 dict 144 str 32 </code></pre> <p>Clearly there is some approximation here, but I've found it very useful for footprint analysis and tuning.</p>
29
2009-08-26T01:45:10Z
[ "python", "memory", "memory-footprint" ]
In-memory size of a Python structure
1,331,471
<p>Is there a reference for the memory size of Python data stucture on 32- and 64-bit platforms?</p> <p>If not, this would be nice to have it on SO. The more exhaustive the better! So how many bytes are used by the following Python structures (depending on the <code>len</code> and the content type when relevant)?</p> <ul> <li><code>int</code></li> <li><code>float</code></li> <li>reference</li> <li><code>str</code></li> <li>unicode string</li> <li><code>tuple</code></li> <li><code>list</code></li> <li><code>dict</code></li> <li><code>set</code></li> <li><code>array.array</code></li> <li><code>numpy.array</code></li> <li><code>deque</code></li> <li>new-style classes object</li> <li>old-style classes object</li> <li>... and everything I am forgetting!</li> </ul> <p>(For containers that keep only references to other objects, we obviously do not want to count the size of the item themselves, since it might be shared.)</p> <p>Furthermore, is there a way to get the memory used by an object at runtime (recursively or not)?</p>
57
2009-08-25T22:56:35Z
12,667,362
<p>Try memory profiler. <a href="http://pypi.python.org/pypi/memory_profiler">memory profiler</a></p> <pre><code>Line # Mem usage Increment Line Contents ============================================== 3 @profile 4 5.97 MB 0.00 MB def my_func(): 5 13.61 MB 7.64 MB a = [1] * (10 ** 6) 6 166.20 MB 152.59 MB b = [2] * (2 * 10 ** 7) 7 13.61 MB -152.59 MB del b 8 13.61 MB 0.00 MB return a </code></pre>
5
2012-10-01T03:56:49Z
[ "python", "memory", "memory-footprint" ]
In-memory size of a Python structure
1,331,471
<p>Is there a reference for the memory size of Python data stucture on 32- and 64-bit platforms?</p> <p>If not, this would be nice to have it on SO. The more exhaustive the better! So how many bytes are used by the following Python structures (depending on the <code>len</code> and the content type when relevant)?</p> <ul> <li><code>int</code></li> <li><code>float</code></li> <li>reference</li> <li><code>str</code></li> <li>unicode string</li> <li><code>tuple</code></li> <li><code>list</code></li> <li><code>dict</code></li> <li><code>set</code></li> <li><code>array.array</code></li> <li><code>numpy.array</code></li> <li><code>deque</code></li> <li>new-style classes object</li> <li>old-style classes object</li> <li>... and everything I am forgetting!</li> </ul> <p>(For containers that keep only references to other objects, we obviously do not want to count the size of the item themselves, since it might be shared.)</p> <p>Furthermore, is there a way to get the memory used by an object at runtime (recursively or not)?</p>
57
2009-08-25T22:56:35Z
20,783,532
<p>Also you can use <a href="https://pypi.python.org/pypi/guppy/">guppy</a> module.</p> <pre><code>&gt;&gt;&gt; from guppy import hpy; hp=hpy() &gt;&gt;&gt; hp.heap() Partition of a set of 25853 objects. Total size = 3320992 bytes. Index Count % Size % Cumulative % Kind (class / dict of class) 0 11731 45 929072 28 929072 28 str 1 5832 23 469760 14 1398832 42 tuple 2 324 1 277728 8 1676560 50 dict (no owner) 3 70 0 216976 7 1893536 57 dict of module 4 199 1 210856 6 2104392 63 dict of type 5 1627 6 208256 6 2312648 70 types.CodeType 6 1592 6 191040 6 2503688 75 function 7 199 1 177008 5 2680696 81 type 8 124 0 135328 4 2816024 85 dict of class 9 1045 4 83600 3 2899624 87 __builtin__.wrapper_descriptor &lt;90 more rows. Type e.g. '_.more' to view.&gt; </code></pre> <p>And:</p> <pre><code>&gt;&gt;&gt; hp.iso(1, [1], "1", (1,), {1:1}, None) Partition of a set of 6 objects. Total size = 560 bytes. Index Count % Size % Cumulative % Kind (class / dict of class) 0 1 17 280 50 280 50 dict (no owner) 1 1 17 136 24 416 74 list 2 1 17 64 11 480 86 tuple 3 1 17 40 7 520 93 str 4 1 17 24 4 544 97 int 5 1 17 16 3 560 100 types.NoneType </code></pre>
6
2013-12-26T10:49:57Z
[ "python", "memory", "memory-footprint" ]
Using Heapy's Memory Profile Browser with Twisted.web
1,331,561
<p>I am trying to profile twisted python code with <a href="http://stackoverflow.com/questions/110259/python-memory-profiler">Heapy</a>. For example (pseudo code):</p> <pre><code>from twisted.web import resource, server from twisted.internet import reactor from guppy import hpy class RootResource(resource.Resource): render_GET(self, path, request): return "Hello World" if __name__ == '__main__': h = hpy() port = 8080 site = server.Site(RootResource(mq)) reactor.listenTCP(port, site) reactor.run() </code></pre> <p>What do I need to do to view Heapy profile results in the <a href="http://guppy-pe.sourceforge.net/pbscreen.jpg">profile browser</a>?</p>
8
2009-08-25T23:22:03Z
1,472,383
<p>After looking over the guppy website and not finding any information about how to launch the profile browser there, I started looking around the guppy source and eventually found guppy/heapy/Prof.py, at the end of which I saw a docstring containing this line:</p> <pre><code>[0] heapy_Use.html#heapykinds.Use.pb </code></pre> <p>Then, remembering that I had see some documentation giving the return type of guppy.hpy as Use, I checked to see if guppy.hpy().pb() would do anything. And, indeed, it does. So that appears to be how the profiler browser is launched. I'm not sure if this is what you were asking, but I needed to figure it out before I could answer the other possible part of your question. :)</p> <p>It seems the simplest way to make this information available would be to make a resource in your web server that invokes Use.pb as part of its rendering process. There are other approaches, such as embedding a manhole in your application, or using a signal handler to trigger it, but I like the resource idea. So, for example:</p> <pre><code>class ProfileBrowser(Resource): def render_GET(self, request): h.pb() return "You saw it, right?" ... root = RootResource(mq) root.putChild("profile-browser", ProfileBrowser()) ... </code></pre> <p>Then you can visit /profile-browser whenever you want to look at the profile browser. The "pb" call blocks until the profile browser is exited (note, just closing the window with the wm destroy button doesn't seem to cause it to return - only the exit menu item seems to) so your server is hung until you dismiss the window, but for debugging purposes that seems like it may be fine.</p>
6
2009-09-24T15:18:55Z
[ "python", "profiling", "heap", "twisted" ]
Extending Jython Syntax
1,331,784
<p>I would like to add syntax to Jython to enable a nicer API for users. For instance, matrix libraries like NumPy would benefit from having both matrix and elementwise operations like Matlab's <code>:*</code> vs. <code>*</code> infix operators.</p> <p>You can create a matrix in Octave using:</p> <pre><code>A = [ 1, 1, 2; 3, 5, 8; 13, 21, 34 ] </code></pre> <p>which is considerably nicer than NumPy's:</p> <pre><code>b = array( [ (1.5,2,3), (4,5,6) ] ) </code></pre> <p><code>R</code> uses formulas "y ~ x + z" for selecting variables in a matrix/data frame. This is considerably nicer than the alternative of <code>["y"] ["x","z"]</code> or parsing the string "y ~ x + y".</p> <p>More complicated examples can be implemented in Cython using <a href="http://www.fiber-space.de/EasyExtend/doc/EE.html" rel="nofollow">Easy Extend</a>. But EasyExtend doesn't work on the JVM.</p> <p>What is the easiest way but reasonably robust way to add syntax to Jython? It would be nice to have a framework to implement entirely new language constructs or define mini languages within jython.</p>
0
2009-08-26T00:41:09Z
1,429,218
<p>To the best of my knowledge there is not a macro / syntax expanding facility similar to EasyExtend, although <a href="http://fiber-space.de/wordpress/" rel="nofollow">the developer of EasyExtend</a> has been working on some jython projects recently (including some which are similar to EE). I suppose you could write a preprocessor of some kind, but I would tend to suggest that syntax extension isn't terribly popular in the python world and you might have better success implementing your own DSL if you really need to.</p>
1
2009-09-15T19:36:46Z
[ "python", "jython", "dsl" ]
Why does weakproxy not always preserve equivalence in python?
1,331,800
<p>MySQLDb uses weak proxy to prevent circular dependencies between cursors and connections.</p> <p>But you would expect from the documentation on weakref that you could still tests for equivalence. Yet:</p> <pre><code>In [36]: interactive.cursor.connection.thread_id() Out[36]: 4267758 In [37]: interactive.web_logic.conns.primary.thread_id() Out[37]: 4267758 In [38]: interactive.cursor.connection == interactive.web_logic.conns.primary Out[38]: False In [39]: interactive.cursor.connection Out[39]: &lt;weakproxy at 0x3881c60 to Connection at 0x94c010&gt; In [40]: interactive.web_logic.conns.primary Out[40]: &lt;_mysql.connection open to 'xendb01' at 94c010&gt; </code></pre> <p>How do I tell if the connections are the same ?</p>
1
2009-08-26T00:47:17Z
1,331,823
<p>If the object is a standard weakref, you need to call it to get the object itself.</p> <pre><code>import weakref class Test(object): pass a = Test() b = weakref.ref(a) a is b() # True a == b() # True </code></pre> <p>Using weakrefs here seems wrong, though: if I construct a connection, create a cursor from it, and discard the connection object, the cursor should remain valid. There shouldn't be a circular dependency unless the connection is keeping a list of all cursors, in which case <em>that</em> is what should be the weakref.</p>
0
2009-08-26T00:56:05Z
[ "python", "weak-references" ]
Why does weakproxy not always preserve equivalence in python?
1,331,800
<p>MySQLDb uses weak proxy to prevent circular dependencies between cursors and connections.</p> <p>But you would expect from the documentation on weakref that you could still tests for equivalence. Yet:</p> <pre><code>In [36]: interactive.cursor.connection.thread_id() Out[36]: 4267758 In [37]: interactive.web_logic.conns.primary.thread_id() Out[37]: 4267758 In [38]: interactive.cursor.connection == interactive.web_logic.conns.primary Out[38]: False In [39]: interactive.cursor.connection Out[39]: &lt;weakproxy at 0x3881c60 to Connection at 0x94c010&gt; In [40]: interactive.web_logic.conns.primary Out[40]: &lt;_mysql.connection open to 'xendb01' at 94c010&gt; </code></pre> <p>How do I tell if the connections are the same ?</p>
1
2009-08-26T00:47:17Z
1,331,996
<p>I've long found <code>weakref.proxy</code>'s design and implementation to be somewhat shaky. Witness...:</p> <pre><code>&gt;&gt;&gt; import weakref &gt;&gt;&gt; ob=set(range(23)) &gt;&gt;&gt; rob=weakref.proxy(ob) &gt;&gt;&gt; rob==ob False &gt;&gt;&gt; rob.__eq__(ob) True </code></pre> <p>...DEFINITELY peculiar! In practice what I use from <code>weakref</code> are weak-key or sometimes weak-value dictionaries; but <code>weakref.ref</code> is sounder than the proxy wrapper on top of it:</p> <pre><code>&gt;&gt;&gt; wr=weakref.ref(ob) &gt;&gt;&gt; wr()==ob True </code></pre> <p>The need to "call" the ref to get the object (or None if the object has since disappeared) unfortunately makes it non-transparent (so a DB API module couldn't do it while staying compliant to the API). I don't understand why MySqlDb wants weak cursor->connection referencing at all, but if they do I see why they felt they had to use proxies rather than refs. However, one pays a very high price for that transparency!</p> <p>Btw, the "explicit <code>__eq__</code>" trick (or an equivalent one with <code>__cmp__</code>, depending on the type of the underlying object) may help you, even though it's definitely inelegant!</p>
3
2009-08-26T01:58:41Z
[ "python", "weak-references" ]
Why does weakproxy not always preserve equivalence in python?
1,331,800
<p>MySQLDb uses weak proxy to prevent circular dependencies between cursors and connections.</p> <p>But you would expect from the documentation on weakref that you could still tests for equivalence. Yet:</p> <pre><code>In [36]: interactive.cursor.connection.thread_id() Out[36]: 4267758 In [37]: interactive.web_logic.conns.primary.thread_id() Out[37]: 4267758 In [38]: interactive.cursor.connection == interactive.web_logic.conns.primary Out[38]: False In [39]: interactive.cursor.connection Out[39]: &lt;weakproxy at 0x3881c60 to Connection at 0x94c010&gt; In [40]: interactive.web_logic.conns.primary Out[40]: &lt;_mysql.connection open to 'xendb01' at 94c010&gt; </code></pre> <p>How do I tell if the connections are the same ?</p>
1
2009-08-26T00:47:17Z
1,332,246
<p>Wrap the non proxy with weakref.proxy and use the identity operator:</p> <pre><code>&gt;&gt;&gt; interactive.cursor.connection is weakref.proxy(interactive.web_logic.conns.primary) True </code></pre> <p>Calling weakref.proxy() twice will return the same proxy object.</p>
1
2009-08-26T03:54:22Z
[ "python", "weak-references" ]
Regular Expression to match cross platform newline characters
1,331,815
<p>My program can accept data that has newline characters of \n, \r\n or \r (eg Unix, PC or Mac styles)</p> <p>What is the best way to construct a regular expression that will match whatever the encoding is?</p> <p>Alternatively, I could use universal_newline support on input, but now I'm interested to see what the regex would be.</p>
33
2009-08-26T00:54:20Z
1,331,840
<p>The regex I use when I want to be precise is <code>"\r\n?|\n"</code>.</p> <p>When I'm not concerned about consistency or empty lines, I use <code>"[\r\n]+"</code>, I imagine it makes my programs somewhere in the order of 0.2% faster.</p>
64
2009-08-26T01:02:00Z
[ "python", "regex", "cross-platform", "eol" ]
Regular Expression to match cross platform newline characters
1,331,815
<p>My program can accept data that has newline characters of \n, \r\n or \r (eg Unix, PC or Mac styles)</p> <p>What is the best way to construct a regular expression that will match whatever the encoding is?</p> <p>Alternatively, I could use universal_newline support on input, but now I'm interested to see what the regex would be.</p>
33
2009-08-26T00:54:20Z
39,022,365
<p>The pattern can be simplified to <code>\r?\n</code> for a little performance gain, if you don't have to deal with the old Mac style (OS 9 is unsupported since February 2002).</p>
0
2016-08-18T15:40:44Z
[ "python", "regex", "cross-platform", "eol" ]
import csv file into mysql database using django web application
1,332,077
<p>i try to upload a csv file into my web application and store it into mysql database but failed.Please can anyone help me?</p> <p>my user.py script:</p> <pre><code>def import_contact(request): if request.method == 'POST': form = UploadContactForm(request.POST, request.FILES) if form.is_valid(): csvfile = request.FILES['file'] print csvfile csvfile.read() testReader = csv.reader(csvfile,delimiter=' ', quotechar='|') for row in testReader: print "|".join(row) return HttpResponseRedirect('/admin') else: form = UploadContactForm() vars = RequestContext(request, { 'form': form }) return render_to_response('admin/import_contact.html', vars) </code></pre> <p>my forms.py script:</p> <pre><code>class UploadContactForm(forms.Form): file = forms.FileField(label='File:', error_messages = {'required': 'File required'}) </code></pre>
0
2009-08-26T02:31:38Z
1,332,903
<p>Since you haven't provided the code for the <code>getcsv</code> function, I'll have to use my crystal ball here a bit.</p> <p>One reason why the print in the <code>for row in testReader:</code> loop isn't working is that <code>getcsv</code> may already processes the file. Use <a href="http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects" rel="nofollow">the <code>seek</code> method</a> to reset the objects position in the file to zero again. That way the for loop will process it properly.</p> <p>Another reason why there's nothing stored in the database might be that in the code you've supplied there doesn't seem to be a reference to a <a href="http://docs.djangoproject.com/en/dev/topics/db/models/" rel="nofollow">model</a>. So how should Django know what it should store and where?</p>
1
2009-08-26T07:20:24Z
[ "python", "django" ]
how to fetch reference property in django template
1,332,290
<p>I am using aep on google app engine</p> <pre><code>class Link(): bag = db.Referencepropery(Bag) #bag have name, id and other property name = db.Stringpropery object_query = Link.all(); p = paginator( object_query) object_list = p.page(1); prefetch_references( object_list.object_list, 'bag') render_to_response(...,{'object_list':object_list.object_list},...) #template {% for object in object_list%} {{object.bag.id}} &lt;!--failed to get any value, why???/--&gt; {% end %} </code></pre>
1
2009-08-26T04:19:42Z
1,333,113
<p>There's several things wrong with your code:</p> <ul> <li>Your model classes need to extend db.Model</li> <li>Your properties need to call the constructor, not just reference it</li> <li>A StringProperty isn't a reference, so "prefetch_reference(objectlist, 'name')" doesn't make any sense.</li> </ul> <p>Here's one that makes a bit more sense:</p> <pre><code>class Link(db.Model): bag = db.ReferenceProperty(Bag) #bag have name, id and other property name = db.StringPropery() def view(): objectlist = get_object_list(.....) prefetch_reference(objectlist,'name') </code></pre>
1
2009-08-26T08:14:26Z
[ "python", "google-app-engine" ]
how to fetch reference property in django template
1,332,290
<p>I am using aep on google app engine</p> <pre><code>class Link(): bag = db.Referencepropery(Bag) #bag have name, id and other property name = db.Stringpropery object_query = Link.all(); p = paginator( object_query) object_list = p.page(1); prefetch_references( object_list.object_list, 'bag') render_to_response(...,{'object_list':object_list.object_list},...) #template {% for object in object_list%} {{object.bag.id}} &lt;!--failed to get any value, why???/--&gt; {% end %} </code></pre>
1
2009-08-26T04:19:42Z
13,339,316
<p>this problem is addressed in a later GAE django framework NON-REL so going to close this issue.</p>
0
2012-11-12T06:37:47Z
[ "python", "google-app-engine" ]
Using UTM with geodjango
1,332,376
<p>I'm looking into using the <a href="http://en.wikipedia.org/wiki/Universal%5FTransverse%5FMercator%5Fcoordinate%5Fsystem" rel="nofollow">UTM</a> coordinate system with geodjango. And I can't figure out how to get the data in properly.</p> <p>I've been browsing the documentation and it seems that the "<a href="http://geodjango.org/docs/geos.html#geosgeometry-geo-input-srid-none" rel="nofollow">GEOSGeometry(geo_input, srid=None)</a>" or "<a href="http://geodjango.org/docs/gdal.html?highlight=convertion#ogrgeometry" rel="nofollow">OGRGeometry</a>" could be used with an EWKT, but I can't figure out how to format the data.</p> <p>It looks like the UTM <a href="http://en.wikipedia.org/wiki/SRID" rel="nofollow">SRID</a> is: 2029</p> <p>From the <a href="http://en.wikipedia.org/wiki/Universal%5FTransverse%5FMercator%5Fcoordinate%5Fsystem" rel="nofollow">wikipedia article</a> the format is written like this: </p> <p>[<em>UTMZone</em>][<em>N or S</em>] [<em>easting</em>] [<em>northing</em>]</p> <p><em>17N 630084 4833438</em> </p> <p>So I tried the following with no luck:</p> <pre><code>&gt;&gt;&gt; from django.contrib.gis.geos import * &gt;&gt;&gt; pnt = GEOSGeometry('SRID=2029;POINT(17N 630084 4833438)') GEOS_ERROR: ParseException: Expected number but encountered word: '17N' &gt;&gt;&gt; &gt;&gt;&gt; from django.contrib.gis.gdal import OGRGeometry &gt;&gt;&gt; pnt = OGRGeometry('SRID=2029;POINT(17N 630084 4833438)') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python26\lib\site-packages\django\contrib\gis\gdal\geometries.py", line 106, in __init__ ogr_t = OGRGeomType(geom_input) File "C:\Python26\lib\site-packages\django\contrib\gis\gdal\geomtype.py", line 31, in __init__ raise OGRException('Invalid OGR String Type "%s"' % type_input) django.contrib.gis.gdal.error.OGRException: Invalid OGR String Type "srid=2029;point(17n 630084 4833438)" </code></pre> <p>Are there any example available to show how this is done?</p> <p>May be I should just do any necessary calulations in UTM and convert to decimal degrees?<br /> In this case does GEOS or other tools in geodjango provide convertion utitilites?</p>
1
2009-08-26T04:48:07Z
1,435,951
<p>The UTM zone (17N) is already specified by the spatial reference system -- <a href="http://spatialreference.org/ref/epsg/2029/" rel="nofollow">SRID 2029</a>, so you don't need to include it in the WKT you pass to the <code>GEOSGeometry</code> constructor.</p> <pre><code>&gt;&gt;&gt; from django.contrib.gis.geos import * &gt;&gt;&gt; pnt = GEOSGeometry('SRID=2029;POINT(630084 4833438)') &gt;&gt;&gt; (pnt.x, pnt.y) (630084.0, 4833438.0) &gt;&gt;&gt; pnt.srid 2029 </code></pre> <p>Then, for example:</p> <pre><code>&gt;&gt;&gt; pnt.transform(4326) # Transform to WGS84 &gt;&gt;&gt; (pnt.x, pnt.y) (-79.387137066054038, 43.644504290860461) &gt;&gt;&gt; pnt.srid 4326 </code></pre>
6
2009-09-16T23:01:01Z
[ "python", "django", "geodjango", "gdal", "geos" ]
Python multiprocessing for bulk file/conversion operation on Windows
1,332,583
<p>I have written a python script which watches a directory for new subdirectories, and then acts on each subdirectory in a loop. We have an external process which creates these subdirectories. Inside each subdirectory is a text file and a number of images. There is one record (line) in the text file for each image. For each subdirectory my script scans the text file, then calls a few external programs, one detects blank images (custom exe), then a call to "mogrify" (part of ImageMagick) which resizes and converts the images and finally a call to 7-zip which pacakges all of the converted images and text file into a single archive.</p> <p>The script runs fine, but is currently sequential. Looping over each subdirectory one at a time. It seems to me that this would be a good chance to do some multi-processing, since this is being run on a dual-CPU machine (8 cores total). </p> <p>The processing of a given subdirectory is independent of all others...they are self-contained.</p> <p>Currently I am just creating a list of sub-directories using a call to os.listdir() and then looping over that list. I figure I could move all of the per-subdirectory code (conversions, etc) into a separate function, and then somehow create a separate process to handle each subdirectory. Since I am somewhat new to Python, some suggestions on how to approach such multiprocessing would be appreciated. I am on Vista x64 running Python 2.6.</p>
0
2009-08-26T05:53:19Z
1,332,629
<p>I agree that the design of this sounds like it could benefit from concurrency. Take a look at <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">the multiprocessing module</a>. You may also want to look at <a href="http://docs.python.org/library/threading.html" rel="nofollow">the threading module</a>, and compare speeds. It's difficult to tell exactly how many cores are necessary to gain a benefit from multiprocessing vs. threading and eight cores is well within the range where threading might be faster (yes, despite the GIL).</p> <p>From a design perspective, my biggest recommendation is to avoid interaction between processes entirely if possible. Have one central thread look for the event that triggers process creation (I'm guessing it's a subdirectory creation?) and then spawn a process to handle the subdirectory. From there on out, the spawned process should not interact with any other processes, ever. From your description it seems like this should be possible.</p> <p>Lastly, I'd like to add in a word of encouragement for moving to <a href="http://docs.python.org/dev/3.0/whatsnew/3.0.html" rel="nofollow">Python 3.0</a>. There is a lot of talk of staying with 2.x but 3.0 does make some real improvements, and as more and more people start moving to Python 3.0, it's going to be more difficult to get tools and support for 2.x.</p>
0
2009-08-26T06:09:45Z
[ "python", "windows", "multiprocessing" ]
How to determine whether java is installed on a system through python?
1,332,598
<p>i needed to run a jar file from python code,but before running that file i want to know whether java is installed on the system or not, using the python code itself.Please help thanks </p>
2
2009-08-26T05:59:12Z
1,332,697
<p>You could simply use the system commands.</p> <p>e.g.</p> <pre><code>&gt;&gt;&gt;import os &gt;&gt;&gt;os.system("java -version") java version "1.5.0_19" </code></pre> <p>You will get the output, ofcourse assuming Java is in the classpath. </p>
3
2009-08-26T06:28:36Z
[ "java", "python" ]
How to determine whether java is installed on a system through python?
1,332,598
<p>i needed to run a jar file from python code,but before running that file i want to know whether java is installed on the system or not, using the python code itself.Please help thanks </p>
2
2009-08-26T05:59:12Z
1,332,722
<p>There is no 100% reliable / portable way to do this, but the following procedure should give you some confidence that Java has been installed and configured properly (on a Linux):</p> <ol> <li>Check that the "JAVA_HOME" environment variable has been set and that it points to a directory containing a "bin" directory and that the "bin" directory contains an executable "java" command.</li> <li>Check that the "java" command found via a search of "PATH" is the one that was found in step 1.</li> <li>Run the "java" command with "-version" to see if the output looks like a normal Java version stamp.</li> </ol> <p>This doesn't guarantee that the user has not done something weird.</p> <p>Actually, if it was me, I wouldn't bother with this. I'd just try to launch the Java app from Python assuming that the "java" on the user's path was the right one. If there were errors, I'd report them.</p>
5
2009-08-26T06:35:48Z
[ "java", "python" ]
Overloading failUnlessEqual in unittest.TestCase
1,332,656
<p>I want to overload failUnlessEqual in unittest.TestCase so I created a new TestCase class:</p> <pre><code>import unittest class MyTestCase(unittest.TestCase): def failUnlessEqual(self, first, second, msg=None): if msg: msg += ' Expected: %r - Received %r' % (first, second) unittest.TestCase.failUnlessEqual(self, first, second, msg) </code></pre> <p>And I am using it like:</p> <pre><code>class test_MyTest(MyTestCase): def testi(self): i = 1 self.assertEqual(i, 2, 'Checking value of i') def testx(self): x = 1 self.assertEqual(x, 2, 'Checking value of i') </code></pre> <p>This is what I get when I run the tests</p> <pre><code>&gt;&gt;&gt; unittest.main() FF ====================================================================== FAIL: testi (__main__.test_MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "&lt;stdin&gt;", line 4, in testi AssertionError: Checking value of i ====================================================================== FAIL: testx (__main__.test_MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "&lt;stdin&gt;", line 7, in testx AssertionError: Checking value of x ---------------------------------------------------------------------- Ran 2 tests in 0.000s FAILED (failures=2) </code></pre> <p>I was expecting that the the message would be 'Checking value of x Expecting: 2 - Received: 1'</p> <p>MyTestCase class is not being used at all. Can you tell me what I am doing wrong?</p>
0
2009-08-26T06:18:33Z
1,332,679
<p>You are calling assertEqual, but define failUnlessEqual. So why would you expect that your method is called - you are calling a different method, after all?</p> <p>Perhaps you have looked at the definition of TestCase, and seen the line</p> <pre><code>assertEqual = assertEquals = failUnlessEqual </code></pre> <p>This means that the method assertEqual has the same definition as failUnlessEqual. Unfortunately, that does not mean that overriding failUnlessEqual will also override assertEqual - assertEqual remains an alias for the failUnlessEqual definition in the base class.</p> <p>To make it work correctly, you need to repeat the assignments in your subclass, thereby redefining all three names.</p>
2
2009-08-26T06:23:29Z
[ "python", "unit-testing", "overloading" ]
How can I access the iphone / ipod clipboard using python?
1,332,846
<p>I want to modify a python application written for the ipod/iphone. It should copy a string into the clipboard so that I can use it in another application. Is it possible to access the iphone clipboard using python? Thanks in advance.</p> <p>UPDATE:</p> <p>Thanks for replying.</p> <p>A bit of background: The python program is a vocabulary program running locally on my ipod. Often I want to look up the vocabulary in a dictionary. Then I always have to repeat the following steps:</p> <ol> <li>Select and copy the word.</li> <li>Close the vocabulary program.</li> <li>Open the dictionary.</li> <li>Paste the word into the text field.</li> <li>Press search.</li> </ol> <p>I want to automate the process, therefore I want the python program to copy the word into the clipboard automatically and start the dictionary. I figured out the part with the starting already, using URL schemes. I was hoping to be able to automate the copying as well.</p>
1
2009-08-26T07:08:28Z
1,333,976
<p>Sorry no, I'm assuming since you mention python that this is a web-based application? If so there is no way you can put something into/take something out of the user's clipboard automatically. However if it is webbased the user will be able to select any text/image and copy to paste elsewhere.</p>
0
2009-08-26T11:12:57Z
[ "iphone", "python", "clipboard", "ipod-touch" ]
How to remotely restart a service on a password protected machine using Python?
1,332,853
<p>I decided to tackle Python as a new language to learn. The first thing I want to do is code a script that will allow me to remotely restart services on other machines from my local machine. How would I accomplish this when the remote machine requires a username and password to log on? I don't need a full solution to be given to me but maybe some pointers on what libraries I should use or any issues I need to address when writing the script.</p> <p>EDIT: All the remote machines are using Windows 2003</p>
0
2009-08-26T07:10:36Z
1,332,880
<p>People usually recommend <a href="http://www.lag.net/paramiko/" rel="nofollow">paramiko</a> as a library to do ssh (and I'm assuming that you need ssh to get into the remote machine). There is a good <a href="http://www.linuxplanet.com/linuxplanet/tutorials/6618/1/" rel="nofollow">tutorial</a> for it.</p> <p><strong>Edit</strong>: On windows, the easiest way is probably to use SysInternals <a href="http://www.linuxhowtos.org/System/procstat.htm" rel="nofollow">psservice</a> utility, to be invoked with os.system; this can start a remote service, and accepts logon credentials. </p> <p>If you want to do it directly in Python, you need <a href="http://docs.activestate.com/activepython/2.4/pywin32/win32service.html" rel="nofollow">win32service.StartService</a>. Before that, you need to open the remote service manager, and then the remote service. Before that, you need to impersonate the user as which you want to perform the operation, see the <a href="http://docs.activestate.com/activepython/2.5/pywin32/Windows%5FNT%5FSecurity%5F.2d.2d%5FImpersonation.html" rel="nofollow">example</a>.</p>
3
2009-08-26T07:15:36Z
[ "python", "remote-access" ]
How to remotely restart a service on a password protected machine using Python?
1,332,853
<p>I decided to tackle Python as a new language to learn. The first thing I want to do is code a script that will allow me to remotely restart services on other machines from my local machine. How would I accomplish this when the remote machine requires a username and password to log on? I don't need a full solution to be given to me but maybe some pointers on what libraries I should use or any issues I need to address when writing the script.</p> <p>EDIT: All the remote machines are using Windows 2003</p>
0
2009-08-26T07:10:36Z
1,332,891
<p>What kind of OS is your remote machine running? If it's linux, run <code>ssh(1)</code> using the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow"><code>subprocess</code> module</a>.</p> <p>If it's windows, then get the <a href="http://python.net/crew/mhammond/win32/Downloads.html" rel="nofollow">win32 extensions</a>. They allow you to call Windows functions. There should be an API to allow to access services. If they don't, there is a tool called <a href="http://commandwindows.com/sc.htm" rel="nofollow"><code>sc</code></a> (<a href="http://commandwindows.com/sc.htm" rel="nofollow">docs</a>) which you can run using the subprocess module.</p>
1
2009-08-26T07:18:02Z
[ "python", "remote-access" ]
How to remotely restart a service on a password protected machine using Python?
1,332,853
<p>I decided to tackle Python as a new language to learn. The first thing I want to do is code a script that will allow me to remotely restart services on other machines from my local machine. How would I accomplish this when the remote machine requires a username and password to log on? I don't need a full solution to be given to me but maybe some pointers on what libraries I should use or any issues I need to address when writing the script.</p> <p>EDIT: All the remote machines are using Windows 2003</p>
0
2009-08-26T07:10:36Z
1,332,896
<p>Take a look at <a href="http://www.nongnu.org/fab/" rel="nofollow">Fabric</a> wich is based on <a href="http://www.lag.net/paramiko/" rel="nofollow">paramiko</a>. This is really a good tool to automate remote tasks with python.</p> <p><a href="http://docs.fabfile.org/0.9/" rel="nofollow">Fabric Documentation</a> will show you how easy it is to use.</p>
3
2009-08-26T07:19:02Z
[ "python", "remote-access" ]
How to remotely restart a service on a password protected machine using Python?
1,332,853
<p>I decided to tackle Python as a new language to learn. The first thing I want to do is code a script that will allow me to remotely restart services on other machines from my local machine. How would I accomplish this when the remote machine requires a username and password to log on? I don't need a full solution to be given to me but maybe some pointers on what libraries I should use or any issues I need to address when writing the script.</p> <p>EDIT: All the remote machines are using Windows 2003</p>
0
2009-08-26T07:10:36Z
1,332,904
<p>Which OS for the target machines? If 'service' is 'Windows NT service', and your local machine is also Windows, I'd use IronPython as the Python language implementation and call straight into the WMI facilities in the .net System.Management namespace -- they're meant for remote admin like that.</p>
1
2009-08-26T07:20:26Z
[ "python", "remote-access" ]
How to remotely restart a service on a password protected machine using Python?
1,332,853
<p>I decided to tackle Python as a new language to learn. The first thing I want to do is code a script that will allow me to remotely restart services on other machines from my local machine. How would I accomplish this when the remote machine requires a username and password to log on? I don't need a full solution to be given to me but maybe some pointers on what libraries I should use or any issues I need to address when writing the script.</p> <p>EDIT: All the remote machines are using Windows 2003</p>
0
2009-08-26T07:10:36Z
15,391,577
<p>On Windows, the <a href="https://pypi.python.org/pypi/WMI/" rel="nofollow">wmi module</a> is now fantastic for this.</p>
0
2013-03-13T16:53:26Z
[ "python", "remote-access" ]
Renaming a HTML file with Python
1,332,876
<p>A bit of background: When I save a web page from e.g. IE8 as "webpage, complete", the images and such that the page contains are placed in a subfolder with the postfix "_files". This convention allows Windows to synchronize the .htm file and the accompanying folder.</p> <p>Now, in order to keep the synchronization intact, when I rename the HTML file from my Python script I want the "_files" folder to be renamed also. Is there an easy way to do this, or will I need to<br /> - rename the .htm file<br /> - rename the _files folder<br /> - parse the .htm file and replace all references to the old _files folder name with the new name?</p>
0
2009-08-26T07:15:24Z
1,332,899
<p>If you rename the folder, I'm not sure how you can get around parsing the <code>.htm</code> file and replacing instances of <code>_files</code> with the new suffix. Perhaps you can use a folder alias (shortcut?) but then that's not a very clean solution.</p>
0
2009-08-26T07:19:32Z
[ "python", "html" ]
Renaming a HTML file with Python
1,332,876
<p>A bit of background: When I save a web page from e.g. IE8 as "webpage, complete", the images and such that the page contains are placed in a subfolder with the postfix "_files". This convention allows Windows to synchronize the .htm file and the accompanying folder.</p> <p>Now, in order to keep the synchronization intact, when I rename the HTML file from my Python script I want the "_files" folder to be renamed also. Is there an easy way to do this, or will I need to<br /> - rename the .htm file<br /> - rename the _files folder<br /> - parse the .htm file and replace all references to the old _files folder name with the new name?</p>
0
2009-08-26T07:15:24Z
1,332,910
<p>There is just one easy way: Have IE save the file again under the new name. But if you want to do it later, you must parse the HTML. In this case, <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> is your friend.</p>
1
2009-08-26T07:21:47Z
[ "python", "html" ]
Renaming a HTML file with Python
1,332,876
<p>A bit of background: When I save a web page from e.g. IE8 as "webpage, complete", the images and such that the page contains are placed in a subfolder with the postfix "_files". This convention allows Windows to synchronize the .htm file and the accompanying folder.</p> <p>Now, in order to keep the synchronization intact, when I rename the HTML file from my Python script I want the "_files" folder to be renamed also. Is there an easy way to do this, or will I need to<br /> - rename the .htm file<br /> - rename the _files folder<br /> - parse the .htm file and replace all references to the old _files folder name with the new name?</p>
0
2009-08-26T07:15:24Z
1,333,124
<p>you can use simple string replace on your HTML file without parsing it, it can of course be troublesome if the text being replaced is mentioned in the HTML itself.. </p> <pre><code>os.rename("test.html", "test2.html") os.rename("test_files", "test2_files") with open("test2.html", "r") as f: s = f.read().replace("test_files", "test2_files") with open("test2.html", "w") as f: f.write(s) </code></pre>
0
2009-08-26T08:17:18Z
[ "python", "html" ]
Tick Python instances from Python
1,333,016
<p>I am interrested in doing a programming game using python, and I would like to do it in the style of GunTactyx (<a href="http://apocalyx.sourceforge.net/guntactyx/index.php" rel="nofollow">http://apocalyx.sourceforge.net/guntactyx/index.php</a>). Only much simpler, as I am primarily interrested in the parallel execution of python scripts from python.</p> <p>Gun Tactyx challenges the player to write a program that controls individual units working together in teams, where each instruction carries a time panalty. Each program is executed in its own protected environment, communicating with the game world through functions that can interact with the game world.</p> <p>I was wondering if there is a Python way of achieving similar effect. </p> <p>Pseudo code structure of the game engine would be something like:</p> <pre><code>Instantiate units with individual programs while 1 Update game world for unit in units: unit.tick() </code></pre> <p>The simulation would run until a timeout or some goal condition.</p> <p>Kind regards</p> <p>/Tax</p>
1
2009-08-26T07:49:29Z
1,333,856
<p>Maybe you should look into fork of python: <a href="http://stackless.com" rel="nofollow">stackless</a>, it allows concurrently running thousands of micro-threads without much performance penalty - every "thread" (these aren't real OS threads) could be one Unit.</p> <p>Also it's very easy to implement Actor model with stackless:</p> <blockquote> <p>In the actor model, everything is an actor (duh!). Actors are objects (in the generic sense, not necessarily the OO sense) that can: Receive messages from other actors. Process the received messages as they see fit. Send messages to other actors. Create new Actors.</p> <p>Actors do not have any direct access to other actors. All communication is accomplished via message passing. This provides a rich model to simulate real-world objects that are loosely-coupled and have limited knowledge of each others internals. </p> <p>from <a href="http://members.verizon.net/olsongt/stackless/why%5Fstackless.html#actors" rel="nofollow"><code>Introduction to concurrent programming with stackless</code></a></p> </blockquote> <p>Alternatively, you could also simulate this behavior by implementing co-routines - using python generators, like shown <a href="http://www.dabeaz.com/generators-uk/" rel="nofollow">here</a>. But I'll guess you'll be better off with stackless, as it's all there already.</p>
1
2009-08-26T10:53:35Z
[ "python" ]
Problem passing bash output to a python script
1,333,107
<p>I'm fairly new to programming and I searched the internet for a way to pass bash output to a Python script.</p> <p>I came up with this in bash.</p> <pre><code>XAS_SVN=`svn info` ssh hudson@test "python/runtests.py $XAS_SVN" </code></pre> <p>And this in python.</p> <pre><code>import sys print sys.argv[1] </code></pre> <p>When I <code>echo $SVN_INFO</code> I get the result.</p> <blockquote> <p>Path: . URL: //svn/rnd-projects/testing/python Repository Root: //svn/rnd-projects Repository UUID: d07d5450-0a36-4e07-90d2-9411ff75afe9 Revision: 140 Node Kind: directory Schedule: normal Last Changed Author: Roy van der Valk Last Changed Rev: 140 Last Changed Date: 2009-06-09 14:13:29 +0200 (Tue, 09 Jun 2009)</p> </blockquote> <p>However the python script just prints the following.</p> <blockquote> <p>Path:</p> </blockquote> <p>Why is this and how can I solve this? I the $SVN_INFO variable not of string type?</p> <p>I know about the subprocess module and the Popen function, but I don't think this is a solution since the python script runs on another server.</p>
1
2009-08-26T08:12:17Z
1,333,116
<p>Yes, you need to put in quotes your input to python/runtest.py because otherwise argv[1] gets it only up to the first space. Like this:</p> <pre><code>ssh hudson@test "python/runtest.py \"$XAS_SVN\"" </code></pre>
0
2009-08-26T08:14:54Z
[ "python", "bash" ]
Problem passing bash output to a python script
1,333,107
<p>I'm fairly new to programming and I searched the internet for a way to pass bash output to a Python script.</p> <p>I came up with this in bash.</p> <pre><code>XAS_SVN=`svn info` ssh hudson@test "python/runtests.py $XAS_SVN" </code></pre> <p>And this in python.</p> <pre><code>import sys print sys.argv[1] </code></pre> <p>When I <code>echo $SVN_INFO</code> I get the result.</p> <blockquote> <p>Path: . URL: //svn/rnd-projects/testing/python Repository Root: //svn/rnd-projects Repository UUID: d07d5450-0a36-4e07-90d2-9411ff75afe9 Revision: 140 Node Kind: directory Schedule: normal Last Changed Author: Roy van der Valk Last Changed Rev: 140 Last Changed Date: 2009-06-09 14:13:29 +0200 (Tue, 09 Jun 2009)</p> </blockquote> <p>However the python script just prints the following.</p> <blockquote> <p>Path:</p> </blockquote> <p>Why is this and how can I solve this? I the $SVN_INFO variable not of string type?</p> <p>I know about the subprocess module and the Popen function, but I don't think this is a solution since the python script runs on another server.</p>
1
2009-08-26T08:12:17Z
1,333,126
<p>Since you have spaces in the variable, you need to escape them or read all the arguments in your script:</p> <pre><code>print ' '.join(sys.argv[1:]) </code></pre> <p>But it might be better to use stdin/stdout to communicate, especially if there can be some characters susceptible to be interpreted by the shell in the output (like "`$'). In the python script do:</p> <pre><code>for l in sys.stdin: sys.stdout.write(l) </code></pre> <p>and in shell:</p> <pre><code>svn info | ssh hudson@test python/runtests.py </code></pre>
1
2009-08-26T08:17:57Z
[ "python", "bash" ]
django template system, calling a function inside a model
1,333,189
<p>I want to call a function from my model at a template such as:</p> <pre><code>class ChannelStatus(models.Model): .............................. .............................. def get_related_deltas(self,epk): mystring = "" if not self.get_error_code_delta(epk): return mystring else: for i in self.get_listof_outage(): item = i.error_code.all() for x in item: if epk == x.id: mystring= mystring +" "+str(i.delta()) return mystring </code></pre> <p>And when I want to call this from the template: assume while rendering, I pass channel_status_list as </p> <pre><code>channel_status_list = ChannelStatus.objects.all() {% for i in channel_status_list %} {{ i.get_related_deltas(3) }} {% endfor %} </code></pre> <p>This doesn't work, I am able to call a function that consumes nothing, but couln't find what to do if it has parameter(s)</p> <p>Cheers</p>
46
2009-08-26T08:31:03Z
1,333,277
<p>You can't call a function with parameters from the template. You can only do this in the view. Alternatively you could write a <a href="https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/#writing-custom-template-filters">custom template filter</a>, which might look like this:</p> <pre><code>@register.filter def related_deltas(obj, epk): return obj.get_related_deltas(epk) </code></pre> <p>So now you can do this in the template:</p> <pre><code>{% for i in channel_status_list %} {{ i|related_deltas:3 }} {% endfor %} </code></pre>
64
2009-08-26T08:51:17Z
[ "python", "django", "django-models", "django-templates" ]
django template system, calling a function inside a model
1,333,189
<p>I want to call a function from my model at a template such as:</p> <pre><code>class ChannelStatus(models.Model): .............................. .............................. def get_related_deltas(self,epk): mystring = "" if not self.get_error_code_delta(epk): return mystring else: for i in self.get_listof_outage(): item = i.error_code.all() for x in item: if epk == x.id: mystring= mystring +" "+str(i.delta()) return mystring </code></pre> <p>And when I want to call this from the template: assume while rendering, I pass channel_status_list as </p> <pre><code>channel_status_list = ChannelStatus.objects.all() {% for i in channel_status_list %} {{ i.get_related_deltas(3) }} {% endfor %} </code></pre> <p>This doesn't work, I am able to call a function that consumes nothing, but couln't find what to do if it has parameter(s)</p> <p>Cheers</p>
46
2009-08-26T08:31:03Z
3,598,020
<p>Another option is to define a property. See <a href="http://adam.gomaa.us/blog/2008/aug/11/the-python-property-builtin/" rel="nofollow">http://adam.gomaa.us/blog/2008/aug/11/the-python-property-builtin/</a> .</p> <p>You write your function that can do pretty much anything you want. You make it a read only property. You call the property from the template.</p> <p>Et voilà !!!!</p>
2
2010-08-30T05:13:40Z
[ "python", "django", "django-models", "django-templates" ]
django template system, calling a function inside a model
1,333,189
<p>I want to call a function from my model at a template such as:</p> <pre><code>class ChannelStatus(models.Model): .............................. .............................. def get_related_deltas(self,epk): mystring = "" if not self.get_error_code_delta(epk): return mystring else: for i in self.get_listof_outage(): item = i.error_code.all() for x in item: if epk == x.id: mystring= mystring +" "+str(i.delta()) return mystring </code></pre> <p>And when I want to call this from the template: assume while rendering, I pass channel_status_list as </p> <pre><code>channel_status_list = ChannelStatus.objects.all() {% for i in channel_status_list %} {{ i.get_related_deltas(3) }} {% endfor %} </code></pre> <p>This doesn't work, I am able to call a function that consumes nothing, but couln't find what to do if it has parameter(s)</p> <p>Cheers</p>
46
2009-08-26T08:31:03Z
4,560,708
<p>If you find that there are too many properties running around everywhere or you have a template filter for every other method that you write, another solution was suggested on IRC thanks @FunkyBob. It's a little well, erm, funky but it is nice in certain cases.</p> <pre><code> class MethodProxy(object): """For consolidating into 1 method the calling of methods with various single args (suitable dictionary keys) class MyModel(models.Model): ... def magic(self, value): # Free the ponies def thing(self): return MethodProxy(self.magic) # Usage &gt;&gt;&gt; m = MyModel() ... &gt;&gt;&gt; m.thing['value'] == m.magic('value') # template {{ m.thing.value }} """ def __init__(self, method): self.method = method def __getitem__(self, key): return self.method(key) </code></pre>
2
2010-12-30T07:05:11Z
[ "python", "django", "django-models", "django-templates" ]
django template system, calling a function inside a model
1,333,189
<p>I want to call a function from my model at a template such as:</p> <pre><code>class ChannelStatus(models.Model): .............................. .............................. def get_related_deltas(self,epk): mystring = "" if not self.get_error_code_delta(epk): return mystring else: for i in self.get_listof_outage(): item = i.error_code.all() for x in item: if epk == x.id: mystring= mystring +" "+str(i.delta()) return mystring </code></pre> <p>And when I want to call this from the template: assume while rendering, I pass channel_status_list as </p> <pre><code>channel_status_list = ChannelStatus.objects.all() {% for i in channel_status_list %} {{ i.get_related_deltas(3) }} {% endfor %} </code></pre> <p>This doesn't work, I am able to call a function that consumes nothing, but couln't find what to do if it has parameter(s)</p> <p>Cheers</p>
46
2009-08-26T08:31:03Z
13,367,016
<p>If the method doesn't require any arguments, you can use the @property decorator and access it normally in the template.</p> <pre><code>class ChannelStatus(models.Model): ... @property def function_you_want_as_property(self): mystring = "" ... </code></pre>
20
2012-11-13T19:03:03Z
[ "python", "django", "django-models", "django-templates" ]
django template system, calling a function inside a model
1,333,189
<p>I want to call a function from my model at a template such as:</p> <pre><code>class ChannelStatus(models.Model): .............................. .............................. def get_related_deltas(self,epk): mystring = "" if not self.get_error_code_delta(epk): return mystring else: for i in self.get_listof_outage(): item = i.error_code.all() for x in item: if epk == x.id: mystring= mystring +" "+str(i.delta()) return mystring </code></pre> <p>And when I want to call this from the template: assume while rendering, I pass channel_status_list as </p> <pre><code>channel_status_list = ChannelStatus.objects.all() {% for i in channel_status_list %} {{ i.get_related_deltas(3) }} {% endfor %} </code></pre> <p>This doesn't work, I am able to call a function that consumes nothing, but couln't find what to do if it has parameter(s)</p> <p>Cheers</p>
46
2009-08-26T08:31:03Z
31,197,650
<p>For > 1 argument, use <a href="https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#simple-tags" rel="nofollow">simple tags</a>:</p> <pre><code>@register.simple_tag def related_deltas(obj, epk, second_arg): return obj.get_related_deltas(epk, second_arg) </code></pre> <p>Template:</p> <pre><code>{% for i in channel_status_list %} {% related_deltas i 3 4 %} {% endfor %} </code></pre> <p><em>(Note the change of syntax from <code>{{</code> to <code>{%</code>)</em></p> <p>Can take <strong>positional</strong> parameters (e.g. <code>related_deltas i 3 second_arg=4 debug=true</code>).</p>
1
2015-07-03T02:45:00Z
[ "python", "django", "django-models", "django-templates" ]
Python: Set with only existence check?
1,333,381
<p>I have a set of lots of big long strings that I want to do existence lookups for. I don't need the whole string ever to be saved. As far as I can tell, the <code>set()</code> actually stored the string which is eating up a lot of my memory.</p> <p>Does such a data structure exist?</p> <pre><code>done = hash_only_set() while len(queue) &gt; 0 : item = queue.pop() if item not in done : process(item) done.add(item) </code></pre> <p>(My queue is constantly being filled by other threads so I have no way of dedupping it at the start).</p>
8
2009-08-26T09:13:44Z
1,333,414
<p>It's certainly possible to keep a set of only hashes:</p> <pre><code>done = set() while len(queue) &gt; 0 : item = queue.pop() h = hash(item) if h not in done : process(item) done.add(h) </code></pre> <p>Notice that because of hash collisions, there is a chance that you consider an item done even though it isn't. </p> <p>If you cannot accept this risk, you really need to save the full strings to be able to tell whether you have seen it before. Alternatively: perhaps the processing itself would be able to tell?</p> <p>Yet alternatively: if you cannot accept to keep the strings in memory, keep them in a database, or create files in a directory with the same name as the string.</p>
10
2009-08-26T09:18:59Z
[ "python", "data-structures", "hash", "set" ]
Python: Set with only existence check?
1,333,381
<p>I have a set of lots of big long strings that I want to do existence lookups for. I don't need the whole string ever to be saved. As far as I can tell, the <code>set()</code> actually stored the string which is eating up a lot of my memory.</p> <p>Does such a data structure exist?</p> <pre><code>done = hash_only_set() while len(queue) &gt; 0 : item = queue.pop() if item not in done : process(item) done.add(item) </code></pre> <p>(My queue is constantly being filled by other threads so I have no way of dedupping it at the start).</p>
8
2009-08-26T09:13:44Z
1,333,444
<p>You can use a data structure called <a href="http://en.wikipedia.org/wiki/Bloom%5Ffilter" rel="nofollow"><strong>Bloom Filter</strong></a> specifically for this purpose. A Python implementation can be found <a href="http://github.com/jaybaird/python-bloomfilter/tree/master" rel="nofollow">here</a>.</p> <p><strong>EDIT</strong>: Important notes:</p> <ol> <li>False positives <em>are</em> possible in this data structure, i.e. a check for the existence of a string could return a positive result even though it was <em>not</em> stored.</li> <li>False negatives (getting a negative result for a string that was stored) are not possible.</li> </ol> <p>That said, the chances of this happening can be brought to a minimum if used properly and so I consider this data structure to be very useful.</p>
4
2009-08-26T09:27:23Z
[ "python", "data-structures", "hash", "set" ]
Python: Set with only existence check?
1,333,381
<p>I have a set of lots of big long strings that I want to do existence lookups for. I don't need the whole string ever to be saved. As far as I can tell, the <code>set()</code> actually stored the string which is eating up a lot of my memory.</p> <p>Does such a data structure exist?</p> <pre><code>done = hash_only_set() while len(queue) &gt; 0 : item = queue.pop() if item not in done : process(item) done.add(item) </code></pre> <p>(My queue is constantly being filled by other threads so I have no way of dedupping it at the start).</p>
8
2009-08-26T09:13:44Z
1,333,462
<p>You would have to think about how to do the lookup, since there are two methods that the set needs, <code>__hash__</code> and <code>__eq__</code>.</p> <p>The hash is a "loose part" that you can take away, but the <code>__eq__</code> is not a loose part that you can save; you have to have two strings for the comparison.</p> <p>If you only need negative confirmation (this item is not part of the set), you could fill a Set collection you implemented yourself with your strings, then you "finalize" the set by removing all strings, except those with collisions (those are kept around for <strong>eq</strong> tests), and you promise not to add more objects to your Set. Now you have an exclusive test available.. you can tell if an object <em>is not</em> in your Set. You can't be certain if "obj in Set == True" is a false positive or not.</p> <p>Edit: This is basically a bloom filter that was cleverly linked, but a bloom filter might use more than one hash per element which is really clever.</p> <p>Edit2: This is my 3-minute bloom filter:</p> <pre><code>class BloomFilter (object): """ Let's make a bloom filter http://en.wikipedia.org/wiki/Bloom_filter __contains__ has false positives, but never false negatives """ def __init__(self, hashes=(hash, )): self.hashes = hashes self.data = set() def __contains__(self, obj): return all((h(obj) in self.data) for h in self.hashes) def add(self, obj): self.data.update(h(obj) for h in self.hashes) </code></pre>
2
2009-08-26T09:29:19Z
[ "python", "data-structures", "hash", "set" ]
Python: Set with only existence check?
1,333,381
<p>I have a set of lots of big long strings that I want to do existence lookups for. I don't need the whole string ever to be saved. As far as I can tell, the <code>set()</code> actually stored the string which is eating up a lot of my memory.</p> <p>Does such a data structure exist?</p> <pre><code>done = hash_only_set() while len(queue) &gt; 0 : item = queue.pop() if item not in done : process(item) done.add(item) </code></pre> <p>(My queue is constantly being filled by other threads so I have no way of dedupping it at the start).</p>
8
2009-08-26T09:13:44Z
1,333,634
<p>You need to know the whole string to have 100% certainty. If you have lots of strings with similar prefixes you could save space by using a trie to store the strings. If your strings are long you could also save space by using a large hash function like SHA-1 to make the possibility of hash collisions so remote as to be irrelevant.</p> <p>If you can make the <code>process()</code> function idempotent - i.e. having it called twice on an item is only a performance issue, then the problem becomes a lot simpler and you can use lossy datastructures, such as bloom filters.</p>
3
2009-08-26T10:06:02Z
[ "python", "data-structures", "hash", "set" ]
Python: Set with only existence check?
1,333,381
<p>I have a set of lots of big long strings that I want to do existence lookups for. I don't need the whole string ever to be saved. As far as I can tell, the <code>set()</code> actually stored the string which is eating up a lot of my memory.</p> <p>Does such a data structure exist?</p> <pre><code>done = hash_only_set() while len(queue) &gt; 0 : item = queue.pop() if item not in done : process(item) done.add(item) </code></pre> <p>(My queue is constantly being filled by other threads so I have no way of dedupping it at the start).</p>
8
2009-08-26T09:13:44Z
1,333,714
<p>If you use a secure (like SHA-256, found in the <code>hashlib</code> module) hash function to hash the strings, it's very unlikely that you would found duplicate (and if you find some you can probably win a prize as with most cryptographic hash functions).</p> <p>The builtin <code>__hash__()</code> method does not guarantee you won't have duplicates (and since it only uses 32 bits, it's very likely you'll find some).</p>
4
2009-08-26T10:21:06Z
[ "python", "data-structures", "hash", "set" ]
Python: Set with only existence check?
1,333,381
<p>I have a set of lots of big long strings that I want to do existence lookups for. I don't need the whole string ever to be saved. As far as I can tell, the <code>set()</code> actually stored the string which is eating up a lot of my memory.</p> <p>Does such a data structure exist?</p> <pre><code>done = hash_only_set() while len(queue) &gt; 0 : item = queue.pop() if item not in done : process(item) done.add(item) </code></pre> <p>(My queue is constantly being filled by other threads so I have no way of dedupping it at the start).</p>
8
2009-08-26T09:13:44Z
1,337,515
<p>As has been hinted already, if the answers offered here (most of which break down in the face of hash collisions) are not acceptable you would need to use a lossless representation of the strings. </p> <p>Python's zlib module provides built-in string compression capabilities and could be used to pre-process the strings before you put them in your set. Note however that the strings would need to be quite long (which you hint that they are) and have minimal entropy in order to save much memory space. Other compression options might provide better space savings and some Python based implementations can be found <a href="http://www.inference.phy.cam.ac.uk/mackay/python/compress/" rel="nofollow">here</a></p>
0
2009-08-26T21:10:44Z
[ "python", "data-structures", "hash", "set" ]
Delete None values from Python dict
1,334,020
<p>Newbie to Python, so this may seem silly.</p> <p>I have two dicts:</p> <pre><code>default = {'a': 'alpha', 'b': 'beta', 'g': 'Gamma'} user = {'a': 'NewAlpha', 'b': None} </code></pre> <p>I need to update my defaults with the values that exist in user. But only for those that have a value not equal to None. So I need to get back a new dict:</p> <pre><code>result = {'a': 'NewAlpha', 'b': 'beta', 'g': 'Gamma'} </code></pre>
8
2009-08-26T11:21:15Z
1,334,038
<pre><code>result = default.copy() result.update((k, v) for k, v in user.iteritems() if v is not None) </code></pre>
18
2009-08-26T11:24:05Z
[ "python" ]
Delete None values from Python dict
1,334,020
<p>Newbie to Python, so this may seem silly.</p> <p>I have two dicts:</p> <pre><code>default = {'a': 'alpha', 'b': 'beta', 'g': 'Gamma'} user = {'a': 'NewAlpha', 'b': None} </code></pre> <p>I need to update my defaults with the values that exist in user. But only for those that have a value not equal to None. So I need to get back a new dict:</p> <pre><code>result = {'a': 'NewAlpha', 'b': 'beta', 'g': 'Gamma'} </code></pre>
8
2009-08-26T11:21:15Z
1,334,040
<p>With the <code>update()</code> method, and some generator expression:</p> <pre><code>D.update((k, v) for k, v in user.iteritems() if v is not None) </code></pre>
7
2009-08-26T11:24:06Z
[ "python" ]
Python design patterns, cross importing
1,334,134
<p>I am using Python for automating a complex procedure that has few options. I want to have the following structure in python. - One "flow-class" containing the flow - One helper class that contains a lot of "black boxes" (functions that do not often get changed).</p> <p>99% of the time, I modify things in the flow-class so I only want code there that is often modified so I do not have to scroll around a lot to find the code I want to modify. This class also contains global variables (configuration settings) that often get changed. The helper class contains global variables that not often get changed.</p> <p>In the flow-class I have a global variable that I want the user to be forced to input at every run. The line looks like this. print ("Would you like to see debug output (enter = no)? ") debug = getUserInput()</p> <p>The getUserInput() function should be located in the helper class as it is never modified. The getUserInput needs a global variable from the flow class, which indicates whether the user input should be consistent with Linux command line or Eclipse (running on Windows).</p> <p>My question is: How can I structure this in the best way? Currently it looks like the following: The flow-class:</p> <pre><code>import helper_class isLinux = 1 debug = getUserInput() </code></pre> <p>The helper-class:</p> <pre><code>import os, flow_class def getUserInput(): userInput = input () if (flow_class.isLinux == 1): userInput = userInput[:-1] return userInput </code></pre> <p>This currently gives me the following error due to the cross importing:</p> <pre><code>Traceback (most recent call last): File "flow_class.py", line 1, in &lt;module&gt; import helper_class File "helper_class.py", line 1, in &lt;module&gt; import os, flow_class File "flow_class.py", line 5, in &lt;module&gt; debug = getUserInput() NameError: name 'getUserInput' is not defined </code></pre> <p>I know that I could obviously solve this by always passing isLinux as a parameter to getUserInput, but this complicates the usage of this method and makes it less intuitive.</p>
1
2009-08-26T11:43:00Z
1,334,202
<blockquote> <p>I know that I could obviously solve this by always passing <code>isLinux</code> as a parameter to getUserInput, but this complicates the usage of this method and makes it less intuitive.</p> </blockquote> <p>Actually using global variables complicates the usage of this program waaaay more than a simple parameter.</p> <p>try something like: </p> <pre><code>debug = getUserInput(isLinux=True) </code></pre> <p>Here's some other suggestions</p> <ul> <li>You mention there are lots of parameters that you'll change often. Should these be hard coded? Try using <a href="http://docs.python.org/library/configparser.html" rel="nofollow">a configuration file</a>, or passing a dict() from 'flow' as a parameter. That way you have a central place to change common variables without having to dive in!</li> <li>your 'flow/helper' class sounds like a <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="nofollow">Controller/Model</a> paradigm. This is good. But your model shouldn't have to import your controller. </li> </ul> <p>These aren't suggestions specific to 'pythonic style' these are general programming practices. If you're concerned about program design try reading <a href="http://rads.stackoverflow.com/amzn/click/020161622X" rel="nofollow">The Pragmatic Programmer</a>, they have great tips for workflow and design. There's also <a href="http://cc2e.com/" rel="nofollow">Code Complete</a> which Roberto suggested.</p>
1
2009-08-26T11:58:52Z
[ "design", "design-patterns", "python-3.x", "python" ]
Python design patterns, cross importing
1,334,134
<p>I am using Python for automating a complex procedure that has few options. I want to have the following structure in python. - One "flow-class" containing the flow - One helper class that contains a lot of "black boxes" (functions that do not often get changed).</p> <p>99% of the time, I modify things in the flow-class so I only want code there that is often modified so I do not have to scroll around a lot to find the code I want to modify. This class also contains global variables (configuration settings) that often get changed. The helper class contains global variables that not often get changed.</p> <p>In the flow-class I have a global variable that I want the user to be forced to input at every run. The line looks like this. print ("Would you like to see debug output (enter = no)? ") debug = getUserInput()</p> <p>The getUserInput() function should be located in the helper class as it is never modified. The getUserInput needs a global variable from the flow class, which indicates whether the user input should be consistent with Linux command line or Eclipse (running on Windows).</p> <p>My question is: How can I structure this in the best way? Currently it looks like the following: The flow-class:</p> <pre><code>import helper_class isLinux = 1 debug = getUserInput() </code></pre> <p>The helper-class:</p> <pre><code>import os, flow_class def getUserInput(): userInput = input () if (flow_class.isLinux == 1): userInput = userInput[:-1] return userInput </code></pre> <p>This currently gives me the following error due to the cross importing:</p> <pre><code>Traceback (most recent call last): File "flow_class.py", line 1, in &lt;module&gt; import helper_class File "helper_class.py", line 1, in &lt;module&gt; import os, flow_class File "flow_class.py", line 5, in &lt;module&gt; debug = getUserInput() NameError: name 'getUserInput' is not defined </code></pre> <p>I know that I could obviously solve this by always passing isLinux as a parameter to getUserInput, but this complicates the usage of this method and makes it less intuitive.</p>
1
2009-08-26T11:43:00Z
1,334,209
<p>I would like to question you on your last sentence. </p> <p>Usually, as also outlined in <a href="http://cc2e.com/" rel="nofollow">CC2</a>, usage of global variables helps in writing code, but not in reading it.<br /> And code is read many more times than it is written; in your case, I understand you modify the same script over and over again.</p> <p>The problem you are facing now is just a consequence of the generic design decision to use global variables.<br /> Explicit parameter passing would make it much clearer, and easier to maintain.</p> <p>As said in the the Zen of Python, <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">explicit is better than implicit</a>.</p>
1
2009-08-26T11:59:27Z
[ "design", "design-patterns", "python-3.x", "python" ]
Python design patterns, cross importing
1,334,134
<p>I am using Python for automating a complex procedure that has few options. I want to have the following structure in python. - One "flow-class" containing the flow - One helper class that contains a lot of "black boxes" (functions that do not often get changed).</p> <p>99% of the time, I modify things in the flow-class so I only want code there that is often modified so I do not have to scroll around a lot to find the code I want to modify. This class also contains global variables (configuration settings) that often get changed. The helper class contains global variables that not often get changed.</p> <p>In the flow-class I have a global variable that I want the user to be forced to input at every run. The line looks like this. print ("Would you like to see debug output (enter = no)? ") debug = getUserInput()</p> <p>The getUserInput() function should be located in the helper class as it is never modified. The getUserInput needs a global variable from the flow class, which indicates whether the user input should be consistent with Linux command line or Eclipse (running on Windows).</p> <p>My question is: How can I structure this in the best way? Currently it looks like the following: The flow-class:</p> <pre><code>import helper_class isLinux = 1 debug = getUserInput() </code></pre> <p>The helper-class:</p> <pre><code>import os, flow_class def getUserInput(): userInput = input () if (flow_class.isLinux == 1): userInput = userInput[:-1] return userInput </code></pre> <p>This currently gives me the following error due to the cross importing:</p> <pre><code>Traceback (most recent call last): File "flow_class.py", line 1, in &lt;module&gt; import helper_class File "helper_class.py", line 1, in &lt;module&gt; import os, flow_class File "flow_class.py", line 5, in &lt;module&gt; debug = getUserInput() NameError: name 'getUserInput' is not defined </code></pre> <p>I know that I could obviously solve this by always passing isLinux as a parameter to getUserInput, but this complicates the usage of this method and makes it less intuitive.</p>
1
2009-08-26T11:43:00Z
1,334,210
<p>you need to do <code>helper_class.getUserIinput()</code> in your <code>flow_class</code>. It's not about cross-importing. Once it's fixed you'll get <code>AttributeError</code> that is indeed related to cross-importing.</p> <p>At this stage you'll need to implement logic of getting <code>getUserInput</code> defined before importing <code>flow_class</code>.</p> <p>And to comment on your last statement: your assumption is not correct. Code would be much clearer if you use explicit local values.</p>
2
2009-08-26T11:59:30Z
[ "design", "design-patterns", "python-3.x", "python" ]
How can I mass-assign SA ORM object attributes?
1,334,171
<p>I have an ORM mapped object, that I want to update. I have all attributes validated and secured in a dictionary (keyword arguments). Now I would like to update all object attributes as in the dictionary.</p> <pre><code>for k,v in kw.items(): setattr(myobject, k, v) </code></pre> <p>doesnt work (AttributeError Exception), thrown from SQLAlchemy.</p> <pre><code>myobject.attr1 = kw['attr1'] myobject.attr2 = kw['attr2'] myobject.attr3 = kw['attr3'] </code></pre> <p>etc is horrible copy paste code, I want to avoid that.#</p> <p>How can i achieve this? SQLAlchemy already does something similar to what I want to do in their constructors ( myobject = MyClass(**kw) ), but I cant find that in all the meta programming obfuscated crap in there.</p> <p>error from SA:</p> <pre><code>&lt;&lt; if self.trackparent: if value is not None: self.sethasparent(instance_state(value), True) if previous is not value and previous is not None: self.sethasparent(instance_state(previous), False) &gt;&gt; self.sethasparent(instance_state(value), True) AttributeError: 'unicode' object has no attribute '_sa_instance_state' </code></pre>
1
2009-08-26T11:50:32Z
1,334,180
<pre><code>myobject.__dict__.update(**kw) </code></pre>
2
2009-08-26T11:53:08Z
[ "python", "sqlalchemy" ]
How can I mass-assign SA ORM object attributes?
1,334,171
<p>I have an ORM mapped object, that I want to update. I have all attributes validated and secured in a dictionary (keyword arguments). Now I would like to update all object attributes as in the dictionary.</p> <pre><code>for k,v in kw.items(): setattr(myobject, k, v) </code></pre> <p>doesnt work (AttributeError Exception), thrown from SQLAlchemy.</p> <pre><code>myobject.attr1 = kw['attr1'] myobject.attr2 = kw['attr2'] myobject.attr3 = kw['attr3'] </code></pre> <p>etc is horrible copy paste code, I want to avoid that.#</p> <p>How can i achieve this? SQLAlchemy already does something similar to what I want to do in their constructors ( myobject = MyClass(**kw) ), but I cant find that in all the meta programming obfuscated crap in there.</p> <p>error from SA:</p> <pre><code>&lt;&lt; if self.trackparent: if value is not None: self.sethasparent(instance_state(value), True) if previous is not value and previous is not None: self.sethasparent(instance_state(previous), False) &gt;&gt; self.sethasparent(instance_state(value), True) AttributeError: 'unicode' object has no attribute '_sa_instance_state' </code></pre>
1
2009-08-26T11:50:32Z
1,335,148
<p>You are trying to assign a unicode string to a relation attribute. Say you have:</p> <pre><code> class ClassA(Base): ... b_id = Column(None, ForeignKey('b.id')) b = relation(ClassB) </code></pre> <p>And you are trying to do:</p> <pre><code> my_object = ClassA() my_object.b = "foo" </code></pre> <p>When you should be doing either:</p> <pre><code> my_object.b_id = "foo" # or my_object.b = session.query(ClassB).get("foo") </code></pre>
3
2009-08-26T14:34:42Z
[ "python", "sqlalchemy" ]
How to change baseclass
1,334,222
<p>I have a class which is derived from a base class, and have many many lines of code</p> <p>e.g.</p> <pre><code>class AutoComplete(TextCtrl): ..... </code></pre> <p>What I want to do is change the baseclass so that it works like</p> <pre><code>class AutoComplete(PriceCtrl): ..... </code></pre> <p>I have use for both type of AutoCompletes and may be would like to add more base classes, so how can I do it dynamically?</p> <p>Composition would have been a solution, but I do not want to modify code a lot.</p> <p>any simple solutions?</p>
3
2009-08-26T12:02:05Z
1,334,242
<p>You could have a factory for your classes:</p> <pre><code>def completefactory(baseclass): class AutoComplete(baseclass): pass return AutoComplete </code></pre> <p>And then use:</p> <pre><code>TextAutoComplete = completefactory(TextCtrl) PriceAutoComplete = completefactory(PriceCtrl) </code></pre> <p>On the other hand depending on what you want to achieve and how your classes look, maybe AutoComplete is meant to be a mixin, so that you would define <code>TextAutoComplete</code> with:</p> <pre><code>class TextAutocomplete(TextCtrl, AutoComplete): pass </code></pre>
7
2009-08-26T12:06:52Z
[ "python", "dynamic", "class" ]
How to change baseclass
1,334,222
<p>I have a class which is derived from a base class, and have many many lines of code</p> <p>e.g.</p> <pre><code>class AutoComplete(TextCtrl): ..... </code></pre> <p>What I want to do is change the baseclass so that it works like</p> <pre><code>class AutoComplete(PriceCtrl): ..... </code></pre> <p>I have use for both type of AutoCompletes and may be would like to add more base classes, so how can I do it dynamically?</p> <p>Composition would have been a solution, but I do not want to modify code a lot.</p> <p>any simple solutions?</p>
3
2009-08-26T12:02:05Z
1,334,256
<p>You could modify the <code>__bases__</code> tuple. For example you could add another baseclass:</p> <pre><code>AutoComplete.__bases__ += (PriceCtrl,) </code></pre> <p>But in general I would try to avoid such hacks, it quickly creates a terrible mess.</p>
1
2009-08-26T12:11:51Z
[ "python", "dynamic", "class" ]
How to change baseclass
1,334,222
<p>I have a class which is derived from a base class, and have many many lines of code</p> <p>e.g.</p> <pre><code>class AutoComplete(TextCtrl): ..... </code></pre> <p>What I want to do is change the baseclass so that it works like</p> <pre><code>class AutoComplete(PriceCtrl): ..... </code></pre> <p>I have use for both type of AutoCompletes and may be would like to add more base classes, so how can I do it dynamically?</p> <p>Composition would have been a solution, but I do not want to modify code a lot.</p> <p>any simple solutions?</p>
3
2009-08-26T12:02:05Z
1,335,308
<p>You could use multiple inheritance for this:</p> <pre><code>class AutoCompleteBase(object): # code for your class # remember to call base implementation with super: # super(AutoCompleteBase, self).some_method() class TextAutoComplete(AutoCompleteBase, TextCtrl): pass class PriceAutoComplete(AutoCompleteBase, PriceCtrl): pass </code></pre> <p>Also, there's the option of a metaclass:</p> <pre><code>class BasesToSeparateClassesMeta(type): """Metaclass to create a separate childclass for each base. NB: doesn't create a class but a list of classes.""" def __new__(self, name, bases, dct): classes = [] for base in bases: cls = type.__new__(self, name, (base,), dct) # Need to init explicitly because not returning a class type.__init__(cls, name, (base,), dct) classes.append(cls) return classes class autocompletes(TextCtrl, PriceCtrl): __metaclass__ = BasesToSeparateClassesMeta # Rest of the code TextAutoComplete, PriceAutoComplete = autocompletes </code></pre> <p>But I'd still suggest the class factory approach already suggested, one level of indentation really isn't that big of a deal.</p>
2
2009-08-26T14:53:41Z
[ "python", "dynamic", "class" ]
Aggregate photos from various services into one Stream
1,334,477
<p>Helllo All, I'm looking to aggregate photos from various streams into one stream in a similar manner as to friend feed. I'd like to be able to watch flickr and picasa and other sites with RSS feeds of my choosing and then create a timeline of top photos.</p> <p>For example, assume that X's below are photos:</p> <pre><code>Event Name -- March 15th X X X X X X X X X more-&gt; Event Name 2 -- March 12th X X X X X X X X X more-&gt; Event Name 3 -- February 15th X X X X X X X X X more-&gt; </code></pre> <p>etc. It would be nice to also be able to filter based on rankings, etc...</p> <p>So, I've been searching for APIs/code libraries for PHP/JavaScript (but could also be Python) that would do such an aggregation, but I have yet to find anything. (My search terms probably weren't the best as it's hard to find anything specific when "picasa" and "flickr" are in the search request.)</p> <p>Any suggestion on some projects that do such a thing? If you've used FriendFeed, you'll know about what I'm looking for.</p> <p>Thanks.<code>enter code here</code></p>
0
2009-08-26T12:54:28Z
1,334,689
<p>Have you checked out <a href="http://gregarius.net/" rel="nofollow">Gregarius</a>. It's a PHP tool which you install on your own server which allows you to combine/group RSS feeds.</p> <p>A group of RSS feeds has its own RSS feed in gregarius. You don't need to look at the frontend you can just use gregarius as backend and use the group RSS feed to visualize your project. </p> <p>Not sure how to do the ranking with Gregarius.</p>
1
2009-08-26T13:28:09Z
[ "php", "javascript", "python" ]
Aggregate photos from various services into one Stream
1,334,477
<p>Helllo All, I'm looking to aggregate photos from various streams into one stream in a similar manner as to friend feed. I'd like to be able to watch flickr and picasa and other sites with RSS feeds of my choosing and then create a timeline of top photos.</p> <p>For example, assume that X's below are photos:</p> <pre><code>Event Name -- March 15th X X X X X X X X X more-&gt; Event Name 2 -- March 12th X X X X X X X X X more-&gt; Event Name 3 -- February 15th X X X X X X X X X more-&gt; </code></pre> <p>etc. It would be nice to also be able to filter based on rankings, etc...</p> <p>So, I've been searching for APIs/code libraries for PHP/JavaScript (but could also be Python) that would do such an aggregation, but I have yet to find anything. (My search terms probably weren't the best as it's hard to find anything specific when "picasa" and "flickr" are in the search request.)</p> <p>Any suggestion on some projects that do such a thing? If you've used FriendFeed, you'll know about what I'm looking for.</p> <p>Thanks.<code>enter code here</code></p>
0
2009-08-26T12:54:28Z
1,334,874
<p>I suggest using <a href="http://developer.yahoo.com/yql/" rel="nofollow">YQL</a>.</p> <blockquote> <p>The Yahoo! Query Language is an expressive SQL-like language that lets you query, filter, and join data across Web services.</p> </blockquote> <p>With it you can do things like the following:</p> <pre><code>select * from query.multi where queries="select enclosure from rss where url='http://picasaweb.google.com/data/feed/base/all?alt=rss&amp;kind=photo&amp;access=public&amp;filter=1&amp;q=Paris&amp;hl=de' LIMIT 5;select * from flickr.photos.search where text='Paris' LIMIT 5" </code></pre> <p>With this query you will get the first 5 images from Picasa RSS-Feed and Flickr-Search matching "Paris". (For Flickr you will have to create the link to the image by yourself)</p> <p>The output format can be either XML, JSON or <a href="http://ajaxian.com/archives/pimping-json-yql-now-offers-jsonp-x" rel="nofollow">JSONP-X</a></p>
2
2009-08-26T13:57:08Z
[ "php", "javascript", "python" ]
AttributeError: 'NoneType' object has no attribute 'GetDataStore'
1,334,607
<p>I guys, I developing a utility in python and i have 2 object the main class and an database helper for get sqlserver data.</p> <p>database.py</p> <pre><code>import _mssql class sqlserver(object): global _host, _userid, _pwd, _db def __new__ (self, host, userid, pwd, database): _host = host _userid = userid _pwd = pwd _db = database def GetDataStore(self, sql): conn = _mssql.connect(server='(local)\\sqlexpress', user='sa', password='xxx', database='Framework.Data2') conn.execute_non_query('CREATE TABLE persons(id INT, name VARCHAR(100))') conn.execute_non_query("INSERT INTO persons VALUES(1, 'John Doe')") conn.execute_non_query("INSERT INTO persons VALUES(2, 'Jane Doe')") </code></pre> <p>gaemodel.py</p> <pre><code>import os import sys from fwk import system, types, databases class helper(object): pass def usage(app_name): return "Usage: %s &lt;project name&gt;" % (app_name) def main(argv): _io = system.io() project_name = argv[1] project_home = os.path.join(_io.CurrentDir(), project_name) _db = databases.sqlserver('(local)\sqlexpress', 'sa', 'P1lim07181702', 'Framework.Data2') _db.GetDataStore("select name from sysobjects where xtype = 'U' and name not like 'Meta%'") str = "from google.appengine.ext import db" #for row in cur: # str += "class %s" % row["name"] print cur if __name__ == "__main__": if len(sys.argv) &gt; 1: main(sys.argv[1:]) else: print usage(sys.argv[0]); </code></pre> <p>My problem is when i try run code return me this error</p> <pre><code>Traceback (most recent call last): File "C:\Projectos\FrameworkGAE\src\gaemodel.py", line 28, in &lt;module&gt; main(sys.argv[1:]) File "C:\Projectos\FrameworkGAE\src\gaemodel.py", line 18, in main _ db. GetDataStore("select name from sysobjects where xtype = 'U' and name not like 'Meta%'") AttributeError: 'NoneType' object has no attribute 'GetDataStore' </code></pre> <p>What is wrong ??</p>
3
2009-08-26T13:16:01Z
1,334,680
<p>Have a look at what <a href="http://docs.python.org/reference/datamodel.html?highlight=%5F%5Fnew%5F%5F#object.%5F%5Fnew%5F%5F" rel="nofollow"><code>__new__</code></a> is supposed to be doing and what arguments it's supposed to have. I think you wanted to use <code>__init__</code> and not <code>__new__</code>. The reason for your particular error is that <code>_db</code> is <code>None</code>.</p>
1
2009-08-26T13:26:24Z
[ "python" ]
AttributeError: 'NoneType' object has no attribute 'GetDataStore'
1,334,607
<p>I guys, I developing a utility in python and i have 2 object the main class and an database helper for get sqlserver data.</p> <p>database.py</p> <pre><code>import _mssql class sqlserver(object): global _host, _userid, _pwd, _db def __new__ (self, host, userid, pwd, database): _host = host _userid = userid _pwd = pwd _db = database def GetDataStore(self, sql): conn = _mssql.connect(server='(local)\\sqlexpress', user='sa', password='xxx', database='Framework.Data2') conn.execute_non_query('CREATE TABLE persons(id INT, name VARCHAR(100))') conn.execute_non_query("INSERT INTO persons VALUES(1, 'John Doe')") conn.execute_non_query("INSERT INTO persons VALUES(2, 'Jane Doe')") </code></pre> <p>gaemodel.py</p> <pre><code>import os import sys from fwk import system, types, databases class helper(object): pass def usage(app_name): return "Usage: %s &lt;project name&gt;" % (app_name) def main(argv): _io = system.io() project_name = argv[1] project_home = os.path.join(_io.CurrentDir(), project_name) _db = databases.sqlserver('(local)\sqlexpress', 'sa', 'P1lim07181702', 'Framework.Data2') _db.GetDataStore("select name from sysobjects where xtype = 'U' and name not like 'Meta%'") str = "from google.appengine.ext import db" #for row in cur: # str += "class %s" % row["name"] print cur if __name__ == "__main__": if len(sys.argv) &gt; 1: main(sys.argv[1:]) else: print usage(sys.argv[0]); </code></pre> <p>My problem is when i try run code return me this error</p> <pre><code>Traceback (most recent call last): File "C:\Projectos\FrameworkGAE\src\gaemodel.py", line 28, in &lt;module&gt; main(sys.argv[1:]) File "C:\Projectos\FrameworkGAE\src\gaemodel.py", line 18, in main _ db. GetDataStore("select name from sysobjects where xtype = 'U' and name not like 'Meta%'") AttributeError: 'NoneType' object has no attribute 'GetDataStore' </code></pre> <p>What is wrong ??</p>
3
2009-08-26T13:16:01Z
1,334,705
<p>First of all:</p> <ul> <li>The <code>__new__</code> method should be named <code>__init__</code>.</li> <li>Remove the global _host etc. line</li> </ul> <p>Then change the <code>__init__</code> method:</p> <pre><code>self.host = host self.userid = userid etc. </code></pre> <p>And change <code>GetDataStore</code>:</p> <pre><code>conn = _mssql.connect(server=self.host, user=self.userid, etc.) </code></pre> <p>That should do the trick.</p> <p>I suggest you read a bit on object-oriented Python.</p>
3
2009-08-26T13:30:24Z
[ "python" ]
AttributeError: 'NoneType' object has no attribute 'GetDataStore'
1,334,607
<p>I guys, I developing a utility in python and i have 2 object the main class and an database helper for get sqlserver data.</p> <p>database.py</p> <pre><code>import _mssql class sqlserver(object): global _host, _userid, _pwd, _db def __new__ (self, host, userid, pwd, database): _host = host _userid = userid _pwd = pwd _db = database def GetDataStore(self, sql): conn = _mssql.connect(server='(local)\\sqlexpress', user='sa', password='xxx', database='Framework.Data2') conn.execute_non_query('CREATE TABLE persons(id INT, name VARCHAR(100))') conn.execute_non_query("INSERT INTO persons VALUES(1, 'John Doe')") conn.execute_non_query("INSERT INTO persons VALUES(2, 'Jane Doe')") </code></pre> <p>gaemodel.py</p> <pre><code>import os import sys from fwk import system, types, databases class helper(object): pass def usage(app_name): return "Usage: %s &lt;project name&gt;" % (app_name) def main(argv): _io = system.io() project_name = argv[1] project_home = os.path.join(_io.CurrentDir(), project_name) _db = databases.sqlserver('(local)\sqlexpress', 'sa', 'P1lim07181702', 'Framework.Data2') _db.GetDataStore("select name from sysobjects where xtype = 'U' and name not like 'Meta%'") str = "from google.appengine.ext import db" #for row in cur: # str += "class %s" % row["name"] print cur if __name__ == "__main__": if len(sys.argv) &gt; 1: main(sys.argv[1:]) else: print usage(sys.argv[0]); </code></pre> <p>My problem is when i try run code return me this error</p> <pre><code>Traceback (most recent call last): File "C:\Projectos\FrameworkGAE\src\gaemodel.py", line 28, in &lt;module&gt; main(sys.argv[1:]) File "C:\Projectos\FrameworkGAE\src\gaemodel.py", line 18, in main _ db. GetDataStore("select name from sysobjects where xtype = 'U' and name not like 'Meta%'") AttributeError: 'NoneType' object has no attribute 'GetDataStore' </code></pre> <p>What is wrong ??</p>
3
2009-08-26T13:16:01Z
1,334,707
<p>I think you want to change databases.py like this:</p> <pre><code>import _mssql class sqlserver(object): def __init__ (self, host, userid, pwd, database): self.host = host self.userid = userid self.pwd = pwd self.db = database def GetDataStore(self, sql): conn = _mssql.connect(server=self.host, user=self.userid, password=self.pwd, database=self.db) conn.execute_non_query('CREATE TABLE persons(id INT, name VARCHAR(100))') conn.execute_non_query("INSERT INTO persons VALUES(1, 'John Doe')") conn.execute_non_query("INSERT INTO persons VALUES(2, 'Jane Doe')") </code></pre>
0
2009-08-26T13:31:37Z
[ "python" ]
percentage difference between two text files
1,334,725
<p>I know that I can use cmp, diff, etc to compare two files, but what I am looking for is a utility that gives me percentage difference between two files. </p> <p>if there is no such utility, any algorithm would do fine too. I have read about fuzzy programming, but I have not quite understand it.</p>
4
2009-08-26T13:34:15Z
1,334,758
<p>You can use difflib.SequenceMatcher <a href="http://docs.python.org/library/difflib.html#difflib.SequenceMatcher.ratio">ratio</a> method</p> <p>From the documentation:</p> <blockquote> <p>Return a measure of the sequences’ similarity as a float in the range [0, 1].</p> </blockquote> <p>For example:</p> <pre><code>from difflib import SequenceMatcher text1 = open(file1).read() text2 = open(file2).read() m = SequenceMatcher(None, text1, text2) m.ratio() </code></pre>
19
2009-08-26T13:39:05Z
[ "python", "linux", "algorithm", "language-agnostic" ]
percentage difference between two text files
1,334,725
<p>I know that I can use cmp, diff, etc to compare two files, but what I am looking for is a utility that gives me percentage difference between two files. </p> <p>if there is no such utility, any algorithm would do fine too. I have read about fuzzy programming, but I have not quite understand it.</p>
4
2009-08-26T13:34:15Z
1,334,820
<p>It looks like Linux has a utility called dwdiff that can give percentage differences by using the "-s" flag</p> <p><a href="http://www.softpanorama.org/Utilities/diff%5Ftools.shtml" rel="nofollow">http://www.softpanorama.org/Utilities/diff_tools.shtml</a> </p>
2
2009-08-26T13:48:42Z
[ "python", "linux", "algorithm", "language-agnostic" ]
percentage difference between two text files
1,334,725
<p>I know that I can use cmp, diff, etc to compare two files, but what I am looking for is a utility that gives me percentage difference between two files. </p> <p>if there is no such utility, any algorithm would do fine too. I have read about fuzzy programming, but I have not quite understand it.</p>
4
2009-08-26T13:34:15Z
33,805,621
<p><a href="http://www.scootersoftware.com/index.php" rel="nofollow">Beyond Compare</a> has very nice file difference statistics export to csv. Differences at line level are reported so it's nice to compare source code files.</p>
0
2015-11-19T13:42:51Z
[ "python", "linux", "algorithm", "language-agnostic" ]
Iteration over list slices
1,335,392
<p>Good day function-wizards,</p> <p>I want an algorithm to iterate over list slices. Slices size is set outside the function and can differ.</p> <p>In my mind it is something like:</p> <pre><code>for list_of_x_items in fatherList: foo(list_of_x_items) </code></pre> <p>Is there a way to properly define <code>list_of_x_items</code> or some other way of doing this?</p> <p>Thank you greatly.</p> <p><em>PS: using python 2.5</em></p> <p><hr /></p> <p><strong>edit1:</strong> So many beautiful answers.. Someone has asked to clarify. Both "partitioning" and "sliding window" terms sound applicable to my task, but I am no expert. So I will explain the problem a bit deeper and add to the question:</p> <p>The fatherList is a multilevel numpy.array I am getting from a file. Function has to find averages of series (user provides the length of series) For averaging I am using the <code>mean()</code> function. Now for question expansion:</p> <p><strong>question update:</strong> How to modify the function you have provided to store the extra items and use them when the next fatherList is fed to the function?</p> <p>for example if the list is lenght 10 and size of a chunk is 3, then the 10th member of the list is stored and appended to the beginning of the next list.</p> <p>Hope I am not assaulting anyone by not creating a separate question.</p> <p><hr /></p> <p><strong>edit2:</strong> Ah, SO will you marry me? Many beautiful answers and only one to choose.. Thank you everyone, I've learned more from this question than from a month of my university studies. I am choosing the OO answer because it will allow me more flexibility in the future.</p> <p><hr /></p> <h3>Related:</h3> <ul> <li><a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></li> </ul>
19
2009-08-26T15:04:04Z
1,335,456
<p>Do you mean something like:</p> <pre><code>def callonslices(size, fatherList, foo): for i in xrange(0, len(fatherList), size): foo(fatherList[i:i+size]) </code></pre> <p>If this is roughly the functionality you want you might, if you desire, dress it up a bit in a generator:</p> <pre><code>def sliceup(size, fatherList): for i in xrange(0, len(fatherList), size): yield fatherList[i:i+size] </code></pre> <p>and then:</p> <pre><code>def callonslices(size, fatherList, foo): for sli in sliceup(size, fatherList): foo(sli) </code></pre>
7
2009-08-26T15:12:18Z
[ "python", "loops", "iteration", "slice" ]
Iteration over list slices
1,335,392
<p>Good day function-wizards,</p> <p>I want an algorithm to iterate over list slices. Slices size is set outside the function and can differ.</p> <p>In my mind it is something like:</p> <pre><code>for list_of_x_items in fatherList: foo(list_of_x_items) </code></pre> <p>Is there a way to properly define <code>list_of_x_items</code> or some other way of doing this?</p> <p>Thank you greatly.</p> <p><em>PS: using python 2.5</em></p> <p><hr /></p> <p><strong>edit1:</strong> So many beautiful answers.. Someone has asked to clarify. Both "partitioning" and "sliding window" terms sound applicable to my task, but I am no expert. So I will explain the problem a bit deeper and add to the question:</p> <p>The fatherList is a multilevel numpy.array I am getting from a file. Function has to find averages of series (user provides the length of series) For averaging I am using the <code>mean()</code> function. Now for question expansion:</p> <p><strong>question update:</strong> How to modify the function you have provided to store the extra items and use them when the next fatherList is fed to the function?</p> <p>for example if the list is lenght 10 and size of a chunk is 3, then the 10th member of the list is stored and appended to the beginning of the next list.</p> <p>Hope I am not assaulting anyone by not creating a separate question.</p> <p><hr /></p> <p><strong>edit2:</strong> Ah, SO will you marry me? Many beautiful answers and only one to choose.. Thank you everyone, I've learned more from this question than from a month of my university studies. I am choosing the OO answer because it will allow me more flexibility in the future.</p> <p><hr /></p> <h3>Related:</h3> <ul> <li><a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></li> </ul>
19
2009-08-26T15:04:04Z
1,335,464
<p>Your question could use some more detail, but how about:</p> <pre><code>def iterate_over_slices(the_list, slice_size): for start in range(0, len(the_list)-slice_size): slice = the_list[start:start+slice_size] foo(slice) </code></pre>
2
2009-08-26T15:13:03Z
[ "python", "loops", "iteration", "slice" ]
Iteration over list slices
1,335,392
<p>Good day function-wizards,</p> <p>I want an algorithm to iterate over list slices. Slices size is set outside the function and can differ.</p> <p>In my mind it is something like:</p> <pre><code>for list_of_x_items in fatherList: foo(list_of_x_items) </code></pre> <p>Is there a way to properly define <code>list_of_x_items</code> or some other way of doing this?</p> <p>Thank you greatly.</p> <p><em>PS: using python 2.5</em></p> <p><hr /></p> <p><strong>edit1:</strong> So many beautiful answers.. Someone has asked to clarify. Both "partitioning" and "sliding window" terms sound applicable to my task, but I am no expert. So I will explain the problem a bit deeper and add to the question:</p> <p>The fatherList is a multilevel numpy.array I am getting from a file. Function has to find averages of series (user provides the length of series) For averaging I am using the <code>mean()</code> function. Now for question expansion:</p> <p><strong>question update:</strong> How to modify the function you have provided to store the extra items and use them when the next fatherList is fed to the function?</p> <p>for example if the list is lenght 10 and size of a chunk is 3, then the 10th member of the list is stored and appended to the beginning of the next list.</p> <p>Hope I am not assaulting anyone by not creating a separate question.</p> <p><hr /></p> <p><strong>edit2:</strong> Ah, SO will you marry me? Many beautiful answers and only one to choose.. Thank you everyone, I've learned more from this question than from a month of my university studies. I am choosing the OO answer because it will allow me more flexibility in the future.</p> <p><hr /></p> <h3>Related:</h3> <ul> <li><a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></li> </ul>
19
2009-08-26T15:04:04Z
1,335,466
<p>Use a generator:</p> <pre><code>big_list = [1,2,3,4,5,6,7,8,9] slice_length = 3 def sliceIterator(lst, sliceLen): for i in range(len(lst) - sliceLen + 1): yield lst[i:i + sliceLen] for slice in sliceIterator(big_list, slice_length): foo(slice) </code></pre> <p><code>sliceIterator</code> implements a "sliding window" of width <code>sliceLen</code> over the squence <code>lst</code>, i.e. it produces overlapping slices: [1,2,3], [2,3,4], [3,4,5], ... Not sure if that is the OP's intention, though.</p>
5
2009-08-26T15:13:22Z
[ "python", "loops", "iteration", "slice" ]
Iteration over list slices
1,335,392
<p>Good day function-wizards,</p> <p>I want an algorithm to iterate over list slices. Slices size is set outside the function and can differ.</p> <p>In my mind it is something like:</p> <pre><code>for list_of_x_items in fatherList: foo(list_of_x_items) </code></pre> <p>Is there a way to properly define <code>list_of_x_items</code> or some other way of doing this?</p> <p>Thank you greatly.</p> <p><em>PS: using python 2.5</em></p> <p><hr /></p> <p><strong>edit1:</strong> So many beautiful answers.. Someone has asked to clarify. Both "partitioning" and "sliding window" terms sound applicable to my task, but I am no expert. So I will explain the problem a bit deeper and add to the question:</p> <p>The fatherList is a multilevel numpy.array I am getting from a file. Function has to find averages of series (user provides the length of series) For averaging I am using the <code>mean()</code> function. Now for question expansion:</p> <p><strong>question update:</strong> How to modify the function you have provided to store the extra items and use them when the next fatherList is fed to the function?</p> <p>for example if the list is lenght 10 and size of a chunk is 3, then the 10th member of the list is stored and appended to the beginning of the next list.</p> <p>Hope I am not assaulting anyone by not creating a separate question.</p> <p><hr /></p> <p><strong>edit2:</strong> Ah, SO will you marry me? Many beautiful answers and only one to choose.. Thank you everyone, I've learned more from this question than from a month of my university studies. I am choosing the OO answer because it will allow me more flexibility in the future.</p> <p><hr /></p> <h3>Related:</h3> <ul> <li><a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></li> </ul>
19
2009-08-26T15:04:04Z
1,335,572
<p>If you want to be able to consume any iterable you can use these functions:</p> <pre><code>from itertools import chain, islice def ichunked(seq, chunksize): """Yields items from an iterator in iterable chunks.""" it = iter(seq) while True: yield chain([it.next()], islice(it, chunksize-1)) def chunked(seq, chunksize): """Yields items from an iterator in list chunks.""" for chunk in ichunked(seq, chunksize): yield list(chunk) </code></pre>
18
2009-08-26T15:28:54Z
[ "python", "loops", "iteration", "slice" ]
Iteration over list slices
1,335,392
<p>Good day function-wizards,</p> <p>I want an algorithm to iterate over list slices. Slices size is set outside the function and can differ.</p> <p>In my mind it is something like:</p> <pre><code>for list_of_x_items in fatherList: foo(list_of_x_items) </code></pre> <p>Is there a way to properly define <code>list_of_x_items</code> or some other way of doing this?</p> <p>Thank you greatly.</p> <p><em>PS: using python 2.5</em></p> <p><hr /></p> <p><strong>edit1:</strong> So many beautiful answers.. Someone has asked to clarify. Both "partitioning" and "sliding window" terms sound applicable to my task, but I am no expert. So I will explain the problem a bit deeper and add to the question:</p> <p>The fatherList is a multilevel numpy.array I am getting from a file. Function has to find averages of series (user provides the length of series) For averaging I am using the <code>mean()</code> function. Now for question expansion:</p> <p><strong>question update:</strong> How to modify the function you have provided to store the extra items and use them when the next fatherList is fed to the function?</p> <p>for example if the list is lenght 10 and size of a chunk is 3, then the 10th member of the list is stored and appended to the beginning of the next list.</p> <p>Hope I am not assaulting anyone by not creating a separate question.</p> <p><hr /></p> <p><strong>edit2:</strong> Ah, SO will you marry me? Many beautiful answers and only one to choose.. Thank you everyone, I've learned more from this question than from a month of my university studies. I am choosing the OO answer because it will allow me more flexibility in the future.</p> <p><hr /></p> <h3>Related:</h3> <ul> <li><a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></li> </ul>
19
2009-08-26T15:04:04Z
1,335,618
<p>If you want to divide a list into slices you can use this trick:</p> <pre><code>list_of_slices = zip(*(iter(the_list),) * slice_size) </code></pre> <p>For example</p> <pre><code>&gt;&gt;&gt; zip(*(iter(range(10)),) * 3) [(0, 1, 2), (3, 4, 5), (6, 7, 8)] </code></pre> <p>If the number of items is not dividable by the slice size and you want to pad the list with None you can do this:</p> <pre><code>&gt;&gt;&gt; map(None, *(iter(range(10)),) * 3) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)] </code></pre> <p>It is a dirty little trick</p> <p><hr /></p> <p>OK, I'll explain how it works. It'll be tricky to explain but I'll try my best.</p> <p>First a little background:</p> <p>In Python you can multiply a list by a number like this:</p> <pre><code>[1, 2, 3] * 3 -&gt; [1, 2, 3, 1, 2, 3, 1, 2, 3] ([1, 2, 3],) * 3 -&gt; ([1, 2, 3], [1, 2, 3], [1, 2, 3]) </code></pre> <p>And an <a href="http://docs.python.org/library/functions.html?highlight=iter#iter">iterator</a> object can be consumed once like this:</p> <pre><code>&gt;&gt;&gt; l=iter([1, 2, 3]) &gt;&gt;&gt; l.next() 1 &gt;&gt;&gt; l.next() 2 &gt;&gt;&gt; l.next() 3 </code></pre> <p>The <a href="http://docs.python.org/library/functions.html#zip">zip</a> function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. For example:</p> <pre><code>zip([1, 2, 3], [20, 30, 40]) -&gt; [(1, 20), (2, 30), (3, 40)] zip(*[(1, 20), (2, 30), (3, 40)]) -&gt; [[1, 2, 3], [20, 30, 40]] </code></pre> <p>The * in front of zip used to unpack arguments. You can find more details <a href="http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists">here</a>. So</p> <pre><code>zip(*[(1, 20), (2, 30), (3, 40)]) </code></pre> <p>is actually equivalent to </p> <pre><code>zip((1, 20), (2, 30), (3, 40)) </code></pre> <p>but works with a variable number of arguments</p> <p>Now back to the trick:</p> <pre><code>list_of_slices = zip(*(iter(the_list),) * slice_size) </code></pre> <p><code>iter(the_list)</code> -> convert the list into an iterator</p> <p><code>(iter(the_list),) * N</code> -> will generate an N reference to the_list iterator.</p> <p><code>zip(*(iter(the_list),) * N)</code> -> will feed those list of iterators into zip. Which in turn will group them into N sized tuples. But since all N items are in fact references to the same iterator <code>iter(the_list)</code> the result will be repeated calls to <code>next()</code> on the original iterator</p> <p>I hope that explains it. I advice you to go with an easier to understand solution. I was only tempted to mention this trick because I like it.</p>
48
2009-08-26T15:35:05Z
[ "python", "loops", "iteration", "slice" ]
Iteration over list slices
1,335,392
<p>Good day function-wizards,</p> <p>I want an algorithm to iterate over list slices. Slices size is set outside the function and can differ.</p> <p>In my mind it is something like:</p> <pre><code>for list_of_x_items in fatherList: foo(list_of_x_items) </code></pre> <p>Is there a way to properly define <code>list_of_x_items</code> or some other way of doing this?</p> <p>Thank you greatly.</p> <p><em>PS: using python 2.5</em></p> <p><hr /></p> <p><strong>edit1:</strong> So many beautiful answers.. Someone has asked to clarify. Both "partitioning" and "sliding window" terms sound applicable to my task, but I am no expert. So I will explain the problem a bit deeper and add to the question:</p> <p>The fatherList is a multilevel numpy.array I am getting from a file. Function has to find averages of series (user provides the length of series) For averaging I am using the <code>mean()</code> function. Now for question expansion:</p> <p><strong>question update:</strong> How to modify the function you have provided to store the extra items and use them when the next fatherList is fed to the function?</p> <p>for example if the list is lenght 10 and size of a chunk is 3, then the 10th member of the list is stored and appended to the beginning of the next list.</p> <p>Hope I am not assaulting anyone by not creating a separate question.</p> <p><hr /></p> <p><strong>edit2:</strong> Ah, SO will you marry me? Many beautiful answers and only one to choose.. Thank you everyone, I've learned more from this question than from a month of my university studies. I am choosing the OO answer because it will allow me more flexibility in the future.</p> <p><hr /></p> <h3>Related:</h3> <ul> <li><a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></li> </ul>
19
2009-08-26T15:04:04Z
1,336,821
<h3>Answer to the last part of the question:</h3> <blockquote> <p>question update: How to modify the function you have provided to store the extra items and use them when the next fatherList is fed to the function?</p> </blockquote> <p>If you need to store state then you can use an object for that.</p> <pre><code>class Chunker(object): """Split `iterable` on evenly sized chunks. Leftovers are remembered and yielded at the next call. """ def __init__(self, chunksize): assert chunksize &gt; 0 self.chunksize = chunksize self.chunk = [] def __call__(self, iterable): """Yield items from `iterable` `self.chunksize` at the time.""" assert len(self.chunk) &lt; self.chunksize for item in iterable: self.chunk.append(item) if len(self.chunk) == self.chunksize: # yield collected full chunk yield self.chunk self.chunk = [] </code></pre> <p>Example:</p> <pre><code>chunker = Chunker(3) for s in "abcd", "efgh": for chunk in chunker(s): print ''.join(chunk) if chunker.chunk: # is there anything left? print ''.join(chunker.chunk) </code></pre> <p>Output:</p> <pre><code>abc def gh </code></pre>
7
2009-08-26T19:02:07Z
[ "python", "loops", "iteration", "slice" ]
Iteration over list slices
1,335,392
<p>Good day function-wizards,</p> <p>I want an algorithm to iterate over list slices. Slices size is set outside the function and can differ.</p> <p>In my mind it is something like:</p> <pre><code>for list_of_x_items in fatherList: foo(list_of_x_items) </code></pre> <p>Is there a way to properly define <code>list_of_x_items</code> or some other way of doing this?</p> <p>Thank you greatly.</p> <p><em>PS: using python 2.5</em></p> <p><hr /></p> <p><strong>edit1:</strong> So many beautiful answers.. Someone has asked to clarify. Both "partitioning" and "sliding window" terms sound applicable to my task, but I am no expert. So I will explain the problem a bit deeper and add to the question:</p> <p>The fatherList is a multilevel numpy.array I am getting from a file. Function has to find averages of series (user provides the length of series) For averaging I am using the <code>mean()</code> function. Now for question expansion:</p> <p><strong>question update:</strong> How to modify the function you have provided to store the extra items and use them when the next fatherList is fed to the function?</p> <p>for example if the list is lenght 10 and size of a chunk is 3, then the 10th member of the list is stored and appended to the beginning of the next list.</p> <p>Hope I am not assaulting anyone by not creating a separate question.</p> <p><hr /></p> <p><strong>edit2:</strong> Ah, SO will you marry me? Many beautiful answers and only one to choose.. Thank you everyone, I've learned more from this question than from a month of my university studies. I am choosing the OO answer because it will allow me more flexibility in the future.</p> <p><hr /></p> <h3>Related:</h3> <ul> <li><a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></li> </ul>
19
2009-08-26T15:04:04Z
1,339,575
<p>I am not sure, but it seems you want to do what is called a moving average. numpy provides facilities for this (the convolve function).</p> <pre> >>> x = numpy.array(range(20)) >>> x array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) >>> n = 2 # moving average window >>> numpy.convolve(numpy.ones(n)/n, x)[n-1:-n+1] array([ 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5, 16.5, 17.5, 18.5]) </pre> <p>The nice thing is that it accomodates different weighting schemes nicely (just change <code>numpy.ones(n) / n</code> to something else).</p> <p>You can find a complete material here: <a href="http://www.scipy.org/Cookbook/SignalSmooth">http://www.scipy.org/Cookbook/SignalSmooth</a></p>
5
2009-08-27T08:11:39Z
[ "python", "loops", "iteration", "slice" ]
Iteration over list slices
1,335,392
<p>Good day function-wizards,</p> <p>I want an algorithm to iterate over list slices. Slices size is set outside the function and can differ.</p> <p>In my mind it is something like:</p> <pre><code>for list_of_x_items in fatherList: foo(list_of_x_items) </code></pre> <p>Is there a way to properly define <code>list_of_x_items</code> or some other way of doing this?</p> <p>Thank you greatly.</p> <p><em>PS: using python 2.5</em></p> <p><hr /></p> <p><strong>edit1:</strong> So many beautiful answers.. Someone has asked to clarify. Both "partitioning" and "sliding window" terms sound applicable to my task, but I am no expert. So I will explain the problem a bit deeper and add to the question:</p> <p>The fatherList is a multilevel numpy.array I am getting from a file. Function has to find averages of series (user provides the length of series) For averaging I am using the <code>mean()</code> function. Now for question expansion:</p> <p><strong>question update:</strong> How to modify the function you have provided to store the extra items and use them when the next fatherList is fed to the function?</p> <p>for example if the list is lenght 10 and size of a chunk is 3, then the 10th member of the list is stored and appended to the beginning of the next list.</p> <p>Hope I am not assaulting anyone by not creating a separate question.</p> <p><hr /></p> <p><strong>edit2:</strong> Ah, SO will you marry me? Many beautiful answers and only one to choose.. Thank you everyone, I've learned more from this question than from a month of my university studies. I am choosing the OO answer because it will allow me more flexibility in the future.</p> <p><hr /></p> <h3>Related:</h3> <ul> <li><a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></li> </ul>
19
2009-08-26T15:04:04Z
23,790,716
<p>For a near-one liner (after <code>itertools</code> import) in the vein of Nadia's answer dealing with non-chunk divisible sizes without padding:</p> <pre><code>&gt;&gt;&gt; import itertools as itt &gt;&gt;&gt; chunksize = 5 &gt;&gt;&gt; myseq = range(18) &gt;&gt;&gt; cnt = itt.count() &gt;&gt;&gt; print [ tuple(grp) for k,grp in itt.groupby(myseq, key=lambda x: cnt.next()//chunksize%2)] [(0, 1, 2, 3, 4), (5, 6, 7, 8, 9), (10, 11, 12, 13, 14), (15, 16, 17)] </code></pre> <p>If you want, you can get rid of the <code>itertools.count()</code> requirement using <code>enumerate()</code>, with a rather uglier:</p> <pre><code>[ [e[1] for e in grp] for k,grp in itt.groupby(enumerate(myseq), key=lambda x: x[0]//chunksize%2) ] </code></pre> <p>(In this example the <code>enumerate()</code> would be superfluous, but not all sequences are neat ranges like this, obviously)</p> <p>Nowhere near as neat as some other answers, but useful in a pinch, especially if already importing <code>itertools</code>.</p>
1
2014-05-21T18:07:21Z
[ "python", "loops", "iteration", "slice" ]
Python urllib.urlopen() call doesn't work with a URL that a browser accepts
1,335,439
<p>If I point Firefox at <a href="http://bitbucket.org/tortoisehg/stable/wiki/Home/ReleaseNotes" rel="nofollow">http://bitbucket.org/tortoisehg/stable/wiki/Home/ReleaseNotes</a>, I get a page of HTML. But if I try this in Python:</p> <pre> import urllib site = 'http://bitbucket.org/tortoisehg/stable/wiki/Home/ReleaseNotes' req = urllib.urlopen(site) text = req.read() </pre> <p>I get the following:</p> <p>500 Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request.</p> <p>What am I doing wrong?</p>
1
2009-08-26T15:09:57Z
1,335,487
<p>I don't think you're doing anything wrong -- it looks like this server was just down? Your script worked fine for me ('text' contained the same data as that displayed in the browser).</p>
-2
2009-08-26T15:16:03Z
[ "python", "urllib", "bitbucket" ]
Python urllib.urlopen() call doesn't work with a URL that a browser accepts
1,335,439
<p>If I point Firefox at <a href="http://bitbucket.org/tortoisehg/stable/wiki/Home/ReleaseNotes" rel="nofollow">http://bitbucket.org/tortoisehg/stable/wiki/Home/ReleaseNotes</a>, I get a page of HTML. But if I try this in Python:</p> <pre> import urllib site = 'http://bitbucket.org/tortoisehg/stable/wiki/Home/ReleaseNotes' req = urllib.urlopen(site) text = req.read() </pre> <p>I get the following:</p> <p>500 Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request.</p> <p>What am I doing wrong?</p>
1
2009-08-26T15:09:57Z
1,335,505
<p>You're doing nothing wrong, on the surface, and as the error page says you should contact the site's administrators because they're the ones with the server logs which may explain what's happening. Fortunately, bitbucket's site admins are a friendly bunch!</p> <p>No doubt there is some header or combination of headers that browsers set one way, urllib sets another way, and a bug on the server gets tickled in the latter case. You may want to see exactly what headers are being sent e.g. with firebug in firefox, and reproduce those until you isolate exactly the server bug; most likely it's going to be the user agent or some "accept"-ish header that's tickling that bug.</p>
3
2009-08-26T15:18:37Z
[ "python", "urllib", "bitbucket" ]
Python urllib.urlopen() call doesn't work with a URL that a browser accepts
1,335,439
<p>If I point Firefox at <a href="http://bitbucket.org/tortoisehg/stable/wiki/Home/ReleaseNotes" rel="nofollow">http://bitbucket.org/tortoisehg/stable/wiki/Home/ReleaseNotes</a>, I get a page of HTML. But if I try this in Python:</p> <pre> import urllib site = 'http://bitbucket.org/tortoisehg/stable/wiki/Home/ReleaseNotes' req = urllib.urlopen(site) text = req.read() </pre> <p>I get the following:</p> <p>500 Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request.</p> <p>What am I doing wrong?</p>
1
2009-08-26T15:09:57Z
1,335,634
<p>You are not doing anything wrong, bitbucket does some user agent detection (to detect mercurial clients for example). Just <a href="http://docs.python.org/library/urllib.html#urllib.%5Furlopener" rel="nofollow">changing the user agent</a> fixes it (if it doesn't have <code>urllib</code> as a substring).</p> <p>You should fill an issue regarding this: <a href="http://bitbucket.org/jespern/bitbucket/issues/new/" rel="nofollow">http://bitbucket.org/jespern/bitbucket/issues/new/</a></p>
3
2009-08-26T15:36:53Z
[ "python", "urllib", "bitbucket" ]
Keyboard input with timeout in Python
1,335,507
<p>How would you prompt the user for some input but timing out after N seconds?</p> <p>Google is pointing to a mail thread about it at <a href="http://mail.python.org/pipermail/python-list/2006-January/533215.html">http://mail.python.org/pipermail/python-list/2006-January/533215.html</a> but it seems not to work. The statement in which the timeout happens, no matter whether it is a sys.input.readline or timer.sleep(), I always get:</p> <blockquote> <p>&lt;type 'exceptions.TypeError'&gt;: [raw_]input expected at most 1 arguments, got 2</p> </blockquote> <p>which somehow the except fails to catch.</p>
16
2009-08-26T15:19:05Z
1,336,751
<p>The example you have linked to is wrong and the exception is actually occuring when calling alarm handler instead of when read blocks. Better try this:</p> <pre><code>import signal TIMEOUT = 5 # number of seconds your want for timeout def interrupted(signum, frame): "called when read times out" print 'interrupted!' signal.signal(signal.SIGALRM, interrupted) def input(): try: print 'You have 5 seconds to type in your stuff...' foo = raw_input() return foo except: # timeout return # set alarm signal.alarm(TIMEOUT) s = input() # disable the alarm after success signal.alarm(0) print 'You typed', s </code></pre>
10
2009-08-26T18:50:00Z
[ "python", "timeout", "keyboard-input" ]
Keyboard input with timeout in Python
1,335,507
<p>How would you prompt the user for some input but timing out after N seconds?</p> <p>Google is pointing to a mail thread about it at <a href="http://mail.python.org/pipermail/python-list/2006-January/533215.html">http://mail.python.org/pipermail/python-list/2006-January/533215.html</a> but it seems not to work. The statement in which the timeout happens, no matter whether it is a sys.input.readline or timer.sleep(), I always get:</p> <blockquote> <p>&lt;type 'exceptions.TypeError'&gt;: [raw_]input expected at most 1 arguments, got 2</p> </blockquote> <p>which somehow the except fails to catch.</p>
16
2009-08-26T15:19:05Z
2,904,057
<p>Using a select call is shorter, and should be much more portable</p> <pre><code>import sys, select print "You have ten seconds to answer!" i, o, e = select.select( [sys.stdin], [], [], 10 ) if (i): print "You said", sys.stdin.readline().strip() else: print "You said nothing!" </code></pre>
45
2010-05-25T11:18:11Z
[ "python", "timeout", "keyboard-input" ]
Keyboard input with timeout in Python
1,335,507
<p>How would you prompt the user for some input but timing out after N seconds?</p> <p>Google is pointing to a mail thread about it at <a href="http://mail.python.org/pipermail/python-list/2006-January/533215.html">http://mail.python.org/pipermail/python-list/2006-January/533215.html</a> but it seems not to work. The statement in which the timeout happens, no matter whether it is a sys.input.readline or timer.sleep(), I always get:</p> <blockquote> <p>&lt;type 'exceptions.TypeError'&gt;: [raw_]input expected at most 1 arguments, got 2</p> </blockquote> <p>which somehow the except fails to catch.</p>
16
2009-08-26T15:19:05Z
3,911,477
<p>And here's one that works on Windows</p> <p>I haven't been able to get any of these examples to work on Windows so I've merged some different StackOverflow answers to get the following:</p> <pre><code> import threading, msvcrt import sys def readInput(caption, default, timeout = 5): class KeyboardThread(threading.Thread): def run(self): self.timedout = False self.input = '' while True: if msvcrt.kbhit(): chr = msvcrt.getche() if ord(chr) == 13: break elif ord(chr) >= 32: self.input += chr if len(self.input) == 0 and self.timedout: break sys.stdout.write('%s(%s):'%(caption, default)); result = default it = KeyboardThread() it.start() it.join(timeout) it.timedout = True if len(it.input) > 0: # wait for rest of input it.join() result = it.input print '' # needed to move to next line return result # and some examples of usage ans = readInput('Please type a name', 'john') print 'The name is %s' % ans ans = readInput('Please enter a number', 10 ) print 'The number is %s' % ans </code></pre>
3
2010-10-12T03:25:58Z
[ "python", "timeout", "keyboard-input" ]
Keyboard input with timeout in Python
1,335,507
<p>How would you prompt the user for some input but timing out after N seconds?</p> <p>Google is pointing to a mail thread about it at <a href="http://mail.python.org/pipermail/python-list/2006-January/533215.html">http://mail.python.org/pipermail/python-list/2006-January/533215.html</a> but it seems not to work. The statement in which the timeout happens, no matter whether it is a sys.input.readline or timer.sleep(), I always get:</p> <blockquote> <p>&lt;type 'exceptions.TypeError'&gt;: [raw_]input expected at most 1 arguments, got 2</p> </blockquote> <p>which somehow the except fails to catch.</p>
16
2009-08-26T15:19:05Z
9,705,295
<p>A late answer :)</p> <p>I would do something like this:</p> <pre><code>from time import sleep print('Please provide input in 20 seconds! (Hit Ctrl-C to start)') try: for i in range(0,20): sleep(1) # could use a backward counter to be preeety :) print('No input is given.') except KeyboardInterrupt: raw_input('Input x:') print('You, you! You know something.') </code></pre> <p>I know this is not the same but many real life problem could be solved this way. (I usually need timeout for user input when I want something to continue running if the user not there at the moment.)</p> <p>Hope this at least partially helps. (If anyone reads it anyway :) )</p>
-4
2012-03-14T15:50:21Z
[ "python", "timeout", "keyboard-input" ]
Keyboard input with timeout in Python
1,335,507
<p>How would you prompt the user for some input but timing out after N seconds?</p> <p>Google is pointing to a mail thread about it at <a href="http://mail.python.org/pipermail/python-list/2006-January/533215.html">http://mail.python.org/pipermail/python-list/2006-January/533215.html</a> but it seems not to work. The statement in which the timeout happens, no matter whether it is a sys.input.readline or timer.sleep(), I always get:</p> <blockquote> <p>&lt;type 'exceptions.TypeError'&gt;: [raw_]input expected at most 1 arguments, got 2</p> </blockquote> <p>which somehow the except fails to catch.</p>
16
2009-08-26T15:19:05Z
25,860,968
<p>I spent a good twenty minutes or so on this, so I thought it was worth a shot to put this up here. It is directly building off of user137673's answer, though. I found it most useful to do something like this:</p> <pre><code>#! /usr/bin/env python import signal timeout = None def main(): inp = stdinWait("You have 5 seconds to type text and press &lt;Enter&gt;... ", "[no text]", 5, "Aw man! You ran out of time!!") if not timeout: print "You entered", inp else: print "You didn't enter anything because I'm on a tight schedule!" def stdinWait(text, default, time, timeoutDisplay = None, **kwargs): signal.signal(signal.SIGALRM, interrupt) signal.alarm(time) # sets timeout global timeout try: inp = raw_input(text) signal.alarm(0) timeout = False except (KeyboardInterrupt): printInterrupt = kwargs.get("printInterrupt", True) if printInterrupt: print "Keyboard interrupt" timeout = True # Do this so you don't mistakenly get input when there is none inp = default except: timeout = True if not timeoutDisplay is None: print timeoutDisplay signal.alarm(0) inp = default return inp def interrupt(signum, frame): raise Exception("") if __name__ == "__main__": main() </code></pre>
1
2014-09-16T04:59:11Z
[ "python", "timeout", "keyboard-input" ]
Keyboard input with timeout in Python
1,335,507
<p>How would you prompt the user for some input but timing out after N seconds?</p> <p>Google is pointing to a mail thread about it at <a href="http://mail.python.org/pipermail/python-list/2006-January/533215.html">http://mail.python.org/pipermail/python-list/2006-January/533215.html</a> but it seems not to work. The statement in which the timeout happens, no matter whether it is a sys.input.readline or timer.sleep(), I always get:</p> <blockquote> <p>&lt;type 'exceptions.TypeError'&gt;: [raw_]input expected at most 1 arguments, got 2</p> </blockquote> <p>which somehow the except fails to catch.</p>
16
2009-08-26T15:19:05Z
27,222,779
<p>Not a Python solution, but...</p> <p>I ran in to this problem with a script running under CentOS (Linux), and what worked for my situation was just running the Bash "read -t" command in a subprocess. Brutal disgusting hack, I know, but I feel guilty enough about how well it worked that I wanted to share it with everyone here.</p> <pre><code>import subprocess subprocess.call('read -t 30', shell=True) </code></pre> <p>All I needed was something that waited for 30 seconds unless the ENTER key was pressed. This worked great.</p>
3
2014-12-01T06:23:49Z
[ "python", "timeout", "keyboard-input" ]
Keyboard input with timeout in Python
1,335,507
<p>How would you prompt the user for some input but timing out after N seconds?</p> <p>Google is pointing to a mail thread about it at <a href="http://mail.python.org/pipermail/python-list/2006-January/533215.html">http://mail.python.org/pipermail/python-list/2006-January/533215.html</a> but it seems not to work. The statement in which the timeout happens, no matter whether it is a sys.input.readline or timer.sleep(), I always get:</p> <blockquote> <p>&lt;type 'exceptions.TypeError'&gt;: [raw_]input expected at most 1 arguments, got 2</p> </blockquote> <p>which somehow the except fails to catch.</p>
16
2009-08-26T15:19:05Z
39,390,830
<p>Analogous to Locane's for windows:</p> <pre><code>import subprocess subprocess.call('timeout /T 30') </code></pre>
0
2016-09-08T12:23:07Z
[ "python", "timeout", "keyboard-input" ]
Python FTP Most Recent File
1,335,552
<p>How do I determine the most recently modified file from an ftp directory listing? I used the max function on the unix timestamp locally, but the ftp listing is harder to parse. The contents of each line is only separated by a space. </p> <pre><code>from ftplib import FTP ftp = FTP('ftp.cwi.nl') ftp.login() data = [] ftp.dir(data.append) ftp.quit() for line in data: print line </code></pre> <p>output:</p> <pre><code>drwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 . dr-xr-srwt 105 ftp-usr pdmaint 1536 Mar 21 14:32 .. -rw-r--r-- 1 ftp-usr pdmaint 5305 Mar 20 09:48 INDEX </code></pre>
3
2009-08-26T15:26:12Z
1,335,757
<p>You can split each line and get the date:</p> <pre><code>date_str = ' '.join(line.split(' ')[5:8]) </code></pre> <p>Then parse the date (check out egenix <a href="http://www.egenix.com/products/python/mxBase/mxDateTime/" rel="nofollow">mxDateTime</a> package, specifically the <code>DateTimeFromString</code> function) to get comparable objects.</p>
0
2009-08-26T15:55:23Z
[ "python", "ftp" ]
Python FTP Most Recent File
1,335,552
<p>How do I determine the most recently modified file from an ftp directory listing? I used the max function on the unix timestamp locally, but the ftp listing is harder to parse. The contents of each line is only separated by a space. </p> <pre><code>from ftplib import FTP ftp = FTP('ftp.cwi.nl') ftp.login() data = [] ftp.dir(data.append) ftp.quit() for line in data: print line </code></pre> <p>output:</p> <pre><code>drwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 . dr-xr-srwt 105 ftp-usr pdmaint 1536 Mar 21 14:32 .. -rw-r--r-- 1 ftp-usr pdmaint 5305 Mar 20 09:48 INDEX </code></pre>
3
2009-08-26T15:26:12Z
1,335,928
<p>To parse the date, you can use (from version 2.5 onwards):</p> <pre><code>datetime.datetime.strptime('Mar 21 14:32', '%b %d %H:%M') </code></pre>
1
2009-08-26T16:22:06Z
[ "python", "ftp" ]
Python FTP Most Recent File
1,335,552
<p>How do I determine the most recently modified file from an ftp directory listing? I used the max function on the unix timestamp locally, but the ftp listing is harder to parse. The contents of each line is only separated by a space. </p> <pre><code>from ftplib import FTP ftp = FTP('ftp.cwi.nl') ftp.login() data = [] ftp.dir(data.append) ftp.quit() for line in data: print line </code></pre> <p>output:</p> <pre><code>drwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 . dr-xr-srwt 105 ftp-usr pdmaint 1536 Mar 21 14:32 .. -rw-r--r-- 1 ftp-usr pdmaint 5305 Mar 20 09:48 INDEX </code></pre>
3
2009-08-26T15:26:12Z
1,336,131
<p>Just to make some corrections:</p> <pre><code>date_str = ' '.join(line.split()[5:8]) time.strptime(date_str, '%b %d %H:%M') # import time </code></pre> <p>And to find the most recent file</p> <pre><code>for line in data: col_list = line.split() date_str = ' '.join(line.split()[5:8]) if datePattern.search(col_list[8]): file_dict[time.strptime(date_str, '%b %d %H:%M')] = col_list[8] date_list = list([key for key, value in file_dict.items()]) s = file_dict[max(date_list)] print s </code></pre>
3
2009-08-26T16:52:45Z
[ "python", "ftp" ]
Python FTP Most Recent File
1,335,552
<p>How do I determine the most recently modified file from an ftp directory listing? I used the max function on the unix timestamp locally, but the ftp listing is harder to parse. The contents of each line is only separated by a space. </p> <pre><code>from ftplib import FTP ftp = FTP('ftp.cwi.nl') ftp.login() data = [] ftp.dir(data.append) ftp.quit() for line in data: print line </code></pre> <p>output:</p> <pre><code>drwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 . dr-xr-srwt 105 ftp-usr pdmaint 1536 Mar 21 14:32 .. -rw-r--r-- 1 ftp-usr pdmaint 5305 Mar 20 09:48 INDEX </code></pre>
3
2009-08-26T15:26:12Z
3,117,005
<p>If the FTP server supports the <code>MLSD</code> command (and quite possibly it does), you can use the <code>FTPDirectory</code> class from <a href="http://stackoverflow.com/questions/2867217/how-to-delete-files-with-a-python-script-from-a-ftp-server-which-are-older-than-7/3114477#3114477">that</a> answer in a related question.</p> <p>Create an <code>ftplib.FTP</code> instance (eg aftp) and an <code>FTPDirectory</code> instance (eg aftpdir), connect to the server, <code>.cwd</code> to the directory you want, and read the files using <code>aftpdir.getdata(aftp)</code>. After that, you get name of the freshest file as:</p> <pre><code>import operator max(aftpdir, key=operator.attrgetter('mtime')).name </code></pre>
4
2010-06-25T09:42:35Z
[ "python", "ftp" ]
Is it a good idea to hash a Python class?
1,335,556
<p>For example, suppose I do this:</p> <pre><code>&gt;&gt;&gt; class foo(object): ... pass ... &gt;&gt;&gt; class bar(foo): ... pass ... &gt;&gt;&gt; some_dict = { foo : 'foo', ... bar : 'bar'} &gt;&gt;&gt; &gt;&gt;&gt; some_dict[bar] 'bar' &gt;&gt;&gt; some_dict[foo] 'foo' &gt;&gt;&gt; hash(bar) 165007700 &gt;&gt;&gt; id(bar) 165007700 </code></pre> <p>Based on that, it looks like the class is getting hashed as its id number. Therefore, there shouldn't be any danger of worrying about, say, a <code>bar</code> hashing as either a <code>foo</code> or a <code>bar</code> or hash values changing if I mutate the class.</p> <p>Is this behavior reliable, or are there any gotchas here?</p>
4
2009-08-26T15:27:15Z
1,335,582
<p>Yes, any object that doesn't implement a <code>__hash__()</code> function will return its id when hashed. From <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fhash%5F%5F">Python Language Reference: Data Model - Basic Customization</a>:</p> <blockquote> <p>User-defined classes have <code>__cmp__()</code> and <code>__hash__()</code> methods by default; with them, all objects compare unequal (except with themselves) and <code>x.__hash__()</code> returns <code>id(x)</code>.</p> </blockquote> <p>However, if you're looking to have a unique identifier, use <code>id</code> to be clear about your intent. A hash of an object should be a combination of the hashes of its components. See the above link for more details.</p>
7
2009-08-26T15:29:36Z
[ "python", "class", "inheritance", "hash", "dictionary" ]
Is it a good idea to hash a Python class?
1,335,556
<p>For example, suppose I do this:</p> <pre><code>&gt;&gt;&gt; class foo(object): ... pass ... &gt;&gt;&gt; class bar(foo): ... pass ... &gt;&gt;&gt; some_dict = { foo : 'foo', ... bar : 'bar'} &gt;&gt;&gt; &gt;&gt;&gt; some_dict[bar] 'bar' &gt;&gt;&gt; some_dict[foo] 'foo' &gt;&gt;&gt; hash(bar) 165007700 &gt;&gt;&gt; id(bar) 165007700 </code></pre> <p>Based on that, it looks like the class is getting hashed as its id number. Therefore, there shouldn't be any danger of worrying about, say, a <code>bar</code> hashing as either a <code>foo</code> or a <code>bar</code> or hash values changing if I mutate the class.</p> <p>Is this behavior reliable, or are there any gotchas here?</p>
4
2009-08-26T15:27:15Z
1,335,991
<p>Classes have default implementations of <code>__eq__</code> and <code>__hash__</code> that use <code>id()</code> to make comparisons and compute hash values, respectively. That is, they compare by identity. The primary rule for implementing <code>__hash__</code> methods is that if two objects compare equal to each other, they must also have the same hash value. Hash values can be seen as just an optimization used by dicts and sets to do find equal objects faster. Consequently, if you change <code>__eq__</code> to do a different kind of equality testing, you must also change your <code>__hash__</code> implementation to agree with that choice.</p> <p>Classes that use identity for comparisons can be freely mutated and used in dicts and sets because their identity never changes. Classes that implement <code>__eq__</code> to compare by value and allow mutation of their values cannot be used in hash collections.</p>
5
2009-08-26T16:31:02Z
[ "python", "class", "inheritance", "hash", "dictionary" ]
Python: ZODB file size growing - not updating?
1,335,615
<p>I am using ZODB to store some data that exists in memory for the sake of persistence. If the service with the data in memory every crashes, restarting will load the data from ZODB rather than querying 100s of thousands of rows in a MySQL db. </p> <p>It seems that every time I save, say 500K of data to my database file, my .fs file grows by 500K, rather than staying at 500K. As an example:</p> <pre><code>storage = FileStorage.FileStorage(MY_PATH) db = DB(storage) connection = db.open() root = connection.root() if not root.has_key('data_db'): root['data_db'] = OOBTree() mydictionary = {'some dictionary with 500K of data'} root['data_db'] = mydictionary root._p_changed = 1 transaction.commit() transaction.abort() connection.close() db.close() storage.close() </code></pre> <p>I want to continuously overwrite the data in root['data_db'] with the current value of mydictionary. When I print len(root['data_db']) it always prints the right number of items from mydictionary, but every time this code runs (with the same exact data) the file size increased by the data size, in this case 500K.</p> <p>Am I doing something wrong here?</p>
1
2009-08-26T15:34:52Z
1,335,705
<p>When the data in ZODB changes, it's appended to the end of the file. Old data is left there. To reduce the filesize, you need to manually "pack" the database.</p> <p>Google came up with <a href="http://mail.zope.org/pipermail/zodb-dev/2004-July/007706.html" rel="nofollow">this mailing list post</a>.</p>
2
2009-08-26T15:48:57Z
[ "python", "zodb" ]
Python: ZODB file size growing - not updating?
1,335,615
<p>I am using ZODB to store some data that exists in memory for the sake of persistence. If the service with the data in memory every crashes, restarting will load the data from ZODB rather than querying 100s of thousands of rows in a MySQL db. </p> <p>It seems that every time I save, say 500K of data to my database file, my .fs file grows by 500K, rather than staying at 500K. As an example:</p> <pre><code>storage = FileStorage.FileStorage(MY_PATH) db = DB(storage) connection = db.open() root = connection.root() if not root.has_key('data_db'): root['data_db'] = OOBTree() mydictionary = {'some dictionary with 500K of data'} root['data_db'] = mydictionary root._p_changed = 1 transaction.commit() transaction.abort() connection.close() db.close() storage.close() </code></pre> <p>I want to continuously overwrite the data in root['data_db'] with the current value of mydictionary. When I print len(root['data_db']) it always prints the right number of items from mydictionary, but every time this code runs (with the same exact data) the file size increased by the data size, in this case 500K.</p> <p>Am I doing something wrong here?</p>
1
2009-08-26T15:34:52Z
1,336,013
<p>Since you asked about another storage system in a comment, you might want to look into SQLite.</p> <p>Even though SQLite behaves the same in appending to data first, it offers the vacuum command to recover unused storage space. From the <a href="http://docs.python.org/library/sqlite3.html" rel="nofollow">Python API</a>, you'll can either use the <a href="http://www.sqlite.org/pragma.html#pragma%5Fauto%5Fvacuum" rel="nofollow">vacuum pragma</a> to do it automatically, or you can just execute <a href="http://www.sqlite.org/lang%5Fvacuum.html" rel="nofollow">the vacuum command</a>.</p>
1
2009-08-26T16:32:54Z
[ "python", "zodb" ]
Performance - Python vs. C#/C++/C reading char-by-char
1,336,259
<p>So I have these giant XML files (and by giant, I mean like 1.5GB+) and they don't have CRLFs. I'm trying to run a diff-like program to find the differences between these files.</p> <p>Since I've yet to find a diff program that won't explode due to memory exhaustion, I've decided the best bet was to add CRLFs after closing tags.</p> <p>I wrote a python script to read char-by-char and add new-lines after '>'. The problem is I'm running this on a single core PC circa-1995 or something ridiculous, and it's only processing about 20MB/hour when I have both converting at the same time.</p> <p>Any idea if writing this in C#/C/C++ instead will yield any benefits? If not, does anyone know of a diff program that will go byte-by-byte? Thanks.</p> <p><hr /></p> <p><strong>EDIT:</strong></p> <p>Here's the code for my processing function...</p> <pre><code>def read_and_format(inputfile, outputfile): ''' Open input and output files, then read char-by-char and add new lines after "&gt;" ''' infile = codecs.open(inputfile,"r","utf-8") outfile = codecs.open(outputfile,"w","utf-8") char = infile.read(1) while(1): if char == "": break else: outfile.write(char) if(char == "&gt;"): outfile.write("\n") char = infile.read(1) infile.close() outfile.close() </code></pre> <p><hr /></p> <p><strong>EDIT2:</strong> Thanks for the awesome responses. Increaseing the read size created an unbelievable speed increase. Problem solved.</p>
0
2009-08-26T17:13:59Z
1,336,278
<p>All of the languages mentioned typically, at some point, revert to the C runtime library for byte by byte file access. Writing this in C will probably be the fastest option.</p> <p>However, I doubt it will provide a huge speed boost. Python is fairly speedy, if you're doing things correctly.</p> <p>The main way to really get a big speed improvement would be to introduce threading. If you read the data in from the file in a large block in one thread, and had a separate thread that did your newline processing + diff processing, you could dramatically improve the speed of this algorithm. This would probably be easier to implement in C++, C#, or IronPython than in C or CPython directly, since they provide very easy, high-level synchronization tools for handling the threading issues (especially when using .NET).</p>
0
2009-08-26T17:16:46Z
[ "c#", "python", "performance", "character" ]
Performance - Python vs. C#/C++/C reading char-by-char
1,336,259
<p>So I have these giant XML files (and by giant, I mean like 1.5GB+) and they don't have CRLFs. I'm trying to run a diff-like program to find the differences between these files.</p> <p>Since I've yet to find a diff program that won't explode due to memory exhaustion, I've decided the best bet was to add CRLFs after closing tags.</p> <p>I wrote a python script to read char-by-char and add new-lines after '>'. The problem is I'm running this on a single core PC circa-1995 or something ridiculous, and it's only processing about 20MB/hour when I have both converting at the same time.</p> <p>Any idea if writing this in C#/C/C++ instead will yield any benefits? If not, does anyone know of a diff program that will go byte-by-byte? Thanks.</p> <p><hr /></p> <p><strong>EDIT:</strong></p> <p>Here's the code for my processing function...</p> <pre><code>def read_and_format(inputfile, outputfile): ''' Open input and output files, then read char-by-char and add new lines after "&gt;" ''' infile = codecs.open(inputfile,"r","utf-8") outfile = codecs.open(outputfile,"w","utf-8") char = infile.read(1) while(1): if char == "": break else: outfile.write(char) if(char == "&gt;"): outfile.write("\n") char = infile.read(1) infile.close() outfile.close() </code></pre> <p><hr /></p> <p><strong>EDIT2:</strong> Thanks for the awesome responses. Increaseing the read size created an unbelievable speed increase. Problem solved.</p>
0
2009-08-26T17:13:59Z
1,336,280
<p>you could try xmldiff - <a href="http://msdn.microsoft.com/en-us/library/aa302294.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa302294.aspx</a> </p> <p>I haven't used it for such huge data but I think it would be reasonably optimized</p>
0
2009-08-26T17:17:30Z
[ "c#", "python", "performance", "character" ]
Performance - Python vs. C#/C++/C reading char-by-char
1,336,259
<p>So I have these giant XML files (and by giant, I mean like 1.5GB+) and they don't have CRLFs. I'm trying to run a diff-like program to find the differences between these files.</p> <p>Since I've yet to find a diff program that won't explode due to memory exhaustion, I've decided the best bet was to add CRLFs after closing tags.</p> <p>I wrote a python script to read char-by-char and add new-lines after '>'. The problem is I'm running this on a single core PC circa-1995 or something ridiculous, and it's only processing about 20MB/hour when I have both converting at the same time.</p> <p>Any idea if writing this in C#/C/C++ instead will yield any benefits? If not, does anyone know of a diff program that will go byte-by-byte? Thanks.</p> <p><hr /></p> <p><strong>EDIT:</strong></p> <p>Here's the code for my processing function...</p> <pre><code>def read_and_format(inputfile, outputfile): ''' Open input and output files, then read char-by-char and add new lines after "&gt;" ''' infile = codecs.open(inputfile,"r","utf-8") outfile = codecs.open(outputfile,"w","utf-8") char = infile.read(1) while(1): if char == "": break else: outfile.write(char) if(char == "&gt;"): outfile.write("\n") char = infile.read(1) infile.close() outfile.close() </code></pre> <p><hr /></p> <p><strong>EDIT2:</strong> Thanks for the awesome responses. Increaseing the read size created an unbelievable speed increase. Problem solved.</p>
0
2009-08-26T17:13:59Z
1,336,282
<p>Reading and writing a single character at a time is almost always going to be slow, because disks are block-based devices, rather than character-based devices - it will read a lot more than just the one byte you're after, and the surplus parts need to be discarded.</p> <p>Try reading and writing more at a time, say, 8192 bytes (8KB) and then finding and adding newlines in that string before writing it out - you should save a lot in performance because a lot less I/O is required.</p> <p>As LBushkin points out, your I/O library may be doing buffering, but unless there is some form of documentation that shows this does indeed happen (for reading AND writing), it's a fairly easy thing to try before rewriting in a different language.</p>
10
2009-08-26T17:17:43Z
[ "c#", "python", "performance", "character" ]
Performance - Python vs. C#/C++/C reading char-by-char
1,336,259
<p>So I have these giant XML files (and by giant, I mean like 1.5GB+) and they don't have CRLFs. I'm trying to run a diff-like program to find the differences between these files.</p> <p>Since I've yet to find a diff program that won't explode due to memory exhaustion, I've decided the best bet was to add CRLFs after closing tags.</p> <p>I wrote a python script to read char-by-char and add new-lines after '>'. The problem is I'm running this on a single core PC circa-1995 or something ridiculous, and it's only processing about 20MB/hour when I have both converting at the same time.</p> <p>Any idea if writing this in C#/C/C++ instead will yield any benefits? If not, does anyone know of a diff program that will go byte-by-byte? Thanks.</p> <p><hr /></p> <p><strong>EDIT:</strong></p> <p>Here's the code for my processing function...</p> <pre><code>def read_and_format(inputfile, outputfile): ''' Open input and output files, then read char-by-char and add new lines after "&gt;" ''' infile = codecs.open(inputfile,"r","utf-8") outfile = codecs.open(outputfile,"w","utf-8") char = infile.read(1) while(1): if char == "": break else: outfile.write(char) if(char == "&gt;"): outfile.write("\n") char = infile.read(1) infile.close() outfile.close() </code></pre> <p><hr /></p> <p><strong>EDIT2:</strong> Thanks for the awesome responses. Increaseing the read size created an unbelievable speed increase. Problem solved.</p>
0
2009-08-26T17:13:59Z
1,336,287
<p>Rather than reading byte by byte, which incurs a disk access for each byte read, try reading ~20 MB at a time and doing your search + replace on that :)</p> <p>You can probably do this in Notepad....</p> <p>Billy3</p>
1
2009-08-26T17:18:53Z
[ "c#", "python", "performance", "character" ]
Performance - Python vs. C#/C++/C reading char-by-char
1,336,259
<p>So I have these giant XML files (and by giant, I mean like 1.5GB+) and they don't have CRLFs. I'm trying to run a diff-like program to find the differences between these files.</p> <p>Since I've yet to find a diff program that won't explode due to memory exhaustion, I've decided the best bet was to add CRLFs after closing tags.</p> <p>I wrote a python script to read char-by-char and add new-lines after '>'. The problem is I'm running this on a single core PC circa-1995 or something ridiculous, and it's only processing about 20MB/hour when I have both converting at the same time.</p> <p>Any idea if writing this in C#/C/C++ instead will yield any benefits? If not, does anyone know of a diff program that will go byte-by-byte? Thanks.</p> <p><hr /></p> <p><strong>EDIT:</strong></p> <p>Here's the code for my processing function...</p> <pre><code>def read_and_format(inputfile, outputfile): ''' Open input and output files, then read char-by-char and add new lines after "&gt;" ''' infile = codecs.open(inputfile,"r","utf-8") outfile = codecs.open(outputfile,"w","utf-8") char = infile.read(1) while(1): if char == "": break else: outfile.write(char) if(char == "&gt;"): outfile.write("\n") char = infile.read(1) infile.close() outfile.close() </code></pre> <p><hr /></p> <p><strong>EDIT2:</strong> Thanks for the awesome responses. Increaseing the read size created an unbelievable speed increase. Problem solved.</p>
0
2009-08-26T17:13:59Z
1,336,338
<p>For the type of problem you describe, I suspect the algorithm you employ for comparing the data will have a much more significant effect than the I/O model or language. In fact, string allocation and search may be more expensive here than anything else.</p> <p>Some general suggestions before you write this yourself:</p> <ol> <li>Try running on a faster machine if you have one available. That will make a huge difference.</li> <li>Look for an existing tool online for doing XML diffs ... don't write one yourself.</li> </ol> <p>If are are going to write this in C# (or Java or C/C++), I would do the following:</p> <ol> <li>Read a fairly large block into memory all at once (let's say between 200k and 1M)</li> <li>Allocate an empty block that's twice that size (this assumes a worst case of every character is a '>')</li> <li>Copy from the input block to the output block conditionally appending a CRLF after each '>' character.</li> <li>Write the new block out to disk.</li> <li>Repeat until all the data has been processed.</li> </ol> <p>Additionally, you could also write such a program to run on multiple threads, so that while once thread is perform CRLF insertions in memory, a separate thread is read blocks in from disk. This type of parallelization is complicated ... so I would only do so if you really need maximum performance.</p> <p>Here's a really simple C# program to get you started, if you need it. It accepts an input file path and an output path on the command line, and performs the substitution you are looking for ('>' ==> CRLF). This sample leaves much to be improved (parallel processing, streaming, some validation, etc)... but it should be a decent start.</p> <pre><code>using System; using System.IO; namespace ExpandBrackets { class Program { static void Main(string[] args) { if (args.Length == 2) { using( StreamReader input = new StreamReader( args[0] ) ) using( StreamWriter output = new StreamWriter( args[1] ) ) { int readSize = 0; int blockSize = 100000; char[] inBuffer = new char[blockSize]; char[] outBuffer = new char[blockSize*3]; while( ( readSize = input.ReadBlock( inBuffer, 0, blockSize ) ) &gt; 0 ) { int writeSize = TransformBlock( inBuffer, outBuffer, readSize ); output.Write( outBuffer, 0, writeSize ); } } } else { Console.WriteLine( "Usage: repchar {inputfile} {outputfile}" ); } } private static int TransformBlock( char[] inBuffer, char[] outBuffer, int size ) { int j = 0; for( int i = 0; i &lt; size; i++ ) { outBuffer[j++] = inBuffer[i]; if (inBuffer[i] == '&gt;') // append CR LF { outBuffer[j++] = '\r'; outBuffer[j++] = '\n'; } } return j; } } } </code></pre>
1
2009-08-26T17:29:47Z
[ "c#", "python", "performance", "character" ]
Performance - Python vs. C#/C++/C reading char-by-char
1,336,259
<p>So I have these giant XML files (and by giant, I mean like 1.5GB+) and they don't have CRLFs. I'm trying to run a diff-like program to find the differences between these files.</p> <p>Since I've yet to find a diff program that won't explode due to memory exhaustion, I've decided the best bet was to add CRLFs after closing tags.</p> <p>I wrote a python script to read char-by-char and add new-lines after '>'. The problem is I'm running this on a single core PC circa-1995 or something ridiculous, and it's only processing about 20MB/hour when I have both converting at the same time.</p> <p>Any idea if writing this in C#/C/C++ instead will yield any benefits? If not, does anyone know of a diff program that will go byte-by-byte? Thanks.</p> <p><hr /></p> <p><strong>EDIT:</strong></p> <p>Here's the code for my processing function...</p> <pre><code>def read_and_format(inputfile, outputfile): ''' Open input and output files, then read char-by-char and add new lines after "&gt;" ''' infile = codecs.open(inputfile,"r","utf-8") outfile = codecs.open(outputfile,"w","utf-8") char = infile.read(1) while(1): if char == "": break else: outfile.write(char) if(char == "&gt;"): outfile.write("\n") char = infile.read(1) infile.close() outfile.close() </code></pre> <p><hr /></p> <p><strong>EDIT2:</strong> Thanks for the awesome responses. Increaseing the read size created an unbelievable speed increase. Problem solved.</p>
0
2009-08-26T17:13:59Z
1,336,387
<p>I put this as a comment on another answer, but in case you miss it--you might want to look at <a href="http://shootout.alioth.debian.org/u64q/benchmark.php?test=all&amp;lang=all&amp;lang2=python&amp;box=1" rel="nofollow">The Shootout</a>. It's a highly optimized set of code for various problems in many languages.</p> <p>According to those results, Python tends to be about 50x slower than c (but it is faster than the other interpreted languages). In comparison Java is about 2x slower than c. If you went to one of the faster compiled languages, I don't see why you wouldn't see a similar increase.</p> <p>By the way, the figures attained from the shootout are wonderfully un-assailable, you can't really challenge them, instead if you don't believe the numbers are fair because the code to solve a problem in your favorite language isn't optimized properly, then you can submit better code yourself. The act of many people doing this means most of the code on there is pretty damn optimized for every popular language. If you show them a more optimized compiler or interpreter, they may include the results from it as well.</p> <p>Oh: except C#, that's only represented by MONO so if Microsoft's compiler is more optimized, it's not shown. All the tests seem to run on Linux machines. My guess is Microsoft's C# should run at about the same speed as Java, but the shootout lists mono as a bit slower (about 3x as slow as C)..</p>
0
2009-08-26T17:41:37Z
[ "c#", "python", "performance", "character" ]
Performance - Python vs. C#/C++/C reading char-by-char
1,336,259
<p>So I have these giant XML files (and by giant, I mean like 1.5GB+) and they don't have CRLFs. I'm trying to run a diff-like program to find the differences between these files.</p> <p>Since I've yet to find a diff program that won't explode due to memory exhaustion, I've decided the best bet was to add CRLFs after closing tags.</p> <p>I wrote a python script to read char-by-char and add new-lines after '>'. The problem is I'm running this on a single core PC circa-1995 or something ridiculous, and it's only processing about 20MB/hour when I have both converting at the same time.</p> <p>Any idea if writing this in C#/C/C++ instead will yield any benefits? If not, does anyone know of a diff program that will go byte-by-byte? Thanks.</p> <p><hr /></p> <p><strong>EDIT:</strong></p> <p>Here's the code for my processing function...</p> <pre><code>def read_and_format(inputfile, outputfile): ''' Open input and output files, then read char-by-char and add new lines after "&gt;" ''' infile = codecs.open(inputfile,"r","utf-8") outfile = codecs.open(outputfile,"w","utf-8") char = infile.read(1) while(1): if char == "": break else: outfile.write(char) if(char == "&gt;"): outfile.write("\n") char = infile.read(1) infile.close() outfile.close() </code></pre> <p><hr /></p> <p><strong>EDIT2:</strong> Thanks for the awesome responses. Increaseing the read size created an unbelievable speed increase. Problem solved.</p>
0
2009-08-26T17:13:59Z
1,336,642
<p>Why don't you just use sed? cat giant.xml | sed 's/>/>\x0a\x0d/g' > giant-with-linebreaks.xml</p>
3
2009-08-26T18:29:45Z
[ "c#", "python", "performance", "character" ]
Performance - Python vs. C#/C++/C reading char-by-char
1,336,259
<p>So I have these giant XML files (and by giant, I mean like 1.5GB+) and they don't have CRLFs. I'm trying to run a diff-like program to find the differences between these files.</p> <p>Since I've yet to find a diff program that won't explode due to memory exhaustion, I've decided the best bet was to add CRLFs after closing tags.</p> <p>I wrote a python script to read char-by-char and add new-lines after '>'. The problem is I'm running this on a single core PC circa-1995 or something ridiculous, and it's only processing about 20MB/hour when I have both converting at the same time.</p> <p>Any idea if writing this in C#/C/C++ instead will yield any benefits? If not, does anyone know of a diff program that will go byte-by-byte? Thanks.</p> <p><hr /></p> <p><strong>EDIT:</strong></p> <p>Here's the code for my processing function...</p> <pre><code>def read_and_format(inputfile, outputfile): ''' Open input and output files, then read char-by-char and add new lines after "&gt;" ''' infile = codecs.open(inputfile,"r","utf-8") outfile = codecs.open(outputfile,"w","utf-8") char = infile.read(1) while(1): if char == "": break else: outfile.write(char) if(char == "&gt;"): outfile.write("\n") char = infile.read(1) infile.close() outfile.close() </code></pre> <p><hr /></p> <p><strong>EDIT2:</strong> Thanks for the awesome responses. Increaseing the read size created an unbelievable speed increase. Problem solved.</p>
0
2009-08-26T17:13:59Z
1,337,252
<p>As others said, if you do it in C it will be pretty much unbeatable, because C buffers I/O, and getc() is inlined (in my memory).</p> <p>Your real performance issue will be in the diff.</p> <p>Maybe there's a pretty good one out there, but for those size files I doubt it. For fun, I'm a do-it-yourselfer. The strategy I would use is to have a rolling window in each file, several megabytes long. The search strategy for mismatches is diagonal search, which is if you are at lines i and j, compare in this sequence:</p> <pre><code>line(i+0) == line(j+0) line(i+0) == line(j+1) line(i+1) == line(j+0) line(i+0) == line(j+2) line(i+1) == line(j+1) line(i+2) == line(j+0) </code></pre> <p>and so on. No doubt there's a better way, but if I'm going to code it myself and manage the rolling windows, that's what I'd try.</p>
0
2009-08-26T20:25:15Z
[ "c#", "python", "performance", "character" ]
job queue implementation for python
1,336,489
<p>Do you know/use any distributed job queue for python? Can you share links or tools</p>
13
2009-08-26T18:01:08Z
1,336,515
<p>You probably want to look at multiprocessing's Queue. Included in Python 2.6, get it on PyPI for earlier versions of Python.</p> <p>Standard library documentation: <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">http://docs.python.org/library/multiprocessing.html</a> On PyPI: <a href="http://pypi.python.org/pypi/multiprocessing" rel="nofollow">http://pypi.python.org/pypi/multiprocessing</a></p>
-1
2009-08-26T18:06:14Z
[ "python", "job-queue" ]