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
Is there a Python function to determine which quarter of the year a date is in?
1,406,131
<p>Sure I could write this myself, but before I go reinventing the wheel is there a function that already does this?</p>
43
2009-09-10T15:54:08Z
1,406,182
<p>Given an instance <code>x</code> of <a href="http://docs.python.org/library/datetime.html?highlight=datetime#datetime.date">datetime.date</a>, <code>(x.month-1)//3</code> will give you the quarter (0 for first quarter, 1 for second quarter, etc -- add 1 if you need to count from 1 instead;-).</p> <p><strong>Edit</strong>: originally two answers, multiply upvoted and even originally ACCEPTED (both currently deleted), were buggy -- not doing the <code>-1</code> before the division, and dividing by 4 instead of 3. Since <code>.month</code> goes 1 to 12, it's easy to check for yourself what formula is right:</p> <pre class="lang-py prettyprint-override"><code>for m in range(1, 13): print m//4 + 1, print </code></pre> <p>gives <code>1 1 1 2 2 2 2 3 3 3 3 4</code> -- two four-month quarters and a single-month one (eep).</p> <pre class="lang-py prettyprint-override"><code>for m in range(1, 13): print (m-1)//3 + 1, print </code></pre> <p>gives <code>1 1 1 2 2 2 3 3 3 4 4 4</code> -- now doesn't this look vastly preferable to you?-)</p> <p>This proves that the question is well warranted, I think;-). I don't think the datetime module should necessarily have every possible useful calendric function, but I do know I maintain a (well-tested;-) <code>datetools</code> module for the use of my (and others') projects at work, which has many little functions to perform all of these calendric computations -- some are complex, some simple, but there's no reason to do the work over and over (even simple work) or risk bugs in such computations;-).</p>
86
2009-09-10T16:02:18Z
[ "python", "date" ]
Is there a Python function to determine which quarter of the year a date is in?
1,406,131
<p>Sure I could write this myself, but before I go reinventing the wheel is there a function that already does this?</p>
43
2009-09-10T15:54:08Z
1,722,770
<p>hmmm so calculations can go wrong, here is a better version (just for the sake of it)</p> <pre><code>first, second, third, fourth=1,2,3,4# you can make strings if you wish :) quarterMap = {} quarterMap.update(dict(zip((1,2,3),(first,)*3))) quarterMap.update(dict(zip((4,5,6),(second,)*3))) quarterMap.update(dict(zip((7,8,9),(third,)*3))) quarterMap.update(dict(zip((10,11,12),(fourth,)*3))) print quarterMap[6] </code></pre>
0
2009-11-12T14:55:58Z
[ "python", "date" ]
Is there a Python function to determine which quarter of the year a date is in?
1,406,131
<p>Sure I could write this myself, but before I go reinventing the wheel is there a function that already does this?</p>
43
2009-09-10T15:54:08Z
4,684,964
<p>I would suggest another arguably cleaner solution. If X is a <code>datetime.datetime.now()</code> instance, then the quarter is:</p> <pre><code>import math Q=math.ceil(X.month/3.) </code></pre> <p>ceil has to be imported from math module as it can't be accessed directly. </p>
9
2011-01-13T20:34:15Z
[ "python", "date" ]
Is there a Python function to determine which quarter of the year a date is in?
1,406,131
<p>Sure I could write this myself, but before I go reinventing the wheel is there a function that already does this?</p>
43
2009-09-10T15:54:08Z
13,766,929
<p>This is an old question but still worthy of discussion.</p> <p>Here is my solution, using the excellent <a href="http://labix.org/python-dateutil" rel="nofollow">dateutil</a> module.</p> <pre><code> from dateutil import rrule,relativedelta year = this_date.year quarters = rrule.rrule(rrule.MONTHLY, bymonth=(1,4,7,10), bysetpos=-1, dtstart=datetime.datetime(year,1,1), count=8) first_day = quarters.before(this_date) last_day = (quarters.after(this_date) -relativedelta.relativedelta(days=1) </code></pre> <p>So <code>first_day</code> is the first day of the quarter, and <code>last_day</code> is the last day of the quarter (calculated by finding the first day of the next quarter, minus one day).</p>
1
2012-12-07T16:21:02Z
[ "python", "date" ]
Is there a Python function to determine which quarter of the year a date is in?
1,406,131
<p>Sure I could write this myself, but before I go reinventing the wheel is there a function that already does this?</p>
43
2009-09-10T15:54:08Z
28,730,328
<p>if <code>m</code> is the month number...</p> <pre><code>import math math.ceil(float(m) / 3) </code></pre>
0
2015-02-25T21:49:18Z
[ "python", "date" ]
Is there a Python function to determine which quarter of the year a date is in?
1,406,131
<p>Sure I could write this myself, but before I go reinventing the wheel is there a function that already does this?</p>
43
2009-09-10T15:54:08Z
35,691,608
<p><strong>IF</strong> you are already using <code>pandas</code>, it's quite simple.</p> <pre><code>import datetime as dt import pandas as pd quarter = pd.Timestamp(dt.date(2016, 2, 29)).quarter assert quarter == 1 </code></pre> <p>If you have a <code>date</code> column in a dataframe, you can easily create a new <code>quarter</code> column:</p> <pre><code>df['quarter'] = df['date'].dt.quarter </code></pre>
2
2016-02-29T03:42:54Z
[ "python", "date" ]
How do I get rid of Python Tkinter root window?
1,406,145
<p>Do you know a smart way to hide or in any other way get rid of the root window that appears, opened by <code>Tk()</code>? I would like just to use a normal dialog.</p> <p>Should I skip the dialog and put all my components in the root window? Is it possible or desirable? Or is there a smarter solution?</p>
24
2009-09-10T15:56:42Z
1,407,668
<p>I haven't tested since I don't have any Python/TKinter environment, but try this.</p> <p>In pure Tk there's a method called "wm" to manage the windows. There you can do something like "wm withdraw .mywindow" where '.mywindow' is a toplevel.</p> <p>In TkInter you should be able to do something similar to:</p> <pre><code>root = Tkinter.Tk() root.withdraw() # won't need this </code></pre> <p>If you want to make the window visible again, call the <a href="http://effbot.org/tkinterbook/wm.htm#Tkinter.Wm.deiconify-method">deiconify</a> (or wm_deiconify) method. </p> <pre><code>root.deiconify() </code></pre>
8
2009-09-10T20:54:41Z
[ "python", "winapi", "tkinter", "tk" ]
How do I get rid of Python Tkinter root window?
1,406,145
<p>Do you know a smart way to hide or in any other way get rid of the root window that appears, opened by <code>Tk()</code>? I would like just to use a normal dialog.</p> <p>Should I skip the dialog and put all my components in the root window? Is it possible or desirable? Or is there a smarter solution?</p>
24
2009-09-10T15:56:42Z
1,407,700
<p>Probably the vast majority of of tk-based applications place all the components in the default root window. This is the most convenient way to do it since it already exists. Choosing to hide the default window and create your own is a perfectly fine thing to do, though it requires just a tiny bit of extra work. </p> <p>To answer your specific question about how to hide it, use the <code>withdraw</code> method of the root window:</p> <pre><code>import Tkinter as tk root = tk.Tk() root.withdraw() </code></pre> <p>For what it's worth, this information is available on the <a href="http://tkinter.unpythonic.net/wiki/How_do_I_hide_the_main_toplevel_Tkinter_automatically_pops_up%3F">Tkinter wiki</a></p> <p>If you want to make the window visible again, call the <a href="http://effbot.org/tkinterbook/wm.htm#Tkinter.Wm.deiconify-method">deiconify</a> (or wm_deiconify) method.</p> <pre><code>root.deiconify() </code></pre> <p>Once you are done with the dialog(s) you are creating, you can destroy the root window along with all other tkinter widgets with the destroy method:</p> <pre><code>root.destroy() </code></pre>
35
2009-09-10T21:02:32Z
[ "python", "winapi", "tkinter", "tk" ]
How do I get rid of Python Tkinter root window?
1,406,145
<p>Do you know a smart way to hide or in any other way get rid of the root window that appears, opened by <code>Tk()</code>? I would like just to use a normal dialog.</p> <p>Should I skip the dialog and put all my components in the root window? Is it possible or desirable? Or is there a smarter solution?</p>
24
2009-09-10T15:56:42Z
26,932,613
<p>On OSX, iconify seems to work better:</p> <pre><code>root = Tkinter.Tk() root.iconify() </code></pre>
3
2014-11-14T14:50:19Z
[ "python", "winapi", "tkinter", "tk" ]
Emacs 23 hangs on python mode when typing string block """
1,406,213
<p>My Emacs hangs (Ubuntu 9 + Emacs 23 + Pyflakes) when I type <code>"""</code> quotes for string blocks.</p> <p>Anybody experienced the same problem? I think, it may not be an Emacs problem but some Python mode or Pyflakes which I use it for error checking.</p> <p>Anybody got around the issue? It is a really frustrating experience.</p>
0
2009-09-10T16:07:40Z
1,408,659
<p>are you using the external python-mode (from package python-mode) or the internal python mode ? I use pyflakes with the internal emacs python mode without any problems and this is my configuration :</p> <pre><code>(when (load "flymake" t) (defun flymake-pyflakes-init () (let* ((temp-file (flymake-init-create-temp-buffer-copy 'flymake-create-temp-inplace)) (local-file (file-relative-name temp-file (file-name-directory buffer-file-name)))) (list "pyflakes" (list local-file)))) (add-to-list 'flymake-allowed-file-name-masks '("\\.py\\'" flymake-pyflakes-init))) </code></pre>
1
2009-09-11T02:04:03Z
[ "python", "emacs", "pyflakes" ]
Emacs 23 hangs on python mode when typing string block """
1,406,213
<p>My Emacs hangs (Ubuntu 9 + Emacs 23 + Pyflakes) when I type <code>"""</code> quotes for string blocks.</p> <p>Anybody experienced the same problem? I think, it may not be an Emacs problem but some Python mode or Pyflakes which I use it for error checking.</p> <p>Anybody got around the issue? It is a really frustrating experience.</p>
0
2009-09-10T16:07:40Z
1,408,670
<p>latest pyflakes in development mode fixed this problem for me. Thanks all</p> <p><strong>sudo easy_install -U pyflakes</strong></p>
2
2009-09-11T02:08:50Z
[ "python", "emacs", "pyflakes" ]
Emacs 23 hangs on python mode when typing string block """
1,406,213
<p>My Emacs hangs (Ubuntu 9 + Emacs 23 + Pyflakes) when I type <code>"""</code> quotes for string blocks.</p> <p>Anybody experienced the same problem? I think, it may not be an Emacs problem but some Python mode or Pyflakes which I use it for error checking.</p> <p>Anybody got around the issue? It is a really frustrating experience.</p>
0
2009-09-10T16:07:40Z
3,036,535
<p>This is the specific pyflakes bug that causes emacs to go nonlinear: <a href="http://divmod.org/trac/ticket/2821" rel="nofollow">http://divmod.org/trac/ticket/2821</a></p>
0
2010-06-14T10:39:34Z
[ "python", "emacs", "pyflakes" ]
Why do I have this TypeError when using tkinter?
1,406,371
<p>so I upgraded to python 3.1.1 from 2.6 and i ran an old program of mine which uses tkinter.</p> <p>I get the following error message which I don't recall getting in the 2.6 version.</p> <pre><code>Exception in Tkinter callback Traceback (most recent call last): File "C:\Python31\lib\tkinter\__init__.py", line 1399, in __call__ return self.func(*args) File "C:\myprog.py", line 77, in &lt;lambda&gt; self.canvas.bind("&lt;Button-3&gt;", lambda event: myfunc_sub(event)) File "C:\myprog.py", line 65, in myfunc_sub temp_ids = self.canvas.find_overlapping(self.canvas.coords(name)[0], self.canvas.coords(name)[1], self.canvas.coords(name)[2],self.canvas.coords(name)[3]) TypeError: 'map' object is not subscriptable </code></pre> <p>I'm pretty sure the line</p> <pre><code>temp_ids = self.canvas.find_overlapping(self.canvas.coords(name)[0], self.canvas.coords(name)[1], self.canvas.coords(name)[2],self.canvas.coords(name)[3]) </code></pre> <p>was ok in the older version. I'm not sure what has changed so that the way i get each coordinate is not possible. </p> <p>from the <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/tkinter.pdf" rel="nofollow">tkinter docs (pdf)</a></p> <blockquote> <p>".find_enclosed ( x1, y1, x2, y2 ) Returns a list of the object IDs of all objects that occur completely within the rectangle whose top left corner is (x1, y1) and bottom right corner is (x2, y2).</p> <p>.find_overlapping ( x1, y1, x2, y2 ) Like the previous method, but returns a list of the object IDs of all the objects that share at least one point with the given rectangle."</p> </blockquote> <p>any ideas on how to fix this? please let me know if you need more info. the tkinter version i have is 8.5, i have idle 3.1.1 and python 3.1.1. i know the pdf link i provided is for 8.4, but i can't imagine there was a change in these functions.</p> <p>thanks!</p>
0
2009-09-10T16:36:29Z
1,406,386
<p>There were several breaking changes from Python 2.X to Python 3.X -- among them, <code>map</code>'s functionality.</p> <p>Have you run your script through <a href="http://docs.python.org/library/2to3.html" rel="nofollow">2to3</a> yet?</p>
3
2009-09-10T16:38:37Z
[ "python", "python-3.x", "tkinter", "typeerror" ]
Why do I have this TypeError when using tkinter?
1,406,371
<p>so I upgraded to python 3.1.1 from 2.6 and i ran an old program of mine which uses tkinter.</p> <p>I get the following error message which I don't recall getting in the 2.6 version.</p> <pre><code>Exception in Tkinter callback Traceback (most recent call last): File "C:\Python31\lib\tkinter\__init__.py", line 1399, in __call__ return self.func(*args) File "C:\myprog.py", line 77, in &lt;lambda&gt; self.canvas.bind("&lt;Button-3&gt;", lambda event: myfunc_sub(event)) File "C:\myprog.py", line 65, in myfunc_sub temp_ids = self.canvas.find_overlapping(self.canvas.coords(name)[0], self.canvas.coords(name)[1], self.canvas.coords(name)[2],self.canvas.coords(name)[3]) TypeError: 'map' object is not subscriptable </code></pre> <p>I'm pretty sure the line</p> <pre><code>temp_ids = self.canvas.find_overlapping(self.canvas.coords(name)[0], self.canvas.coords(name)[1], self.canvas.coords(name)[2],self.canvas.coords(name)[3]) </code></pre> <p>was ok in the older version. I'm not sure what has changed so that the way i get each coordinate is not possible. </p> <p>from the <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/tkinter.pdf" rel="nofollow">tkinter docs (pdf)</a></p> <blockquote> <p>".find_enclosed ( x1, y1, x2, y2 ) Returns a list of the object IDs of all objects that occur completely within the rectangle whose top left corner is (x1, y1) and bottom right corner is (x2, y2).</p> <p>.find_overlapping ( x1, y1, x2, y2 ) Like the previous method, but returns a list of the object IDs of all the objects that share at least one point with the given rectangle."</p> </blockquote> <p>any ideas on how to fix this? please let me know if you need more info. the tkinter version i have is 8.5, i have idle 3.1.1 and python 3.1.1. i know the pdf link i provided is for 8.4, but i can't imagine there was a change in these functions.</p> <p>thanks!</p>
0
2009-09-10T16:36:29Z
1,406,393
<pre><code>self.canvas.coords(name) </code></pre> <p>return a <code>map object</code>, and as the error states <code>map</code> object is unsubscriptable in python 3. you need to change <code>coords</code> to be a tuple or a list.</p> <p>you need to change your code to be:</p> <pre><code>temp_ids = self.canvas.find_overlapping(*tuple(self.canvas.coords(name))) </code></pre>
2
2009-09-10T16:40:02Z
[ "python", "python-3.x", "tkinter", "typeerror" ]
Splitting a string with no line breaks into a list of lines with a maximum column count
1,406,493
<p>I have a long string (multiple paragraphs) which I need to split into a list of line strings. The determination of what makes a "line" is based on:</p> <ul> <li>The number of characters in the line is less than or equal to X (where X is a fixed number of columns per line_)</li> <li>OR, there is a newline in the original string (that will force a new "line" to be created.</li> </ul> <p>I know I can do this algorithmically but I was wondering if python has something that can handle this case. It's essentially word-wrapping a string. </p> <p>And, by the way, the output lines must be broken on word boundaries, not character boundaries.</p> <p>Here's an example of input and output:</p> <p>Input: </p> <pre><code>"Within eight hours of Wilson's outburst, his Democratic opponent, former-Marine Rob Miller, had received nearly 3,000 individual contributions raising approximately $100,000, the Democratic Congressional Campaign Committee said. Wilson, a conservative Republican who promotes a strong national defense and reining in the size of government, won a special election to the House in 2001, succeeding the late Rep. Floyd Spence, R-S.C. Wilson had worked on Spence's staff on Capitol Hill and also had served as an intern for Sen. Strom Thurmond, R-S.C." </code></pre> <p>Output:</p> <pre><code>"Within eight hours of Wilson's outburst, his" "Democratic opponent, former-Marine Rob Miller," " had received nearly 3,000 individual " "contributions raising approximately $100,000," " the Democratic Congressional Campaign Committee" " said." "" "Wilson, a conservative Republican who promotes a " "strong national defense and reining in the size " "of government, won a special election to the House" " in 2001, succeeding the late Rep. Floyd Spence, " "R-S.C. Wilson had worked on Spence's staff on " "Capitol Hill and also had served as an intern" " for Sen. Strom Thurmond, R-S.C." </code></pre>
6
2009-09-10T16:59:30Z
1,406,514
<p>You probably want to use the textwrap function in the standard library:</p> <p><a href="http://docs.python.org/library/textwrap.html" rel="nofollow">http://docs.python.org/library/textwrap.html</a></p>
4
2009-09-10T17:03:29Z
[ "python", "text-manipulation" ]
Splitting a string with no line breaks into a list of lines with a maximum column count
1,406,493
<p>I have a long string (multiple paragraphs) which I need to split into a list of line strings. The determination of what makes a "line" is based on:</p> <ul> <li>The number of characters in the line is less than or equal to X (where X is a fixed number of columns per line_)</li> <li>OR, there is a newline in the original string (that will force a new "line" to be created.</li> </ul> <p>I know I can do this algorithmically but I was wondering if python has something that can handle this case. It's essentially word-wrapping a string. </p> <p>And, by the way, the output lines must be broken on word boundaries, not character boundaries.</p> <p>Here's an example of input and output:</p> <p>Input: </p> <pre><code>"Within eight hours of Wilson's outburst, his Democratic opponent, former-Marine Rob Miller, had received nearly 3,000 individual contributions raising approximately $100,000, the Democratic Congressional Campaign Committee said. Wilson, a conservative Republican who promotes a strong national defense and reining in the size of government, won a special election to the House in 2001, succeeding the late Rep. Floyd Spence, R-S.C. Wilson had worked on Spence's staff on Capitol Hill and also had served as an intern for Sen. Strom Thurmond, R-S.C." </code></pre> <p>Output:</p> <pre><code>"Within eight hours of Wilson's outburst, his" "Democratic opponent, former-Marine Rob Miller," " had received nearly 3,000 individual " "contributions raising approximately $100,000," " the Democratic Congressional Campaign Committee" " said." "" "Wilson, a conservative Republican who promotes a " "strong national defense and reining in the size " "of government, won a special election to the House" " in 2001, succeeding the late Rep. Floyd Spence, " "R-S.C. Wilson had worked on Spence's staff on " "Capitol Hill and also had served as an intern" " for Sen. Strom Thurmond, R-S.C." </code></pre>
6
2009-09-10T16:59:30Z
1,406,526
<p><strong>EDIT</strong></p> <p>What you are looking for is <a href="http://docs.python.org/library/textwrap.html#module-textwrap">textwrap</a>, but that's only part of the solution not the complete one. To take newline into account you need to do this:</p> <pre><code>from textwrap import wrap '\n'.join(['\n'.join(wrap(block, width=50)) for block in text.splitlines()]) &gt;&gt;&gt; print '\n'.join(['\n'.join(wrap(block, width=50)) for block in text.splitlines()]) Within eight hours of Wilson's outburst, his Democratic opponent, former-Marine Rob Miller, had received nearly 3,000 individual contributions raising approximately $100,000, the Democratic Congressional Campaign Committee said. Wilson, a conservative Republican who promotes a strong national defense and reining in the size of government, won a special election to the House in 2001, succeeding the late Rep. Floyd Spence, R-S.C. Wilson had worked on Spence's staff on Capitol Hill and also had served as an intern for Sen. Strom Thurmond </code></pre>
12
2009-09-10T17:05:17Z
[ "python", "text-manipulation" ]
Non-critical unittest failures
1,406,552
<p>I'm using Python's built-in <a href="http://docs.python.org/library/unittest.html" rel="nofollow">unittest</a> module and I want to write a few tests that are not critical.</p> <p>I mean, if my program passes such tests, that's great! However, if it doesn't pass, it's not really a problem, the program will still work.</p> <p>For example, my program is designed to work with a custom type "A". If it fails to work with "A", then it's broken. However, for convenience, most of it should also work with another type "B", but that's not mandatory. If it fails to work with "B", then it's not broken (because it still works with "A", which is its main purpose). Failing to work with "B" is not critical, I will just miss a "bonus feature" I could have.</p> <p>Another (hypothetical) example is when writing an OCR. The algorithm should recognize most images from the tests, but it's okay if some of them fails. (and no, I'm not writing an OCR)</p> <p>Is there any way to write non-critical tests in unittest (or other testing framework)?</p>
3
2009-09-10T17:11:51Z
1,406,570
<p>As a practical matter, I'd probably use print statements to indicate failure in that case. A more correct solution is to use warnings:</p> <p><a href="http://docs.python.org/library/warnings.html" rel="nofollow">http://docs.python.org/library/warnings.html</a></p> <p>You could, however, use the logging facility to generate a more detailed record of your test results (i.e. set your "B" class failures to write warnings to the logs).</p> <p><a href="http://docs.python.org/library/logging.html" rel="nofollow">http://docs.python.org/library/logging.html</a></p> <p>Edit:</p> <p>The way we handle this in Django is that we have some tests we expect to fail, and we have others that we skip based on the environment. Since we can generally predict whether a test SHOULD fail or pass (i.e. if we can't import a certain module, the system doesn't have it, and so the test won't work), we can skip failing tests intelligently. This means that we still run every test that will pass, and have no tests that "might" pass. Unit tests are most useful when they do things predictably, and being able to detect whether or not a test SHOULD pass before we run it makes this possible.</p>
7
2009-09-10T17:16:11Z
[ "python", "unit-testing" ]
Non-critical unittest failures
1,406,552
<p>I'm using Python's built-in <a href="http://docs.python.org/library/unittest.html" rel="nofollow">unittest</a> module and I want to write a few tests that are not critical.</p> <p>I mean, if my program passes such tests, that's great! However, if it doesn't pass, it's not really a problem, the program will still work.</p> <p>For example, my program is designed to work with a custom type "A". If it fails to work with "A", then it's broken. However, for convenience, most of it should also work with another type "B", but that's not mandatory. If it fails to work with "B", then it's not broken (because it still works with "A", which is its main purpose). Failing to work with "B" is not critical, I will just miss a "bonus feature" I could have.</p> <p>Another (hypothetical) example is when writing an OCR. The algorithm should recognize most images from the tests, but it's okay if some of them fails. (and no, I'm not writing an OCR)</p> <p>Is there any way to write non-critical tests in unittest (or other testing framework)?</p>
3
2009-09-10T17:11:51Z
1,406,576
<p>Im not totally sure how unittest works, but most unit testing frameworks have something akin to categories. I suppose you could just categorize such tests, mark them to be ignored, and then run them only when your interested in them. But I know from experience that ignored tests very quickly become...just that ignored tests that nobody ever runs and are therefore a waste of time and energy to write them. </p> <p>My advice is for your app to do, or do not, there is no try.</p>
4
2009-09-10T17:17:30Z
[ "python", "unit-testing" ]
Non-critical unittest failures
1,406,552
<p>I'm using Python's built-in <a href="http://docs.python.org/library/unittest.html" rel="nofollow">unittest</a> module and I want to write a few tests that are not critical.</p> <p>I mean, if my program passes such tests, that's great! However, if it doesn't pass, it's not really a problem, the program will still work.</p> <p>For example, my program is designed to work with a custom type "A". If it fails to work with "A", then it's broken. However, for convenience, most of it should also work with another type "B", but that's not mandatory. If it fails to work with "B", then it's not broken (because it still works with "A", which is its main purpose). Failing to work with "B" is not critical, I will just miss a "bonus feature" I could have.</p> <p>Another (hypothetical) example is when writing an OCR. The algorithm should recognize most images from the tests, but it's okay if some of them fails. (and no, I'm not writing an OCR)</p> <p>Is there any way to write non-critical tests in unittest (or other testing framework)?</p>
3
2009-09-10T17:11:51Z
1,406,584
<p>You could write your test so that they count success rate. With OCR you could throw at code 1000 images and require that 95% is successful. </p> <p>If your program must work with type A then if this fails the test fails. If it's not required to work with B, what is the value of doing such a test ?</p>
-1
2009-09-10T17:19:34Z
[ "python", "unit-testing" ]
Non-critical unittest failures
1,406,552
<p>I'm using Python's built-in <a href="http://docs.python.org/library/unittest.html" rel="nofollow">unittest</a> module and I want to write a few tests that are not critical.</p> <p>I mean, if my program passes such tests, that's great! However, if it doesn't pass, it's not really a problem, the program will still work.</p> <p>For example, my program is designed to work with a custom type "A". If it fails to work with "A", then it's broken. However, for convenience, most of it should also work with another type "B", but that's not mandatory. If it fails to work with "B", then it's not broken (because it still works with "A", which is its main purpose). Failing to work with "B" is not critical, I will just miss a "bonus feature" I could have.</p> <p>Another (hypothetical) example is when writing an OCR. The algorithm should recognize most images from the tests, but it's okay if some of them fails. (and no, I'm not writing an OCR)</p> <p>Is there any way to write non-critical tests in unittest (or other testing framework)?</p>
3
2009-09-10T17:11:51Z
1,406,610
<p>Asserts in unit tests are binary: they will work or they will fail, there's no mid-term.</p> <p>Given that, to create those "non-critical" tests you should not use assertions when you don't want the tests to fail. You should do this carefully so you don't compromise the "usefulness" of the test.</p> <p>My advice to your OCR example is that you use something to record the success rate in your tests code and then create one assertion like: "assert success_rate > 8.5", and that should give the effect you desire.</p>
4
2009-09-10T17:27:20Z
[ "python", "unit-testing" ]
Non-critical unittest failures
1,406,552
<p>I'm using Python's built-in <a href="http://docs.python.org/library/unittest.html" rel="nofollow">unittest</a> module and I want to write a few tests that are not critical.</p> <p>I mean, if my program passes such tests, that's great! However, if it doesn't pass, it's not really a problem, the program will still work.</p> <p>For example, my program is designed to work with a custom type "A". If it fails to work with "A", then it's broken. However, for convenience, most of it should also work with another type "B", but that's not mandatory. If it fails to work with "B", then it's not broken (because it still works with "A", which is its main purpose). Failing to work with "B" is not critical, I will just miss a "bonus feature" I could have.</p> <p>Another (hypothetical) example is when writing an OCR. The algorithm should recognize most images from the tests, but it's okay if some of them fails. (and no, I'm not writing an OCR)</p> <p>Is there any way to write non-critical tests in unittest (or other testing framework)?</p>
3
2009-09-10T17:11:51Z
1,406,832
<p>There are some test systems that allow warnings rather than failures, but test_unit is not one of them (I don't know which ones do, offhand) unless you want to extend it (which is possible).</p> <p>You can make the tests so that they log warnings rather than fail.</p> <p>Another way to handle this is to separate out the tests and only run them to get the pass/fail reports and not have any build dependencies (this depends on your build setup).</p>
1
2009-09-10T18:08:33Z
[ "python", "unit-testing" ]
Non-critical unittest failures
1,406,552
<p>I'm using Python's built-in <a href="http://docs.python.org/library/unittest.html" rel="nofollow">unittest</a> module and I want to write a few tests that are not critical.</p> <p>I mean, if my program passes such tests, that's great! However, if it doesn't pass, it's not really a problem, the program will still work.</p> <p>For example, my program is designed to work with a custom type "A". If it fails to work with "A", then it's broken. However, for convenience, most of it should also work with another type "B", but that's not mandatory. If it fails to work with "B", then it's not broken (because it still works with "A", which is its main purpose). Failing to work with "B" is not critical, I will just miss a "bonus feature" I could have.</p> <p>Another (hypothetical) example is when writing an OCR. The algorithm should recognize most images from the tests, but it's okay if some of them fails. (and no, I'm not writing an OCR)</p> <p>Is there any way to write non-critical tests in unittest (or other testing framework)?</p>
3
2009-09-10T17:11:51Z
1,406,948
<p>Take a look at Nose : <a href="http://somethingaboutorange.com/mrl/projects/nose/0.11.1/" rel="nofollow">http://somethingaboutorange.com/mrl/projects/nose/0.11.1/</a></p> <p>There are plenty of command line options for selecting tests to run, and you can keep your existing unittest tests.</p>
0
2009-09-10T18:33:06Z
[ "python", "unit-testing" ]
Non-critical unittest failures
1,406,552
<p>I'm using Python's built-in <a href="http://docs.python.org/library/unittest.html" rel="nofollow">unittest</a> module and I want to write a few tests that are not critical.</p> <p>I mean, if my program passes such tests, that's great! However, if it doesn't pass, it's not really a problem, the program will still work.</p> <p>For example, my program is designed to work with a custom type "A". If it fails to work with "A", then it's broken. However, for convenience, most of it should also work with another type "B", but that's not mandatory. If it fails to work with "B", then it's not broken (because it still works with "A", which is its main purpose). Failing to work with "B" is not critical, I will just miss a "bonus feature" I could have.</p> <p>Another (hypothetical) example is when writing an OCR. The algorithm should recognize most images from the tests, but it's okay if some of them fails. (and no, I'm not writing an OCR)</p> <p>Is there any way to write non-critical tests in unittest (or other testing framework)?</p>
3
2009-09-10T17:11:51Z
1,407,485
<p>From <a href="http://docs.python.org/library/unittest.html" rel="nofollow">unittest</a> documentation which you link:</p> <blockquote> <p>Instead of unittest.main(), there are other ways to run the tests with a finer level of control, less terse output, and no requirement to be run from the command line. For example, the last two lines may be replaced with:</p> <pre><code>suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions) unittest.TextTestRunner(verbosity=2).run(suite) </code></pre> </blockquote> <p>In your case, you can create separate <a href="http://docs.python.org/library/unittest.html#unittest.TestSuite" rel="nofollow"><code>TestSuite</code></a> instances for the criticial and non-critical tests. You could control which suite is passed to the test runner with a command line argument. Test suites can also contain other test suites so you can create big hierarchies if you want.</p>
2
2009-09-10T20:16:41Z
[ "python", "unit-testing" ]
Non-critical unittest failures
1,406,552
<p>I'm using Python's built-in <a href="http://docs.python.org/library/unittest.html" rel="nofollow">unittest</a> module and I want to write a few tests that are not critical.</p> <p>I mean, if my program passes such tests, that's great! However, if it doesn't pass, it's not really a problem, the program will still work.</p> <p>For example, my program is designed to work with a custom type "A". If it fails to work with "A", then it's broken. However, for convenience, most of it should also work with another type "B", but that's not mandatory. If it fails to work with "B", then it's not broken (because it still works with "A", which is its main purpose). Failing to work with "B" is not critical, I will just miss a "bonus feature" I could have.</p> <p>Another (hypothetical) example is when writing an OCR. The algorithm should recognize most images from the tests, but it's okay if some of them fails. (and no, I'm not writing an OCR)</p> <p>Is there any way to write non-critical tests in unittest (or other testing framework)?</p>
3
2009-09-10T17:11:51Z
1,407,582
<p>Another possibility is to create a "B" branch (you ARE using some sort of version control, right?) and have your unit tests for "B" in there. That way, you keep your release version's unit tests clean (Look, all dots!), but still have tests for B. If you're using a modern version control system like git or mercurial (I'm partial to mercurial), branching/cloning and merging are trivial operations, so that's what I'd recommend.</p> <p>However, I think you're using tests for something they're not meant to do. The real question is "How important to you is it that 'B' works?" Because your test suite should only have tests in it that you care whether they pass or fail. Tests that, if they fail, it means the code is broken. That's why I suggested only testing "B" in the "B" branch, since that would be the branch where you are developing the "B" feature. </p> <p>You could test using logger or print commands, if you like. But if you don't care enough that it's broken to have it flagged in your unit tests, I'd seriously question whether you care enough to test it at all. Besides, that adds needless complexity (extra variables to set debug level, multiple testing vectors that are completely independent of each other yet operate within the same space, causing potential collisions and errors, etc, etc). Unless you're developing a "Hello, World!" app, I suspect your problem set is complicated enough without adding additional, unnecessary complications.</p>
0
2009-09-10T20:36:18Z
[ "python", "unit-testing" ]
Non-critical unittest failures
1,406,552
<p>I'm using Python's built-in <a href="http://docs.python.org/library/unittest.html" rel="nofollow">unittest</a> module and I want to write a few tests that are not critical.</p> <p>I mean, if my program passes such tests, that's great! However, if it doesn't pass, it's not really a problem, the program will still work.</p> <p>For example, my program is designed to work with a custom type "A". If it fails to work with "A", then it's broken. However, for convenience, most of it should also work with another type "B", but that's not mandatory. If it fails to work with "B", then it's not broken (because it still works with "A", which is its main purpose). Failing to work with "B" is not critical, I will just miss a "bonus feature" I could have.</p> <p>Another (hypothetical) example is when writing an OCR. The algorithm should recognize most images from the tests, but it's okay if some of them fails. (and no, I'm not writing an OCR)</p> <p>Is there any way to write non-critical tests in unittest (or other testing framework)?</p>
3
2009-09-10T17:11:51Z
1,423,506
<p>Thank you for the great answers. No only one answer was really complete, so I'm writing here <a href="http://meta.stackexchange.com/questions/13413/how-do-i-combine-two-answers-to-create-the-best-answer-on-stackoverflow/13414#13414">a combination of all answers that helped me</a>. If you like this answer, please vote up the people who were responsible for this.</p> <p><strong>Conclusions</strong></p> <p>Unit tests (or at least unit tests in <code>unittest</code> module) are binary. As <a href="http://stackoverflow.com/questions/1406552/non-critical-unittest-failures/1406610#1406610">Guilherme Chapiewski says</a>: <em>they will work or they will fail, there's no mid-term.</em></p> <p>Thus, my conclusion is that unit tests are not exactly the right tool for this job. It seems that unit tests are more concerned about <em>"keep everything working, no failure is expected"</em>, and thus I can't (or it's not easy) to have non-binary tests.</p> <p>So, unit tests don't seem the right tool if I'm trying to improve an algorithm or an implementation, because unit tests can't tell me how better is one version when compared to the other (supposing both of them are correctly implemented, then both will pass all unit tests).</p> <p><strong>My final solution</strong></p> <p>My final solution is based on <a href="http://stackoverflow.com/questions/1406552/non-critical-unittest-failures/1406576#1406576">ryber's idea</a> and code shown in <a href="http://stackoverflow.com/questions/1406552/non-critical-unittest-failures/1407485#1407485">wcoenen answer</a>. I'm basically extending the default <code>TextTestRunner</code> and making it less verbose. Then, my main code call two test suits: the critical one using the standard <code>TextTestRunner</code>, and the non-critical one, with my own less-verbose version.</p> <pre><code>class _TerseTextTestResult(unittest._TextTestResult): def printErrorList(self, flavour, errors): for test, err in errors: #self.stream.writeln(self.separator1) self.stream.writeln("%s: %s" % (flavour,self.getDescription(test))) #self.stream.writeln(self.separator2) #self.stream.writeln("%s" % err) class TerseTextTestRunner(unittest.TextTestRunner): def _makeResult(self): return _TerseTextTestResult(self.stream, self.descriptions, self.verbosity) if __name__ == '__main__': sys.stderr.write("Running non-critical tests:\n") non_critical_suite = unittest.TestLoader().loadTestsFromTestCase(TestSomethingNonCritical) TerseTextTestRunner(verbosity=1).run(non_critical_suite) sys.stderr.write("\n") sys.stderr.write("Running CRITICAL tests:\n") suite = unittest.TestLoader().loadTestsFromTestCase(TestEverythingImportant) unittest.TextTestRunner(verbosity=1).run(suite) </code></pre> <p><strong>Possible improvements</strong></p> <p>It should still be useful to know if there is any testing framework with non-binary tests, like <a href="http://stackoverflow.com/questions/1406552/non-critical-unittest-failures/1406832#1406832">Kathy Van Stone suggested</a>. Probably I won't use it this simple personal project, but it might be useful on future projects.</p>
1
2009-09-14T19:42:08Z
[ "python", "unit-testing" ]
Non-critical unittest failures
1,406,552
<p>I'm using Python's built-in <a href="http://docs.python.org/library/unittest.html" rel="nofollow">unittest</a> module and I want to write a few tests that are not critical.</p> <p>I mean, if my program passes such tests, that's great! However, if it doesn't pass, it's not really a problem, the program will still work.</p> <p>For example, my program is designed to work with a custom type "A". If it fails to work with "A", then it's broken. However, for convenience, most of it should also work with another type "B", but that's not mandatory. If it fails to work with "B", then it's not broken (because it still works with "A", which is its main purpose). Failing to work with "B" is not critical, I will just miss a "bonus feature" I could have.</p> <p>Another (hypothetical) example is when writing an OCR. The algorithm should recognize most images from the tests, but it's okay if some of them fails. (and no, I'm not writing an OCR)</p> <p>Is there any way to write non-critical tests in unittest (or other testing framework)?</p>
3
2009-09-10T17:11:51Z
3,999,906
<p>Python 2.7 (and 3.1) added support for skipping some test methods or test cases, as well as marking some tests as <strong>expected failure</strong>.</p> <p><a href="http://docs.python.org/library/unittest.html#skipping-tests-and-expected-failures" rel="nofollow">http://docs.python.org/library/unittest.html#skipping-tests-and-expected-failures</a></p> <p>Tests marked as expected failure won't be counted as failure on a TestResult.</p>
0
2010-10-22T18:41:31Z
[ "python", "unit-testing" ]
How do I keep state between requests in AppEngine (Python)?
1,406,636
<p>I'm writing a simple app with AppEngine, using Python. After a successful insert by a user and redirect, I'd like to display a flash confirmation message on the next page. </p> <p>What's the best way to keep state between one request and the next? Or is this not possible because AppEngine is distributed? I guess, the underlying question is whether AppEngine provides a persistent session object. </p> <p>Thanks</p> <p>Hannes</p>
1
2009-09-10T17:32:58Z
1,406,722
<p>No session support is included in App Engine itself, but you can add your own session support.</p> <p><a href="http://gaeutilities.appspot.com/" rel="nofollow">GAE Utilities</a> is one library made specifically for this; a more heavyweight alternative is to use django sessions through <a href="http://code.google.com/p/app-engine-patch/" rel="nofollow">App Engine Patch</a>.</p>
3
2009-09-10T17:49:51Z
[ "python", "google-app-engine" ]
How do I keep state between requests in AppEngine (Python)?
1,406,636
<p>I'm writing a simple app with AppEngine, using Python. After a successful insert by a user and redirect, I'd like to display a flash confirmation message on the next page. </p> <p>What's the best way to keep state between one request and the next? Or is this not possible because AppEngine is distributed? I guess, the underlying question is whether AppEngine provides a persistent session object. </p> <p>Thanks</p> <p>Hannes</p>
1
2009-09-10T17:32:58Z
1,406,768
<p>The ways to reliable keep state between requests are memcache, the datastore or through the user (cookies or post/get).</p> <p>You can use the runtime cache too, but this is very unreliable as you don't know if a request will end up in the same runtime or the runtime can drop it's entire cache if it feels like it.</p> <p>I really wouldn't use the runtime cache except for very specific situations, for example I use it to cache the serialization of objects to json as that is pretty slow and if the caching is gone I can regenerate the result easily.</p>
3
2009-09-10T17:55:50Z
[ "python", "google-app-engine" ]
What class to use for money representation?
1,406,737
<p>What class should I use for representation of money to avoid most rounding errors?</p> <p>Should I use <code>Decimal</code>, or a simple built-in <code>number</code>?</p> <p>Is there any existing <code>Money</code> class with support for currency conversion that I could use?</p> <p>Any pitfalls that I should avoid?</p>
10
2009-09-10T17:52:04Z
1,406,764
<p>You might be interested in <a href="http://quantlib.org/index.shtml" rel="nofollow">QuantLib</a> for working with finance. </p> <p>It has built in classes for handling currency types and claims 4 years of active development.</p>
3
2009-09-10T17:55:20Z
[ "python", "money", "rounding-error", "arbitrary-precision", "precision" ]
What class to use for money representation?
1,406,737
<p>What class should I use for representation of money to avoid most rounding errors?</p> <p>Should I use <code>Decimal</code>, or a simple built-in <code>number</code>?</p> <p>Is there any existing <code>Money</code> class with support for currency conversion that I could use?</p> <p>Any pitfalls that I should avoid?</p>
10
2009-09-10T17:52:04Z
1,406,792
<p>You could have a look at this library: <a href="http://code.google.com/p/python-money/" rel="nofollow">python-money</a>. Since I've no experience with it I cannot comment on its usefullness.</p> <p>A 'trick' you could employ to handle currency as integers: </p> <ul> <li>Multiply by 100 / Divide by 100 (e.g. $100,25 -> 10025) to have a representation in 'cents'</li> </ul>
3
2009-09-10T17:59:53Z
[ "python", "money", "rounding-error", "arbitrary-precision", "precision" ]
What class to use for money representation?
1,406,737
<p>What class should I use for representation of money to avoid most rounding errors?</p> <p>Should I use <code>Decimal</code>, or a simple built-in <code>number</code>?</p> <p>Is there any existing <code>Money</code> class with support for currency conversion that I could use?</p> <p>Any pitfalls that I should avoid?</p>
10
2009-09-10T17:52:04Z
1,406,800
<p>I assume that you talking about Python. <a href="http://code.google.com/p/python-money/" rel="nofollow">http://code.google.com/p/python-money/</a> "Primitives for working with money and currencies in Python" - the title is self explanatory :)</p>
3
2009-09-10T18:01:25Z
[ "python", "money", "rounding-error", "arbitrary-precision", "precision" ]
What class to use for money representation?
1,406,737
<p>What class should I use for representation of money to avoid most rounding errors?</p> <p>Should I use <code>Decimal</code>, or a simple built-in <code>number</code>?</p> <p>Is there any existing <code>Money</code> class with support for currency conversion that I could use?</p> <p>Any pitfalls that I should avoid?</p>
10
2009-09-10T17:52:04Z
1,408,693
<p>Just use <a href="http://docs.python.org/library/decimal.html">decimal</a>.</p>
5
2009-09-11T02:20:28Z
[ "python", "money", "rounding-error", "arbitrary-precision", "precision" ]
What class to use for money representation?
1,406,737
<p>What class should I use for representation of money to avoid most rounding errors?</p> <p>Should I use <code>Decimal</code>, or a simple built-in <code>number</code>?</p> <p>Is there any existing <code>Money</code> class with support for currency conversion that I could use?</p> <p>Any pitfalls that I should avoid?</p>
10
2009-09-10T17:52:04Z
11,620,751
<p>Never use a floating point number to represent money. Floating numbers do not represent numbers in decimal notation accurately. You would end with a nightmare of compound rounding errors, and unable to reliably convert between currencies. See <a href="http://martinfowler.com/eaaCatalog/money.html" rel="nofollow" title="Money Pattern">Martin Fowler's short essay on the subject</a>.</p> <p>If you decide to write your own class, I recommend basing it on the <a href="http://docs.python.org/library/decimal.html" rel="nofollow" title="decimal">decimal</a> data type.</p> <p>I don't think python-money is a good option, because it wasn't maintained for quite some time and its source code has some strange and useless code, and exchanging currencies is simply broken.</p> <p>Try <a href="http://pypi.python.org/pypi/py-moneyed" rel="nofollow" title="python-moneyed">py-moneyed</a>. It's an improvement over python-money.</p>
2
2012-07-23T21:25:53Z
[ "python", "money", "rounding-error", "arbitrary-precision", "precision" ]
What class to use for money representation?
1,406,737
<p>What class should I use for representation of money to avoid most rounding errors?</p> <p>Should I use <code>Decimal</code>, or a simple built-in <code>number</code>?</p> <p>Is there any existing <code>Money</code> class with support for currency conversion that I could use?</p> <p>Any pitfalls that I should avoid?</p>
10
2009-09-10T17:52:04Z
17,941,227
<p>Simple, light-weight, yet extensible idea:</p> <pre><code>class Money(): def __init__(self, value): # internally use Decimal or cents as long self._cents = long(0) # Now parse 'value' as needed e.g. locale-specific user-entered string, cents, Money, etc. # Decimal helps in conversion def as_my_app_specific_protocol(self): # some application-specific representation def __str__(self): # user-friendly form, locale specific if needed # rich comparison and basic arithmetics def __lt__(self, other): return self._cents &lt; Money(other)._cents def __add__(self, other): return Money(self._cents + Money(other)._cents) </code></pre> <p>You can:</p> <ul> <li>Implement only what you need in your application.</li> <li>Extend it as you grow.</li> <li>Change internal representation and implementation as needed.</li> </ul>
0
2013-07-30T07:50:53Z
[ "python", "money", "rounding-error", "arbitrary-precision", "precision" ]
What class to use for money representation?
1,406,737
<p>What class should I use for representation of money to avoid most rounding errors?</p> <p>Should I use <code>Decimal</code>, or a simple built-in <code>number</code>?</p> <p>Is there any existing <code>Money</code> class with support for currency conversion that I could use?</p> <p>Any pitfalls that I should avoid?</p>
10
2009-09-10T17:52:04Z
17,941,472
<p>It depends what you'd like to use <code>Money</code> for. </p> <p>For financial modelling of price and risk <code>double</code> (Python's <code>float</code>) is good enough because all models are inaccurate (some of them are useful though), so one doesn't get any useful extra precision by using infinite precision numbers.</p> <p>For currency conversions you need currency rates. The currency rate one can get in practise depends on the amount and other factors. Again, currency rate conversion is just a multiplication and it is often implemented by distinct class <code>CcyPair</code>.</p>
0
2013-07-30T08:05:40Z
[ "python", "money", "rounding-error", "arbitrary-precision", "precision" ]
What is Facebook's new Tornado framework?
1,406,912
<p>Facebook just open-sourced <a href="http://developers.facebook.com/opensource.php">a framework called Tornado</a>. </p> <p>What is it? What does it help a site do?</p> <p>I believe Facebook uses a LAMP structure. Is it useful for smaller sites which are written under the LAMP stack? </p>
15
2009-09-10T18:24:25Z
1,406,930
<p>It looks like it is a web-server optimized for high-concurrency and high-scalability, but made for smaller payloads.</p> <p>It was designed to support 10,000 concurrent users well.</p> <blockquote> <p>The framework is distinct from most mainstream web server frameworks (and certainly most Python frameworks) because it is non-blocking and reasonably fast. Because it is non-blocking and uses epoll, it can handle thousands of simultaneous standing connections, which means it is ideal for real-time web services. We built the web server specifically to handle FriendFeed's real-time features — every active user of FriendFeed maintains an open connection to the FriendFeed servers. (For more information on scaling servers to support thousands of clients, see The C10K problem.)</p> </blockquote> <p>It will run on a LMP stack, but it takes the place of Apache.</p> <p>See the <a href="http://www.kegel.com/c10k.html">C10K</a> problem.</p>
13
2009-09-10T18:27:38Z
[ "python", "facebook", "tornado" ]
What is Facebook's new Tornado framework?
1,406,912
<p>Facebook just open-sourced <a href="http://developers.facebook.com/opensource.php">a framework called Tornado</a>. </p> <p>What is it? What does it help a site do?</p> <p>I believe Facebook uses a LAMP structure. Is it useful for smaller sites which are written under the LAMP stack? </p>
15
2009-09-10T18:24:25Z
1,416,089
<p>It has <a href="http://github.com/facebook/tornado/blob/master/tornado/database.py" rel="nofollow">'database' module</a> with blocking queries. Maybe they run multiple instances of this server to minimize blocking problems and maybe it is not used for whole friendfeed, only in some parts related to real-time behavior (i heard that HTTP connections persist open to check for updates, and threading behavior would be bad for this).</p> <p>I don't think it is usable as general-purpose framework for any web applications.</p>
0
2009-09-12T20:41:06Z
[ "python", "facebook", "tornado" ]
What is Facebook's new Tornado framework?
1,406,912
<p>Facebook just open-sourced <a href="http://developers.facebook.com/opensource.php">a framework called Tornado</a>. </p> <p>What is it? What does it help a site do?</p> <p>I believe Facebook uses a LAMP structure. Is it useful for smaller sites which are written under the LAMP stack? </p>
15
2009-09-10T18:24:25Z
3,854,210
<p>Looking for an alternative (single threaded, asynchronous, event driven high performance web server) running on the JVM? </p> <p><a href="http://www.deftserver.org" rel="nofollow">Deft web server</a></p> <p>(Disclaimer: I'm a Deft committer) </p>
1
2010-10-04T10:08:45Z
[ "python", "facebook", "tornado" ]
What is Facebook's new Tornado framework?
1,406,912
<p>Facebook just open-sourced <a href="http://developers.facebook.com/opensource.php">a framework called Tornado</a>. </p> <p>What is it? What does it help a site do?</p> <p>I believe Facebook uses a LAMP structure. Is it useful for smaller sites which are written under the LAMP stack? </p>
15
2009-09-10T18:24:25Z
6,518,959
<p>Tornado is a simple, fast python webserver and a micro web framework. Its provides the very basic framework to write a dynamic website. Its very easy to learn and extend to meet specific need of a demanding web application since it does not come in your way. The best part of using Tornado is it does not create thread per request so scales very nicely for large number of requests. I am using it for one of my project and loving it.</p>
0
2011-06-29T10:09:56Z
[ "python", "facebook", "tornado" ]
How to generate basic CRUD functionality in python given a database tables
1,407,016
<p>I want to develop a desktop application using python with basic crud operation. Is there any library in python that can generate a code for CRUD functionality and user interface given a database table.</p>
2
2009-09-10T18:45:49Z
1,407,116
<p>If it were me, I would consider borrowing django's ORM, but then again, I'm already familiar with it.</p> <p>Having said that, I like working with it, it's usable outside the framework, and it will give you mysql, postgres, or sqlite support. You could also hook up the django admin site to your models and have a web-based editor. </p> <p>There are surely other ORMs and code generators out there too (I hope some python gurus will point some out, I'm kind of curious). </p>
0
2009-09-10T19:04:38Z
[ "python", "database", "desktop", "crud" ]
How to generate basic CRUD functionality in python given a database tables
1,407,016
<p>I want to develop a desktop application using python with basic crud operation. Is there any library in python that can generate a code for CRUD functionality and user interface given a database table.</p>
2
2009-09-10T18:45:49Z
1,407,136
<p>Hopefully, this won't be the best option you end up with, but, in the tradition of using web-interfaces for desktop applications, you could always try <a href="http://www.djangoproject.com/" rel="nofollow">django</a>. I would particularLY take a look at the <a href="http://docs.djangoproject.com/en/dev/ref/django-admin/#inspectdb" rel="nofollow"><code>inspectdb</code></a> command, which will generate the ORM code for you.</p> <p>The advantage is that it won't require that much code to get off the ground, and if you just want to use it from the desktop, you don't need a webserver; you can use the provided test server. The bundled admin site is easy to get off the ground, and flexible up to a point; past which people seem to invest a lot of time battling it (probably a testimony to how helpful it is at first).</p> <p>There are many disadvantages, not the least of which is the possibility of having to use html/javascript/css when you want to start customizing a lot.</p>
3
2009-09-10T19:07:40Z
[ "python", "database", "desktop", "crud" ]
How to generate basic CRUD functionality in python given a database tables
1,407,016
<p>I want to develop a desktop application using python with basic crud operation. Is there any library in python that can generate a code for CRUD functionality and user interface given a database table.</p>
2
2009-09-10T18:45:49Z
1,408,043
<p>If you want something really small and simple, I like the <a href="http://autumn-orm.org/" rel="nofollow">Autumn</a> ORM.</p> <p>If you use the Django ORM, you can use the automatically-generated Django admin interface, which is really nice. It's basically a web-based GUI for browsing and editing records in your database.</p> <p>If you think you will need advanced SQL features, SQLAlchemy is a good way to go. I suspect for a desktop application, Django or Autumn would be better.</p> <p>There are other Python ORMs, such as Storm. Do a Google search on "python ORM". See also the discussion on this web site: <a href="http://stackoverflow.com/questions/53428/what-are-some-good-python-orm-solutions">http://stackoverflow.com/questions/53428/what-are-some-good-python-orm-solutions</a></p>
0
2009-09-10T22:23:10Z
[ "python", "database", "desktop", "crud" ]
distutils setup.py and %post %postun
1,407,021
<p>I am newbie. I am buidling rpm package for my own app and decided to use distutils to do achieve it. I managed to create some substitue of %post by using advice from this website, which i really am thankfull for, but i am having problems with %postun. Let me describe what i have done. In setup.py i run command that creates symbolic link which is needed to run application. It works good but problem is when i want to remove rpm, link stays there. So i figured that i should use %postun in spec file. My question is: is there a way to do this in setup.py or do i have to manually edit spec file? Please advise or point me some manuals or anything. Thank you</p>
4
2009-09-10T18:47:46Z
1,472,692
<p>Neither distutils nor setuptools have uninstall functionality.</p> <p>At some point, the python community agreed that uninstall should be handled by the packaging system. In this case you want to use rpm, so there is probably a way inside of rpm system to remove packages, but you will not find that in distutils or setuptools.</p> <p>@ pycon2009, there was a presentation on distutils and setuptools. You can find all of the videos here</p> <p><a href="http://pycon.blip.tv/file/2061520/" rel="nofollow">Eggs and Buildout Deployment in Python - Part 1</a></p> <p><a href="http://pycon.blip.tv/file/2061678/" rel="nofollow">Eggs and Buildout Deployment in Python - Part 2</a> </p> <p><a href="http://pycon.blip.tv/file/2061724/" rel="nofollow">Eggs and Buildout Deployment in Python - Part 3</a></p> <p>There is a video called <a href="http://pycon.blip.tv/file/2072580/" rel="nofollow">How to Build Applications Linux Distributions will Package</a>. I have not seen it, but it seems to be appropriate.</p>
0
2009-09-24T16:09:08Z
[ "python", "distutils", "rpm", "specifications" ]
distutils setup.py and %post %postun
1,407,021
<p>I am newbie. I am buidling rpm package for my own app and decided to use distutils to do achieve it. I managed to create some substitue of %post by using advice from this website, which i really am thankfull for, but i am having problems with %postun. Let me describe what i have done. In setup.py i run command that creates symbolic link which is needed to run application. It works good but problem is when i want to remove rpm, link stays there. So i figured that i should use %postun in spec file. My question is: is there a way to do this in setup.py or do i have to manually edit spec file? Please advise or point me some manuals or anything. Thank you</p>
4
2009-09-10T18:47:46Z
1,509,052
<p>Yes, you can specify a post install script, all you need is to declare in the bdist_rpm in the options arg the file you want to use:</p> <pre><code>setup( ... options = {'bdist_rpm':{'post_install' : 'post_install', 'post_uninstall' : 'post_uninstall'}}, ...) </code></pre> <p>In the post_uninstall file, put he code you need to remove the link, somethink like:</p> <pre><code>rm -f /var/lib/mylink </code></pre>
2
2009-10-02T11:46:13Z
[ "python", "distutils", "rpm", "specifications" ]
python database / sql programming - where to start
1,407,248
<p>What is the best way to use an embedded database, say sqlite in Python:</p> <ol> <li>Should be small footprint. I'm only needing few thousands records per table. And just a handful of tables per database.</li> <li>If it's one provided by Python default installation, then great. Must be open-source, available on Windows and Linus. </li> <li>Better if SQL is not written directly, but no ORM is fully needed. Something that will shield me from the actual database, but not that huge of a library. Something similar to ADO will be great.</li> <li>Mostly will be used through code, but if there is a GUI front end, then that is great</li> <li>Need just a few pages to get started with. I don't want to go through pages reading what a table is and how a Select statement works. I know all of that.</li> <li>Support for Python 3 is preferred, but 2.x is okay too.</li> </ol> <p><em>The usage is not a web app. It's a small database to hold at most 5 tables. The data in each table is just a few string columns. Think something just larger than a pickled dictionary</em></p> <p><strong>Update</strong>: Many thanks for the great suggestions.<br /> The use-case I'm talking about is fairly simple. One you'd probably do in a day or two.<br /> It's a 100ish line Python script that gathers data about a relatively large number of files (say 10k), and creates metadata files about them, and then one large metadata file about the whole files tree. I just need to avoid re-processing the files already processed, and create the metadata for the updated files, and update the main metadata file. In a way, cache the processed data, and only update it on file updates. If the cache is corrupt / unavailable, then simply process the whole tree. It might take 20 minutes, but that's okay.</p> <p>Note that all processing is done in-memory.</p> <p>I would like to avoid any external dependencies, so that the script can easily be put on any system with just a Python installation on it. Being Windows, it is sometimes hard to get all the components installed. So, In my opinion, even a database might be an overkill. </p> <p>You probably wouldn't fire up an Office Word/Writer to write a small post it type note, similarly I am reluctant on using something like Django for this use-case.</p> <p>Where to start?</p>
7
2009-09-10T19:31:36Z
1,407,259
<p>start with Django</p> <p><a href="http://www.djangoproject.com/" rel="nofollow">http://www.djangoproject.com/</a></p> <p>ORM is the way to go here. You won't regret it. The tutorial here <a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/" rel="nofollow">http://docs.djangoproject.com/en/dev/intro/tutorial01/</a> is fairly gentle.</p> <p>Why Django/ORM ? Django will have you up an running in about half an hour, will manage your database connections, data management interfaces, etc. Django works SQLLite: you won't need to manage a MySQL/PostGre instance.</p> <p>EDIT1: You don't need to use the web-app portion of Django for this. You can use the db.Model classes to manipulate your data directly. Whatever standalone app/script you will come up with, you can just use the Django data-model layer. And when you decide you want a web front-end, or atleast would like to edit your data via the admin console - you can post back here and thank me ( or everyone that said use an ORM ) :)</p>
2
2009-09-10T19:33:28Z
[ "python", "database", "sqlite", "ado" ]
python database / sql programming - where to start
1,407,248
<p>What is the best way to use an embedded database, say sqlite in Python:</p> <ol> <li>Should be small footprint. I'm only needing few thousands records per table. And just a handful of tables per database.</li> <li>If it's one provided by Python default installation, then great. Must be open-source, available on Windows and Linus. </li> <li>Better if SQL is not written directly, but no ORM is fully needed. Something that will shield me from the actual database, but not that huge of a library. Something similar to ADO will be great.</li> <li>Mostly will be used through code, but if there is a GUI front end, then that is great</li> <li>Need just a few pages to get started with. I don't want to go through pages reading what a table is and how a Select statement works. I know all of that.</li> <li>Support for Python 3 is preferred, but 2.x is okay too.</li> </ol> <p><em>The usage is not a web app. It's a small database to hold at most 5 tables. The data in each table is just a few string columns. Think something just larger than a pickled dictionary</em></p> <p><strong>Update</strong>: Many thanks for the great suggestions.<br /> The use-case I'm talking about is fairly simple. One you'd probably do in a day or two.<br /> It's a 100ish line Python script that gathers data about a relatively large number of files (say 10k), and creates metadata files about them, and then one large metadata file about the whole files tree. I just need to avoid re-processing the files already processed, and create the metadata for the updated files, and update the main metadata file. In a way, cache the processed data, and only update it on file updates. If the cache is corrupt / unavailable, then simply process the whole tree. It might take 20 minutes, but that's okay.</p> <p>Note that all processing is done in-memory.</p> <p>I would like to avoid any external dependencies, so that the script can easily be put on any system with just a Python installation on it. Being Windows, it is sometimes hard to get all the components installed. So, In my opinion, even a database might be an overkill. </p> <p>You probably wouldn't fire up an Office Word/Writer to write a small post it type note, similarly I am reluctant on using something like Django for this use-case.</p> <p>Where to start?</p>
7
2009-09-10T19:31:36Z
1,407,302
<p>I started here:</p> <p><a href="http://www.devshed.com/c/a/Python/Using-SQLite-in-Python" rel="nofollow">http://www.devshed.com/c/a/Python/Using-SQLite-in-Python</a></p> <p>It's 5 (short) pages with just the essentials got me going right away.</p>
3
2009-09-10T19:41:45Z
[ "python", "database", "sqlite", "ado" ]
python database / sql programming - where to start
1,407,248
<p>What is the best way to use an embedded database, say sqlite in Python:</p> <ol> <li>Should be small footprint. I'm only needing few thousands records per table. And just a handful of tables per database.</li> <li>If it's one provided by Python default installation, then great. Must be open-source, available on Windows and Linus. </li> <li>Better if SQL is not written directly, but no ORM is fully needed. Something that will shield me from the actual database, but not that huge of a library. Something similar to ADO will be great.</li> <li>Mostly will be used through code, but if there is a GUI front end, then that is great</li> <li>Need just a few pages to get started with. I don't want to go through pages reading what a table is and how a Select statement works. I know all of that.</li> <li>Support for Python 3 is preferred, but 2.x is okay too.</li> </ol> <p><em>The usage is not a web app. It's a small database to hold at most 5 tables. The data in each table is just a few string columns. Think something just larger than a pickled dictionary</em></p> <p><strong>Update</strong>: Many thanks for the great suggestions.<br /> The use-case I'm talking about is fairly simple. One you'd probably do in a day or two.<br /> It's a 100ish line Python script that gathers data about a relatively large number of files (say 10k), and creates metadata files about them, and then one large metadata file about the whole files tree. I just need to avoid re-processing the files already processed, and create the metadata for the updated files, and update the main metadata file. In a way, cache the processed data, and only update it on file updates. If the cache is corrupt / unavailable, then simply process the whole tree. It might take 20 minutes, but that's okay.</p> <p>Note that all processing is done in-memory.</p> <p>I would like to avoid any external dependencies, so that the script can easily be put on any system with just a Python installation on it. Being Windows, it is sometimes hard to get all the components installed. So, In my opinion, even a database might be an overkill. </p> <p>You probably wouldn't fire up an Office Word/Writer to write a small post it type note, similarly I am reluctant on using something like Django for this use-case.</p> <p>Where to start?</p>
7
2009-09-10T19:31:36Z
1,407,345
<p>Django is perfect for this but the poster is not clear if he needs to actually make a compiled EXE or a web app. Django is only for web apps.</p> <p>I'm not sure where you really get "heavy" from. Django is grossly smaller in terms of lines of code than any other major web app framework.</p>
0
2009-09-10T19:48:41Z
[ "python", "database", "sqlite", "ado" ]
python database / sql programming - where to start
1,407,248
<p>What is the best way to use an embedded database, say sqlite in Python:</p> <ol> <li>Should be small footprint. I'm only needing few thousands records per table. And just a handful of tables per database.</li> <li>If it's one provided by Python default installation, then great. Must be open-source, available on Windows and Linus. </li> <li>Better if SQL is not written directly, but no ORM is fully needed. Something that will shield me from the actual database, but not that huge of a library. Something similar to ADO will be great.</li> <li>Mostly will be used through code, but if there is a GUI front end, then that is great</li> <li>Need just a few pages to get started with. I don't want to go through pages reading what a table is and how a Select statement works. I know all of that.</li> <li>Support for Python 3 is preferred, but 2.x is okay too.</li> </ol> <p><em>The usage is not a web app. It's a small database to hold at most 5 tables. The data in each table is just a few string columns. Think something just larger than a pickled dictionary</em></p> <p><strong>Update</strong>: Many thanks for the great suggestions.<br /> The use-case I'm talking about is fairly simple. One you'd probably do in a day or two.<br /> It's a 100ish line Python script that gathers data about a relatively large number of files (say 10k), and creates metadata files about them, and then one large metadata file about the whole files tree. I just need to avoid re-processing the files already processed, and create the metadata for the updated files, and update the main metadata file. In a way, cache the processed data, and only update it on file updates. If the cache is corrupt / unavailable, then simply process the whole tree. It might take 20 minutes, but that's okay.</p> <p>Note that all processing is done in-memory.</p> <p>I would like to avoid any external dependencies, so that the script can easily be put on any system with just a Python installation on it. Being Windows, it is sometimes hard to get all the components installed. So, In my opinion, even a database might be an overkill. </p> <p>You probably wouldn't fire up an Office Word/Writer to write a small post it type note, similarly I am reluctant on using something like Django for this use-case.</p> <p>Where to start?</p>
7
2009-09-10T19:31:36Z
1,407,569
<p>I highly recommend the use of a good ORM. When you can work with Python objects to manage your database rows, life is so much easier.</p> <p>I am a fan of the ORM in Django. But that was already recommended and you said that is too heavyweight.</p> <p>This leaves me with exactly one ORM to recommend: <a href="http://autumn-orm.org/">Autumn</a>. Very lightweight, works great with SQLite. If your embedded application will be multithreaded, then you absolutely want Autumn; it has extensions to support multithreaded SQLite. (Full disclosure: I wrote those extensions and contributed them. I wrote them while working for RealNetworks, and my bosses permitted me to donate them, so a public thank-you to RealNetworks.)</p> <p>Autumn is written in pure Python. For SQLite, it uses the Python official SQLite module to do the actual SQL stuff. The memory footprint of Autumn itself is tiny.</p> <p>I do not recommend APSW. In my humble opinion, it doesn't really do very much to help you; it just provides a way to execute SQL statements, and leaves you to master the SQL way of doing things. Also, it supports every single feature of SQLite, even the ones you rarely use, and as a result it actually has a larger memory footprint than Autumn, while not being as easy to use.</p>
6
2009-09-10T20:34:07Z
[ "python", "database", "sqlite", "ado" ]
python database / sql programming - where to start
1,407,248
<p>What is the best way to use an embedded database, say sqlite in Python:</p> <ol> <li>Should be small footprint. I'm only needing few thousands records per table. And just a handful of tables per database.</li> <li>If it's one provided by Python default installation, then great. Must be open-source, available on Windows and Linus. </li> <li>Better if SQL is not written directly, but no ORM is fully needed. Something that will shield me from the actual database, but not that huge of a library. Something similar to ADO will be great.</li> <li>Mostly will be used through code, but if there is a GUI front end, then that is great</li> <li>Need just a few pages to get started with. I don't want to go through pages reading what a table is and how a Select statement works. I know all of that.</li> <li>Support for Python 3 is preferred, but 2.x is okay too.</li> </ol> <p><em>The usage is not a web app. It's a small database to hold at most 5 tables. The data in each table is just a few string columns. Think something just larger than a pickled dictionary</em></p> <p><strong>Update</strong>: Many thanks for the great suggestions.<br /> The use-case I'm talking about is fairly simple. One you'd probably do in a day or two.<br /> It's a 100ish line Python script that gathers data about a relatively large number of files (say 10k), and creates metadata files about them, and then one large metadata file about the whole files tree. I just need to avoid re-processing the files already processed, and create the metadata for the updated files, and update the main metadata file. In a way, cache the processed data, and only update it on file updates. If the cache is corrupt / unavailable, then simply process the whole tree. It might take 20 minutes, but that's okay.</p> <p>Note that all processing is done in-memory.</p> <p>I would like to avoid any external dependencies, so that the script can easily be put on any system with just a Python installation on it. Being Windows, it is sometimes hard to get all the components installed. So, In my opinion, even a database might be an overkill. </p> <p>You probably wouldn't fire up an Office Word/Writer to write a small post it type note, similarly I am reluctant on using something like Django for this use-case.</p> <p>Where to start?</p>
7
2009-09-10T19:31:36Z
1,407,607
<p>What you're looking for is <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>, which is fast becoming the de facto standard Python data access layer. To make your first experiences with SQLAlchemy even easier, check out <a href="http://elixir.ematia.de/trac/wiki" rel="nofollow">Elixir</a>, which is a thin ActiveRecord-style wrapper around SQLAlchemy.</p> <p><strong>Update</strong>: Reread the question and saw the bit about not needing a full ORM. I'd still suggest going the SQLAlchemy route, just because it gives you a ridiculously easy way to work with databases in Python that you can reuse for any kind of database. Time spent working directly with SQLite is wasted once you need to connect to Oracle or something.</p>
3
2009-09-10T20:42:08Z
[ "python", "database", "sqlite", "ado" ]
python database / sql programming - where to start
1,407,248
<p>What is the best way to use an embedded database, say sqlite in Python:</p> <ol> <li>Should be small footprint. I'm only needing few thousands records per table. And just a handful of tables per database.</li> <li>If it's one provided by Python default installation, then great. Must be open-source, available on Windows and Linus. </li> <li>Better if SQL is not written directly, but no ORM is fully needed. Something that will shield me from the actual database, but not that huge of a library. Something similar to ADO will be great.</li> <li>Mostly will be used through code, but if there is a GUI front end, then that is great</li> <li>Need just a few pages to get started with. I don't want to go through pages reading what a table is and how a Select statement works. I know all of that.</li> <li>Support for Python 3 is preferred, but 2.x is okay too.</li> </ol> <p><em>The usage is not a web app. It's a small database to hold at most 5 tables. The data in each table is just a few string columns. Think something just larger than a pickled dictionary</em></p> <p><strong>Update</strong>: Many thanks for the great suggestions.<br /> The use-case I'm talking about is fairly simple. One you'd probably do in a day or two.<br /> It's a 100ish line Python script that gathers data about a relatively large number of files (say 10k), and creates metadata files about them, and then one large metadata file about the whole files tree. I just need to avoid re-processing the files already processed, and create the metadata for the updated files, and update the main metadata file. In a way, cache the processed data, and only update it on file updates. If the cache is corrupt / unavailable, then simply process the whole tree. It might take 20 minutes, but that's okay.</p> <p>Note that all processing is done in-memory.</p> <p>I would like to avoid any external dependencies, so that the script can easily be put on any system with just a Python installation on it. Being Windows, it is sometimes hard to get all the components installed. So, In my opinion, even a database might be an overkill. </p> <p>You probably wouldn't fire up an Office Word/Writer to write a small post it type note, similarly I am reluctant on using something like Django for this use-case.</p> <p>Where to start?</p>
7
2009-09-10T19:31:36Z
1,408,573
<p>Another option to add to the other good suggestions: <a href="http://elixir.ematia.de/trac/wiki" rel="nofollow">Elixir</a>. It provides a simplified declarative layer on top of <code>SQLAlchemy</code>, so it should be easier to dive into, but it also allows you to call upon the full power of <code>SQLAlchemy</code> if and when you need it.</p>
0
2009-09-11T01:28:44Z
[ "python", "database", "sqlite", "ado" ]
python database / sql programming - where to start
1,407,248
<p>What is the best way to use an embedded database, say sqlite in Python:</p> <ol> <li>Should be small footprint. I'm only needing few thousands records per table. And just a handful of tables per database.</li> <li>If it's one provided by Python default installation, then great. Must be open-source, available on Windows and Linus. </li> <li>Better if SQL is not written directly, but no ORM is fully needed. Something that will shield me from the actual database, but not that huge of a library. Something similar to ADO will be great.</li> <li>Mostly will be used through code, but if there is a GUI front end, then that is great</li> <li>Need just a few pages to get started with. I don't want to go through pages reading what a table is and how a Select statement works. I know all of that.</li> <li>Support for Python 3 is preferred, but 2.x is okay too.</li> </ol> <p><em>The usage is not a web app. It's a small database to hold at most 5 tables. The data in each table is just a few string columns. Think something just larger than a pickled dictionary</em></p> <p><strong>Update</strong>: Many thanks for the great suggestions.<br /> The use-case I'm talking about is fairly simple. One you'd probably do in a day or two.<br /> It's a 100ish line Python script that gathers data about a relatively large number of files (say 10k), and creates metadata files about them, and then one large metadata file about the whole files tree. I just need to avoid re-processing the files already processed, and create the metadata for the updated files, and update the main metadata file. In a way, cache the processed data, and only update it on file updates. If the cache is corrupt / unavailable, then simply process the whole tree. It might take 20 minutes, but that's okay.</p> <p>Note that all processing is done in-memory.</p> <p>I would like to avoid any external dependencies, so that the script can easily be put on any system with just a Python installation on it. Being Windows, it is sometimes hard to get all the components installed. So, In my opinion, even a database might be an overkill. </p> <p>You probably wouldn't fire up an Office Word/Writer to write a small post it type note, similarly I am reluctant on using something like Django for this use-case.</p> <p>Where to start?</p>
7
2009-09-10T19:31:36Z
1,409,333
<p>This is an aggregate of answers, in no particular order:</p> <p>Everybody is recommending an ORM layer. Which makes perfect sense, if you really need a database. Well, that was sort of requested in the title :-)</p> <ol> <li><a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a></li> <li><a href="http://autumn-orm.org/" rel="nofollow">Autumn</a></li> <li><a href="http://www.djangoproject.com/" rel="nofollow">Django ORM</a></li> <li>Use SQLite official support <a href="http://pysqlite.org/" rel="nofollow">Pysqlite</a></li> <li><a href="https://storm.canonical.com/" rel="nofollow">Storm</a></li> <li><a href="http://elixir.ematia.de/trac/wiki" rel="nofollow">Elixir</a></li> <li>Just use Python's own Pickle</li> </ol> <p>But I'm starting to think that if an in-memory database is sufficient, in this will be used in scripts only, not a web app or even a desktop gui, then option 7 is also perfectly valid, provided no transaction support is needed and "database" integrity is not an issue.</p>
1
2009-09-11T06:41:53Z
[ "python", "database", "sqlite", "ado" ]
python database / sql programming - where to start
1,407,248
<p>What is the best way to use an embedded database, say sqlite in Python:</p> <ol> <li>Should be small footprint. I'm only needing few thousands records per table. And just a handful of tables per database.</li> <li>If it's one provided by Python default installation, then great. Must be open-source, available on Windows and Linus. </li> <li>Better if SQL is not written directly, but no ORM is fully needed. Something that will shield me from the actual database, but not that huge of a library. Something similar to ADO will be great.</li> <li>Mostly will be used through code, but if there is a GUI front end, then that is great</li> <li>Need just a few pages to get started with. I don't want to go through pages reading what a table is and how a Select statement works. I know all of that.</li> <li>Support for Python 3 is preferred, but 2.x is okay too.</li> </ol> <p><em>The usage is not a web app. It's a small database to hold at most 5 tables. The data in each table is just a few string columns. Think something just larger than a pickled dictionary</em></p> <p><strong>Update</strong>: Many thanks for the great suggestions.<br /> The use-case I'm talking about is fairly simple. One you'd probably do in a day or two.<br /> It's a 100ish line Python script that gathers data about a relatively large number of files (say 10k), and creates metadata files about them, and then one large metadata file about the whole files tree. I just need to avoid re-processing the files already processed, and create the metadata for the updated files, and update the main metadata file. In a way, cache the processed data, and only update it on file updates. If the cache is corrupt / unavailable, then simply process the whole tree. It might take 20 minutes, but that's okay.</p> <p>Note that all processing is done in-memory.</p> <p>I would like to avoid any external dependencies, so that the script can easily be put on any system with just a Python installation on it. Being Windows, it is sometimes hard to get all the components installed. So, In my opinion, even a database might be an overkill. </p> <p>You probably wouldn't fire up an Office Word/Writer to write a small post it type note, similarly I am reluctant on using something like Django for this use-case.</p> <p>Where to start?</p>
7
2009-09-10T19:31:36Z
1,802,137
<p>There's an easy-to-use Python module that meets all the stated objectives: </p> <p><a href="http://yserial.sourceforge.net/" rel="nofollow">http://yserial.sourceforge.net/</a></p> <p>Serialization + persistance: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful "standard" module for a database to store schema-less data.</p> <p>Surprisingly, there is not much difference between in-memory and persistent solutions for most practical purposes.</p> <p>As for "shield me from the actual database", with y_serial, one cannot even tell that SQLite is behind it all. If you construct your records as Python dictionaries, you can concentrate on just writing code (not stored procedures).</p>
0
2009-11-26T07:47:27Z
[ "python", "database", "sqlite", "ado" ]
python database / sql programming - where to start
1,407,248
<p>What is the best way to use an embedded database, say sqlite in Python:</p> <ol> <li>Should be small footprint. I'm only needing few thousands records per table. And just a handful of tables per database.</li> <li>If it's one provided by Python default installation, then great. Must be open-source, available on Windows and Linus. </li> <li>Better if SQL is not written directly, but no ORM is fully needed. Something that will shield me from the actual database, but not that huge of a library. Something similar to ADO will be great.</li> <li>Mostly will be used through code, but if there is a GUI front end, then that is great</li> <li>Need just a few pages to get started with. I don't want to go through pages reading what a table is and how a Select statement works. I know all of that.</li> <li>Support for Python 3 is preferred, but 2.x is okay too.</li> </ol> <p><em>The usage is not a web app. It's a small database to hold at most 5 tables. The data in each table is just a few string columns. Think something just larger than a pickled dictionary</em></p> <p><strong>Update</strong>: Many thanks for the great suggestions.<br /> The use-case I'm talking about is fairly simple. One you'd probably do in a day or two.<br /> It's a 100ish line Python script that gathers data about a relatively large number of files (say 10k), and creates metadata files about them, and then one large metadata file about the whole files tree. I just need to avoid re-processing the files already processed, and create the metadata for the updated files, and update the main metadata file. In a way, cache the processed data, and only update it on file updates. If the cache is corrupt / unavailable, then simply process the whole tree. It might take 20 minutes, but that's okay.</p> <p>Note that all processing is done in-memory.</p> <p>I would like to avoid any external dependencies, so that the script can easily be put on any system with just a Python installation on it. Being Windows, it is sometimes hard to get all the components installed. So, In my opinion, even a database might be an overkill. </p> <p>You probably wouldn't fire up an Office Word/Writer to write a small post it type note, similarly I am reluctant on using something like Django for this use-case.</p> <p>Where to start?</p>
7
2009-09-10T19:31:36Z
19,759,324
<p>If you don't want to use an ORM, you can give a try to <a href="https://pypi.python.org/pypi/python-sql" rel="nofollow">python-sql</a> to create your SQL queries.</p>
0
2013-11-03T23:06:37Z
[ "python", "database", "sqlite", "ado" ]
Why does the Python gettext module require a compilation step (.po -> .mo)?
1,407,364
<p>I don't see that the compilation step is adding any value.</p>
0
2009-09-10T19:52:00Z
1,407,416
<p>I think that the compilation is .po -> .mo</p> <blockquote> <p>The letters PO in .po files means Portable Object, to distinguish it from .mo files, where MO stands for Machine Object.</p> <p>MO files are meant to be read by programs, and are binary in nature. A few systems already offer tools for creating and handling MO files as part of the Native Language Support coming with the system, but the format of these MO files is often different from system to system, and non-portable.</p> </blockquote> <p><a href="http://www.gnu.org/software/gettext/manual/gettext.html#Files" rel="nofollow">GNU `gettext' utilities - 1.4 Files Conveying Translations</a></p>
0
2009-09-10T20:02:00Z
[ "python", "gettext" ]
Why does the Python gettext module require a compilation step (.po -> .mo)?
1,407,364
<p>I don't see that the compilation step is adding any value.</p>
0
2009-09-10T19:52:00Z
1,408,109
<p>Reading just quickly about <code>.mo</code> files, it is clear that:</p> <ul> <li>It is a machine-readable representation</li> <li>It is a hash table</li> </ul> <p>Given gettext's function, to lookup strings by keys <em>at runtime</em>, it is reasonable for this lookup to be implemented efficiently.</p> <p>Also, it is needed for gettext's performance impact to be negligible; else interest to play nice with the international community would be even lower for english-speaking hackers (from all countries, we all speak english, programming languages are in english).</p> <p>Making the .mo file an already processed representation is good since</p> <ul> <li>The format is well suited for quick lookup (hash table)</li> <li>The format needs little processing at application launch (custom-representation binary)</li> </ul>
5
2009-09-10T22:43:41Z
[ "python", "gettext" ]
Why does the Python gettext module require a compilation step (.po -> .mo)?
1,407,364
<p>I don't see that the compilation step is adding any value.</p>
0
2009-09-10T19:52:00Z
2,021,653
<p>Because gettext module in Python follows GNU gettext standards which required to use PO files for do translations by people, and MO files for using by application in runtime. When you're using gettext module you're actually using GNUTranslations class, which name suggests it's implementation of GNU gettext.</p> <p>But you can provide your own Translations class and load translations from PO files, there is nothing special about it. There is even some implementation of PO files reader in standard Python distribution, see script msgfmt.py in Tools directory.</p>
1
2010-01-07T16:02:54Z
[ "python", "gettext" ]
How do I regex match with grouping with unknown number of groups
1,407,435
<p>I want to do a regex match (in Python) on the output log of a program. The log contains some lines that look like this:</p> <pre><code>... VALUE 100 234 568 9233 119 ... VALUE 101 124 9223 4329 1559 ... </code></pre> <p>I would like to capture the list of numbers that occurs after the first incidence of the line that starts with VALUE. i.e., I want it to return <code>('100','234','568','9233','119')</code>. The problem is that I do not know in advance how many numbers there will be.</p> <p>I tried to use this as a regex: </p> <pre><code>VALUE (?:(\d+)\s)+ </code></pre> <p>This matches the line, but it only captures the last value, so I just get ('119',).</p>
13
2009-09-10T20:06:45Z
1,407,457
<p>What you're looking for is a <em>parser</em>, instead of a regular expression match. In your case, I would consider using a very simple parser, <a href="http://docs.python.org/library/stdtypes.html#str.split"><code>split()</code></a>:</p> <pre><code>s = "VALUE 100 234 568 9233 119" a = s.split() if a[0] == "VALUE": print [int(x) for x in a[1:]] </code></pre> <p>You can use a regular expression to see whether your input line matches your expected format (using the regex in your question), then you can run the above code without having to check for <code>"VALUE"</code> and knowing that the <code>int(x)</code> conversion will always succeed since you've already confirmed that the following character groups are all digits.</p>
12
2009-09-10T20:12:21Z
[ "python", "regex" ]
How do I regex match with grouping with unknown number of groups
1,407,435
<p>I want to do a regex match (in Python) on the output log of a program. The log contains some lines that look like this:</p> <pre><code>... VALUE 100 234 568 9233 119 ... VALUE 101 124 9223 4329 1559 ... </code></pre> <p>I would like to capture the list of numbers that occurs after the first incidence of the line that starts with VALUE. i.e., I want it to return <code>('100','234','568','9233','119')</code>. The problem is that I do not know in advance how many numbers there will be.</p> <p>I tried to use this as a regex: </p> <pre><code>VALUE (?:(\d+)\s)+ </code></pre> <p>This matches the line, but it only captures the last value, so I just get ('119',).</p>
13
2009-09-10T20:06:45Z
1,407,470
<p>You could just run you're main match regex then run a secondary regex on those matches to get the numbers:</p> <pre><code>matches = Regex.Match(log) foreach (Match match in matches) { submatches = Regex2.Match(match) } </code></pre> <p>This is of course also if you don't want to write a full parser.</p>
0
2009-09-10T20:14:27Z
[ "python", "regex" ]
How do I regex match with grouping with unknown number of groups
1,407,435
<p>I want to do a regex match (in Python) on the output log of a program. The log contains some lines that look like this:</p> <pre><code>... VALUE 100 234 568 9233 119 ... VALUE 101 124 9223 4329 1559 ... </code></pre> <p>I would like to capture the list of numbers that occurs after the first incidence of the line that starts with VALUE. i.e., I want it to return <code>('100','234','568','9233','119')</code>. The problem is that I do not know in advance how many numbers there will be.</p> <p>I tried to use this as a regex: </p> <pre><code>VALUE (?:(\d+)\s)+ </code></pre> <p>This matches the line, but it only captures the last value, so I just get ('119',).</p>
13
2009-09-10T20:06:45Z
1,407,491
<pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; reg = re.compile('\d+') &gt;&gt;&gt; reg.findall('VALUE 100 234 568 9233 119') ['100', '234', '568', '9223', '119'] </code></pre> <p>That doesn't validate that the keyword 'VALUE' appears at the beginning of the string, and it doesn't validate that there is exactly one space between items, but if you can do that as a separate step (or if you don't need to do that at all), then it will find all digit sequences in any string.</p>
6
2009-09-10T20:17:51Z
[ "python", "regex" ]
Does python logging.handlers.RotatingFileHandler allow creation of a group writable log file?
1,407,474
<p>I'm using the standard python (2.5.2) logging module, specifically the RotatingFileHandler, on a linux system. My application supports both a command-line interface and a web-service interface. I would like to have both write to the same log file. However, when the log file gets rotated, the new file has 644 permissions and is owned by the web server user which prevents the command-line user from writing to it. Can I specify that new log files should be group-writable in the logging configuration or during logging initialization?</p> <p>I have looked into the 'mode' setting (r/w/a), but it doesn't seem to support any file permissions.</p>
23
2009-09-10T20:14:44Z
1,407,835
<p>I resorted to scanning the logging.handlers module and was unable to see any way to specify a different file permissions mode. So, I have a solution now based on extending the RotatingFileHandler as a custom handler. It was fairly painless, once I found some nice references to creating one. The code for the custom handler is below.</p> <pre><code>class GroupWriteRotatingFileHandler(handlers.RotatingFileHandler): def doRollover(self): """ Override base class method to make the new log file group writable. """ # Rotate the file first. handlers.RotatingFileHandler.doRollover(self) # Add group write to the current permissions. currMode = os.stat(self.baseFilename).st_mode os.chmod(self.baseFilename, currMode | stat.S_IWGRP) </code></pre> <p>I also discovered that to reference the custom handler from a logging config file, I had to bind my module to the logging namespace. Simple to do, but annoying.</p> <pre><code>from mynamespace.logging import custom_handlers logging.custom_handlers = custom_handlers </code></pre> <p>References I found useful: <a href="http://mail.python.org/pipermail/python-list/2007-October/634318.html">binding custom handlers</a> and <a href="http://stackoverflow.com/questions/935930/creating-a-logging-handler-to-connect-to-oracle/1014450#1014450">creating custom handlers</a></p>
14
2009-09-10T21:29:32Z
[ "python", "logging" ]
Does python logging.handlers.RotatingFileHandler allow creation of a group writable log file?
1,407,474
<p>I'm using the standard python (2.5.2) logging module, specifically the RotatingFileHandler, on a linux system. My application supports both a command-line interface and a web-service interface. I would like to have both write to the same log file. However, when the log file gets rotated, the new file has 644 permissions and is owned by the web server user which prevents the command-line user from writing to it. Can I specify that new log files should be group-writable in the logging configuration or during logging initialization?</p> <p>I have looked into the 'mode' setting (r/w/a), but it doesn't seem to support any file permissions.</p>
23
2009-09-10T20:14:44Z
6,779,307
<p>Here is a slightly better solution. this overrides the _open method that is used. setting the umask before creating then returning it back to what it was.</p> <pre><code>class GroupWriteRotatingFileHandler(logging.handlers.RotatingFileHandler): def _open(self): prevumask=os.umask(0o002) #os.fdopen(os.open('/path/to/file', os.O_WRONLY, 0600)) rtv=logging.handlers.RotatingFileHandler._open(self) os.umask(prevumask) return rtv </code></pre>
20
2011-07-21T16:16:39Z
[ "python", "logging" ]
Does python logging.handlers.RotatingFileHandler allow creation of a group writable log file?
1,407,474
<p>I'm using the standard python (2.5.2) logging module, specifically the RotatingFileHandler, on a linux system. My application supports both a command-line interface and a web-service interface. I would like to have both write to the same log file. However, when the log file gets rotated, the new file has 644 permissions and is owned by the web server user which prevents the command-line user from writing to it. Can I specify that new log files should be group-writable in the logging configuration or during logging initialization?</p> <p>I have looked into the 'mode' setting (r/w/a), but it doesn't seem to support any file permissions.</p>
23
2009-09-10T20:14:44Z
11,852,400
<p>James Gardner has written a handler that only rotates files, not creating or deleting them: <a href="http://packages.python.org/logrotate/index.html" rel="nofollow">http://packages.python.org/logrotate/index.html</a></p>
1
2012-08-07T19:01:29Z
[ "python", "logging" ]
Does python logging.handlers.RotatingFileHandler allow creation of a group writable log file?
1,407,474
<p>I'm using the standard python (2.5.2) logging module, specifically the RotatingFileHandler, on a linux system. My application supports both a command-line interface and a web-service interface. I would like to have both write to the same log file. However, when the log file gets rotated, the new file has 644 permissions and is owned by the web server user which prevents the command-line user from writing to it. Can I specify that new log files should be group-writable in the logging configuration or during logging initialization?</p> <p>I have looked into the 'mode' setting (r/w/a), but it doesn't seem to support any file permissions.</p>
23
2009-09-10T20:14:44Z
37,519,766
<pre><code>$ chgrp loggroup logdir $ chmod g+w logdir $ chmod g+s logdir $ usermod -a -G loggroup myuser $ umask 0002 </code></pre>
0
2016-05-30T07:19:02Z
[ "python", "logging" ]
Python: How do I convert a NonType variable to a String?
1,407,557
<p>I have the following function: </p> <pre><code>&gt;&gt;&gt; def rule(x): ... rule = bin(x)[2:].zfill(8) ... rule = str(rule) ... print rule </code></pre> <p>I am trying to convert rule into a string, but when I run the following command, here is what I get: </p> <pre><code>&gt;&gt;&gt; type(rule(20)) 00010100 &lt;type 'NoneType'&gt; </code></pre> <p>What is a NoneType variable and how can I convert this variable into a string? </p> <p>Thanks, </p>
1
2009-09-10T20:32:16Z
1,407,572
<p>you need to do:</p> <pre><code>def rule(x): return bin(x)[2:].zfill(8) </code></pre> <p>All functions return <code>None</code> implicitly if no <code>return</code> statement was encountered during execution of the function (as it is in your case).</p>
5
2009-09-10T20:34:50Z
[ "python" ]
Python: How do I convert a NonType variable to a String?
1,407,557
<p>I have the following function: </p> <pre><code>&gt;&gt;&gt; def rule(x): ... rule = bin(x)[2:].zfill(8) ... rule = str(rule) ... print rule </code></pre> <p>I am trying to convert rule into a string, but when I run the following command, here is what I get: </p> <pre><code>&gt;&gt;&gt; type(rule(20)) 00010100 &lt;type 'NoneType'&gt; </code></pre> <p>What is a NoneType variable and how can I convert this variable into a string? </p> <p>Thanks, </p>
1
2009-09-10T20:32:16Z
1,407,583
<p>Your rule function doesn't return anything -- it only prints. So, rule(20) returns None -- the python object representing 'no value'. You can't turn that into a string, at least not in the way you are expecting.</p> <p>You need to define rule to return something, like this:</p> <pre><code>&gt;&gt;&gt; def rule(x): ... rule=bin(x)[2:].zfill(8) ... rule=str(rule) ... return rule </code></pre> <p>Then it will return a string object.</p>
1
2009-09-10T20:36:27Z
[ "python" ]
Is there a Rake equivalent in Python?
1,407,837
<p>Rake is a software build tool written in Ruby (like ant or make), and so all its files are written in this language. Does something like this exist in Python?</p>
69
2009-09-10T21:29:57Z
1,407,850
<p><a href="http://paver.github.com/paver/">Paver</a> has a similar set of goals, though I don't really know how it compares.</p>
25
2009-09-10T21:32:26Z
[ "python", "build-automation" ]
Is there a Rake equivalent in Python?
1,407,837
<p>Rake is a software build tool written in Ruby (like ant or make), and so all its files are written in this language. Does something like this exist in Python?</p>
69
2009-09-10T21:29:57Z
1,407,853
<p>I would check out <a href="http://docs.python.org/library/distutils.html" rel="nofollow"><code>distutils</code></a>:</p> <blockquote> <p>The <code>distutils</code> package provides support for building and installing additional modules into a Python installation. The new modules may be either 100%-pure Python, or may be extension modules written in C, or may be collections of Python packages which include modules coded in both Python and C.</p> </blockquote>
0
2009-09-10T21:32:30Z
[ "python", "build-automation" ]
Is there a Rake equivalent in Python?
1,407,837
<p>Rake is a software build tool written in Ruby (like ant or make), and so all its files are written in this language. Does something like this exist in Python?</p>
69
2009-09-10T21:29:57Z
1,407,897
<p><a href="http://code.google.com/p/waf/">Waf</a> is a Python-based framework for configuring, compiling and installing applications. It derives from the concepts of other build tools such as Scons, Autotools, CMake or Ant.</p>
5
2009-09-10T21:42:14Z
[ "python", "build-automation" ]
Is there a Rake equivalent in Python?
1,407,837
<p>Rake is a software build tool written in Ruby (like ant or make), and so all its files are written in this language. Does something like this exist in Python?</p>
69
2009-09-10T21:29:57Z
1,407,964
<p>Also check out buildout, which isn't so much a make system for software, as a make system for a deployment. </p> <p><a href="http://pypi.python.org/pypi/pysqlite/2.5.5" rel="nofollow">http://pypi.python.org/pypi/pysqlite/2.5.5</a></p> <p>So it's not a direct rake equivalent, but may be a better match for what you want to do, or a really lousy one.</p>
0
2009-09-10T22:00:39Z
[ "python", "build-automation" ]
Is there a Rake equivalent in Python?
1,407,837
<p>Rake is a software build tool written in Ruby (like ant or make), and so all its files are written in this language. Does something like this exist in Python?</p>
69
2009-09-10T21:29:57Z
7,619,913
<p>There is <a href="https://github.com/JeremySkinner/Phantom" rel="nofollow">Phantom</a> in Boo (which isn't python but nearly).</p>
0
2011-10-01T11:22:38Z
[ "python", "build-automation" ]
Is there a Rake equivalent in Python?
1,407,837
<p>Rake is a software build tool written in Ruby (like ant or make), and so all its files are written in this language. Does something like this exist in Python?</p>
69
2009-09-10T21:29:57Z
8,704,821
<p>Although it is more commonly used for deployment, <a href="http://readthedocs.org/docs/fabric/en/latest/">Fabric</a> might be interesting for this use case.</p>
4
2012-01-02T20:00:58Z
[ "python", "build-automation" ]
Is there a Rake equivalent in Python?
1,407,837
<p>Rake is a software build tool written in Ruby (like ant or make), and so all its files are written in this language. Does something like this exist in Python?</p>
69
2009-09-10T21:29:57Z
12,166,213
<p>Shovel seems promising:</p> <p><a href="http://devblog.seomoz.org/2012/03/shovel-rake-for-python/">Shovel — Rake for Python</a></p> <p><a href="https://github.com/seomoz/shovel">https://github.com/seomoz/shovel</a></p>
13
2012-08-28T19:30:04Z
[ "python", "build-automation" ]
Is there a Rake equivalent in Python?
1,407,837
<p>Rake is a software build tool written in Ruby (like ant or make), and so all its files are written in this language. Does something like this exist in Python?</p>
69
2009-09-10T21:29:57Z
17,372,701
<p><a href="http://docs.pyinvoke.org/en/latest/">Invoke</a> — <a href="http://docs.fabfile.org/en/latest">Fabric</a> without the SSH dependencies.</p> <p>The <a href="http://docs.fabfile.org/en/1.6/roadmap.html">Fabric roadmap</a> discusses that <a href="http://docs.fabfile.org/en/latest">Fabric</a> 1.x will be split into three portions:</p> <ol> <li><a href="http://docs.pyinvoke.org/en/latest/">Invoke</a> — The non-SSH task execution.</li> <li><a href="http://docs.fabfile.org/en/latest">Fabric</a> 2.x — The remote execution and deployment library that utilizes <a href="http://docs.pyinvoke.org/en/latest/">Invoke</a>.</li> <li><a href="https://github.com/fabric/patchwork">Patchwork</a> — The "common deployment/sysadmin operations, built on Fabric."</li> </ol> <p>Invoke is a Python (2.6+ and 3.3+) task execution tool &amp; library, drawing inspiration from various sources to arrive at a powerful &amp; clean feature set.</p> <p>Below are a few descriptive statements from <a href="http://docs.pyinvoke.org/en/latest/">Invoke</a>'s website:</p> <blockquote> <ul> <li>Invoke is a Python (2.6+ and 3.3+) task execution tool &amp; library, drawing inspiration from various sources to arrive at a powerful &amp; clean feature set.</li> <li>Like Ruby’s Rake tool and Invoke’s own predecessor Fabric 1.x, it provides a clean, high level API for running shell commands and defining/organizing task functions from a tasks.py file.</li> </ul> </blockquote>
30
2013-06-28T19:57:57Z
[ "python", "build-automation" ]
Is there a Rake equivalent in Python?
1,407,837
<p>Rake is a software build tool written in Ruby (like ant or make), and so all its files are written in this language. Does something like this exist in Python?</p>
69
2009-09-10T21:29:57Z
37,995,638
<p>There is also <a href="http://pydoit.org/" rel="nofollow">doit</a> - I came across it while looking for these things a while ago, though I didn't get very far with evaluating it.</p>
0
2016-06-23T15:16:33Z
[ "python", "build-automation" ]
Python urllib, minidom and parsing international characters
1,407,874
<p>When I try to retrieve information from Google weather API with the following URL,</p> <p><a href="http://www.google.com/ig/api?weather=Munich,Germany&amp;hl=de" rel="nofollow">http://www.google.com/ig/api?weather=Munich,Germany&amp;hl=de</a></p> <p>and then try to parse it with minidom, I get error that the document is not well formed.</p> <p>I use following code </p> <pre><code>sock = urllib.urlopen(url) # above mentioned url doc = minidom.parse(sock) </code></pre> <p>I think the German characters in the response is the cause of the error. </p> <p>What is the correct way of doing this ?</p>
0
2009-09-10T21:35:31Z
1,408,002
<p>This seems to work:</p> <pre><code>sock = urllib.urlopen(url) # There is a nicer way for this, but I don't remember right now: encoding = sock.headers['Content-type'].split('charset=')[1] data = sock.read() dom = minidom.parseString(data.decode(encoding).encode('ascii', 'xmlcharrefreplace')) </code></pre> <p>I guess minidom doesn't handle anything non-ascii. You might want to look into lxml instead, it does.</p>
2
2009-09-10T22:10:03Z
[ "python", "internationalization", "urllib", "minidom" ]
Python urllib, minidom and parsing international characters
1,407,874
<p>When I try to retrieve information from Google weather API with the following URL,</p> <p><a href="http://www.google.com/ig/api?weather=Munich,Germany&amp;hl=de" rel="nofollow">http://www.google.com/ig/api?weather=Munich,Germany&amp;hl=de</a></p> <p>and then try to parse it with minidom, I get error that the document is not well formed.</p> <p>I use following code </p> <pre><code>sock = urllib.urlopen(url) # above mentioned url doc = minidom.parse(sock) </code></pre> <p>I think the German characters in the response is the cause of the error. </p> <p>What is the correct way of doing this ?</p>
0
2009-09-10T21:35:31Z
1,408,052
<p>The encoding sent in the headers is iso-8859-1 according to python's urllib.urlopen (although firefox's live http headers seems to disagree with me in this case - reports utf-8). In the xml itself there is no encoding specified --> that's why xml.dom.minidom assumes it's utf-8. </p> <p>So the following should fix this specific issue:</p> <pre><code>import urllib from xml.dom import minidom sock = urllib.urlopen('http://www.google.com/ig/api?weather=Munich,Germany&amp;hl=de') s = sock.read() encoding = sock.headers['Content-type'].split('charset=')[1] # iso-8859-1 doc = minidom.parseString(s.decode(encoding).encode('utf-8')) </code></pre> <p><strong>Edit</strong>: I've updated this answer after the comment of Glenn Maynard. I took the liberty of taking one line out of the answer of Lennert Regebro.</p>
1
2009-09-10T22:25:45Z
[ "python", "internationalization", "urllib", "minidom" ]
Create an executable process without using shell on Python 2.5 and below
1,407,992
<p>Just what the title says:</p> <ol> <li>The <code>subprocess</code> module cannot be used as this should work on 2.4 and 2.5</li> <li>Shell process should not be spawned to pass arguments.</li> </ol> <p>To explain (2), consider the following code:</p> <pre><code>&gt;&gt;&gt; x=os.system('foo arg') sh: foo: not found &gt;&gt;&gt; x=os.popen('foo arg') sh: foo: not found &gt;&gt;&gt; </code></pre> <p>As you can see <code>os.system</code> and <code>os.popen</code> runs the given command ("foo") via a system shell ("sh"). I don't want this to happen (otherwise, ugly 'not found' messages are printed to program stderr without my control).</p> <p>Finally, I should be able to pass arguments to this program ('arg' in the above example). </p> <p>How would one go about doing this in Python 2.5 and 2.4?</p>
1
2009-09-10T22:07:41Z
1,408,008
<p>You probably need to use the subprocess module which is available in Python 2.4</p> <pre><code>Popen("/home/user/foo" + " arg") &gt;&gt;&gt; Popen("foo arg", shell=False) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.6/subprocess.py", line 595, in __init__ errread, errwrite) File "/usr/lib/python2.6/subprocess.py", line 1092, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory </code></pre> <p>You will need to include the full path since you aren't using the shell.</p> <p><a href="http://docs.python.org/library/subprocess.html#replacing-os-system" rel="nofollow">http://docs.python.org/library/subprocess.html#replacing-os-system</a></p> <p>Alternatively you can also pass subprocess.PIPE to the stderr and stdout to suppress the messages. See the link above for more details.</p>
3
2009-09-10T22:11:33Z
[ "python", "process", "fork", "subprocess", "popen" ]
Create an executable process without using shell on Python 2.5 and below
1,407,992
<p>Just what the title says:</p> <ol> <li>The <code>subprocess</code> module cannot be used as this should work on 2.4 and 2.5</li> <li>Shell process should not be spawned to pass arguments.</li> </ol> <p>To explain (2), consider the following code:</p> <pre><code>&gt;&gt;&gt; x=os.system('foo arg') sh: foo: not found &gt;&gt;&gt; x=os.popen('foo arg') sh: foo: not found &gt;&gt;&gt; </code></pre> <p>As you can see <code>os.system</code> and <code>os.popen</code> runs the given command ("foo") via a system shell ("sh"). I don't want this to happen (otherwise, ugly 'not found' messages are printed to program stderr without my control).</p> <p>Finally, I should be able to pass arguments to this program ('arg' in the above example). </p> <p>How would one go about doing this in Python 2.5 and 2.4?</p>
1
2009-09-10T22:07:41Z
1,408,234
<p>As previously described, you can (and should) use the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module.</p> <p>By default, <code>shell</code> parameter is <code>False</code>. This is good, and quite safe. Also, you don't need to pass the full path, just pass the executable name and the arguments as a sequence (tuple or list).</p> <pre><code>import subprocess # This works fine p = subprocess.Popen(["echo","2"]) # These will raise OSError exception: p = subprocess.Popen("echo 2") p = subprocess.Popen(["echo 2"]) p = subprocess.Popen(["echa", "2"]) </code></pre> <p>You can also use these two convenience functions already defined in subprocess module:</p> <pre><code># Their arguments are the same as the Popen constructor retcode = subprocess.call(["echo", "2"]) subprocess.check_call(["echo", "2"]) </code></pre> <p>Remember you can redirect <code>stdout</code> and/or <code>stderr</code> to <code>PIPE</code>, and thus it won't be printed to the screen (but the output is still available for reading by your python program). By default, <code>stdout</code> and <code>stderr</code> are both <code>None</code>, which means <em>no redirection</em>, which means they will use the same stdout/stderr as your python program.</p> <p>Also, you can use <code>shell=True</code> and redirect the <code>stdout</code>.<code>stderr</code> to a PIPE, and thus no message will be printed:</p> <pre><code># This will work fine, but no output will be printed p = subprocess.Popen("echo 2", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # This will NOT raise an exception, and the shell error message is redirected to PIPE p = subprocess.Popen("echa 2", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) </code></pre>
0
2009-09-10T23:25:52Z
[ "python", "process", "fork", "subprocess", "popen" ]
Thread local storage in Python
1,408,171
<p>How do I use thread local storage in Python?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/104983/what-is-thread-local-storage-in-python-and-why-do-i-need-it">What is “thread local storage” in Python, and why do I need it?</a> - This thread appears to be focused more on when variables are shared.</li> <li><a href="http://stackoverflow.com/questions/1403471/efficient-way-to-determine-whether-a-particular-function-is-on-the-stack-in-pytho/1403485#1403485">Efficient way to determine whether a particular function is on the stack in Python</a> - Alex Martelli gives a nice solution</li> </ul>
32
2009-09-10T23:03:33Z
1,408,178
<p>As noted in the question, Alex Martelli gives a solution <a href="http://stackoverflow.com/questions/1403471/efficient-way-to-determine-whether-a-particular-function-is-on-the-stack-in-pytho/1403485#1403485">here</a>. This function allows us to use a factory function to generate a default value for each thread.</p> <pre><code>#Code originally posted by Alex Martelli #Modified to use standard Python variable name conventions import threading threadlocal = threading.local() def threadlocal_var(varname, factory, *args, **kwargs): v = getattr(threadlocal, varname, None) if v is None: v = factory(*args, **kwargs) setattr(threadlocal, varname, v) return v </code></pre>
11
2009-09-10T23:05:44Z
[ "python", "multithreading", "thread-local-storage" ]
Thread local storage in Python
1,408,171
<p>How do I use thread local storage in Python?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/104983/what-is-thread-local-storage-in-python-and-why-do-i-need-it">What is “thread local storage” in Python, and why do I need it?</a> - This thread appears to be focused more on when variables are shared.</li> <li><a href="http://stackoverflow.com/questions/1403471/efficient-way-to-determine-whether-a-particular-function-is-on-the-stack-in-pytho/1403485#1403485">Efficient way to determine whether a particular function is on the stack in Python</a> - Alex Martelli gives a nice solution</li> </ul>
32
2009-09-10T23:03:33Z
1,408,192
<p>Can also write</p> <pre><code>import threading mydata = threading.local() mydata.x = 1 </code></pre> <p>mydata.x will only exist in the current thread</p>
4
2009-09-10T23:10:52Z
[ "python", "multithreading", "thread-local-storage" ]
Thread local storage in Python
1,408,171
<p>How do I use thread local storage in Python?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/104983/what-is-thread-local-storage-in-python-and-why-do-i-need-it">What is “thread local storage” in Python, and why do I need it?</a> - This thread appears to be focused more on when variables are shared.</li> <li><a href="http://stackoverflow.com/questions/1403471/efficient-way-to-determine-whether-a-particular-function-is-on-the-stack-in-pytho/1403485#1403485">Efficient way to determine whether a particular function is on the stack in Python</a> - Alex Martelli gives a nice solution</li> </ul>
32
2009-09-10T23:03:33Z
13,240,093
<p>Thread local storage is useful for instance if you have a thread worker pool and each thread needs access to its own resource, like a network or database connection. Note that the <code>threading</code> module uses the regular concept of threads (which have access to the process global data), but these are not too useful due to the global interpreter lock. The different <code>multiprocessing</code> module creates a new sub-process for each, so any global will be thread local.</p> <h1>threading module</h1> <p>Here is a simple example:</p> <pre><code>import threading from threading import current_thread threadLocal = threading.local() def hi(): initialized = getattr(threadLocal, 'initialized', None) if initialized is None: print("Nice to meet you", current_thread().name) threadLocal.initialized = True else: print("Welcome back", current_thread().name) hi(); hi() </code></pre> <p>This will print out:</p> <pre><code>Nice to meet you MainThread Welcome back MainThread </code></pre> <p>One important thing that is easily overlooked: a <code>threading.local()</code> object only needs to be created once, not once per thread nor once per function call. The <code>global</code> or <code>class</code> level are ideal locations.</p> <p>Here is why: <code>threading.local()</code> actually creates a new instance each time it is called (just like any factory or class call would), so calling <code>threading.local()</code> multiple times constantly overwrites the original object, which in all likelihood is not what one wants. When any thread accesses an existing <code>threadLocal</code> variable (or whatever it is called), it gets its own private view of that variable.</p> <p>This won't work as intended:</p> <pre><code>import threading from threading import current_thread def wont_work(): threadLocal = threading.local() #oops, this creates a new dict each time! initialized = getattr(threadLocal, 'initialized', None) if initialized is None: print("First time for", current_thread().name) threadLocal.initialized = True else: print("Welcome back", current_thread().name) wont_work(); wont_work() </code></pre> <p>Will result in this output:</p> <pre><code>First time for MainThread First time for MainThread </code></pre> <h1>multiprocessing module</h1> <p>All global variables are thread local, since the <code>multiprocessing</code> module creates a new process for each thread.</p> <p>Consider this example, where the <code>processed</code> counter is an example of thread local storage:</p> <pre><code>from multiprocessing import Pool from random import random from time import sleep import os processed=0 def f(x): sleep(random()) global processed processed += 1 print("Processed by %s: %s" % (os.getpid(), processed)) return x*x if __name__ == '__main__': pool = Pool(processes=4) print(pool.map(f, range(10))) </code></pre> <p>It will output something like this:</p> <pre><code>Processed by 7636: 1 Processed by 9144: 1 Processed by 5252: 1 Processed by 7636: 2 Processed by 6248: 1 Processed by 5252: 2 Processed by 6248: 2 Processed by 9144: 2 Processed by 7636: 3 Processed by 5252: 3 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] </code></pre> <p>... of course, the thread IDs and the counts for each and order will vary from run to run.</p>
53
2012-11-05T20:46:39Z
[ "python", "multithreading", "thread-local-storage" ]
Thread local storage in Python
1,408,171
<p>How do I use thread local storage in Python?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/104983/what-is-thread-local-storage-in-python-and-why-do-i-need-it">What is “thread local storage” in Python, and why do I need it?</a> - This thread appears to be focused more on when variables are shared.</li> <li><a href="http://stackoverflow.com/questions/1403471/efficient-way-to-determine-whether-a-particular-function-is-on-the-stack-in-pytho/1403485#1403485">Efficient way to determine whether a particular function is on the stack in Python</a> - Alex Martelli gives a nice solution</li> </ul>
32
2009-09-10T23:03:33Z
29,781,795
<p>Thread-local storage can simply be thought of as a namespace (with values accessed via attribute notation). The difference is that each thread transparently gets its own set of attributes/values, so that one thread doesn't see the values from another thread.</p> <p>Just like an ordinary object, you can create multiple <code>threading.local</code> instances in your code. They can be local variables, class or instance members, or global variables. Each one is a separate namespace.</p> <p>Here's a simple example:</p> <pre><code>import threading class Worker(threading.Thread): ns = threading.local() def run(self): self.ns.val = 0 for i in range(5): self.ns.val += 1 print("Thread:", self.name, "value:", self.ns.val) w1 = Worker() w2 = Worker() w1.start() w2.start() w1.join() w2.join() </code></pre> <p>Output:</p> <pre><code>Thread: Thread-1 value: 1 Thread: Thread-2 value: 1 Thread: Thread-1 value: 2 Thread: Thread-2 value: 2 Thread: Thread-1 value: 3 Thread: Thread-2 value: 3 Thread: Thread-1 value: 4 Thread: Thread-2 value: 4 Thread: Thread-1 value: 5 Thread: Thread-2 value: 5 </code></pre> <p>Note how each thread maintains its own counter, even though the <code>ns</code> attribute is a class member (and hence shared between the threads).</p> <p>The same example could have used an instance variable or a local variable, but that wouldn't show much, as there's no sharing then (a dict would work just as well). There are cases where you'd need thread-local storage as instance variables or local variables, but they tend to be relatively rare (and pretty subtle).</p>
9
2015-04-21T19:49:46Z
[ "python", "multithreading", "thread-local-storage" ]
Nice Python Decorators
1,408,253
<p>How do I nicely write a decorator?</p> <p>In particular issues include: compatibility with other decorators, preserving of signatures, etc.</p> <p>I would like to avoid dependency on the decorator module if possible, but if there were sufficient advantages, then I would consider it.</p> <p>Related</p> <ul> <li><a href="http://stackoverflow.com/questions/147816/preserving-signatures-of-decorated-functions">Preserving signatures of decorated functions</a> - much more specific question. The answer here is to use the third-party decorator module annotating the decorator with @decorator.decorator</li> </ul>
3
2009-09-10T23:31:09Z
1,408,412
<p>Use functools to preserve the name and doc. The signature won't be preserved.</p> <p>Directly from the <a href="http://docs.python.org/library/functools.html" rel="nofollow">doc</a>. </p> <pre><code>&gt;&gt;&gt; from functools import wraps &gt;&gt;&gt; def my_decorator(f): ... @wraps(f) ... def wrapper(*args, **kwds): ... print 'Calling decorated function' ... return f(*args, **kwds) ... return wrapper ... &gt;&gt;&gt; @my_decorator ... def example(): ... """Docstring""" ... print 'Called example function' ... &gt;&gt;&gt; example() Calling decorated function Called example function &gt;&gt;&gt; example.__name__ 'example' &gt;&gt;&gt; example.__doc__ 'Docstring' </code></pre>
6
2009-09-11T00:20:52Z
[ "python", "decorator" ]
Nice Python Decorators
1,408,253
<p>How do I nicely write a decorator?</p> <p>In particular issues include: compatibility with other decorators, preserving of signatures, etc.</p> <p>I would like to avoid dependency on the decorator module if possible, but if there were sufficient advantages, then I would consider it.</p> <p>Related</p> <ul> <li><a href="http://stackoverflow.com/questions/147816/preserving-signatures-of-decorated-functions">Preserving signatures of decorated functions</a> - much more specific question. The answer here is to use the third-party decorator module annotating the decorator with @decorator.decorator</li> </ul>
3
2009-09-10T23:31:09Z
1,408,431
<p>Writing a good decorator is no different then writing a good function. Which means, ideally, using docstrings and making sure the decorator is included in your testing framework.</p> <p>You should definitely use either the <code>decorator</code> library or, better, the <code>functools.wraps()</code> decorator in the standard library (since 2.5).</p> <p>Beyond that, it's best to keep your decorators narrowly focused and well designed. Don't use <code>*args</code> or <code>**kw</code> if your decorator expects specific arguments. And <em>do</em> fill in what arguments you expect, so instead of:</p> <pre><code>def keep_none(func): def _exec(*args, **kw): return None if args[0] is None else func(*args, **kw) return _exec </code></pre> <p>... use ...</p> <pre><code>def keep_none(func): """Wraps a function which expects a value as the first argument, and ensures the function won't get called with *None*. If it is, this will return *None*. &gt;&gt;&gt; def f(x): ... return x + 5 &gt;&gt;&gt; f(1) 6 &gt;&gt;&gt; f(None) is None Traceback (most recent call last): ... TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' &gt;&gt;&gt; f = keep_none(f) &gt;&gt;&gt; f(1) 6 &gt;&gt;&gt; f(None) is None True""" @wraps(func) def _exec(value, *args, **kw): return None if value is None else func(value, *args, **kw) return _exec </code></pre>
5
2009-09-11T00:28:27Z
[ "python", "decorator" ]
Get file creation time with Python on linux
1,408,272
<p>os.stat returns st_mtime and st_ctime attributes, the modification time is st_mtime and st_ctime "change time" on POSIX. is there any function that return the creation time of a file using python and under Linux?</p>
18
2009-09-10T23:35:39Z
1,408,281
<p><a href="http://www.faqs.org/faqs/unix-faq/faq/part3/section-1.html">You probably</a> <a href="http://linux.die.net/man/2/stat">can't.</a>:</p> <blockquote> <p>3.1) How do I find the creation time of a file?</p> <p>You can't - it isn't stored anywhere. Files have a last-modified time (shown by "ls -l"), a last-accessed time (shown by "ls -lu") and an inode change time (shown by "ls -lc"). The latter is often referred to as the "creation time" - even in some man pages - but that's wrong; it's also set by such operations as mv, ln, chmod, chown and chgrp.</p> <p>The man page for "stat(2)" discusses this.</p> </blockquote>
25
2009-09-10T23:38:21Z
[ "python", "linux" ]
Get file creation time with Python on linux
1,408,272
<p>os.stat returns st_mtime and st_ctime attributes, the modification time is st_mtime and st_ctime "change time" on POSIX. is there any function that return the creation time of a file using python and under Linux?</p>
18
2009-09-10T23:35:39Z
1,408,287
<p>try:</p> <pre><code>st_birthtime </code></pre> <p>It isnt' guaranteed to be available on all systems though. From the docs:</p> <blockquote> <p>On some Unix systems (such as Linux), the following attributes may also be available: st_blocks (number of blocks allocated for file), st_blksize (filesystem blocksize), st_rdev (type of device if an inode device). st_flags (user defined flags for file).</p> <p>On other Unix systems (such as FreeBSD), the following attributes may be available (but may be only filled out if root tries to use them): st_gen (file generation number), st_birthtime (time of file creation).</p> </blockquote> <p><a href="http://docs.python.org/2/library/os.html#os.stat">http://docs.python.org/2/library/os.html#os.stat</a></p>
13
2009-09-10T23:39:19Z
[ "python", "linux" ]
Get file creation time with Python on linux
1,408,272
<p>os.stat returns st_mtime and st_ctime attributes, the modification time is st_mtime and st_ctime "change time" on POSIX. is there any function that return the creation time of a file using python and under Linux?</p>
18
2009-09-10T23:35:39Z
31,150,571
<p>You might explain why you want to do this.</p> <p>An indirect solution might be to use some <a href="https://en.wikipedia.org/wiki/Revision_control" rel="nofollow">revision control</a> system (a.k.a. version control system = VCS) to manage the files whose birth time is needed.</p> <p>So you could use <a href="http://git-scm.com/" rel="nofollow">git</a> on such files (i.e. handle them as "source code"). Then you know not only when they have been created (in fact registered in the VCS using <code>git add</code>), but why, by whom, what for, etc... Use <code>git log</code> to get all this...</p> <p>Of course you somehow need to educate your users to use a VCS like <code>git</code></p>
1
2015-07-01T00:10:20Z
[ "python", "linux" ]
Get file creation time with Python on linux
1,408,272
<p>os.stat returns st_mtime and st_ctime attributes, the modification time is st_mtime and st_ctime "change time" on POSIX. is there any function that return the creation time of a file using python and under Linux?</p>
18
2009-09-10T23:35:39Z
31,246,246
<p>According to a thread <a href="http://www.linuxquestions.org/questions/linux-enterprise-47/how-to-find-creation-date-of-a-file-in-rhel-5-a-4175518213/" rel="nofollow">here</a> <em>OS X's HFS and Microsoft's NTFS also both track the birth time, and I'm told the OS X and Cygwin versions of stat() return this information.</em> which looking at the <a href="https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/stat.1.html" rel="nofollow">osx stat manpage</a> seems correct at least for mac:</p> <p><strong>a, m, c, B</strong></p> <blockquote> <p>The time file was last accessed or modified, of when the inode was last changed, or the <strong>birth time of the inode</strong>.</p> </blockquote> <p>For linux newer filesystems like ext4, Btrfs and JFS do support this using <a href="http://manpages.ubuntu.com/manpages/trusty/man8/debugfs.8.html" rel="nofollow">debugfs</a>, there is a bash function taken from <a href="http://moiseevigor.github.io/software/2015/01/30/get-file-creation-time-on-linux-with-ext4/" rel="nofollow">here</a> that will extract the date-created timestamp:</p> <blockquote> <p>You may recover the file creation date if you deal with capable filesystem like EXT4 - journaling file system for Linux:</p> <p>Improved timestamps</p> <p>... Ext4 provides timestamps measured in nanoseconds. In addition, ext4 also adds support for date-created timestamps. But there no consensus in the community on that so</p> <p>... as Theodore Ts'o points out, while it is easy to add an extra creation-date field in the inode (thus technically enabling support for date-created timestamps in ext4), it is more difficult to modify or add the necessary system calls, like stat() (which would probably require a new version) and the various libraries that depend on them (like glibc). These changes would require coordination of many projects. So even if ext4 developers implement initial support for creation-date timestamps, this feature will not be available to user programs for now. Which end up with the Linus final quote</p> <p>Let's wait five years and see if there is actually any consensus on it being needed and used at all, rather than rush into something just because "we can".</p> </blockquote> <pre><code>xstat() { for target in "${@}"; do inode=$(ls -di "${target}" | cut -d ' ' -f 1) fs=$(df "${target}" | tail -1 | awk '{print $1}') crtime=$(sudo debugfs -R 'stat &lt;'"${inode}"'&gt;' "${fs}" 2&gt;/dev/null | grep -oP 'crtime.*--\s*\K.*') printf "%s\t%s\n" "${crtime}" "${target}" done } </code></pre> <p>Running it returns the creation date:</p> <pre><code>:~$ echo 'print("hello world")' &gt; blah.py :~$ xstat "blah.py" Mon Jul 6 13:43:39 2015 blah.py :~$ echo 'print("goodbye world")' &gt; blah.py :~$ xstat "blah.py" Mon Jul 6 13:43:39 2015 blah.py </code></pre> <p>So unless the file system supports it then it is not possible, if the file system does then you could run the <code>debugfs</code> using subprocess and parse the output.</p>
1
2015-07-06T12:45:50Z
[ "python", "linux" ]
Get file creation time with Python on linux
1,408,272
<p>os.stat returns st_mtime and st_ctime attributes, the modification time is st_mtime and st_ctime "change time" on POSIX. is there any function that return the creation time of a file using python and under Linux?</p>
18
2009-09-10T23:35:39Z
39,476,826
<p>Certain file systems do support recording the birth time, but Linux does not provide an interface for obtaining it.</p> <p>See <a href="http://lwn.net/Articles/397442/" rel="nofollow">http://lwn.net/Articles/397442/</a></p> <p>If one atempts to use the "stat" command to obtain it: % stat -c %w {file or dir}</p> <p>The result will be a "-" due to it not having the ability to retrieving it. However, one can use this sample method utilizing debugfs with xstat to retrieve it (providing again, that the file system being used supports collecting it.) </p> <p><a href="https://gist.github.com/moiseevigor/8c496f632137605b322e" rel="nofollow">https://gist.github.com/moiseevigor/8c496f632137605b322e</a></p> <pre><code>xstat() { for target in "${@}"; do inode=$(ls -di "${target}" | cut -d ' ' -f 1) fs=$(df "${target}" | tail -1 | awk '{print $1}') crtime=$(sudo debugfs -R 'stat &lt;'"${inode}"'&gt;' "${fs}" 2&gt;/dev/null | grep -oP 'crtime.*--\s*\K.*') printf "%s\t%s\n" "${crtime}" "${target}" done } </code></pre> <p>Note this requires sudo.</p>
0
2016-09-13T18:32:11Z
[ "python", "linux" ]
Help with Python/Qt4 and QTableWidget column click
1,408,277
<p>I'm trying to learn PyQt4 and GUI design with QtDesigner. I've got my basic GUI designed, and I now want to capture when the user clicks on a column header.</p> <p>My thought is that I need to override QTableWidget, but I don't know how to attach to the signal. Here's my class so far:</p> <pre><code>class MyTableWidget(QtGui.QTableWidget): def __init__(self, parent = None): super(MyTableWidget, self).__init__(parent) self.connect(self, SIGNAL('itemClicked(QTreeWidgetItem*)'), self.onClick) def onClick(self): print "Here!" </code></pre> <p>But, setting a breakpoint in the onClick, nothing is firing.</p> <p>Can somebody please help me?</p> <p>TIA Mike</p>
0
2009-09-10T23:37:27Z
1,408,465
<p>OK, the SIGNAL needed is:</p> <pre><code>self.connect(self.horizontalHeader(), SIGNAL('sectionClicked(int)'), self.onClick) </code></pre>
2
2009-09-11T00:42:18Z
[ "python", "qt4", "pyqt4" ]
Python: NoneType errors.Do they look familiar
1,408,286
<p>I've been looking for the NoneType for half a day. I've put 'print' and dir() all through the generation of the Object represented by t2. I've looked at the data structure after the crash using 'post mortem' and nowhere can I find a NoneType. I was wondering if perhaps it's one of those errors that are initiated by some other part of the code (wishful thinking) and I was wondering if anybody recognizes this? ( k2 is an 'int' )</p> <pre><code> File "C:\Python26\Code\OO.py", line 48, in removeSubtreeFromTree assert getattr(parent, branch) is subtreenode TypeError: getattr(): attribute name must be string, not 'NoneType File "C:\Python26\Code\OO.py", line 94, in theSwapper st2, p2, b2 = self.removeSubtreeFromTree(t2, k2) TypeError: 'NoneType' object is not iterable </code></pre>
0
2009-09-10T23:38:55Z
1,408,303
<p>for some reason, at the point of the assert line, the value of <code>branch</code> is <strong><code>None</code></strong>. </p> <p>If your second exception is separate, Then most likely what is happening is the method call <code>self.removeSubtreeFromTree()</code> is returning None, instead of a sequence (like a tuple), so when Python tries to unpack it into the variables, it fails.</p>
2
2009-09-10T23:43:30Z
[ "python" ]
Python: NoneType errors.Do they look familiar
1,408,286
<p>I've been looking for the NoneType for half a day. I've put 'print' and dir() all through the generation of the Object represented by t2. I've looked at the data structure after the crash using 'post mortem' and nowhere can I find a NoneType. I was wondering if perhaps it's one of those errors that are initiated by some other part of the code (wishful thinking) and I was wondering if anybody recognizes this? ( k2 is an 'int' )</p> <pre><code> File "C:\Python26\Code\OO.py", line 48, in removeSubtreeFromTree assert getattr(parent, branch) is subtreenode TypeError: getattr(): attribute name must be string, not 'NoneType File "C:\Python26\Code\OO.py", line 94, in theSwapper st2, p2, b2 = self.removeSubtreeFromTree(t2, k2) TypeError: 'NoneType' object is not iterable </code></pre>
0
2009-09-10T23:38:55Z
1,408,304
<p><code>NoneType</code> is the type of the <code>None</code> object. So, in the first error, <code>branch</code> is <code>None</code>. The second error is tougher to diagnose without seeing the source code, but suggests that somewhere in <code>t2</code>, the data structure isn't exactly as you believe.</p> <p>When this comes up for me, I usually find that I've forgotten to end one of my functions with a <code>return</code> statement. Functions without an explicit return will return <code>None</code>.</p>
5
2009-09-10T23:43:33Z
[ "python" ]
Python: NoneType errors.Do they look familiar
1,408,286
<p>I've been looking for the NoneType for half a day. I've put 'print' and dir() all through the generation of the Object represented by t2. I've looked at the data structure after the crash using 'post mortem' and nowhere can I find a NoneType. I was wondering if perhaps it's one of those errors that are initiated by some other part of the code (wishful thinking) and I was wondering if anybody recognizes this? ( k2 is an 'int' )</p> <pre><code> File "C:\Python26\Code\OO.py", line 48, in removeSubtreeFromTree assert getattr(parent, branch) is subtreenode TypeError: getattr(): attribute name must be string, not 'NoneType File "C:\Python26\Code\OO.py", line 94, in theSwapper st2, p2, b2 = self.removeSubtreeFromTree(t2, k2) TypeError: 'NoneType' object is not iterable </code></pre>
0
2009-09-10T23:38:55Z
1,408,419
<p>I agree with Managu that it's likely you've forgotten to return a value from a function. I do that all the time.</p> <p>As another possibility, I presume you are writing some kind of tree data structure. Is it possible that you're using None to indicate "this node has no children" and you aren't handling that case correctly?</p>
1
2009-09-11T00:24:15Z
[ "python" ]
Python: NoneType errors.Do they look familiar
1,408,286
<p>I've been looking for the NoneType for half a day. I've put 'print' and dir() all through the generation of the Object represented by t2. I've looked at the data structure after the crash using 'post mortem' and nowhere can I find a NoneType. I was wondering if perhaps it's one of those errors that are initiated by some other part of the code (wishful thinking) and I was wondering if anybody recognizes this? ( k2 is an 'int' )</p> <pre><code> File "C:\Python26\Code\OO.py", line 48, in removeSubtreeFromTree assert getattr(parent, branch) is subtreenode TypeError: getattr(): attribute name must be string, not 'NoneType File "C:\Python26\Code\OO.py", line 94, in theSwapper st2, p2, b2 = self.removeSubtreeFromTree(t2, k2) TypeError: 'NoneType' object is not iterable </code></pre>
0
2009-09-10T23:38:55Z
1,408,510
<p>Another one that got me was in-place functions, like list.append() (can't use that in a function call, list.append() returns None and changes the variable).</p> <p>I spent the better part of a day and a half chasing that bug....</p>
0
2009-09-11T00:58:12Z
[ "python" ]
NumPy array slice using None
1,408,311
<p>This had me scratching my head for a while. I was unintentionally slicing an array with None and getting something other than an error (I expected an error). Instead, it returns an array with an extra dimension.</p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; a = numpy.arange(4).reshape(2,2) &gt;&gt;&gt; a array([[0, 1], [2, 3]]) &gt;&gt;&gt; a[None] array([[[0, 1], [2, 3]]]) </code></pre> <p>Is this behavior intentional or a side-effect? If intentional, is there some rationale for it?</p>
12
2009-09-10T23:45:07Z
1,408,435
<p>Using None is equivalent to using <code>numpy.newaxis</code>, so yes, it's intentional. In fact, they're the same thing, but, of course, <code>newaxis</code> spells it out better.</p> <p><a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#numpy.newaxis">The docs</a></p> <p><a href="http://stackoverflow.com/questions/944863/numpy-should-i-use-newaxis-or-none">A related SO question</a>.</p>
16
2009-09-11T00:29:39Z
[ "python", "arrays", "numpy" ]
send an arbitrary number of inputs from python to a .exe
1,408,326
<p><pre><code> p = subprocess.Popen(args = "myprog.exe" + " " + str(input1) + " " + str(input2) + " " + str(input3) + " " + strpoints, stdout = subprocess.PIPE) </pre></code></p> <p>in the code above, input1, input2, and input3 are all integers that get converted to strings. the variable "strpoints" is a list of arbitrary length of strings. input1 tells myprog the length of strpoints. of course, when i try to run the above code, i get the following error message:</p> <blockquote> <p>TypeError: Can't convert 'list' object to str implicitly</p> </blockquote> <p>how do i pass all the elements of strpoints to myprog.exe? am i doomed to having to do str(strpoints) and then have myprog.exe parse this for commas, apostrophes, etc.? e.g.,</p> <blockquote> <p>`>>> x = ['a', 'b']</p> <p>`>>> str(x)</p> <p>"['a', 'b']"</p> </blockquote> <p>or should i create a huge string in advance? e.g.,</p> <blockquote> <p>'>>> x = ['a', 'b']</p> <p>'>>> stringify(x)</p> <p>' a b'</p> </blockquote> <p>where stringify would be something like <pre><code> def stringify(strlist): rlist = "" for i in strlist: rlist = rlist + i + " " return rlist </pre></code></p>
2
2009-09-10T23:48:56Z
1,408,334
<p>Try using string.join: </p> <pre><code>p = subprocess.Popen(args = "myprog.exe" + " " + str(input1) + " " + str(input2) + " " + str(input3) + " " + " ".join(strpoints), stdout = subprocess.PIPE) </code></pre>
4
2009-09-10T23:50:59Z
[ "python", "executable" ]
send an arbitrary number of inputs from python to a .exe
1,408,326
<p><pre><code> p = subprocess.Popen(args = "myprog.exe" + " " + str(input1) + " " + str(input2) + " " + str(input3) + " " + strpoints, stdout = subprocess.PIPE) </pre></code></p> <p>in the code above, input1, input2, and input3 are all integers that get converted to strings. the variable "strpoints" is a list of arbitrary length of strings. input1 tells myprog the length of strpoints. of course, when i try to run the above code, i get the following error message:</p> <blockquote> <p>TypeError: Can't convert 'list' object to str implicitly</p> </blockquote> <p>how do i pass all the elements of strpoints to myprog.exe? am i doomed to having to do str(strpoints) and then have myprog.exe parse this for commas, apostrophes, etc.? e.g.,</p> <blockquote> <p>`>>> x = ['a', 'b']</p> <p>`>>> str(x)</p> <p>"['a', 'b']"</p> </blockquote> <p>or should i create a huge string in advance? e.g.,</p> <blockquote> <p>'>>> x = ['a', 'b']</p> <p>'>>> stringify(x)</p> <p>' a b'</p> </blockquote> <p>where stringify would be something like <pre><code> def stringify(strlist): rlist = "" for i in strlist: rlist = rlist + i + " " return rlist </pre></code></p>
2
2009-09-10T23:48:56Z
1,408,346
<p>args can be a sequence:</p> <pre><code>p = subprocess.Popen(args = ["myprog.exe"] + [str(x) for x in [input1,input2,input3]] + strpoints,stdout = subprocess.PIPE) </code></pre> <p>This is more correct if your arguments contain shell metacharacters e.g. ' * and you don't want them interpreted as such.</p>
7
2009-09-10T23:55:37Z
[ "python", "executable" ]
send an arbitrary number of inputs from python to a .exe
1,408,326
<p><pre><code> p = subprocess.Popen(args = "myprog.exe" + " " + str(input1) + " " + str(input2) + " " + str(input3) + " " + strpoints, stdout = subprocess.PIPE) </pre></code></p> <p>in the code above, input1, input2, and input3 are all integers that get converted to strings. the variable "strpoints" is a list of arbitrary length of strings. input1 tells myprog the length of strpoints. of course, when i try to run the above code, i get the following error message:</p> <blockquote> <p>TypeError: Can't convert 'list' object to str implicitly</p> </blockquote> <p>how do i pass all the elements of strpoints to myprog.exe? am i doomed to having to do str(strpoints) and then have myprog.exe parse this for commas, apostrophes, etc.? e.g.,</p> <blockquote> <p>`>>> x = ['a', 'b']</p> <p>`>>> str(x)</p> <p>"['a', 'b']"</p> </blockquote> <p>or should i create a huge string in advance? e.g.,</p> <blockquote> <p>'>>> x = ['a', 'b']</p> <p>'>>> stringify(x)</p> <p>' a b'</p> </blockquote> <p>where stringify would be something like <pre><code> def stringify(strlist): rlist = "" for i in strlist: rlist = rlist + i + " " return rlist </pre></code></p>
2
2009-09-10T23:48:56Z
1,408,428
<p>Avoid concatenating all arguments into one string using that string.</p> <p>It's a lot simpler and better and safer to just pass a sequence (list or tuple) of arguments. This is specially true if any argument contains a space character (which is quite common for filenames).</p>
1
2009-09-11T00:26:46Z
[ "python", "executable" ]
send an arbitrary number of inputs from python to a .exe
1,408,326
<p><pre><code> p = subprocess.Popen(args = "myprog.exe" + " " + str(input1) + " " + str(input2) + " " + str(input3) + " " + strpoints, stdout = subprocess.PIPE) </pre></code></p> <p>in the code above, input1, input2, and input3 are all integers that get converted to strings. the variable "strpoints" is a list of arbitrary length of strings. input1 tells myprog the length of strpoints. of course, when i try to run the above code, i get the following error message:</p> <blockquote> <p>TypeError: Can't convert 'list' object to str implicitly</p> </blockquote> <p>how do i pass all the elements of strpoints to myprog.exe? am i doomed to having to do str(strpoints) and then have myprog.exe parse this for commas, apostrophes, etc.? e.g.,</p> <blockquote> <p>`>>> x = ['a', 'b']</p> <p>`>>> str(x)</p> <p>"['a', 'b']"</p> </blockquote> <p>or should i create a huge string in advance? e.g.,</p> <blockquote> <p>'>>> x = ['a', 'b']</p> <p>'>>> stringify(x)</p> <p>' a b'</p> </blockquote> <p>where stringify would be something like <pre><code> def stringify(strlist): rlist = "" for i in strlist: rlist = rlist + i + " " return rlist </pre></code></p>
2
2009-09-10T23:48:56Z
1,408,449
<p>Any thought that you might want to enclose those strings in quotes, in case they have embedded spaces? Something like:</p> <pre><code>if strpoints: finalargs = '"' + '" "'.join(strpoints) + '"' else: finalargs = "" p = subprocess.Popen(args = "myprog.exe" + " " + str(input1) + " " + str(input2) + " " + str(input3) + " " + finalargs, stdout = subprocess.PIPE) </code></pre> <p>This makes your string longer, but will preserve the integrity of your individual elements in the list.</p>
0
2009-09-11T00:35:11Z
[ "python", "executable" ]
Keyboard Interrupts with python's multiprocessing Pool
1,408,356
<p>How can I handle KeyboardInterrupt events with python's multiprocessing Pools? Here is a simple example:</p> <pre><code>from multiprocessing import Pool from time import sleep from sys import exit def slowly_square(i): sleep(1) return i*i def go(): pool = Pool(8) try: results = pool.map(slowly_square, range(40)) except KeyboardInterrupt: # **** THIS PART NEVER EXECUTES. **** pool.terminate() print "You cancelled the program!" sys.exit(1) print "\nFinally, here are the results: ", results if __name__ == "__main__": go() </code></pre> <p>When running the code above, the <code>KeyboardInterrupt</code> gets raised when I press <code>^C</code>, but the process simply hangs at that point and I have to kill it externally.</p> <p>I want to be able to press <code>^C</code> at any time and cause all of the processes to exit gracefully.</p>
78
2009-09-10T23:59:35Z
1,408,425
<p>Strangely enough it looks like you have to handle the <code>KeyboardInterrupt</code> in the children as well. I would have expected this to work as written... try changing <code>slowly_square</code> to:</p> <pre><code>def slowly_square(i): try: sleep(1) return i * i except KeyboardInterrupt: print 'You EVIL bastard!' return 0 </code></pre> <p>That should work as you expected.</p>
-4
2009-09-11T00:26:22Z
[ "python", "multiprocessing", "pool", "keyboardinterrupt" ]