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
Django not picking up changes to INSTALLED_APPS in settings.py
901,061
<p>I'm trying to get South to work - it worked fine on my PC, but I'm struggling to deploy it on my webhost.</p> <p>Right now it seems that any changes I make to add/remove items from INSTALLED_APPS aren't being picked up by <code>syncdb</code> or <code>diffsettings</code>. I've added <code>south</code> to my list of ...
2
2009-05-23T07:15:26Z
902,195
<p>The answer, it turns out, is that I'm a moron. I'd done this:</p> <p>In <code>settings.py</code>:</p> <pre><code>... INSTALLED_APPS = ( ... ) ... from localsettings import * </code></pre> <p>In <code>localsettings.py</code></p> <pre><code>... INSTALLED_APPS = ( ... ) ... </code></pre> <p>I'd created <c...
2
2009-05-23T18:52:06Z
[ "python", "django" ]
finding substring
901,070
<p><br /> Thanks in advance.I want to find all the substring that occurs between K and N,eventhough K and N occurs in between any number of times. for example<br /> a='KANNKAAN'</p> <p>OUTPUT;<br /> [KANNKAAN, KANN , KAN ,KAAN]</p>
1
2009-05-23T07:29:12Z
901,098
<pre><code>import re def occurences(ch_searched, str_input): return [i.start() for i in re.finditer(ch_searched, str_input)] def betweeners(str_input, ch_from, ch_to): starts = occurences(ch_from, str_input) ends = occurences(ch_to, str_input) result = [] for start in starts: for end in en...
2
2009-05-23T07:51:05Z
[ "python" ]
finding substring
901,070
<p><br /> Thanks in advance.I want to find all the substring that occurs between K and N,eventhough K and N occurs in between any number of times. for example<br /> a='KANNKAAN'</p> <p>OUTPUT;<br /> [KANNKAAN, KANN , KAN ,KAAN]</p>
1
2009-05-23T07:29:12Z
901,418
<p>Another way:</p> <pre><code>def findbetween(text, begin, end): for match in re.findall(begin + '.*' +end, text): yield match for m in findbetween(match[1:], begin, end): yield m for m in findbetween(match[:-1], begin, end): yield m &gt;&gt;&gt; list(findbetween('...
1
2009-05-23T12:06:24Z
[ "python" ]
Replace in Python-* equivalent?
901,074
<p>If I am finding &amp; replacing some text how can I get it to replace some text that will change each day so ie anything between (( &amp; )) whatever it is?</p> <p>Cheers!</p>
0
2009-05-23T07:30:50Z
901,080
<p>Use regular expressions (<a href="http://docs.python.org/library/re.html" rel="nofollow">http://docs.python.org/library/re.html</a>)?</p> <p>Could you please be more specific, I don't think I fully understand what you are trying to accomplish.</p> <p>EDIT:</p> <p>Ok, now I see. This may be done even easier, but h...
4
2009-05-23T07:36:49Z
[ "python", "replace" ]
Dynamic function calls in Python using XMLRPC
901,391
<p>I'm writing a class which I intend to use to create subroutines, constructor as following:</p> <pre><code>def __init__(self,menuText,RPC_params,RPC_call): #Treat the params #Call the given RPC_call with the treated params </code></pre> <p>The problem is that I want to call the function on the pattern "<stron...
1
2009-05-23T11:41:19Z
901,400
<p>You <em>can</em> use <code>getattr</code> to get the function name from the server proxy, so calling the function like this will work:</p> <pre><code>getattr(rpc, function_name)(*params) </code></pre>
2
2009-05-23T11:53:56Z
[ "python", "function", "xml-rpc", "rpc" ]
Python: Joining Multiple Lists to one single Sentence
901,412
<p>Howdy, I've got multiple lists. For example:</p> <pre><code>[u'This/ABC'] [u'is/ABC'] [u'not/ABC'] [u'even/ABC'] [u'close/ABC'] [u'to/ABC'] [u'funny/ABC'] [u'./ABC'] [u'O/ABC'] [u'noez/ABC'] [u'!/ABC'] </code></pre> <p>I need to join this List to</p> <pre><code>This/ABC is/ABC not/ABC even/ABC close/ABC to/ABC f...
3
2009-05-23T12:01:08Z
901,415
<p>If you put them all in a list, for example like this:</p> <pre><code>a = [ [u'This/ABC'], [u'is/ABC'], ... ] </code></pre> <p>You can get your result by adding all the lists and using a regular join on the result:</p> <pre><code>result = ' '.join(sum(a, [])) </code></pre> <p><hr /></p> <p>After re-r...
6
2009-05-23T12:05:16Z
[ "python", "list", "join" ]
Python: Joining Multiple Lists to one single Sentence
901,412
<p>Howdy, I've got multiple lists. For example:</p> <pre><code>[u'This/ABC'] [u'is/ABC'] [u'not/ABC'] [u'even/ABC'] [u'close/ABC'] [u'to/ABC'] [u'funny/ABC'] [u'./ABC'] [u'O/ABC'] [u'noez/ABC'] [u'!/ABC'] </code></pre> <p>I need to join this List to</p> <pre><code>This/ABC is/ABC not/ABC even/ABC close/ABC to/ABC f...
3
2009-05-23T12:01:08Z
901,419
<p>If you put all your lists in one list, you can do it like this:</p> <pre><code>' '.join(e[0] for e in [[u'This/ABC'], [u'is/ABC']]) </code></pre>
0
2009-05-23T12:06:26Z
[ "python", "list", "join" ]
Python: Joining Multiple Lists to one single Sentence
901,412
<p>Howdy, I've got multiple lists. For example:</p> <pre><code>[u'This/ABC'] [u'is/ABC'] [u'not/ABC'] [u'even/ABC'] [u'close/ABC'] [u'to/ABC'] [u'funny/ABC'] [u'./ABC'] [u'O/ABC'] [u'noez/ABC'] [u'!/ABC'] </code></pre> <p>I need to join this List to</p> <pre><code>This/ABC is/ABC not/ABC even/ABC close/ABC to/ABC f...
3
2009-05-23T12:01:08Z
901,422
<p>Easy:</p> <pre><code>x = [[u'O/ABC'], [u'noez/ABC'], [u'!/ABC']] print ' '.join(y[0] for y in x) </code></pre>
1
2009-05-23T12:06:55Z
[ "python", "list", "join" ]
Python: Joining Multiple Lists to one single Sentence
901,412
<p>Howdy, I've got multiple lists. For example:</p> <pre><code>[u'This/ABC'] [u'is/ABC'] [u'not/ABC'] [u'even/ABC'] [u'close/ABC'] [u'to/ABC'] [u'funny/ABC'] [u'./ABC'] [u'O/ABC'] [u'noez/ABC'] [u'!/ABC'] </code></pre> <p>I need to join this List to</p> <pre><code>This/ABC is/ABC not/ABC even/ABC close/ABC to/ABC f...
3
2009-05-23T12:01:08Z
901,624
<p>To join lists, try the chain function in the module itertools, For example, you can try</p> <pre><code>import itertools print ' '.join(itertools.chain(mylist)) </code></pre> <p>if the new line between the two lists are intentional, then add '\n' at the end of the first list</p> <pre><code>import itertools a = [[u...
3
2009-05-23T14:34:35Z
[ "python", "list", "join" ]
How do I include image files in Django templates?
901,551
<p>I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:</p> <pre><code>dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ </code></pre> <p>I have a JPG file that needs to be ...
39
2009-05-23T13:45:07Z
901,587
<p>In production, you'll just have the HTML generated from your template pointing to wherever the host has media files stored. So your template will just have for example</p> <pre><code>&lt;img src="../media/foo.png"&gt; </code></pre> <p>And then you'll just make sure that directory is there with the relevant file(s)...
20
2009-05-23T14:04:01Z
[ "python", "django", "django-templates" ]
How do I include image files in Django templates?
901,551
<p>I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:</p> <pre><code>dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ </code></pre> <p>I have a JPG file that needs to be ...
39
2009-05-23T13:45:07Z
901,701
<p>Your </p> <pre><code>&lt;img src="/home/tony/london.jpg" /&gt; </code></pre> <p>will work for a HTML file read from disk, as it will assume the URL is <code>file:///home/...</code>. For a file served from a webserver though, the URL will become something like: <code>http://www.yourdomain.com/home/tony/london.jpg</...
3
2009-05-23T15:12:28Z
[ "python", "django", "django-templates" ]
How do I include image files in Django templates?
901,551
<p>I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:</p> <pre><code>dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ </code></pre> <p>I have a JPG file that needs to be ...
39
2009-05-23T13:45:07Z
1,235,542
<p>Try this,</p> <h2>settings.py</h2> <pre><code># typically, os.path.join(os.path.dirname(__file__), 'media') MEDIA_ROOT = '&lt;your_path&gt;/media' MEDIA_URL = '/media/' </code></pre> <h2>urls.py</h2> <pre><code>urlpatterns = patterns('', (r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve',...
53
2009-08-05T20:25:36Z
[ "python", "django", "django-templates" ]
How do I include image files in Django templates?
901,551
<p>I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:</p> <pre><code>dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ </code></pre> <p>I have a JPG file that needs to be ...
39
2009-05-23T13:45:07Z
4,284,974
<p>I have spent two solid days working on this so I just thought I'd share my solution as well. As of 26/11/10 the current branch is 1.2.X so that means you'll have to have the following in you <em>settings.py</em>:</p> <pre><code>MEDIA_ROOT = "&lt;path_to_files&gt;" (i.e. /home/project/django/app/templates/static) ME...
8
2010-11-26T11:42:45Z
[ "python", "django", "django-templates" ]
How do I include image files in Django templates?
901,551
<p>I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:</p> <pre><code>dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ </code></pre> <p>I have a JPG file that needs to be ...
39
2009-05-23T13:45:07Z
11,161,478
<p>Another way to do it:</p> <pre><code>MEDIA_ROOT = '/home/USER/Projects/REPO/src/PROJECT/APP/static/media/' MEDIA_URL = '/static/media/' </code></pre> <p>This would require you to move your media folder to a sub directory of a static folder.</p> <p>Then in your template you can use:</p> <pre><code>&lt;img class="...
1
2012-06-22T17:44:40Z
[ "python", "django", "django-templates" ]
How do I include image files in Django templates?
901,551
<p>I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:</p> <pre><code>dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ </code></pre> <p>I have a JPG file that needs to be ...
39
2009-05-23T13:45:07Z
12,356,998
<p>I do understand, that your question was about files stored in MEDIA_ROOT, but sometimes it can be possible to store content in static, when you are not planning to create content of that type anymore.<br> May be this is a rare case, but anyway - if you have a huge amount of "pictures of the day" for your site - and ...
5
2012-09-10T17:54:12Z
[ "python", "django", "django-templates" ]
How do I include image files in Django templates?
901,551
<p>I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:</p> <pre><code>dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ </code></pre> <p>I have a JPG file that needs to be ...
39
2009-05-23T13:45:07Z
17,036,758
<p>I tried various method it didn't work.But this worked.Hope it will work for you as well. The file/directory must be at this locations:</p> <p>projec/your_app/templates project/your_app/static</p> <h2>settings.py</h2> <pre><code>import os PROJECT_DIR = os.path.realpath(os.path.dirname(_____file_____)) STATIC_R...
0
2013-06-11T04:59:48Z
[ "python", "django", "django-templates" ]
How do I include image files in Django templates?
901,551
<p>I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:</p> <pre><code>dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ </code></pre> <p>I have a JPG file that needs to be ...
39
2009-05-23T13:45:07Z
25,724,854
<p>If your file is a model field within a model, you can also use ".url" in your template tag to get the image.</p> <p>For example.</p> <p>If this is your model:</p> <pre><code>class Foo(models.Model): foo = models.TextField() bar = models.FileField(upload_to="foo-pictures", blank = True) </code></pre> <p...
2
2014-09-08T12:58:19Z
[ "python", "django", "django-templates" ]
How do I include image files in Django templates?
901,551
<p>I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:</p> <pre><code>dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ </code></pre> <p>I have a JPG file that needs to be ...
39
2009-05-23T13:45:07Z
30,411,331
<p>/media directory under project root</p> <h2>Settings.py</h2> <pre><code>BASE_DIR = os.path.dirname(os.path.dirname(__file__)) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') </code></pre> <h2>urls.py</h2> <pre><code> urlpatterns += patterns('django.views.static',(r'^media/(?P&lt;path&gt;.*)...
2
2015-05-23T09:58:05Z
[ "python", "django", "django-templates" ]
Wxwidget Grid
901,704
<p>I posted this in the mailing list, but the reply I got wasn't too clear, so maybe I'll have better luck here.</p> <p>I currently have a grid with data in it. I would like to know if there is a way to give each generated row an ID, or at least, associate each row with an object.</p> <p>It may make it more clear if ...
2
2009-05-23T15:13:30Z
901,806
<p>What I did when I encountered such a case was to create a column for IDs and set its width to 0.</p>
3
2009-05-23T16:02:23Z
[ "python", "wxpython", "wxwidgets" ]
Wxwidget Grid
901,704
<p>I posted this in the mailing list, but the reply I got wasn't too clear, so maybe I'll have better luck here.</p> <p>I currently have a grid with data in it. I would like to know if there is a way to give each generated row an ID, or at least, associate each row with an object.</p> <p>It may make it more clear if ...
2
2009-05-23T15:13:30Z
902,083
<p>You could make your own GridTableBase that implements this, for a simple example to get you started see my answer to <a href="http://stackoverflow.com/questions/328003/wxpython-updating-a-dict-or-other-appropriate-data-type-from-wx-lib-sheet-csheet/328078#328078">this</a> question.</p>
2
2009-05-23T18:05:19Z
[ "python", "wxpython", "wxwidgets" ]
Executing *nix binaries in Python
901,829
<p>I need to run the following command:</p> <pre><code>screen -dmS RealmD top </code></pre> <p><em>Essentially invoking GNU screen in the background with the session title 'RealmD' with the top command being run inside screen. The command MUST be invoked this way so there can't be a substitute for screen at this time...
1
2009-05-23T16:12:09Z
901,836
<p>Use <a href="http://docs.python.org/3.0/library/os.html#os.system" rel="nofollow">os.system</a>:</p> <pre><code>os.system("screen -dmS RealmD top") </code></pre> <p>Then in a separate shell you can have a look at <code>top</code> by running <code>screen -rd RealmD</code>.</p>
6
2009-05-23T16:16:13Z
[ "python", "screen" ]
Executing *nix binaries in Python
901,829
<p>I need to run the following command:</p> <pre><code>screen -dmS RealmD top </code></pre> <p><em>Essentially invoking GNU screen in the background with the session title 'RealmD' with the top command being run inside screen. The command MUST be invoked this way so there can't be a substitute for screen at this time...
1
2009-05-23T16:12:09Z
901,842
<p><code>os.system</code> is the simplest way, but, for many more possibilities and degrees of freedom, also look at the standard library <a href="http://docs.python.org/library/subprocess.html" rel="nofollow"><code>subprocess</code></a> module (unless Stephan202's wonderfully simple use of <code>os.system</code> meets...
11
2009-05-23T16:20:59Z
[ "python", "screen" ]
python factory functions compared to class
901,892
<p>Just working through learning python and started to look at nested/factory functions (simple example):</p> <pre><code>def maker(N): def action(X): return X * N return action </code></pre> <p>Are there any advantages of factory functions over creating a class? performance? memory? clean up?</p>
13
2009-05-23T16:43:25Z
901,902
<p>Nesting functions allows one to create custom functions on the fly.</p> <p>Have a look at e.g. <a href="http://www.python.org/dev/peps/pep-0318/" rel="nofollow">decorators</a>. The resulting functions depend on variables that are bound at creation time and do not need to be changed afterwards. So using a class for...
2
2009-05-23T16:49:17Z
[ "python", "function" ]
python factory functions compared to class
901,892
<p>Just working through learning python and started to look at nested/factory functions (simple example):</p> <pre><code>def maker(N): def action(X): return X * N return action </code></pre> <p>Are there any advantages of factory functions over creating a class? performance? memory? clean up?</p>
13
2009-05-23T16:43:25Z
902,010
<p>What I like most about nested functions is that it is less verbose than classes. The equivalent class definition to your maker function is:</p> <pre><code>class clsmaker(object): def __init__(self, N): self.N = N def __call__(self, X): return X * self.N </code></pre> <p>That doesn't seem so bad u...
23
2009-05-23T17:38:58Z
[ "python", "function" ]
python factory functions compared to class
901,892
<p>Just working through learning python and started to look at nested/factory functions (simple example):</p> <pre><code>def maker(N): def action(X): return X * N return action </code></pre> <p>Are there any advantages of factory functions over creating a class? performance? memory? clean up?</p>
13
2009-05-23T16:43:25Z
902,809
<p>Comparing a function factory to a class is comparing apples and oranges. Use a class if you have a cohesive collection of data and functions, together called an object. Use a function factory if you need a function, and want to parameterize its creation.</p> <p>Your choice of the two techniques should depend on t...
9
2009-05-24T00:55:57Z
[ "python", "function" ]
Python OSError: [Errno 2]
901,982
<p>I have the following code that is attempting to start each of the "commands" below in Linux. The module attempts to keep each of the 2 commands running if either should crash for whatever reason.</p> <pre><code>#!/usr/bin/env python import subprocess commands = [ ["screen -dmS RealmD top"], ["screen -DmS RealmD to...
31
2009-05-23T17:24:03Z
901,990
<p>Only guess is that it can't find <code>screen</code>. Try <code>/usr/bin/screen</code> or whatever <code>which screen</code> gives you.</p>
6
2009-05-23T17:29:51Z
[ "python", "subprocess" ]
Python OSError: [Errno 2]
901,982
<p>I have the following code that is attempting to start each of the "commands" below in Linux. The module attempts to keep each of the 2 commands running if either should crash for whatever reason.</p> <pre><code>#!/usr/bin/env python import subprocess commands = [ ["screen -dmS RealmD top"], ["screen -DmS RealmD to...
31
2009-05-23T17:24:03Z
901,992
<p>Use <code>["screen", "-dmS", "RealmD", "top"]</code> instead of <code>["screen -dmS RealmD top"]</code>.</p> <p>Maybe also use the complete path to <code>screen</code>.</p> <p>If the program still cannot be found you can also go through your shell with <code>shell=True</code>, but then you need to quote and escape...
53
2009-05-23T17:31:21Z
[ "python", "subprocess" ]
Python OSError: [Errno 2]
901,982
<p>I have the following code that is attempting to start each of the "commands" below in Linux. The module attempts to keep each of the 2 commands running if either should crash for whatever reason.</p> <pre><code>#!/usr/bin/env python import subprocess commands = [ ["screen -dmS RealmD top"], ["screen -DmS RealmD to...
31
2009-05-23T17:24:03Z
15,282,684
<p>The problem is that your command should be split. subprocces requires that the cmd is a list, not a string. It shouldn't be:</p> <pre><code>subprocess.call('''awk 'BEGIN {FS="\t";OFS="\n"} {a[$1]=a [$1] OFS $2 FS $3 FS $4} END {for (i in a) {print i a[i]}}' 2_lcsorted.txt &gt; 2_locus_2.txt''') </code></pre> <p>T...
6
2013-03-07T22:05:54Z
[ "python", "subprocess" ]
Python OSError: [Errno 2]
901,982
<p>I have the following code that is attempting to start each of the "commands" below in Linux. The module attempts to keep each of the 2 commands running if either should crash for whatever reason.</p> <pre><code>#!/usr/bin/env python import subprocess commands = [ ["screen -dmS RealmD top"], ["screen -DmS RealmD to...
31
2009-05-23T17:24:03Z
17,066,679
<pre><code>commands = [ "screen -dmS RealmD top", "screen -DmS RealmD top -d 5" ] programs = [ subprocess.Popen(c.split()) for c in commands ] </code></pre>
2
2013-06-12T13:21:50Z
[ "python", "subprocess" ]
Why can I not view my Google App Engine cron admin page?
902,039
<p>When I go to <a href="http://localhost:8080/%5Fah/admin/cron" rel="nofollow">http://localhost:8080/_ah/admin/cron</a>, as stated in Google's docs, I get the following:</p> <pre><code>Traceback (most recent call last): File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 501,...
1
2009-05-23T17:50:14Z
902,200
<p>Congratulations! You've found a bug. Can you file a bug on the <a href="http://code.google.com/p/googleappengine/issues/list" rel="nofollow">public issue tracker</a>, please? If you want to fix it for yourself immediately, delete the 'self' argument in the line referenced at the end of that stacktrace.</p>
3
2009-05-23T18:54:58Z
[ "python", "google-app-engine", "cron", "stack-trace" ]
Why can I not view my Google App Engine cron admin page?
902,039
<p>When I go to <a href="http://localhost:8080/%5Fah/admin/cron" rel="nofollow">http://localhost:8080/_ah/admin/cron</a>, as stated in Google's docs, I get the following:</p> <pre><code>Traceback (most recent call last): File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 501,...
1
2009-05-23T17:50:14Z
903,334
<p>This is definitely a bug in Google App Engine. If you check <a href="http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/cron/groctimespecification.py?r=54#112" rel="nofollow">groctimespecification.py</a>, you'll see that <code>IntervalTimeSpecification</code> inherits from <code>Tim...
4
2009-05-24T08:30:19Z
[ "python", "google-app-engine", "cron", "stack-trace" ]
Auto-restart system in Python
902,085
<p>I need to detect when a program crashes or is not running using python and restart it. I need a method that doesn't necessarily rely on the python module being the parent process.</p> <p>I'm considering implementing a while loop that essentially does </p> <pre><code>ps -ef | grep process name </code></pre> <p>and...
5
2009-05-23T18:07:22Z
902,142
<p>I haven't tried it myself, but there is a <a href="http://pypi.python.org/pypi/PSI" rel="nofollow">Python System Information</a> module that can be used to find processes and get information about them. AFAIR there is a <code>ProcessTable</code> class that can be used to inspect the running processes, but it doesn't...
0
2009-05-23T18:31:42Z
[ "python", "linux", "restart", "pid" ]
Auto-restart system in Python
902,085
<p>I need to detect when a program crashes or is not running using python and restart it. I need a method that doesn't necessarily rely on the python module being the parent process.</p> <p>I'm considering implementing a while loop that essentially does </p> <pre><code>ps -ef | grep process name </code></pre> <p>and...
5
2009-05-23T18:07:22Z
902,166
<p>I'd go the command-line route (it's just easier imho) as long as you only check every second or two the resource usage should be infintesimal compared to the available processing on any system less than 10 years old.</p>
0
2009-05-23T18:42:11Z
[ "python", "linux", "restart", "pid" ]
Auto-restart system in Python
902,085
<p>I need to detect when a program crashes or is not running using python and restart it. I need a method that doesn't necessarily rely on the python module being the parent process.</p> <p>I'm considering implementing a while loop that essentially does </p> <pre><code>ps -ef | grep process name </code></pre> <p>and...
5
2009-05-23T18:07:22Z
902,189
<p>Why implement it yourself? An existing utility like <a href="http://libslack.org/daemon/" rel="nofollow">daemon</a> or Debian's <code>start-stop-daemon</code> is more likely to get the other difficult stuff right about running long-living server processes.</p> <p>Anyway, when you start the service, put its pid in <...
4
2009-05-23T18:50:19Z
[ "python", "linux", "restart", "pid" ]
Auto-restart system in Python
902,085
<p>I need to detect when a program crashes or is not running using python and restart it. I need a method that doesn't necessarily rely on the python module being the parent process.</p> <p>I'm considering implementing a while loop that essentially does </p> <pre><code>ps -ef | grep process name </code></pre> <p>and...
5
2009-05-23T18:07:22Z
902,258
<p>Please don't reinvent init. Your OS has capabilities to do this that require nearly no system resources and will definitely do it better and more reliably than anything you can reproduce.</p> <p>Classic Linux has /etc/inittab</p> <p>Ubuntu has /etc/event.d (upstart)</p> <p>OS X has launchd</p> <p>Solaris has sm...
3
2009-05-23T19:22:54Z
[ "python", "linux", "restart", "pid" ]
Auto-restart system in Python
902,085
<p>I need to detect when a program crashes or is not running using python and restart it. I need a method that doesn't necessarily rely on the python module being the parent process.</p> <p>I'm considering implementing a while loop that essentially does </p> <pre><code>ps -ef | grep process name </code></pre> <p>and...
5
2009-05-23T18:07:22Z
902,477
<p>The following code checks a given process in a given interval, and restarts it.</p> <pre><code>#Restarts a given process if it is finished. #Compatible with Python 2.5, tested on Windows XP. import threading import time import subprocess class ProcessChecker(threading.Thread): def __init__(self, process_path, ...
1
2009-05-23T20:55:14Z
[ "python", "linux", "restart", "pid" ]
Auto-restart system in Python
902,085
<p>I need to detect when a program crashes or is not running using python and restart it. I need a method that doesn't necessarily rely on the python module being the parent process.</p> <p>I'm considering implementing a while loop that essentially does </p> <pre><code>ps -ef | grep process name </code></pre> <p>and...
5
2009-05-23T18:07:22Z
7,682,140
<p>maybe you need <a href="http://supervisord.org" rel="nofollow">http://supervisord.org</a></p>
1
2011-10-07T01:08:17Z
[ "python", "linux", "restart", "pid" ]
Django, custom template filters - regex problems
902,184
<p>I'm trying to implement a WikiLink template filter in Django that queries the database model to give different responses depending on Page existence, identical to Wikipedia's red links. The filter does not raise an Error but instead doesn't do anything to the input.</p> <p><strong>WikiLink</strong> is defined as: <...
2
2009-05-23T18:48:57Z
902,263
<p>This is the type of problem that falls quickly to a small set of unit tests.</p> <p>Pieces of the filter that can be tested in isolation (with a bit of code restructuring):</p> <ul> <li>Determining whether or not value contains the pattern you're looking for</li> <li>What string gets generated if there is a matchi...
3
2009-05-23T19:24:19Z
[ "python", "regex", "django", "django-templates" ]
Django, custom template filters - regex problems
902,184
<p>I'm trying to implement a WikiLink template filter in Django that queries the database model to give different responses depending on Page existence, identical to Wikipedia's red links. The filter does not raise an Error but instead doesn't do anything to the input.</p> <p><strong>WikiLink</strong> is defined as: <...
2
2009-05-23T18:48:57Z
902,273
<p>If your string contains other text in addition to the wiki-link, your filter won't work because you are using <code>re.match</code> instead of <code>re.search</code>. <code>re.match</code> matches at the beginning of the string. <code>re.search</code> matches anywhere in the string. See <a href="http://docs.python.o...
4
2009-05-23T19:28:33Z
[ "python", "regex", "django", "django-templates" ]
Django, custom template filters - regex problems
902,184
<p>I'm trying to implement a WikiLink template filter in Django that queries the database model to give different responses depending on Page existence, identical to Wikipedia's red links. The filter does not raise an Error but instead doesn't do anything to the input.</p> <p><strong>WikiLink</strong> is defined as: <...
2
2009-05-23T18:48:57Z
902,579
<p>Code:</p> <pre><code>import re def page_exists(alias): if alias == 'ThisIsAWikiLink': return True return False def wikilink(value): if value == None: return None for alias, text in re.findall('\[\[\s*(.*?)\s*\|\s*(.*?)\s*\]\]',value): if page_exists(alias): va...
1
2009-05-23T21:57:04Z
[ "python", "regex", "django", "django-templates" ]
Django, custom template filters - regex problems
902,184
<p>I'm trying to implement a WikiLink template filter in Django that queries the database model to give different responses depending on Page existence, identical to Wikipedia's red links. The filter does not raise an Error but instead doesn't do anything to the input.</p> <p><strong>WikiLink</strong> is defined as: <...
2
2009-05-23T18:48:57Z
902,871
<p>This is the working code in case someone needs it:</p> <pre><code>from django import template from django.template.defaultfilters import stringfilter from sites.wiki.models import Page import re register = template.Library() @register.filter @stringfilter def wikilink(value): WIKILINK_RE = re.compile(r'\[\[ ?(....
0
2009-05-24T01:38:17Z
[ "python", "regex", "django", "django-templates" ]
How to use variables in SQL statement in Python?
902,408
<p>Ok so I'm not that experienced in Python.</p> <p>I have the following Python code: </p> <pre><code>cursor.execute("INSERT INTO table VALUES var1, var2, var3,") </code></pre> <p>where <code>var1</code> is an integer, <code>var2</code> &amp; <code>var3</code> are strings.</p> <p>How can I write the variable names ...
30
2009-05-23T20:20:33Z
902,417
<pre><code>cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3)) </code></pre> <p>Note that the parameters are passed as a tuple.</p> <p>The database API does proper escaping and quoting of variables. Be careful not to use the string formatting operator (<code>%</code>), because</p> <ol> <li>it...
33
2009-05-23T20:25:24Z
[ "python", "sql" ]
How to use variables in SQL statement in Python?
902,408
<p>Ok so I'm not that experienced in Python.</p> <p>I have the following Python code: </p> <pre><code>cursor.execute("INSERT INTO table VALUES var1, var2, var3,") </code></pre> <p>where <code>var1</code> is an integer, <code>var2</code> &amp; <code>var3</code> are strings.</p> <p>How can I write the variable names ...
30
2009-05-23T20:20:33Z
902,426
<p><a href="http://www.amk.ca/python/writing/DB-API.html">http://www.amk.ca/python/writing/DB-API.html</a></p> <p>Be careful when you simply append values of variables to your statements: Imagine a user naming himself <code>';DROP TABLE Users;'</code> -- That's why you need to use sql escaping, which Python provides f...
12
2009-05-23T20:28:11Z
[ "python", "sql" ]
How to use variables in SQL statement in Python?
902,408
<p>Ok so I'm not that experienced in Python.</p> <p>I have the following Python code: </p> <pre><code>cursor.execute("INSERT INTO table VALUES var1, var2, var3,") </code></pre> <p>where <code>var1</code> is an integer, <code>var2</code> &amp; <code>var3</code> are strings.</p> <p>How can I write the variable names ...
30
2009-05-23T20:20:33Z
902,836
<p>Different implementations of the Python DB-API are allowed to use different placeholders, so you'll need to find out which one you're using -- it could be (e.g. with MySQLdb):</p> <pre><code>cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3)) </code></pre> <p>or (e.g. with sqlite3 from the ...
24
2009-05-24T01:14:23Z
[ "python", "sql" ]
How to use variables in SQL statement in Python?
902,408
<p>Ok so I'm not that experienced in Python.</p> <p>I have the following Python code: </p> <pre><code>cursor.execute("INSERT INTO table VALUES var1, var2, var3,") </code></pre> <p>where <code>var1</code> is an integer, <code>var2</code> &amp; <code>var3</code> are strings.</p> <p>How can I write the variable names ...
30
2009-05-23T20:20:33Z
21,734,918
<p>Many ways. <strong>DON'T</strong> use the most obvious one (<code>%s</code> with <code>%</code>) in real code, it's open to <a href="http://en.wikipedia.org/wiki/SQL_injection">attacks</a>.</p> <p>Here copy-paste'd <strong><a href="http://docs.python.org/2/library/sqlite3.html">from pydoc of sqlite3</a></strong>:</...
11
2014-02-12T17:16:52Z
[ "python", "sql" ]
Problem with my hangman game
902,520
<p>I'm trying to learn python and I'm attempting a hangman game. But when I try and compare the user's guess to the word, it doesn't work. What am I missing?</p> <pre><code>import sys import codecs import random if __name__ == '__main__': try: wordlist = codecs.open("words.txt", "r") except Exception ...
0
2009-05-23T21:25:17Z
902,530
<p>In your "<code>for word in wordlist</code>" loop, each word will end in a newline. Try adding <code>word = word.strip()</code> as the next line.</p> <p>By the way your last loop could be replaced with:</p> <pre><code>if guess in word: print ("Yessssh") </code></pre> <p>Bonus tip: when adding "debug prints", i...
8
2009-05-23T21:31:59Z
[ "python", "python-3.x" ]
Problem with my hangman game
902,520
<p>I'm trying to learn python and I'm attempting a hangman game. But when I try and compare the user's guess to the word, it doesn't work. What am I missing?</p> <pre><code>import sys import codecs import random if __name__ == '__main__': try: wordlist = codecs.open("words.txt", "r") except Exception ...
0
2009-05-23T21:25:17Z
19,480,398
<p>This is what i did for my hangman game:</p> <pre><code> for x in range(0, len(secretword)): if letter == secretword[x]: for x in range(len(secretword)): if secretword[x] in letter: hiddenletter = hiddenletter[:x] + secretword[x] +hiddenlett...
0
2013-10-20T17:15:34Z
[ "python", "python-3.x" ]
Issue with adding new properties to existing Google AppEngine data models / entities
902,633
<p>In GAE, I have a model called Foo, with existing entities, and attempt to add a new property called <em>memcached</em> to Foo that takes datetime values for the last time this value was set to memcache. If I try to query and sort on this property, or even filter for entities that do not have a value for <em>memcach...
4
2009-05-23T22:24:15Z
902,672
<p>There's nothing for it but to go through each of your existing entities and add the property, <a href="http://code.google.com/appengine/articles/update%5Fschema.html">here is the official documentation which walks you through the process</a>.</p>
8
2009-05-23T22:53:58Z
[ "python", "google-app-engine", "properties", "bigtable" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
902,774
<p>You can use <a href="https://github.com/drj11/pypng/" rel="nofollow">PyPNG</a>. It's a pure Python (no dependencies) open source PNG encoder/decoder and it <a href="http://packages.python.org/pypng/ex.html#numpy" rel="nofollow">supports</a> writing NumPy arrays as images.</p>
21
2009-05-24T00:26:05Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
977,040
<p>If you have matplotlib, you can do:</p> <pre><code>import matplotlib.pyplot as plt plt.imshow(matrix) #Needs to be in row,col order plt.savefig(filename) </code></pre>
15
2009-06-10T17:29:37Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
978,306
<p>matplotlib svn has a new function to save images as just an image -- no axes etc. it's a very simple function to backport too, if you don't want to install svn (copied straight from image.py in matplotlib svn, removed the docstring for brevity):</p> <pre><code>def imsave(fname, arr, vmin=None, vmax=None, cmap=None...
2
2009-06-10T21:43:06Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
1,713,101
<p>This uses PIL, but maybe some might find it useful:</p> <pre><code>import scipy.misc scipy.misc.imsave('outfile.jpg', image_array) </code></pre> <p><strong>EDIT</strong>: The current <code>scipy</code> version started to normalize all images so that min(data) become black and max(data) become white. This is unwant...
107
2009-11-11T04:53:29Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
8,538,444
<p>An answer using PIL (just in case it's useful).</p> <p>given a numpy array "A":</p> <pre><code>import Image im = Image.fromarray(A) im.save("your_file.jpeg") </code></pre> <p>you can replace "jpeg" with almost any format you want. More details about the formats <a href="http://www.pythonware.com/library/pil/handb...
32
2011-12-16T18:21:39Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
19,174,800
<p>Pure Python (2 &amp; 3), a snippet without 3rd party dependencies.</p> <p>This function writes compressed, true-color (4 bytes per pixel) <code>RGBA</code> PNG's.</p> <pre><code>def write_png(buf, width, height): """ buf: must be bytes or a bytearray in Python3.x, a regular string in Python2.x. "...
28
2013-10-04T06:33:01Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
21,034,111
<p>Addendum to @ideasman42's answer:</p> <pre><code>def saveAsPNG(array, filename): import struct if any([len(row) != len(array[0]) for row in array]): raise ValueError, "Array should have elements of equal size" #First row becomes top row of image. flat = []; map(f...
6
2014-01-10T00:33:20Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
22,823,821
<p>With <code>matplotlib</code>:</p> <pre><code>import matplotlib matplotlib.image.imsave('name.png', array) </code></pre> <p>Works with matplotlib 1.3.1, I don't know about lower version. From the docstring:</p> <pre><code>Arguments: *fname*: A string containing a path to a filename, or a Python file-like ob...
9
2014-04-02T21:51:28Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
25,377,156
<p>If you happen to use [Py]Qt already, you may be interested in <a href="http://hmeine.github.io/qimage2ndarray/" rel="nofollow">qimage2ndarray</a>. Starting with version 1.4 (just released), PySide is supported as well, and there will be a tiny <code>imsave(filename, array)</code> function similar to scipy's, but us...
1
2014-08-19T06:46:08Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
27,115,931
<p>There's <code>opencv</code> for python (<a href="http://docs.opencv.org/trunk/doc/py_tutorials/py_tutorials.html">http://docs.opencv.org/trunk/doc/py_tutorials/py_tutorials.html</a>).</p> <pre><code>import cv2 import numpy as np cv2.imwrite("filename.png", np.zeros((10,10))) </code></pre> <p>useful if you need to...
10
2014-11-24T23:10:45Z
[ "python", "image", "numpy" ]
Saving a Numpy array as an image
902,761
<p>I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.</p>
74
2009-05-24T00:08:50Z
32,853,604
<p>The world probably doesn't need yet another package for writing a numpy array to a PNG file, but for those who can't get enough, I recently put up <code>numpngw</code> on github:</p> <p><a href="https://github.com/WarrenWeckesser/numpngw" rel="nofollow">https://github.com/WarrenWeckesser/numpngw</a></p> <p>and on ...
1
2015-09-29T20:56:04Z
[ "python", "image", "numpy" ]
Compiling Python, curses.h not found
902,833
<p>I'm attempting to build Python 2.6.2 from source on my Linux system. It has ncurses installed on /usr/local/, and curses.h is on /usr/local/include/ncurses. So curses.h isn't found on the include path, and those packages fail in the Python build.</p> <p>What's the right solution to this? Is Python supposed to in...
1
2009-05-24T01:12:18Z
902,866
<p>With many Open Source packages, you can set:</p> <pre><code>export CPPFLAGS="-I/usr/local/include" </code></pre> <p>or even:</p> <pre><code>export CPPFLAGS="-I/usr/local/include/ncurses" </code></pre> <p>before running the configure script. I haven't compiled Python recently enough to be sure that works, but it...
4
2009-05-24T01:35:02Z
[ "python", "configure", "curses" ]
How does the win32com python.Interpreter work?
902,895
<p>Ok, so I'm trying to google the win32com python package and the python.Interpreter COM server. Unfortunately, python.Interpreter ends up as "python Interpreter" and not giving me any COM server results.</p> <p>I'm trying to make a pluggable program that has a plugin to allow python code to run, and it seems like t...
0
2009-05-24T01:58:11Z
902,939
<p>See <a href="http://books.google.com/books?id=ns1WMyLVnRMC&amp;pg=PA232&amp;lpg=PA232&amp;dq=win32com+%22python.interpreter%22&amp;source=bl&amp;ots=NVpe-E8eGg&amp;sig=imGi73WQyOmP4rJC6-jpz4stb9M&amp;hl=en&amp;ei=xrAYSsTHBZH0tAORqeCSDw&amp;sa=X&amp;oi=book_result&amp;ct=result&amp;resnum=6#PPA232,M1" rel="nofollow">...
1
2009-05-24T02:31:21Z
[ "python", "com" ]
Data storage to ease data interpolation in Python
902,910
<p>I have 20+ tables similar to table 1. Where all letters represent actual values.</p> <pre><code>Table 1: $ / cars |&lt;1 | 2 | 3 | 4+ &lt;10,000 | a | b | c | d 20,000 | e | f | g | h 30,000 | i | j | k | l 40,000+ | m | n | o | p </code></pre> <p>A user input could be for example, (2.4, 24594) which is a va...
6
2009-05-24T02:14:27Z
902,931
<p>There's nothing special about bilinear interpolation that makes your use case particularly odd; you just have to do two lookups (for storage units of full rows/columns) or four lookups (for array-type storage). The most efficient method depends on your access patterns and the structure of the data.</p> <p>If your e...
0
2009-05-24T02:23:35Z
[ "python", "interpolation" ]
Data storage to ease data interpolation in Python
902,910
<p>I have 20+ tables similar to table 1. Where all letters represent actual values.</p> <pre><code>Table 1: $ / cars |&lt;1 | 2 | 3 | 4+ &lt;10,000 | a | b | c | d 20,000 | e | f | g | h 30,000 | i | j | k | l 40,000+ | m | n | o | p </code></pre> <p>A user input could be for example, (2.4, 24594) which is a va...
6
2009-05-24T02:14:27Z
902,933
<p>I'd keep a sorted list of the first column, and use the <code>bisect</code> module in the standard library to look for the values -- it's the best way to get the immediately-lower and immediately-higher indices. Every other column can be kept as another list parallel to this one. </p>
3
2009-05-24T02:25:32Z
[ "python", "interpolation" ]
Data storage to ease data interpolation in Python
902,910
<p>I have 20+ tables similar to table 1. Where all letters represent actual values.</p> <pre><code>Table 1: $ / cars |&lt;1 | 2 | 3 | 4+ &lt;10,000 | a | b | c | d 20,000 | e | f | g | h 30,000 | i | j | k | l 40,000+ | m | n | o | p </code></pre> <p>A user input could be for example, (2.4, 24594) which is a va...
6
2009-05-24T02:14:27Z
903,071
<p>If you want the most computationally efficient solution I can think of and are not restricted to the standard library, then I would recommend scipy/numpy. First, store the a..p array as a 2D numpy array and then both the $4k-10k and 1-4 arrays as 1D numpy arrays. Use scipy's interpolate.interp1d if both 1D arrays ...
7
2009-05-24T04:28:26Z
[ "python", "interpolation" ]
How to embed a Poll in a Web Page
903,104
<p>I want to create a simple online poll application. I have created a backend in python that handles vote tracking, poll display, results display and admin setup. However, if I wanted a third party to be able to embed the poll in their website, what would be the recommended way of doing so? I would love to be able ...
1
2009-05-24T04:53:43Z
903,112
<p>Make your app into a Google Gadget, Open Social gadget, or other kind of gadgets -- these are all designed to be embeddable into third-party pages with as little fuss as possible.</p>
1
2009-05-24T04:57:23Z
[ "javascript", "python", "cross-domain" ]
How to embed a Poll in a Web Page
903,104
<p>I want to create a simple online poll application. I have created a backend in python that handles vote tracking, poll display, results display and admin setup. However, if I wanted a third party to be able to embed the poll in their website, what would be the recommended way of doing so? I would love to be able ...
1
2009-05-24T04:53:43Z
903,139
<p>IFrame is the easiest no muss no fuss solution if you want to allow postbacks.</p> <p>Or, this is a bit left field and oldschool, but could you use a 1x1 transparent gif as your vote submission? They click the link (radio/span/whatever), you set the src of an image to something that lives on your server. Something ...
1
2009-05-24T05:17:18Z
[ "javascript", "python", "cross-domain" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
903,135
<p>The first.</p> <p>Shorter is better. Exceptions should be exceptional.</p>
-1
2009-05-24T05:14:59Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
903,138
<p><code>hasattr</code> internally and rapidly performs the same task as the <code>try/except</code> block: it's a very specific, optimized, one-task tool and thus should be preferred, when applicable, to the very general-purpose alternative.</p>
60
2009-05-24T05:17:15Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
903,155
<p>If it's just one attribute you're testing, I'd say use <code>hasattr</code>. However, if you're doing <em>several</em> accesses to attributes which may or may not exist then using a <code>try</code> block may save you some typing.</p>
4
2009-05-24T05:32:01Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
903,162
<p>I would say it depends on whether your function may accept objects without the attribute <strong>by design</strong>, e.g. if you have two callers to the function, one providing an object with the attribute and the other providing an object without it. </p> <p>If the only case where you'll get an object without the ...
13
2009-05-24T05:37:42Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
903,173
<p>From a practical point of view, in most languages using a conditional will always be consderably faster than handling an exception.</p> <p>If you're wanting to handle the case of an attribute not existing somewhere outside of the current function, the exception is the better way to go. An indicator that you may wan...
2
2009-05-24T05:44:44Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
903,238
<p><em>Any benches that illustrate difference in performance?</em></p> <p>timeit it's your friend</p> <pre><code>$ python -mtimeit -s 'class C(object): a = 4 c = C()' 'hasattr(c, "nonexistent")' 1000000 loops, best of 3: 1.87 usec per loop $ python -mtimeit -s 'class C(object): a = 4 c = C()' 'hasattr(c, "a")' 100000...
66
2009-05-24T06:41:27Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
903,304
<p>I'd suggest option 2. Option 1 has a race condition if some other thread is adding or removing the attribute.</p> <p>Also python has an <a href="http://jaynes.colorado.edu/PythonIdioms.html" rel="nofollow">Idiom</a>, that EAFP ('easier to ask forgiveness than permission') is better than LBYL ('look before you leap'...
2
2009-05-24T08:00:38Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
1,063,055
<p>If not having the attribute is <strong>not</strong> an error condition, the exception handling variant has a problem: it would catch also AttributeErrors that might come <em>internally</em> when accessing obj.attribute (for instance because attribute is a property so that accessing it calls some code).</p>
2
2009-06-30T10:52:28Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
12,855,092
<p>At least when it is up to just what's going on in the program, leaving out the human part of readability, etc. (which is actually most of the time more imortant than performance (at least in this case - with that performance span), as Roee Adler and others pointed out).</p> <p>Nevertheless looking at it from that p...
0
2012-10-12T08:29:57Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
16,186,050
<p>I almost always use <code>hasattr</code>: it's the correct choice for most cases.</p> <p>The problematic case is when a class overrides <code>__getattr__</code>: <code>hasattr</code> will <strong>catch all exceptions</strong> instead of catching just <code>AttributeError</code> like you expect. In other words, the ...
15
2013-04-24T07:32:57Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
hasattr() vs try-except block to deal with non-existent attributes
903,130
<pre><code>if hasattr(obj, 'attribute'): # do somthing </code></pre> <p>vs</p> <pre><code>try: # access obj.attribute except AttributeError, e: # deal with AttributeError </code></pre> <p>Which should be preferred and why?</p>
54
2009-05-24T05:11:59Z
16,727,179
<p>There is a third, and often better, alternative:</p> <pre><code>attr = getattr(obj, 'attribute', None) if attr is not None: print attr </code></pre> <p>Advantages:</p> <ol> <li><p><code>getattr</code> does not have the bad <a href="http://stackoverflow.com/a/16186050/243712">exception-swallowing behavior poi...
12
2013-05-24T03:18:35Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
How to implement hotlinking prevention in Google App Engine
903,144
<p>My application is on GAE and I'm trying to figure out how to prevent hotlinking of images dynamically served (e.g. /image?id=E23432E) in Python. Please advise.</p>
5
2009-05-24T05:21:29Z
903,307
<p>In Google webapp framework, you can extract the referer from the <a href="http://code.google.com/appengine/docs/python/tools/webapp/requestclass.html" rel="nofollow">Request class</a>:</p> <pre><code>def get(self): referer = self.request.headers.get("Referer") # Will be None if no referer given in header. <...
11
2009-05-24T08:02:20Z
[ "python", "google-app-engine", "hotlinking" ]
How do I install Python Imaging Library on Mac OS X?
903,242
<p>I'm an extremely amateur programmer; I've done some recreational algorithmics programming, but I honestly have no idea how libraries and programming languages really fit together. I'm supposed to work on a project that requires some image processing, so I've been trying to install PIL for a while, but I haven't been...
6
2009-05-24T06:47:30Z
903,244
<p>GCC is the GNU compiler. It's a very useful thing to have. You just need to install it in whatever mac-friendly way exists.</p> <p><a href="http://www.tech-recipes.com/rx/726/mac-os-x-install-gcc-compiler/" rel="nofollow">http://www.tech-recipes.com/rx/726/mac-os-x-install-gcc-compiler/</a></p>
0
2009-05-24T06:52:10Z
[ "python", "osx", "module" ]
How do I install Python Imaging Library on Mac OS X?
903,242
<p>I'm an extremely amateur programmer; I've done some recreational algorithmics programming, but I honestly have no idea how libraries and programming languages really fit together. I'm supposed to work on a project that requires some image processing, so I've been trying to install PIL for a while, but I haven't been...
6
2009-05-24T06:47:30Z
903,245
<p>You need to install the developer tools that come on your Mac OS X install DVD.</p>
3
2009-05-24T06:52:13Z
[ "python", "osx", "module" ]
How do I install Python Imaging Library on Mac OS X?
903,242
<p>I'm an extremely amateur programmer; I've done some recreational algorithmics programming, but I honestly have no idea how libraries and programming languages really fit together. I'm supposed to work on a project that requires some image processing, so I've been trying to install PIL for a while, but I haven't been...
6
2009-05-24T06:47:30Z
903,254
<p>Actually, assuming you're still using the default 2.5.x Python that comes with OS X (at least as of 10.5.6), there's a <a href="http://pythonmac.org/packages/py25-fat/index.html" rel="nofollow">pre-built installer package</a> for it (download the <a href="http://pythonmac.org/packages/py25-fat/dmg/PIL-1.1.6-py2.5-ma...
4
2009-05-24T07:00:48Z
[ "python", "osx", "module" ]
How do I install Python Imaging Library on Mac OS X?
903,242
<p>I'm an extremely amateur programmer; I've done some recreational algorithmics programming, but I honestly have no idea how libraries and programming languages really fit together. I'm supposed to work on a project that requires some image processing, so I've been trying to install PIL for a while, but I haven't been...
6
2009-05-24T06:47:30Z
5,879,621
<p>So this is from awhile ago, but I just ran into the problem.</p> <p>The issues lies with -> </p> <pre><code>/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/distutils/sysconfig.py </code></pre> <p>or wherever your python install is.</p> <p>there is a line that sets the compile flags:</p...
0
2011-05-04T06:53:10Z
[ "python", "osx", "module" ]
Python - get static information
903,497
<p>i have to get static information from one 'module' to another. I'm trying to write logger with information about code place from where we're logging. For example, in some file:</p> <pre><code>LogObject.Log('Describe error', STATIC_INFORMATION) </code></pre> <p>Static information is class name, file name and functi...
1
2009-05-24T10:35:43Z
903,553
<p>First, please use lower-case names for objects and methods. Only use UpperCase Names for Class definitions. </p> <p>More importantly, you want a clever introspective function in every class, it appears. </p> <pre><code>class Loggable( object ): def identification( self ): return self.__class__.__m...
2
2009-05-24T11:13:18Z
[ "python", "variables", "static" ]
Python - get static information
903,497
<p>i have to get static information from one 'module' to another. I'm trying to write logger with information about code place from where we're logging. For example, in some file:</p> <pre><code>LogObject.Log('Describe error', STATIC_INFORMATION) </code></pre> <p>Static information is class name, file name and functi...
1
2009-05-24T10:35:43Z
903,588
<p>I don't think "static" is the world you're looking for. If I understand you correctly, you want to write a function that will return the filename, class name and method name of the caller.</p> <p>Basically, you should use sys._getframe(1) to access the previous frame, and work from there.</p> <p>Example:</p> <pre...
3
2009-05-24T11:33:37Z
[ "python", "variables", "static" ]
Python's 'with' statement versus 'with .. as'
903,557
<p>Having just pulled my hair off because of a difference, I'd like to know what the difference <em>really</em> is in Python 2.5.</p> <p>I had two blocks of code (<code>dbao.getConnection()</code> returns a MySQLdb connection).</p> <pre><code>conn = dbao.getConnection() with conn: # Do stuff </code></pre> <p>And...
14
2009-05-24T11:17:24Z
903,594
<p>The with statement is there to allow for example making sure that transaction is started and stopped correctly.</p> <p>In case of database connections in python, I think the natural thing to do is to create a cursor at the beginning of the with statement and then commit or rollback the transaction at the end of it....
1
2009-05-24T11:36:54Z
[ "python", "syntax" ]
Python's 'with' statement versus 'with .. as'
903,557
<p>Having just pulled my hair off because of a difference, I'd like to know what the difference <em>really</em> is in Python 2.5.</p> <p>I had two blocks of code (<code>dbao.getConnection()</code> returns a MySQLdb connection).</p> <pre><code>conn = dbao.getConnection() with conn: # Do stuff </code></pre> <p>And...
14
2009-05-24T11:17:24Z
904,357
<p>In general terms, the value assigned by the <code>as</code> part of a <code>with</code> statement is going to be whatever gets returned by the <a href="http://docs.python.org/library/stdtypes.html#contextmanager.%5F%5Fenter%5F%5F"><code>__enter__</code> method of the context manager</a>.</p>
18
2009-05-24T18:18:37Z
[ "python", "syntax" ]
Python's 'with' statement versus 'with .. as'
903,557
<p>Having just pulled my hair off because of a difference, I'd like to know what the difference <em>really</em> is in Python 2.5.</p> <p>I had two blocks of code (<code>dbao.getConnection()</code> returns a MySQLdb connection).</p> <pre><code>conn = dbao.getConnection() with conn: # Do stuff </code></pre> <p>And...
14
2009-05-24T11:17:24Z
904,590
<p>It may be a little confusing at first glance, but </p> <pre><code>with babby() as b: ... </code></pre> <p>is <em>not</em> equivalent to</p> <pre><code>b = babby() with b: ... </code></pre> <p>To see why, here's how the context manager would be implemented:</p> <pre><code>class babby(object): def __e...
27
2009-05-24T20:34:40Z
[ "python", "syntax" ]
python, regular expressions, named groups and "logical or" operator
903,562
<p>In python regular expression, named and unnamed groups are both defined with '(' and ')'. This leads to a weird behavior. Regexp</p> <pre><code>"(?P&lt;a&gt;1)=(?P&lt;b&gt;2)" </code></pre> <p>used with text "1=2" will find named group "a" with value "1" and named group "b" with value "2". But if i want to use "lo...
5
2009-05-24T11:18:20Z
903,567
<p>Use <code>(?:)</code> to get rid of the unnamed group:</p> <pre><code>r"(?:(?P&lt;a&gt;1)=(?P&lt;b&gt;2))|(?P&lt;c&gt;3)" </code></pre> <p>From the documentation of <a href="http://docs.python.org/library/re.html">re</a>:</p> <blockquote> <p>(?:...) A non-grouping version of regular parentheses. Matches whate...
12
2009-05-24T11:21:18Z
[ "python", "regex" ]
How can I draw automatic graphs using dot in Python on a Mac?
903,582
<p>I am producing graphs in a Python program, and now I need to visualize them.</p> <p>I am using Tkinter as GUI to visualize all the other data, and I would like to have a small subwindow inside with the graph of the data. At the moment I have the data being represented in a .dot file. And then I keep graphviz open, ...
0
2009-05-24T11:28:35Z
903,833
<p>I do not have a mac to test it on, but the <a href="http://networkx.lanl.gov/index.html" rel="nofollow">NetworkX</a> package includes methods to <a href="http://networkx.lanl.gov/reference/generated/networkx.read%5Fdot.html" rel="nofollow">read .dot files</a> and <a href="http://networkx.lanl.gov/reference/generated...
2
2009-05-24T14:10:54Z
[ "python", "osx", "graphviz", "dot", "dyld" ]
How can I draw automatic graphs using dot in Python on a Mac?
903,582
<p>I am producing graphs in a Python program, and now I need to visualize them.</p> <p>I am using Tkinter as GUI to visualize all the other data, and I would like to have a small subwindow inside with the graph of the data. At the moment I have the data being represented in a .dot file. And then I keep graphviz open, ...
0
2009-05-24T11:28:35Z
905,316
<p>Quick <a href="http://www.google.com/search?q=python%2Bgraphviz" rel="nofollow">Google</a> pulls up <a href="http://code.google.com/p/pydot/" rel="nofollow">http://code.google.com/p/pydot/</a>. I haven't tried it but it looks promising.</p>
1
2009-05-25T04:28:13Z
[ "python", "osx", "graphviz", "dot", "dyld" ]
is it possible to call python methods from a C program?
903,596
<p>I remember seeing somewhere that you could call python methods from inside C using</p> <pre><code>#include "python.h" </code></pre> <p>But I can't seem to find the source for this or any examples.</p> <p>How can I call python methods from inside a C program?</p>
0
2009-05-24T11:37:32Z
903,602
<p><a href="http://www.python.org/doc/2.5.2/ext/callingPython.html" rel="nofollow">Here's</a> a doc item from the python site about extending C with python functionality</p> <p><a href="http://www.python.org/doc/2.5.2/ext/simpleExample.html" rel="nofollow">Here's</a> the start of the documentation (where it refers to ...
5
2009-05-24T11:40:03Z
[ "python", "c", "embedding" ]
is it possible to call python methods from a C program?
903,596
<p>I remember seeing somewhere that you could call python methods from inside C using</p> <pre><code>#include "python.h" </code></pre> <p>But I can't seem to find the source for this or any examples.</p> <p>How can I call python methods from inside a C program?</p>
0
2009-05-24T11:37:32Z
903,604
<p>Check out <a href="http://docs.python.org/c-api/" rel="nofollow">http://docs.python.org/c-api</a></p>
2
2009-05-24T11:41:58Z
[ "python", "c", "embedding" ]
How to tell when a function in another class has been called
903,818
<p>I have two Python classes, call them "C1" and "C2". Inside C1 is a function named "F1" and inside C2 is a function named "F2". Is there a way to execute F2 each time F1 is run without making a direct call to F2 from within F1? Is there some other mechanism by which to know when a function from inside another class h...
2
2009-05-24T14:03:45Z
903,831
<p>I believe that what you are trying to do would fit into the realm of <a href="http://en.wikipedia.org/wiki/Aspect-oriented%5Fprogramming" rel="nofollow">Aspect Oriented Programming</a>. However I have never used this methodology and don't even know if it can/has been implemented in Python.</p> <p><strong>Edit</str...
2
2009-05-24T14:10:13Z
[ "python", "class" ]
How to tell when a function in another class has been called
903,818
<p>I have two Python classes, call them "C1" and "C2". Inside C1 is a function named "F1" and inside C2 is a function named "F2". Is there a way to execute F2 each time F1 is run without making a direct call to F2 from within F1? Is there some other mechanism by which to know when a function from inside another class h...
2
2009-05-24T14:03:45Z
903,856
<p>You can do aspect-oriented programming with function and method decorators since Python 2.2:</p> <pre><code>@decorator(decorator_args) def functionToBeDecorated(function_args) : pass </code></pre>
2
2009-05-24T14:20:28Z
[ "python", "class" ]
How to tell when a function in another class has been called
903,818
<p>I have two Python classes, call them "C1" and "C2". Inside C1 is a function named "F1" and inside C2 is a function named "F2". Is there a way to execute F2 each time F1 is run without making a direct call to F2 from within F1? Is there some other mechanism by which to know when a function from inside another class h...
2
2009-05-24T14:03:45Z
903,861
<p>It really depends on why you don't want to call F2 directly from within F1. You could always create a third class (C3) which encapsulates both C1 and C2. When F3 is called, it will call both F1 and F2. This is known as the Mediator pattern - <a href="http://en.wikipedia.org/wiki/Mediator_pattern" rel="nofollow">h...
2
2009-05-24T14:21:31Z
[ "python", "class" ]
How to tell when a function in another class has been called
903,818
<p>I have two Python classes, call them "C1" and "C2". Inside C1 is a function named "F1" and inside C2 is a function named "F2". Is there a way to execute F2 each time F1 is run without making a direct call to F2 from within F1? Is there some other mechanism by which to know when a function from inside another class h...
2
2009-05-24T14:03:45Z
903,868
<p>You catch all accesses to F1 with <code>__getattr__</code> . This will allow you to do extra processing or return your own function in place of F1</p> <pre><code>class C1: def __getattr__(self,name): if name == 'F1': C2.F2() return self[name] </code></pre> <p>I should warn you that this will call C2.F2 e...
0
2009-05-24T14:25:27Z
[ "python", "class" ]
How to tell when a function in another class has been called
903,818
<p>I have two Python classes, call them "C1" and "C2". Inside C1 is a function named "F1" and inside C2 is a function named "F2". Is there a way to execute F2 each time F1 is run without making a direct call to F2 from within F1? Is there some other mechanism by which to know when a function from inside another class h...
2
2009-05-24T14:03:45Z
903,898
<p>You can write a little helper decorator that will make the call for you. The advantage is that it's easy to tell who is going to call what by looking at the code. And you can add as many function calls as you want. It works like registering a callback function:</p> <pre><code>from functools import wraps def oncall...
3
2009-05-24T14:37:29Z
[ "python", "class" ]
How to tell when a function in another class has been called
903,818
<p>I have two Python classes, call them "C1" and "C2". Inside C1 is a function named "F1" and inside C2 is a function named "F2". Is there a way to execute F2 each time F1 is run without making a direct call to F2 from within F1? Is there some other mechanism by which to know when a function from inside another class h...
2
2009-05-24T14:03:45Z
904,482
<p>Not knowing what is you are trying to achieve, i would suggest taking a look at pydispatcher. It allows you to implement the Observer pattern </p> <p>Basically, you register F2 with the dispatcher so that it will be called when a specific 'signal' is emitted. Your F1 'emits a signal' that says "I've been called"....
1
2009-05-24T19:25:44Z
[ "python", "class" ]
Prevent splitting Window when using pythoncomplete in Vim
903,847
<p>I'm using VIM with pythoncomplete. When I'm making a completion, the current window is splitted and calltips are shown in the upper pane. I hate that! Is there a way to prevent that behavior or at least limit the size of the upper pane automaticly?</p>
5
2009-05-24T14:17:20Z
903,882
<p>You need to do something like:</p> <pre><code>set completeopt-=preview </code></pre> <p>This will prevent the opening of the preview window. </p>
5
2009-05-24T14:29:10Z
[ "python", "autocomplete", "vim" ]
How do you extract a column from a multi-dimensional array?
903,853
<p>Does anybody know how to extract a column from a multi-dimensional array in Python?</p>
80
2009-05-24T14:19:47Z
903,867
<p>Could it be that you're using a <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#indexing-multi-dimensional-arrays">NumPy array</a>? Python has the <a href="http://docs.python.org/library/array.html">array</a> module, but that does not support multi-dimensional arrays. Normal Python lists are singl...
75
2009-05-24T14:24:23Z
[ "python", "arrays", "multidimensional-array", "extraction" ]