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 |
|---|---|---|---|---|---|---|---|---|---|
Improve a IRC Client in Python | 1,121,002 | <p>How i can make some improvement in my IRC client made in Python. The improvement is: How i can put something that the user can type the <em>HOST, PORT, NICK, INDENT and REALNAME</em> strings and the message? And here is the code of the program:</p>
<blockquote>
<p>simplebot.py</p>
<pre><code>import sys
import socket
import string
HOST="irc.freenode.net"
PORT=6667
NICK="MauBot"
IDENT="maubot"
REALNAME="MauritsBot"
readbuffer=""
s=socket.socket( )
s.connect((HOST, PORT))
s.send("NICK %s\r\n" % NICK)
s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))
while 1:
readbuffer=readbuffer+s.recv(1024)
temp=string.split(readbuffer, "\n")
readbuffer=temp.pop( )
for line in temp:
line=string.rstrip(line)
line=string.split(line)
if(line[0]=="PING"):
s.send("PONG %s\r\n" % line[1])
</code></pre>
</blockquote>
<p>Remember that i'm starting in Python development. Here is where i have found this code: <a href="http://oreilly.com/pub/h/1968" rel="nofollow">http://oreilly.com/pub/h/1968</a>.Thanks.</p>
| 0 | 2009-07-13T17:47:09Z | 1,121,180 | <p>If you're trying to carry out actions in response to user input, maybe the <code>cmd</code> module will help you out:</p>
<ul>
<li><a href="http://docs.python.org/library/cmd.html" rel="nofollow">cmd â Support for line-oriented command interpreters</a></li>
<li><a href="http://blog.doughellmann.com/2008/05/pymotw-cmd.html" rel="nofollow">PyMOTW: cmd</a></li>
</ul>
<p>If you're interested in the IRC protocol itself, this tutorial on using sockets to write an IRC client in python may be of use:</p>
<ul>
<li><a href="http://www.devshed.com/index2.php?option=content&task=view&id=607&pop=1&hide%5Fads=1&page=0&hide%5Fjs=1" rel="nofollow">Python and IRC</a></li>
</ul>
| 1 | 2009-07-13T18:19:30Z | [
"python",
"sockets",
"client",
"python-3.x",
"irc"
] |
Eliminating certain Django Session Calls | 1,121,299 | <p>I was wondering if I could eliminate django session calls for specific views. For example, if I have a password reset form I don't want a call to the DB to check for a session or not. Thanks!</p>
| 0 | 2009-07-13T18:40:29Z | 1,121,363 | <p>Sessions are lazily loaded: if you don't use the session during a request, Django won't load it.</p>
<p>This includes request.user: if you access it, it accesses the session to find the user. (It loads lazily, too--if you don't access request.user, it won't access the session, either.)</p>
<p>So, figure out what's accessing the session and eliminate it--and if you can't, at least you'll know why the session is being pulled in.</p>
| 1 | 2009-07-13T18:50:12Z | [
"python",
"django",
"session"
] |
How to model one way one-to-one relationship in Django | 1,121,488 | <p>I want to model an article with revisions in Django:</p>
<p>I have following in my article's models.py:</p>
<pre><code>class Article(models.Model):
title = models.CharField(blank=False, max_length=80)
slug = models.SlugField(max_length=80)
def __unicode__(self):
return self.title
class ArticleRevision(models.Model):
article = models.ForeignKey(Article)
revision_nr = models.PositiveSmallIntegerField(blank=True, null=True)
body = models.TextField(blank=False)
</code></pre>
<p>On the artlcle model I want to have 2 direct references to a revision - one would point to a published revision and another to a revision that is being actively edited. However from what I understand, OneToOne and ForeignKey references generate a backreference on the other side of the model reference, so my question is, how do i create a one-way one-to-one reference in Django?</p>
<p>Is there some special incantation for that or do I have to fake it by including state into revision and custom implementations of the fields that ask for a revision in specific state?</p>
<p><strong>Edit:</strong> I guess, I've done somewhat poor job of explaining my intent. Let's try it on a higher abstraction level:</p>
<p>My original intent was to implement a sort of revisioned article model, where each article may have multiple revisions, where one of those revisions may be "published" and one actively edited.</p>
<p>This means that the article will have one-to-many relationship to revisions (represented by <code>ForeignKey(Article)</code> reference in <em>ArticleRevision</em> class) and two one way references from Article to revision: <em><code>published_revision</code></em> and <em><code>edited_revision</code></em>.</p>
<p>My question is mainly, how can I model this with Django's ORM.</p>
| 3 | 2009-07-13T19:11:54Z | 1,121,514 | <p>What is wrong with the link going both ways? I would think that the <a href="https://docs.djangoproject.com/en/dev/ref/models/fields/#onetoonefield" rel="nofollow"><code>OneToOneField</code></a> would be the perfect choice here. Is there a specific reason why this will be a detriment to your application? If you don't need the backreference why can't you just ignore it?</p>
| 4 | 2009-07-13T19:17:13Z | [
"python",
"django",
"django-models"
] |
How to model one way one-to-one relationship in Django | 1,121,488 | <p>I want to model an article with revisions in Django:</p>
<p>I have following in my article's models.py:</p>
<pre><code>class Article(models.Model):
title = models.CharField(blank=False, max_length=80)
slug = models.SlugField(max_length=80)
def __unicode__(self):
return self.title
class ArticleRevision(models.Model):
article = models.ForeignKey(Article)
revision_nr = models.PositiveSmallIntegerField(blank=True, null=True)
body = models.TextField(blank=False)
</code></pre>
<p>On the artlcle model I want to have 2 direct references to a revision - one would point to a published revision and another to a revision that is being actively edited. However from what I understand, OneToOne and ForeignKey references generate a backreference on the other side of the model reference, so my question is, how do i create a one-way one-to-one reference in Django?</p>
<p>Is there some special incantation for that or do I have to fake it by including state into revision and custom implementations of the fields that ask for a revision in specific state?</p>
<p><strong>Edit:</strong> I guess, I've done somewhat poor job of explaining my intent. Let's try it on a higher abstraction level:</p>
<p>My original intent was to implement a sort of revisioned article model, where each article may have multiple revisions, where one of those revisions may be "published" and one actively edited.</p>
<p>This means that the article will have one-to-many relationship to revisions (represented by <code>ForeignKey(Article)</code> reference in <em>ArticleRevision</em> class) and two one way references from Article to revision: <em><code>published_revision</code></em> and <em><code>edited_revision</code></em>.</p>
<p>My question is mainly, how can I model this with Django's ORM.</p>
| 3 | 2009-07-13T19:11:54Z | 1,122,236 | <p>The back-references that Django produces are programatic, and do not affect the underlying Database schema. In other words, if you have a one-to-one or foreign key field on your Article pointing to your Revision, a column will be added to the Article table in the database, but not to the Revision table.</p>
<p>Thus, removing the reverse relationship from the revision to the article is unnecessary. If you really feel strongly about it, and want to document in your code that the backlink is never used, a fairly common Django idiom is to give the fields a related_name attribute like <code>_unused_1</code>. So your Article model might look like the following:</p>
<pre><code>class Article(models.Model):
title = models.CharField(blank=False, max_length=80)
slug = models.SlugField(max_length=80)
revision_1 = models.OneToOneField(ArticleRevision, related_name='_unused_1')
revision_2 = models.OneToOneField(ArticleRevision, related_name='_unused_2')
def __unicode__(self):
return self.title
</code></pre>
<p>That said, it's rare that a one-to-one relationship is actually useful in an application (unless you're optimizing for some reason) and I'd suggest carefully reviewing your DB schema to make sure this is really what you want. It may make sense to keep a single ForeignKey field on your ArticleRevision pointing back to an Article (since an ArticleRevision will, presumably, always need to be associated with an Article) and adding another column to Revision indicating whether it's published.</p>
| 2 | 2009-07-13T21:40:31Z | [
"python",
"django",
"django-models"
] |
Python to drive Emacs; pymacs doesn't work | 1,121,759 | <p>I've got a python script that loops indefinitely waiting for input, and then
does something when the input happens. My problem is then making python
tell emacs to do something. I just need some way to send emacs input
and make emacs evaluate that input.</p>
<p>Here's some code to illustrate my problem...</p>
<pre><code>while(1):
on_off = query_lightswitch
if on_off == 0:
send_text_to_emacs("(setq 'lightswitch t)")
</code></pre>
<p>Ideally I'd send emacs a string that it evaluates in its elisp interpreter.
I've tried pymacs, but it looks like pymacs is made to start stuff from
emacs rather than python. When I try something like this in pymacs
it locks up until the loop terminates. This looks like a problem I could
solve with unix pipelines, if I knew enough.
If anybody out there has any ideas on how to solve this problem I'd
be much obliged, thanks. </p>
| 1 | 2009-07-13T20:08:56Z | 1,121,792 | <p>You can use <a href="http://www.emacswiki.org/emacs/GnuClient" rel="nofollow">gnuclient</a> (shipped with Emacs 22) (or <a href="http://www.emacswiki.org/emacs/EmacsClient" rel="nofollow">emacsclient</a> for earlier Emacsen), to evaluate code from external programs and connect to a running Emacs.</p>
<p>Getting Emacs to evaluate code by itself would look something like this:</p>
<pre><code>gnuclient -q -batch -eval "(setq 'lightswitch t)"
</code></pre>
| 4 | 2009-07-13T20:16:10Z | [
"python",
"emacs",
"pymacs"
] |
What is the maximum simultaneous HTTP connections allowed on one machine (windows server 2008) using python | 1,121,951 | <p>To be more specific, I'm using python and making a pool of HTTPConnection (httplib) and was wondering if there is an limit on the number of concurrent HTTP connections on a windows server.</p>
| 3 | 2009-07-13T20:48:19Z | 1,122,107 | <p>AFAIK, the numbers of internet sockets (necessary to make TCP/IP connections) is naturally limited on every machine, but it's pretty high. 1000 simulatneous connections shouldn't be a problem for the client machine, as each socket uses only little memory. If you start receiving data through all these channels, this might change though. I've heard of test setups that created a couple of thousands connections simultaneously from a single client.</p>
<p>The story is usually different for the server, when it does heavy lifting for each incoming connection (like forking off a worker process etc.). 1000 incoming connections <em>will</em> impact its performance, and coming from the same client they can easily be taken for a DoS attack. I hope you're in charge of both the client and the server... or is it the same machine?</p>
| 2 | 2009-07-13T21:15:06Z | [
"python"
] |
What is the maximum simultaneous HTTP connections allowed on one machine (windows server 2008) using python | 1,121,951 | <p>To be more specific, I'm using python and making a pool of HTTPConnection (httplib) and was wondering if there is an limit on the number of concurrent HTTP connections on a windows server.</p>
| 3 | 2009-07-13T20:48:19Z | 1,122,135 | <p>Per the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html" rel="nofollow">HTTP RFC</a>, a client should not maintain more than 2 simultaneous connections to a webserver or proxy. However, most browsers don't honor that - firefox 3.5 allows 6 per server and 8 per proxy.</p>
<p>In short, you should not be opening 1000 connections to a single server, unless your intent <em>is</em> to impact the performance of the server. Stress testing your server would be a good legitimate example.</p>
<p><hr /></p>
<p>[Edit]<br>
If this is a proxy you're talking about, then that's a little different story. My suggestion is to use connection pooling. Figure out how many simultaneous connections give you the most requests per second and set a hard limit. Extra requests just have to wait in a queue until the pool frees up. Just be aware than a single process is usually capped at 1024 file descriptors by default.</p>
<p>Take a look through <a href="http://httpd.apache.org/docs/2.2/mod/mod%5Fproxy.html" rel="nofollow">apache's mod_proxy</a> for ideas on how to handle this.</p>
| 3 | 2009-07-13T21:20:19Z | [
"python"
] |
Write unit tests for restish in Python | 1,122,192 | <p>I'm writing a RESTful API in Python using the <a href="http://ish.io/projects/show/restish" rel="nofollow">restish</a> framework. I would like to write some unit tests (using the unittest package, for example), that will make different requests to my application and validate the results. The unit tests should be able to run as-is, without needing to start a separate web-server process. How do I set up a mock environment using restish to do this?</p>
<p>Thanks</p>
| 1 | 2009-07-13T21:30:39Z | 1,122,458 | <p>I test everything using <a href="http://pythonpaste.org/webtest/" rel="nofollow" title="WebTest">WebTest</a> and <a href="http://code.google.com/p/python-nose/" rel="nofollow" title="Nose">NoseTests</a> and I can strongly recommend it. It's fast, flexible and easy to set up. Just pass it your wsgi function and you're good to go.</p>
| 1 | 2009-07-13T22:30:32Z | [
"python",
"unit-testing"
] |
Write unit tests for restish in Python | 1,122,192 | <p>I'm writing a RESTful API in Python using the <a href="http://ish.io/projects/show/restish" rel="nofollow">restish</a> framework. I would like to write some unit tests (using the unittest package, for example), that will make different requests to my application and validate the results. The unit tests should be able to run as-is, without needing to start a separate web-server process. How do I set up a mock environment using restish to do this?</p>
<p>Thanks</p>
| 1 | 2009-07-13T21:30:39Z | 1,123,296 | <p>Since restish is a WSGI framework, you can take advantage of any one of a number of WSGI testing tools:</p>
<ul>
<li><a href="http://wsgi.org/wsgi/Testing" rel="nofollow">http://wsgi.org/wsgi/Testing</a></li>
</ul>
<p>At least a few of those tools, such as Twill, should be able to test your application without starting a separate web server. (For example, see the "<a href="http://ivory.idyll.org/articles/wsgi-intro/testing-wsgi-apps-with-twill.html" rel="nofollow">Testing WSGI Apps with Twill</a>" link for more details.)</p>
<p>You might want to ask on the restish forum/list if they have a preferred tool for this type of thing.</p>
| 1 | 2009-07-14T03:19:46Z | [
"python",
"unit-testing"
] |
Write unit tests for restish in Python | 1,122,192 | <p>I'm writing a RESTful API in Python using the <a href="http://ish.io/projects/show/restish" rel="nofollow">restish</a> framework. I would like to write some unit tests (using the unittest package, for example), that will make different requests to my application and validate the results. The unit tests should be able to run as-is, without needing to start a separate web-server process. How do I set up a mock environment using restish to do this?</p>
<p>Thanks</p>
| 1 | 2009-07-13T21:30:39Z | 1,132,247 | <p>Restish has a built in TestApp class that can be used to test restish apps.
Assuming you have a "test" dir in your root restish project callte "restest" created with <a href="http://pythonpaste.org/script/" rel="nofollow">paster</a>.</p>
<pre><code>import os
import unittest
from paste.fixture import TestApp
class RootTest (unittest.TestCase):
def setUp(self):
self.app = TestApp('config:%s/../development.ini' % os.path.dirname(os.path.abspath(__file__)))
def tearDown(self):
self.app = None
def test_html(self):
res = self.app.get('/')
res.mustcontain('Hello from restest!')
if __name__ == '__main__':
unittest.main()
</code></pre>
| 1 | 2009-07-15T15:46:43Z | [
"python",
"unit-testing"
] |
Which revision of html5lib is stable? | 1,122,494 | <p><a href="http://code.google.com/p/html5lib/" rel="nofollow">html5lib</a> notes that it's latest release (0.11) is somewhat old. Using the Python portion, I have recursion problems as noted in <a href="http://code.google.com/p/html5lib/issues/detail?id=70" rel="nofollow">Issue 70</a> and <a href="http://code.google.com/p/html5lib/issues/detail?id=59" rel="nofollow">Issue 59</a> but can't find a recent Mercurial revision that is stable.</p>
<p>The latest tip is no good, I got the following error from <code>python setup.py install</code>:</p>
<pre><code>byte-compiling build/bdist.linux-x86_64/egg/html5lib/treewalkers/_base.py to _base.pyc
File "build/bdist.linux-x86_64/egg/html5lib/treewalkers/_base.py", line 40
"data": []}
^
SyntaxError: invalid syntax
</code></pre>
<p>And I get the following errors at runtime:</p>
<pre><code> soup = parser.parse(page.read())
File "build/bdist.linux-x86_64/egg/html5lib/html5parser.py", line 165, in parse
File "build/bdist.linux-x86_64/egg/html5lib/html5parser.py", line 144, in _parse
File "build/bdist.linux-x86_64/egg/html5lib/html5parser.py", line 454, in processDoctype
TypeError: insertDoctype() takes exactly 4 arguments (2 given)
</code></pre>
<p>I'm using it on Python 2.5.2 with lxml and BeautifulSoup.</p>
| 2 | 2009-07-13T22:42:51Z | 4,365,917 | <p>As of January 2010, it looks like version 0.90 is what you want:</p>
<p><a href="http://code.google.com/p/html5lib/downloads/list" rel="nofollow">http://code.google.com/p/html5lib/downloads/list</a></p>
| 1 | 2010-12-06T11:30:53Z | [
"python",
"html5lib"
] |
What can I attach to pylons.request in Pylons? | 1,122,537 | <p>I want keep track of a unique identifier for each browser that connects to my web application (that is written in Pylons.) I keep a cookie on the client to keep track of this, but if the cookie isn't present, then I want to generate a new unique identifier that will be sent back to the client with the response, but I also may want to access this value from other code used to generate the response.</p>
<p>Is attaching this value to pylons.request safe? Or do I need to do something like use threading_local to make a thread local that I reset when each new request is handled?</p>
| 2 | 2009-07-13T22:53:56Z | 1,126,737 | <p><em>Why</em> do you want a unique identifier? Basically every visitor already gets a unique identifier, his Session. <a href="http://pypi.python.org/pypi/Beaker/" rel="nofollow">Beaker</a>, Pylons session and caching middleware, does all the work and tracks visitors, usually with a Session cookie. So don't care about tracking users, just use the Session for what it's made for, to store whatever user specific stuff you have .</p>
<pre><code>from pylons import session
session["something"] = whatever()
session.save()
# somewhen later
something = session["something"]
</code></pre>
| 3 | 2009-07-14T17:07:34Z | [
"python",
"thread-safety",
"pylons"
] |
What can I attach to pylons.request in Pylons? | 1,122,537 | <p>I want keep track of a unique identifier for each browser that connects to my web application (that is written in Pylons.) I keep a cookie on the client to keep track of this, but if the cookie isn't present, then I want to generate a new unique identifier that will be sent back to the client with the response, but I also may want to access this value from other code used to generate the response.</p>
<p>Is attaching this value to pylons.request safe? Or do I need to do something like use threading_local to make a thread local that I reset when each new request is handled?</p>
| 2 | 2009-07-13T22:53:56Z | 1,128,979 | <p>Whatever you were to set on the request will only survive for the duration of the request. the problem you are describing is more appropriately handled with a Session as TCH4k has said. It's already enabled in the middleware, so go ahead.</p>
| 0 | 2009-07-15T01:43:11Z | [
"python",
"thread-safety",
"pylons"
] |
Django ManyToMany Template rendering and performance issues | 1,122,605 | <p>I've got a django model that contains a manytomany relationship, of the type,</p>
<pre><code>class MyModel(models.Model):
name = ..
refby = models.ManyToManyField(MyModel2)
..
class MyModel2(..):
name = ..
date = ..
</code></pre>
<p>I need to render it in my template such that I am able to render all the mymodel2 objects that refer to mymodel. Currently, I do something like the following,</p>
<pre><code>{% for i in mymodel_obj_list %}
{{i.name}}
{% for m in i.refby.all|dictsortreversed:"date"|slice:"3" %}
{{.. }}
{% endfor %}
<div> <!--This div toggles hidden/visible, shows next 12-->
{% for n in i.refby.all|dictsortreversed:"date"|slice:"3:15" %}
{{.. }}
{% endfor %}
</div>
{% endfor %}
</code></pre>
<p>As the code suggests, I only want to show the latest 3 mymodel2 objects, sorted in reverse order by date, although the next 12 do get loaded.</p>
<p>Is this a very inefficient method of doing so? (Given that results for the refby.all could be a few 100s, and the total no of results in "mymodel_obj_list" is also in 100s - I use a paginator there).</p>
<p>In which case, whats the best method to pre-compute these refby's and render them to the template? Should I do the sorting and computation in the view, and then pass it? I wasn't sure how to do this in order to maintain my pagination.</p>
<p>View code looks something like,</p>
<pre><code>obj_list = Table.objects.filter(..) # Few 100 records
pl = CustomPaginatorClass(obj_list...)
</code></pre>
<p>And I pass the pl to the page as mymodel_obj_list.</p>
<p>Thanks!</p>
| 3 | 2009-07-13T23:09:48Z | 1,122,693 | <blockquote>
<p>Should I do the sorting and
computation in the view, and then pass
it?</p>
</blockquote>
<p>Yes, definitely.</p>
<p>It is not really a matter of performance (as Django's querysets are lazily evaluated, I suspect the final performance could be very similar in both cases) but of code organization.<br />
Templates should not contain any business logic, only presentation. Of course, sometimes this model breaks down, but in general you should try as much as possible to keep into that direction.</p>
| 0 | 2009-07-13T23:34:23Z | [
"python",
"django",
"performance",
"django-templates",
"many-to-many"
] |
Django ManyToMany Template rendering and performance issues | 1,122,605 | <p>I've got a django model that contains a manytomany relationship, of the type,</p>
<pre><code>class MyModel(models.Model):
name = ..
refby = models.ManyToManyField(MyModel2)
..
class MyModel2(..):
name = ..
date = ..
</code></pre>
<p>I need to render it in my template such that I am able to render all the mymodel2 objects that refer to mymodel. Currently, I do something like the following,</p>
<pre><code>{% for i in mymodel_obj_list %}
{{i.name}}
{% for m in i.refby.all|dictsortreversed:"date"|slice:"3" %}
{{.. }}
{% endfor %}
<div> <!--This div toggles hidden/visible, shows next 12-->
{% for n in i.refby.all|dictsortreversed:"date"|slice:"3:15" %}
{{.. }}
{% endfor %}
</div>
{% endfor %}
</code></pre>
<p>As the code suggests, I only want to show the latest 3 mymodel2 objects, sorted in reverse order by date, although the next 12 do get loaded.</p>
<p>Is this a very inefficient method of doing so? (Given that results for the refby.all could be a few 100s, and the total no of results in "mymodel_obj_list" is also in 100s - I use a paginator there).</p>
<p>In which case, whats the best method to pre-compute these refby's and render them to the template? Should I do the sorting and computation in the view, and then pass it? I wasn't sure how to do this in order to maintain my pagination.</p>
<p>View code looks something like,</p>
<pre><code>obj_list = Table.objects.filter(..) # Few 100 records
pl = CustomPaginatorClass(obj_list...)
</code></pre>
<p>And I pass the pl to the page as mymodel_obj_list.</p>
<p>Thanks!</p>
| 3 | 2009-07-13T23:09:48Z | 1,123,397 | <p>I assume <code>mymodel_obj_list</code> is a QuerySet. You're accessing a foreign key field inside the loop, which means, by default, Django will look up each object's refby one at a time, when you access it. If you're displaying a lot of rows, this is extremely slow.</p>
<p>Call select_related on the QuerySet, to pull in all of these foreign key fields in advance.</p>
<p><a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related</a></p>
| 4 | 2009-07-14T04:14:28Z | [
"python",
"django",
"performance",
"django-templates",
"many-to-many"
] |
List comprehension python | 1,122,612 | <p>What is the equivalent list comprehension in python of the following Common Lisp code:</p>
<pre><code>(loop for x = input then (if (evenp x)
(/ x 2)
(+1 (* 3 x)))
collect x
until (= x 1))
</code></pre>
| 2 | 2009-07-13T23:11:11Z | 1,122,652 | <p>1</p>
<p>I have discovered a truly marvelous proof of this, which this margin is too narrow to contain.</p>
<p>In all seriousness though, I don't believe you can do this with Python list comprehensions. They have basically the same power as map and filter, so you can't break out or look at previous values without resorting to hackery.</p>
| 0 | 2009-07-13T23:21:04Z | [
"python",
"lisp",
"list-comprehension"
] |
List comprehension python | 1,122,612 | <p>What is the equivalent list comprehension in python of the following Common Lisp code:</p>
<pre><code>(loop for x = input then (if (evenp x)
(/ x 2)
(+1 (* 3 x)))
collect x
until (= x 1))
</code></pre>
| 2 | 2009-07-13T23:11:11Z | 1,122,653 | <p>I believe you are writing the hailstone sequence, although I could be wrong since I am not fluent in Lisp.</p>
<p>As far as I know, you can't do this in only a list comprehension, since each element depends on the last.</p>
<p>How I would do it would be this</p>
<pre><code>def hailstone(n):
yield n
while n!=1
if n%2 == 0: # even
n = n / 2
else: # odd
n = 3 * n + 1
yield n
list = [ x for x in hailstone(input) ]
</code></pre>
<p>Of course, input would hold whatever your input was.</p>
<p>My hailstone function could probably be more concise. My goal was clarity.</p>
| 9 | 2009-07-13T23:21:24Z | [
"python",
"lisp",
"list-comprehension"
] |
List comprehension python | 1,122,612 | <p>What is the equivalent list comprehension in python of the following Common Lisp code:</p>
<pre><code>(loop for x = input then (if (evenp x)
(/ x 2)
(+1 (* 3 x)))
collect x
until (= x 1))
</code></pre>
| 2 | 2009-07-13T23:11:11Z | 1,122,663 | <p>A list comprehension is used to take an existing sequence and perform some function and/or filter to it, resulting in a new list. So, in this case a list comprehension is not appropriate since you don't have a starting sequence. An example with a while loop:</p>
<pre><code>numbers = []
x=input()
while x != 1:
numbers.append(x)
if x % 2 == 0: x /= 2
else: x = 3 * x + 1
</code></pre>
| 10 | 2009-07-13T23:24:13Z | [
"python",
"lisp",
"list-comprehension"
] |
List comprehension python | 1,122,612 | <p>What is the equivalent list comprehension in python of the following Common Lisp code:</p>
<pre><code>(loop for x = input then (if (evenp x)
(/ x 2)
(+1 (* 3 x)))
collect x
until (= x 1))
</code></pre>
| 2 | 2009-07-13T23:11:11Z | 1,122,731 | <p>As Kiv said, a list comprehension requires a known sequence to iterate over.</p>
<p>Having said that, if you had a sequence and were fixated on using a list comprehension, your solution would probably include something like this:</p>
<pre><code>[not (x % 2) and (x / 2) or (3 * x + 1) for x in sequence]
</code></pre>
<p>Mike Cooper's answer is a better solution because it both retains the <code>x != 1</code> termination, and this line doesn't read cleanly.</p>
| 3 | 2009-07-13T23:45:36Z | [
"python",
"lisp",
"list-comprehension"
] |
List comprehension python | 1,122,612 | <p>What is the equivalent list comprehension in python of the following Common Lisp code:</p>
<pre><code>(loop for x = input then (if (evenp x)
(/ x 2)
(+1 (* 3 x)))
collect x
until (= x 1))
</code></pre>
| 2 | 2009-07-13T23:11:11Z | 1,123,651 | <p>Python doesn't have this kind of control structure built in, but you can generalize this into a function like this:</p>
<pre><code>def unfold(evolve, initial, until):
state = initial
yield state
while not until(state):
state = evolve(state)
yield state
</code></pre>
<p>After this your expression can be written as:</p>
<pre><code>def is_even(n): return not n % 2
unfold(lambda x: x/2 if is_even(x) else 3*x + 1,
initial=input, until=lambda x: x == 1)
</code></pre>
<p>But the Pythonic way to do it is using a generator function:</p>
<pre><code>def produce(x):
yield x
while x != 1:
x = x / 2 if is_even(x) else 3*x + 1
yield x
</code></pre>
| 4 | 2009-07-14T05:51:10Z | [
"python",
"lisp",
"list-comprehension"
] |
List comprehension python | 1,122,612 | <p>What is the equivalent list comprehension in python of the following Common Lisp code:</p>
<pre><code>(loop for x = input then (if (evenp x)
(/ x 2)
(+1 (* 3 x)))
collect x
until (= x 1))
</code></pre>
| 2 | 2009-07-13T23:11:11Z | 1,126,359 | <p>The hackery referred to by Laurence:</p>
<p>You can do it in one list comprehension, it just ends up being AWFUL python. Unreadable python. Terrible python. I only present the following as a curiosity, not as an actual answer. Don't do this in code you actually want to use, only if you fancy having a play with the inner workings on python. </p>
<p>So, 3 approaches: </p>
<p><hr /></p>
<h2>Helping List 1</h2>
<p>1: Using a helping list, answer ends up in the helping list. This appends values to the list being iterated over until you've reached the value you want to stop at.</p>
<pre><code>A = [10]
print [None if A[-1] == 1
else A.append(A[-1]/2) if (A[-1]%2==0)
else A.append(3*A[-1]+1)
for i in A]
print A
</code></pre>
<p>result:</p>
<pre><code>[None, None, None, None, None, None, None]
[10, 5, 16, 8, 4, 2, 1]
</code></pre>
<p><hr /></p>
<h2>Helping List 2</h2>
<p>2: Using a helping list, but with the result being the output of the list comprehension. This mostly relies on <code>list.append(...)</code> returning <code>None</code>, <code>not None</code> evaluating as <code>True</code> and <code>True</code> being considered <code>1</code> for the purposes of arithmetic. Sigh.</p>
<pre><code>A=[10]
print [A[0]*(not A.append(A[0])) if len(A) == 1
else 1 if A[-1] == 2 else (A[-1]/2)*(not A.append(A[-1]/2)) if (A[-1]%2==0)
else (3*A[-1]+1)*(not A.append(3*A[-1]+1))
for i in A]
</code></pre>
<p>result:</p>
<pre><code>[10, 5, 16, 8, 4, 2, 1]
</code></pre>
<p><hr /></p>
<h2>Referencing the List Comprehension from within</h2>
<p>3: Not using a helping list, but referring back to the list comprehension as it's being built. This is a bit fragile, and probably wont work in all environments. If it doesn't work, try running the code on its own:</p>
<pre><code>from itertools import chain, takewhile
initialValue = 10
print [i if len(locals()['_[1]']) == 0
else (locals()['_[1]'][-1]/2) if (locals()['_[1]'][-1]%2==0)
else (3*locals()['_[1]'][-1]+1)
for i in takewhile(lambda x:x>1, chain([initialValue],locals()['_[1]']))]
</code></pre>
<p>result:</p>
<pre><code>[10, 5, 16, 8, 4, 2, 1]
</code></pre>
<p><hr /></p>
<p>So, now forget that you read this. This is dark, dark and dingy python. Evil python. And we all know python isn't evil. Python is lovely and nice. So you can't have read this, because this sort of thing can't exist. Good good. </p>
| 4 | 2009-07-14T15:55:53Z | [
"python",
"lisp",
"list-comprehension"
] |
Is it acceptable to use tricks to save programmer when putting data in your code? | 1,122,691 | <p>Example: It's really annoying to type a list of strings in python:</p>
<pre><code>["January", "February", "March", "April", ...]
</code></pre>
<p>I often do something like this to save me having to type quotation marks all over the place:</p>
<pre><code>"January February March April May June July August ...".split()
</code></pre>
<p>Those took the same amount of time, and I got 2x the # of months typed in. Another example:</p>
<pre><code>[('a', '9'), ('4', '3'), ('z', 'x')...]
</code></pre>
<p>instead of:</p>
<pre><code>map(tuple, "a9 43 zx".split())
</code></pre>
<p>which took much less time.</p>
| 9 | 2009-07-13T23:34:04Z | 1,122,705 | <p>I would find this acceptable, if a bit lazy, as long as what is being done isn't too performance critical. You could always go back and optimize it if you need more speed.</p>
| -2 | 2009-07-13T23:37:37Z | [
"python",
"coding-style"
] |
Is it acceptable to use tricks to save programmer when putting data in your code? | 1,122,691 | <p>Example: It's really annoying to type a list of strings in python:</p>
<pre><code>["January", "February", "March", "April", ...]
</code></pre>
<p>I often do something like this to save me having to type quotation marks all over the place:</p>
<pre><code>"January February March April May June July August ...".split()
</code></pre>
<p>Those took the same amount of time, and I got 2x the # of months typed in. Another example:</p>
<pre><code>[('a', '9'), ('4', '3'), ('z', 'x')...]
</code></pre>
<p>instead of:</p>
<pre><code>map(tuple, "a9 43 zx".split())
</code></pre>
<p>which took much less time.</p>
| 9 | 2009-07-13T23:34:04Z | 1,122,710 | <p>Code is usually read many times, and it is written only once.<br />
Saving writing time at the expense of readability is not usually a good choice, unless you are doing some throw-away code.</p>
<p>The second version is less explicit, and you need some time to understand what the code is doing. And we are simply talking about variable instantiation, not about algorithms!</p>
| 32 | 2009-07-13T23:38:17Z | [
"python",
"coding-style"
] |
Is it acceptable to use tricks to save programmer when putting data in your code? | 1,122,691 | <p>Example: It's really annoying to type a list of strings in python:</p>
<pre><code>["January", "February", "March", "April", ...]
</code></pre>
<p>I often do something like this to save me having to type quotation marks all over the place:</p>
<pre><code>"January February March April May June July August ...".split()
</code></pre>
<p>Those took the same amount of time, and I got 2x the # of months typed in. Another example:</p>
<pre><code>[('a', '9'), ('4', '3'), ('z', 'x')...]
</code></pre>
<p>instead of:</p>
<pre><code>map(tuple, "a9 43 zx".split())
</code></pre>
<p>which took much less time.</p>
| 9 | 2009-07-13T23:34:04Z | 1,122,719 | <p>In general, I think this is a bad idea. The first example isn't SO bad (it's sort of a substitute for python's lack of qw), but the second is much more difficult to understand. In particular, I think this sort of thing is very unpythonic, and certainly not appropriate when writing Python code, at any rate. Code readability is much more important than saving a little time writing the code. If you really have THAT much data to hardcode, write a script to generate it for you.</p>
| 5 | 2009-07-13T23:40:52Z | [
"python",
"coding-style"
] |
Is it acceptable to use tricks to save programmer when putting data in your code? | 1,122,691 | <p>Example: It's really annoying to type a list of strings in python:</p>
<pre><code>["January", "February", "March", "April", ...]
</code></pre>
<p>I often do something like this to save me having to type quotation marks all over the place:</p>
<pre><code>"January February March April May June July August ...".split()
</code></pre>
<p>Those took the same amount of time, and I got 2x the # of months typed in. Another example:</p>
<pre><code>[('a', '9'), ('4', '3'), ('z', 'x')...]
</code></pre>
<p>instead of:</p>
<pre><code>map(tuple, "a9 43 zx".split())
</code></pre>
<p>which took much less time.</p>
| 9 | 2009-07-13T23:34:04Z | 1,122,721 | <p>How often do you really need to type <code>["January", "February"... etc]</code>?</p>
<p>Granted your approach might save you time but why add complexity to your code for no good reason other than you are a bit lazy?</p>
<p>If you really do have to type it that often... Copy-Paste!</p>
| 3 | 2009-07-13T23:41:01Z | [
"python",
"coding-style"
] |
Is it acceptable to use tricks to save programmer when putting data in your code? | 1,122,691 | <p>Example: It's really annoying to type a list of strings in python:</p>
<pre><code>["January", "February", "March", "April", ...]
</code></pre>
<p>I often do something like this to save me having to type quotation marks all over the place:</p>
<pre><code>"January February March April May June July August ...".split()
</code></pre>
<p>Those took the same amount of time, and I got 2x the # of months typed in. Another example:</p>
<pre><code>[('a', '9'), ('4', '3'), ('z', 'x')...]
</code></pre>
<p>instead of:</p>
<pre><code>map(tuple, "a9 43 zx".split())
</code></pre>
<p>which took much less time.</p>
| 9 | 2009-07-13T23:34:04Z | 1,122,727 | <blockquote>
<p><em>...I often do something like this to save me having to type quotation marks all over the place...</em></p>
</blockquote>
<p>I think such a thing should be done only once per program. If you do the same "all over the place" then it doesn't matter which one do you use, you're creating a monster. </p>
<p>Such declaration should be written only ONCE for all the code. </p>
| 1 | 2009-07-13T23:42:18Z | [
"python",
"coding-style"
] |
Is it acceptable to use tricks to save programmer when putting data in your code? | 1,122,691 | <p>Example: It's really annoying to type a list of strings in python:</p>
<pre><code>["January", "February", "March", "April", ...]
</code></pre>
<p>I often do something like this to save me having to type quotation marks all over the place:</p>
<pre><code>"January February March April May June July August ...".split()
</code></pre>
<p>Those took the same amount of time, and I got 2x the # of months typed in. Another example:</p>
<pre><code>[('a', '9'), ('4', '3'), ('z', 'x')...]
</code></pre>
<p>instead of:</p>
<pre><code>map(tuple, "a9 43 zx".split())
</code></pre>
<p>which took much less time.</p>
| 9 | 2009-07-13T23:34:04Z | 1,122,728 | <p>It's a reasonable thing to do for data that you don't expect to change, such as months or days of the weeks. It's also reasonable to do this while mocking up or stubbing out interactions with files or databases, because it isolates your code for testing. However, this isn't a good long-term solution for production code, nor does it really save you much time. Anything big enough to allow big time-savings is big enough to require storing data someplace else, like a separate file o a database. </p>
| 1 | 2009-07-13T23:43:17Z | [
"python",
"coding-style"
] |
Is it acceptable to use tricks to save programmer when putting data in your code? | 1,122,691 | <p>Example: It's really annoying to type a list of strings in python:</p>
<pre><code>["January", "February", "March", "April", ...]
</code></pre>
<p>I often do something like this to save me having to type quotation marks all over the place:</p>
<pre><code>"January February March April May June July August ...".split()
</code></pre>
<p>Those took the same amount of time, and I got 2x the # of months typed in. Another example:</p>
<pre><code>[('a', '9'), ('4', '3'), ('z', 'x')...]
</code></pre>
<p>instead of:</p>
<pre><code>map(tuple, "a9 43 zx".split())
</code></pre>
<p>which took much less time.</p>
| 9 | 2009-07-13T23:34:04Z | 1,122,733 | <p>In production code, do it the right way. In test code, as long as this idiom shows up more than once or twice, I think this is acceptable. If, in test code, this situation shows up once or twice, do it the right way. </p>
| 3 | 2009-07-13T23:46:54Z | [
"python",
"coding-style"
] |
Is it acceptable to use tricks to save programmer when putting data in your code? | 1,122,691 | <p>Example: It's really annoying to type a list of strings in python:</p>
<pre><code>["January", "February", "March", "April", ...]
</code></pre>
<p>I often do something like this to save me having to type quotation marks all over the place:</p>
<pre><code>"January February March April May June July August ...".split()
</code></pre>
<p>Those took the same amount of time, and I got 2x the # of months typed in. Another example:</p>
<pre><code>[('a', '9'), ('4', '3'), ('z', 'x')...]
</code></pre>
<p>instead of:</p>
<pre><code>map(tuple, "a9 43 zx".split())
</code></pre>
<p>which took much less time.</p>
| 9 | 2009-07-13T23:34:04Z | 1,122,737 | <p>A good text editor can make these things a non-issue. For example, I can type the following line in my code:</p>
<pre><code>print `"January February March April May June July August September October November December".split()`
</code></pre>
<p>And then using the key sequence <code>V:!python<ENTER></code> I can run the line through the python interpreter, and the output is the following:</p>
<pre><code>['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
</code></pre>
<p>I'm using Vim for my example, but I'm sure this is just as easy with Emacs, TextMate, etc.</p>
| 19 | 2009-07-13T23:50:07Z | [
"python",
"coding-style"
] |
Is it acceptable to use tricks to save programmer when putting data in your code? | 1,122,691 | <p>Example: It's really annoying to type a list of strings in python:</p>
<pre><code>["January", "February", "March", "April", ...]
</code></pre>
<p>I often do something like this to save me having to type quotation marks all over the place:</p>
<pre><code>"January February March April May June July August ...".split()
</code></pre>
<p>Those took the same amount of time, and I got 2x the # of months typed in. Another example:</p>
<pre><code>[('a', '9'), ('4', '3'), ('z', 'x')...]
</code></pre>
<p>instead of:</p>
<pre><code>map(tuple, "a9 43 zx".split())
</code></pre>
<p>which took much less time.</p>
| 9 | 2009-07-13T23:34:04Z | 1,122,739 | <p>I don't think that type of thing should be in the source.</p>
<p>If I were you, I'd have Python evaluate the respective second versions and then paste the results into my source code.</p>
| 0 | 2009-07-13T23:50:29Z | [
"python",
"coding-style"
] |
Is it acceptable to use tricks to save programmer when putting data in your code? | 1,122,691 | <p>Example: It's really annoying to type a list of strings in python:</p>
<pre><code>["January", "February", "March", "April", ...]
</code></pre>
<p>I often do something like this to save me having to type quotation marks all over the place:</p>
<pre><code>"January February March April May June July August ...".split()
</code></pre>
<p>Those took the same amount of time, and I got 2x the # of months typed in. Another example:</p>
<pre><code>[('a', '9'), ('4', '3'), ('z', 'x')...]
</code></pre>
<p>instead of:</p>
<pre><code>map(tuple, "a9 43 zx".split())
</code></pre>
<p>which took much less time.</p>
| 9 | 2009-07-13T23:34:04Z | 1,122,788 | <p>In a reasonably smart editor you could:</p>
<ol>
<li>Select the lines of interest, </li>
<li>insert the replacement (<code><space></code> by "<code><space></code>" for the 1st ex.), </li>
<li>check selected lines checkbox, </li>
<li>click replace all,</li>
<li>bam.. your done.</li>
</ol>
<p>Readable <em>and</em> easy to type... respect the power of the editor!</p>
| 6 | 2009-07-14T00:05:54Z | [
"python",
"coding-style"
] |
Is it acceptable to use tricks to save programmer when putting data in your code? | 1,122,691 | <p>Example: It's really annoying to type a list of strings in python:</p>
<pre><code>["January", "February", "March", "April", ...]
</code></pre>
<p>I often do something like this to save me having to type quotation marks all over the place:</p>
<pre><code>"January February March April May June July August ...".split()
</code></pre>
<p>Those took the same amount of time, and I got 2x the # of months typed in. Another example:</p>
<pre><code>[('a', '9'), ('4', '3'), ('z', 'x')...]
</code></pre>
<p>instead of:</p>
<pre><code>map(tuple, "a9 43 zx".split())
</code></pre>
<p>which took much less time.</p>
| 9 | 2009-07-13T23:34:04Z | 1,124,082 | <p>I think putting statements like</p>
<p>"January February March April May June July August ...".split()</p>
<p>at module global level is fine. This way it is only executed once during import. I even sometimes use it in non-performance critical functions because of the reduced line noise. </p>
<p>On a sidenote i think that Python Interpreters could be made to execute the "split()" at compile-time which would eradicate the method-call overhead. Reason being that a string is a builtin literal and Python does not allow to add/override methods on the very base string type so the compiler can know that "".split() can only refer to one specific method. </p>
| 0 | 2009-07-14T08:00:08Z | [
"python",
"coding-style"
] |
Is it acceptable to use tricks to save programmer when putting data in your code? | 1,122,691 | <p>Example: It's really annoying to type a list of strings in python:</p>
<pre><code>["January", "February", "March", "April", ...]
</code></pre>
<p>I often do something like this to save me having to type quotation marks all over the place:</p>
<pre><code>"January February March April May June July August ...".split()
</code></pre>
<p>Those took the same amount of time, and I got 2x the # of months typed in. Another example:</p>
<pre><code>[('a', '9'), ('4', '3'), ('z', 'x')...]
</code></pre>
<p>instead of:</p>
<pre><code>map(tuple, "a9 43 zx".split())
</code></pre>
<p>which took much less time.</p>
| 9 | 2009-07-13T23:34:04Z | 1,139,963 | <p>I all but swear by <a href="http://www.powells.com/partner/24934/biblio/9780735619678" rel="nofollow">Steve McConnell's <em>Code Complete</em></a>: one of the core insights is that bad programmers write code in order to get computers to do something, period, while good programmers write first to write code that people can understand and only second to get the computer to do things.</p>
<p>(Having code that is written without readability as a major concern is like trying to find things in a closet or filing cabinet where people just cram stuff in without any thought to making something you can navigate and find things in.)</p>
<p>I think you could profit a lot from reading <em>Code Complete</em>; I know I did.</p>
| 1 | 2009-07-16T20:06:04Z | [
"python",
"coding-style"
] |
Is it acceptable to use tricks to save programmer when putting data in your code? | 1,122,691 | <p>Example: It's really annoying to type a list of strings in python:</p>
<pre><code>["January", "February", "March", "April", ...]
</code></pre>
<p>I often do something like this to save me having to type quotation marks all over the place:</p>
<pre><code>"January February March April May June July August ...".split()
</code></pre>
<p>Those took the same amount of time, and I got 2x the # of months typed in. Another example:</p>
<pre><code>[('a', '9'), ('4', '3'), ('z', 'x')...]
</code></pre>
<p>instead of:</p>
<pre><code>map(tuple, "a9 43 zx".split())
</code></pre>
<p>which took much less time.</p>
| 9 | 2009-07-13T23:34:04Z | 2,122,735 | <p>your quick and clever methods while nice, take more time to read which is not good. Readability comes first always. </p>
| 1 | 2010-01-23T09:45:26Z | [
"python",
"coding-style"
] |
bash/cygwin/$PATH: Do I really have to reboot to alter $PATH? | 1,122,924 | <p>I wanted to use the Python installed under cygwin rather than one installed under WinXP directly, so I edited ~/.bashrc and sourced it. Nothing changed. I tried other things, but nothing I did changed $PATH in any way. So I rebooted. Aha; now $PATH has changed to what I wanted.</p>
<p>But, can anyone explain WHY this happened? When do changes to the environment (and its variables) made via cygwin (and bash) take effect only after a reboot?</p>
<p>(Is this any way to run a railroad?) (This question is unlikely to win any points, but I'm curious, and I'm also tired of wading through docs which don't help on this point.)</p>
| 5 | 2009-07-14T00:45:44Z | 1,122,953 | <p>You may need to re-initialize bash's hashes after modifying the path variable:</p>
<pre><code>hash -r
</code></pre>
| 0 | 2009-07-14T00:57:32Z | [
"python",
"bash",
"path",
"cygwin",
"reboot"
] |
bash/cygwin/$PATH: Do I really have to reboot to alter $PATH? | 1,122,924 | <p>I wanted to use the Python installed under cygwin rather than one installed under WinXP directly, so I edited ~/.bashrc and sourced it. Nothing changed. I tried other things, but nothing I did changed $PATH in any way. So I rebooted. Aha; now $PATH has changed to what I wanted.</p>
<p>But, can anyone explain WHY this happened? When do changes to the environment (and its variables) made via cygwin (and bash) take effect only after a reboot?</p>
<p>(Is this any way to run a railroad?) (This question is unlikely to win any points, but I'm curious, and I'm also tired of wading through docs which don't help on this point.)</p>
| 5 | 2009-07-14T00:45:44Z | 1,122,991 | <p>Try:</p>
<pre><code>PATH="${PATH}:${PYTHON}"; export PATH
</code></pre>
<p>Or:</p>
<pre><code>export PATH="${PATH}:${PYTHON}"
</code></pre>
<p>the quotes preserve the spaces and newlines that you <strong><em>don't</em></strong> have in your directory names. I repeat <strong><em>"don't"</em></strong>.</p>
<p>If you want to change the path for the current environment and any subsequent processes, use something similar to either of the commands above; they are equivalent.</p>
<p>If you want to change the path for the next time you start Bash, edit <code>~/.bashrc</code> and add one of the above (for example) or edit the existing <code>PATH</code> setting command that you find there.</p>
<p>If you want to affect both the current environment and any subsequent ones (i.e. have an immediate and a "permanent" affect), edit <code>~/.bashrc</code> and do one of the following: type one of the first two forms shown above <strong>or</strong> source the <code>~/.bashrc</code> file. Sometimes, you may not want to do the sourcing if, for example, it would undo some temporary thing that you're making use of currently like have some other variables set differently than <code>~/.bashrc</code> would set (reset) them to.</p>
<p>I don't think you need to worry about hash unless you're either doing some serious rearranging or adding some local replacements for system utilities perhaps.</p>
| 3 | 2009-07-14T01:15:56Z | [
"python",
"bash",
"path",
"cygwin",
"reboot"
] |
bash/cygwin/$PATH: Do I really have to reboot to alter $PATH? | 1,122,924 | <p>I wanted to use the Python installed under cygwin rather than one installed under WinXP directly, so I edited ~/.bashrc and sourced it. Nothing changed. I tried other things, but nothing I did changed $PATH in any way. So I rebooted. Aha; now $PATH has changed to what I wanted.</p>
<p>But, can anyone explain WHY this happened? When do changes to the environment (and its variables) made via cygwin (and bash) take effect only after a reboot?</p>
<p>(Is this any way to run a railroad?) (This question is unlikely to win any points, but I'm curious, and I'm also tired of wading through docs which don't help on this point.)</p>
| 5 | 2009-07-14T00:45:44Z | 1,123,086 | <p>If you want your changes to be permanent, you should modify the proper file (.bashrc in this case) and perform ONE of the following actions:</p>
<ul>
<li>Restart the cygwin window</li>
<li>source .bashrc (This should work, even if is not working for you)</li>
<li>. .bashrc (that is dot <space> <filename>)</li>
</ul>
<p>However, .bashrc is used by default when using a BASH shell, so if you are using another shell (csh, ksh, zsh, etc) then your changes will not be reflected by modifying .bashrc.</p>
| 2 | 2009-07-14T01:55:17Z | [
"python",
"bash",
"path",
"cygwin",
"reboot"
] |
bash/cygwin/$PATH: Do I really have to reboot to alter $PATH? | 1,122,924 | <p>I wanted to use the Python installed under cygwin rather than one installed under WinXP directly, so I edited ~/.bashrc and sourced it. Nothing changed. I tried other things, but nothing I did changed $PATH in any way. So I rebooted. Aha; now $PATH has changed to what I wanted.</p>
<p>But, can anyone explain WHY this happened? When do changes to the environment (and its variables) made via cygwin (and bash) take effect only after a reboot?</p>
<p>(Is this any way to run a railroad?) (This question is unlikely to win any points, but I'm curious, and I'm also tired of wading through docs which don't help on this point.)</p>
| 5 | 2009-07-14T00:45:44Z | 1,123,139 | <p>A couple of things to try and rule out at least:</p>
<ol>
<li><p>Do you get the same behavior as the following from the shell? (Pasted from my cygwin, which works as expected.)</p>
<pre>
$ echo $PATH
/usr/local/bin:/usr/bin:/bin
$ export PATH=$PATH:/cygdrive/c/python/bin
$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/cygdrive/c/python/bin
</pre></li>
<li><p>Is your bashrc setting the PATH in a similar way to the above? (i.e. the second command).</p></li>
<li><p>Does your bashrc contain a "source" or "." command anywhere? (Maybe it's sourcing another file which overwrites your PATH variable.)</p></li>
</ol>
| 1 | 2009-07-14T02:16:47Z | [
"python",
"bash",
"path",
"cygwin",
"reboot"
] |
Does Python have anonymous classes? | 1,123,000 | <p>I'm wondering if Python has anything like the C# anonymous classes feature. To clarify, here's a sample C# snippet:</p>
<pre><code>var foo = new { x = 1, y = 2 };
var bar = new { y = 2, x = 1 };
foo.Equals(bar); // "true"
</code></pre>
<p>In Python, I would imagine something like this:</p>
<pre><code>foo = record(x = 1, y = 2)
bar = record(y = 2, x = 1)
foo == bar # true
</code></pre>
<p>The specific requirement is being able to create an object with specified fields in expression context (e.g. usable in lambdas and other places where statements aren't allowed), with no additional external declarations, and ability to access individual components by name via the normal member access syntax <code>foo.bar</code>. The created object should also implement structural comparison <em>by component names</em> (not by position, as tuples do).</p>
<p>In particular: tuples isn't it because their components are not named; classes isn't it because they require a declaration; dicts isn't it because they have undesired <code>foo["bar"]</code> syntax to access components.</p>
<p><a href="http://docs.python.org/library/collections.html?highlight=namedtuples#namedtuple-factory-function-for-tuples-with-named-fields">namedtuple</a> isn't it, because it still requires a name even if you define the type inline, and the comparison is position-based, not name-based. In particular:</p>
<pre><code> def foo(): return namedtuple("Foo", "x y")(x = 1, y = 2)
def bar(): return namedtuple("Foo", "y x")(x = 1, y = 2)
foo() == bar() # False because fields are compared in order, and not by name
# True would be desired instead
</code></pre>
<p>I know how to write such a thing in Python if needed. But I would like to know if there's anything like that in the Python standard library, or any popular third-party libraries.</p>
<h2>[EDIT]</h2>
<p>Just for the sake of it, here's a single-expression solution that combines two very informative answers by Ken and alanlcode, yielding structural equality without any extra outside declarations:</p>
<pre><code>type("", (), { \
"__init__": (lambda self, **kwargs: self.__dict__.update(kwargs)), \
"__eq__": (lambda self, other: self.__dict__ == other.__dict__) } \
)(x = 1, y = 2)
</code></pre>
<p>Technically, it satisfies all the requirements of the question, but I sincerely hope that no-one ever uses it (I definitely won't).</p>
| 51 | 2009-07-14T01:22:55Z | 1,123,026 | <p>The pythonic way would be to use a <code>dict</code>:</p>
<pre><code>>>> foo = dict(x=1, y=2)
>>> bar = dict(y=2, x=1)
>>> foo == bar
True
</code></pre>
<p>Meets all your requirements except that you still have to do <code>foo['x']</code> instead of <code>foo.x</code>. </p>
<p>If that's a problem, you could easily define a class such as:</p>
<pre><code>class Bunch(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
def __eq__(self, other):
return self.__dict__ == other.__dict__
</code></pre>
<p>Or, a nice and short one</p>
<pre><code>class Bunch(dict):
__getattr__, __setattr__ = dict.get, dict.__setitem__
</code></pre>
<p>(but note that this second one has problems as Alex points out in his comment!)</p>
| 37 | 2009-07-14T01:32:06Z | [
"python"
] |
Does Python have anonymous classes? | 1,123,000 | <p>I'm wondering if Python has anything like the C# anonymous classes feature. To clarify, here's a sample C# snippet:</p>
<pre><code>var foo = new { x = 1, y = 2 };
var bar = new { y = 2, x = 1 };
foo.Equals(bar); // "true"
</code></pre>
<p>In Python, I would imagine something like this:</p>
<pre><code>foo = record(x = 1, y = 2)
bar = record(y = 2, x = 1)
foo == bar # true
</code></pre>
<p>The specific requirement is being able to create an object with specified fields in expression context (e.g. usable in lambdas and other places where statements aren't allowed), with no additional external declarations, and ability to access individual components by name via the normal member access syntax <code>foo.bar</code>. The created object should also implement structural comparison <em>by component names</em> (not by position, as tuples do).</p>
<p>In particular: tuples isn't it because their components are not named; classes isn't it because they require a declaration; dicts isn't it because they have undesired <code>foo["bar"]</code> syntax to access components.</p>
<p><a href="http://docs.python.org/library/collections.html?highlight=namedtuples#namedtuple-factory-function-for-tuples-with-named-fields">namedtuple</a> isn't it, because it still requires a name even if you define the type inline, and the comparison is position-based, not name-based. In particular:</p>
<pre><code> def foo(): return namedtuple("Foo", "x y")(x = 1, y = 2)
def bar(): return namedtuple("Foo", "y x")(x = 1, y = 2)
foo() == bar() # False because fields are compared in order, and not by name
# True would be desired instead
</code></pre>
<p>I know how to write such a thing in Python if needed. But I would like to know if there's anything like that in the Python standard library, or any popular third-party libraries.</p>
<h2>[EDIT]</h2>
<p>Just for the sake of it, here's a single-expression solution that combines two very informative answers by Ken and alanlcode, yielding structural equality without any extra outside declarations:</p>
<pre><code>type("", (), { \
"__init__": (lambda self, **kwargs: self.__dict__.update(kwargs)), \
"__eq__": (lambda self, other: self.__dict__ == other.__dict__) } \
)(x = 1, y = 2)
</code></pre>
<p>Technically, it satisfies all the requirements of the question, but I sincerely hope that no-one ever uses it (I definitely won't).</p>
| 51 | 2009-07-14T01:22:55Z | 1,123,040 | <p>I don't remember offhand if there's a built-in but writing it yourself is shorter than typing your question. :-)</p>
<pre><code>class record(object):
def __init__(self, **kwargs): self.__dict__ = kwargs
def __eq__(self, r2): return self.__dict__ == r2.__dict__
def __ne__(self, r2): return self.__dict__ != r2.__dict__
foo = record(x=1, y=2)
bar = record(y=2, x=1)
foo == bar # => true
</code></pre>
| 6 | 2009-07-14T01:36:11Z | [
"python"
] |
Does Python have anonymous classes? | 1,123,000 | <p>I'm wondering if Python has anything like the C# anonymous classes feature. To clarify, here's a sample C# snippet:</p>
<pre><code>var foo = new { x = 1, y = 2 };
var bar = new { y = 2, x = 1 };
foo.Equals(bar); // "true"
</code></pre>
<p>In Python, I would imagine something like this:</p>
<pre><code>foo = record(x = 1, y = 2)
bar = record(y = 2, x = 1)
foo == bar # true
</code></pre>
<p>The specific requirement is being able to create an object with specified fields in expression context (e.g. usable in lambdas and other places where statements aren't allowed), with no additional external declarations, and ability to access individual components by name via the normal member access syntax <code>foo.bar</code>. The created object should also implement structural comparison <em>by component names</em> (not by position, as tuples do).</p>
<p>In particular: tuples isn't it because their components are not named; classes isn't it because they require a declaration; dicts isn't it because they have undesired <code>foo["bar"]</code> syntax to access components.</p>
<p><a href="http://docs.python.org/library/collections.html?highlight=namedtuples#namedtuple-factory-function-for-tuples-with-named-fields">namedtuple</a> isn't it, because it still requires a name even if you define the type inline, and the comparison is position-based, not name-based. In particular:</p>
<pre><code> def foo(): return namedtuple("Foo", "x y")(x = 1, y = 2)
def bar(): return namedtuple("Foo", "y x")(x = 1, y = 2)
foo() == bar() # False because fields are compared in order, and not by name
# True would be desired instead
</code></pre>
<p>I know how to write such a thing in Python if needed. But I would like to know if there's anything like that in the Python standard library, or any popular third-party libraries.</p>
<h2>[EDIT]</h2>
<p>Just for the sake of it, here's a single-expression solution that combines two very informative answers by Ken and alanlcode, yielding structural equality without any extra outside declarations:</p>
<pre><code>type("", (), { \
"__init__": (lambda self, **kwargs: self.__dict__.update(kwargs)), \
"__eq__": (lambda self, other: self.__dict__ == other.__dict__) } \
)(x = 1, y = 2)
</code></pre>
<p>Technically, it satisfies all the requirements of the question, but I sincerely hope that no-one ever uses it (I definitely won't).</p>
| 51 | 2009-07-14T01:22:55Z | 1,123,050 | <p>Quoted from <a href="http://norvig.com/python-iaq.html" rel="nofollow">this page</a>:</p>
<pre><code> class Struct:
def __init__(self, **entries): self.__dict__.update(entries)
def __eq__(self, other): return self.__dict__ == other.__dict__
def __neq__(self, other): return self.__dict__ != other.__dict__
options = Struct(answer=42, linelen = 80, font='courier')
options.answer
>>> 42
options.answer = 'plastics'
vars(options)
>>> {'answer': 'plastics', 'font': 'courier', 'linelen': 80}
</code></pre>
| 3 | 2009-07-14T01:40:01Z | [
"python"
] |
Does Python have anonymous classes? | 1,123,000 | <p>I'm wondering if Python has anything like the C# anonymous classes feature. To clarify, here's a sample C# snippet:</p>
<pre><code>var foo = new { x = 1, y = 2 };
var bar = new { y = 2, x = 1 };
foo.Equals(bar); // "true"
</code></pre>
<p>In Python, I would imagine something like this:</p>
<pre><code>foo = record(x = 1, y = 2)
bar = record(y = 2, x = 1)
foo == bar # true
</code></pre>
<p>The specific requirement is being able to create an object with specified fields in expression context (e.g. usable in lambdas and other places where statements aren't allowed), with no additional external declarations, and ability to access individual components by name via the normal member access syntax <code>foo.bar</code>. The created object should also implement structural comparison <em>by component names</em> (not by position, as tuples do).</p>
<p>In particular: tuples isn't it because their components are not named; classes isn't it because they require a declaration; dicts isn't it because they have undesired <code>foo["bar"]</code> syntax to access components.</p>
<p><a href="http://docs.python.org/library/collections.html?highlight=namedtuples#namedtuple-factory-function-for-tuples-with-named-fields">namedtuple</a> isn't it, because it still requires a name even if you define the type inline, and the comparison is position-based, not name-based. In particular:</p>
<pre><code> def foo(): return namedtuple("Foo", "x y")(x = 1, y = 2)
def bar(): return namedtuple("Foo", "y x")(x = 1, y = 2)
foo() == bar() # False because fields are compared in order, and not by name
# True would be desired instead
</code></pre>
<p>I know how to write such a thing in Python if needed. But I would like to know if there's anything like that in the Python standard library, or any popular third-party libraries.</p>
<h2>[EDIT]</h2>
<p>Just for the sake of it, here's a single-expression solution that combines two very informative answers by Ken and alanlcode, yielding structural equality without any extra outside declarations:</p>
<pre><code>type("", (), { \
"__init__": (lambda self, **kwargs: self.__dict__.update(kwargs)), \
"__eq__": (lambda self, other: self.__dict__ == other.__dict__) } \
)(x = 1, y = 2)
</code></pre>
<p>Technically, it satisfies all the requirements of the question, but I sincerely hope that no-one ever uses it (I definitely won't).</p>
| 51 | 2009-07-14T01:22:55Z | 1,123,054 | <p>1) See <a href="http://uszla.me.uk/space/blog/2008/11/06">http://uszla.me.uk/space/blog/2008/11/06</a>. You can create an anonymous object with slightly ugly syntax by using the <code>type</code> built-in function:</p>
<pre><code> anon_object_2 = type("", (), {})()
</code></pre>
<p>where the 3rd parameter is the dict that will contain the fields of your object.</p>
<pre><code> foo = type("", (), dict(y=1))()
foo.y == 1
</code></pre>
<p>2) Another variation is proposed by Peter Norvig at <a href="http://norvig.com/python-iaq.html">http://norvig.com/python-iaq.html</a>. It is also similar to the answer posted by Ken.</p>
<pre><code>class Struct:
def __init__(self, **entries): self.__dict__.update(entries)
>>> options = Struct(answer=42, linelen = 80, font='courier')
>>> options.answer
42
</code></pre>
<p>The benefit of this method is that you can implement equality by contents of the dict, which the first option doesn't have.</p>
| 19 | 2009-07-14T01:40:29Z | [
"python"
] |
Does Python have anonymous classes? | 1,123,000 | <p>I'm wondering if Python has anything like the C# anonymous classes feature. To clarify, here's a sample C# snippet:</p>
<pre><code>var foo = new { x = 1, y = 2 };
var bar = new { y = 2, x = 1 };
foo.Equals(bar); // "true"
</code></pre>
<p>In Python, I would imagine something like this:</p>
<pre><code>foo = record(x = 1, y = 2)
bar = record(y = 2, x = 1)
foo == bar # true
</code></pre>
<p>The specific requirement is being able to create an object with specified fields in expression context (e.g. usable in lambdas and other places where statements aren't allowed), with no additional external declarations, and ability to access individual components by name via the normal member access syntax <code>foo.bar</code>. The created object should also implement structural comparison <em>by component names</em> (not by position, as tuples do).</p>
<p>In particular: tuples isn't it because their components are not named; classes isn't it because they require a declaration; dicts isn't it because they have undesired <code>foo["bar"]</code> syntax to access components.</p>
<p><a href="http://docs.python.org/library/collections.html?highlight=namedtuples#namedtuple-factory-function-for-tuples-with-named-fields">namedtuple</a> isn't it, because it still requires a name even if you define the type inline, and the comparison is position-based, not name-based. In particular:</p>
<pre><code> def foo(): return namedtuple("Foo", "x y")(x = 1, y = 2)
def bar(): return namedtuple("Foo", "y x")(x = 1, y = 2)
foo() == bar() # False because fields are compared in order, and not by name
# True would be desired instead
</code></pre>
<p>I know how to write such a thing in Python if needed. But I would like to know if there's anything like that in the Python standard library, or any popular third-party libraries.</p>
<h2>[EDIT]</h2>
<p>Just for the sake of it, here's a single-expression solution that combines two very informative answers by Ken and alanlcode, yielding structural equality without any extra outside declarations:</p>
<pre><code>type("", (), { \
"__init__": (lambda self, **kwargs: self.__dict__.update(kwargs)), \
"__eq__": (lambda self, other: self.__dict__ == other.__dict__) } \
)(x = 1, y = 2)
</code></pre>
<p>Technically, it satisfies all the requirements of the question, but I sincerely hope that no-one ever uses it (I definitely won't).</p>
| 51 | 2009-07-14T01:22:55Z | 1,123,114 | <p>The type(...) form will fail the structural comparison requirement (without getting really ugly). The dict(...) form doesn't meet the attribute accessor requirement.</p>
<p>The <a href="http://code.activestate.com/recipes/361668/">attrdict</a> seems to fall in the middle somewhere:</p>
<pre><code>class attrdict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self
a = attrdict(x=1, y=2)
b = attrdict(y=2, x=1)
print a.x, a.y
print b.x, b.y
print a == b
</code></pre>
<p>But it means defining a special class.</p>
<p>OK, I just noticed the update to the question. I'll just note that you can specify <code>dict</code> for the bases parameter and only need to specify the constructor then (in the icky type expression). I prefer attrdict. :-)</p>
| 6 | 2009-07-14T02:07:20Z | [
"python"
] |
Does Python have anonymous classes? | 1,123,000 | <p>I'm wondering if Python has anything like the C# anonymous classes feature. To clarify, here's a sample C# snippet:</p>
<pre><code>var foo = new { x = 1, y = 2 };
var bar = new { y = 2, x = 1 };
foo.Equals(bar); // "true"
</code></pre>
<p>In Python, I would imagine something like this:</p>
<pre><code>foo = record(x = 1, y = 2)
bar = record(y = 2, x = 1)
foo == bar # true
</code></pre>
<p>The specific requirement is being able to create an object with specified fields in expression context (e.g. usable in lambdas and other places where statements aren't allowed), with no additional external declarations, and ability to access individual components by name via the normal member access syntax <code>foo.bar</code>. The created object should also implement structural comparison <em>by component names</em> (not by position, as tuples do).</p>
<p>In particular: tuples isn't it because their components are not named; classes isn't it because they require a declaration; dicts isn't it because they have undesired <code>foo["bar"]</code> syntax to access components.</p>
<p><a href="http://docs.python.org/library/collections.html?highlight=namedtuples#namedtuple-factory-function-for-tuples-with-named-fields">namedtuple</a> isn't it, because it still requires a name even if you define the type inline, and the comparison is position-based, not name-based. In particular:</p>
<pre><code> def foo(): return namedtuple("Foo", "x y")(x = 1, y = 2)
def bar(): return namedtuple("Foo", "y x")(x = 1, y = 2)
foo() == bar() # False because fields are compared in order, and not by name
# True would be desired instead
</code></pre>
<p>I know how to write such a thing in Python if needed. But I would like to know if there's anything like that in the Python standard library, or any popular third-party libraries.</p>
<h2>[EDIT]</h2>
<p>Just for the sake of it, here's a single-expression solution that combines two very informative answers by Ken and alanlcode, yielding structural equality without any extra outside declarations:</p>
<pre><code>type("", (), { \
"__init__": (lambda self, **kwargs: self.__dict__.update(kwargs)), \
"__eq__": (lambda self, other: self.__dict__ == other.__dict__) } \
)(x = 1, y = 2)
</code></pre>
<p>Technically, it satisfies all the requirements of the question, but I sincerely hope that no-one ever uses it (I definitely won't).</p>
| 51 | 2009-07-14T01:22:55Z | 13,828,824 | <p>Looks like Python 3.3 has added exactly this thing in the form of <a href="http://docs.python.org/3/library/types.html#types.SimpleNamespace"><code>types.SimpleNamespace</code></a> class.</p>
| 12 | 2012-12-11T21:29:13Z | [
"python"
] |
Does Python have anonymous classes? | 1,123,000 | <p>I'm wondering if Python has anything like the C# anonymous classes feature. To clarify, here's a sample C# snippet:</p>
<pre><code>var foo = new { x = 1, y = 2 };
var bar = new { y = 2, x = 1 };
foo.Equals(bar); // "true"
</code></pre>
<p>In Python, I would imagine something like this:</p>
<pre><code>foo = record(x = 1, y = 2)
bar = record(y = 2, x = 1)
foo == bar # true
</code></pre>
<p>The specific requirement is being able to create an object with specified fields in expression context (e.g. usable in lambdas and other places where statements aren't allowed), with no additional external declarations, and ability to access individual components by name via the normal member access syntax <code>foo.bar</code>. The created object should also implement structural comparison <em>by component names</em> (not by position, as tuples do).</p>
<p>In particular: tuples isn't it because their components are not named; classes isn't it because they require a declaration; dicts isn't it because they have undesired <code>foo["bar"]</code> syntax to access components.</p>
<p><a href="http://docs.python.org/library/collections.html?highlight=namedtuples#namedtuple-factory-function-for-tuples-with-named-fields">namedtuple</a> isn't it, because it still requires a name even if you define the type inline, and the comparison is position-based, not name-based. In particular:</p>
<pre><code> def foo(): return namedtuple("Foo", "x y")(x = 1, y = 2)
def bar(): return namedtuple("Foo", "y x")(x = 1, y = 2)
foo() == bar() # False because fields are compared in order, and not by name
# True would be desired instead
</code></pre>
<p>I know how to write such a thing in Python if needed. But I would like to know if there's anything like that in the Python standard library, or any popular third-party libraries.</p>
<h2>[EDIT]</h2>
<p>Just for the sake of it, here's a single-expression solution that combines two very informative answers by Ken and alanlcode, yielding structural equality without any extra outside declarations:</p>
<pre><code>type("", (), { \
"__init__": (lambda self, **kwargs: self.__dict__.update(kwargs)), \
"__eq__": (lambda self, other: self.__dict__ == other.__dict__) } \
)(x = 1, y = 2)
</code></pre>
<p>Technically, it satisfies all the requirements of the question, but I sincerely hope that no-one ever uses it (I definitely won't).</p>
| 51 | 2009-07-14T01:22:55Z | 30,543,074 | <p>If you want the instance to be anonymous as well (using the object directly in an expression), then you're bound to use the type-expression. However in many cases the instance will not be anonymous, but assigned to a variable. This case can be handled in a reasonable way in python by using metaclasses or decorators. </p>
<p>An example using decorator:</p>
<pre><code>def anonymous(cls):
return cls()
@anonymous
class foo:
x = 42
def bar(self):
return self.x
</code></pre>
<p>The decorator in this case causes the class <code>foo</code> to be instantiated an put into the variable <code>foo</code> instead of the class itself. The class itself will not be accessible from any namespace although it has a name:</p>
<pre><code>>>> foo
<__main__.foo instance at 0x7fd2938d8320>
>>> foo.bar()
42
</code></pre>
<p>Another feature in python that accomodates for many use cases is that it's legal to define classes locally, which means that they would become a symbol local to that function, which in turns gives it some degree of anonymity.</p>
| 1 | 2015-05-30T06:28:17Z | [
"python"
] |
Python Function Decorators in Google App Engine | 1,123,117 | <p>I'm having trouble using python function decorators in Google's AppEngine. I'm not that familiar with decorators, but they seem useful in web programming when you might want to force a user to login before executing certain functions. </p>
<p>Anyway, I was following along with a flickr login example <a href="http://stuvel.eu/flickrapi/documentation/#example-using-django" rel="nofollow">here</a> that uses django and decorates a function to require the flickr login. I can't seem to get this type of decorator to work in AppEngine.</p>
<p>I've boiled it down to this:</p>
<pre><code>def require_auth(func):
def check_auth(*args, **kwargs):
print "Authenticated."
return func(*args, **kwargs)
return check_auth
@require_auth
def content():
print "Release sensitive data!"
content()
</code></pre>
<p>This code works from the commandline, but when I run it in GoogleAppEngineLauncher (OS X), I get the following error:</p>
<pre><code>check_auth() takes at least 1 argument (0 given)
</code></pre>
<p>And I'm not really sure why...</p>
<p>EDIT to include actual code:
@asperous.us I changed the definition of content() to include variable arguments, is that what you meant?
@Alex Martelli, 'print' does work within AppEngine, but still a completely fair criticism.
Like I said, I'm trying to use the flickr login from the link above. I tried to put it into my app like so:</p>
<pre><code>def require_flickr_auth(view):
def protected_view(request,*args, **kwargs):
if 'token' in request.session:
token = request.session['token']
log.info('Getting token from session: %s' % token)
else:
token = None
log.info('No token in session')
f = flickrapi.FlickrAPI(api_key, api_secret,
token=token, store_token=False)
if token:
# We have a token, but it might not be valid
log.info('Verifying token')
try:
f.auth_checkToken()
except flickrapi.FlickrError:
token = None
del request.session['token']
if not token:
# No valid token, so redirect to Flickr
log.info('Redirecting user to Flickr to get frob')
url = f.web_login_url(perms='read')
print "Redirect to %s" % url
# If the token is valid, we can call the decorated view.
log.info('Token is valid')
return view(request,*args, **kwargs)
return protected_view
@require_flickr_auth
def content(*args, **kwargs):
print 'Welcome, oh authenticated user!'
def main():
print 'Content-Type: text/plain'
content()
if __name__ == "__main__":
main()
</code></pre>
<p>When I remove the @require_flickr_auth decoration, the string 'Welcome ...' prints out just fine. Otherwise I get a big ugly AppEngine exception page with </p>
<pre><code>type 'exceptions.TypeError': protected_view() takes at least 1 argument (0 given)
</code></pre>
<p>at the bottom.</p>
| 2 | 2009-07-14T02:08:38Z | 1,123,126 | <p>Decorators were added in python 2.4 (I think), maybe googleapp is using an older version?
You can also do:</p>
<pre><code>def content():
print "Release sensitive data!"
content = require_auth(content)
</code></pre>
<p>it will do the same thing as the decorator, it is just a little more work.</p>
| 0 | 2009-07-14T02:11:27Z | [
"python",
"google-app-engine",
"decorator"
] |
Python Function Decorators in Google App Engine | 1,123,117 | <p>I'm having trouble using python function decorators in Google's AppEngine. I'm not that familiar with decorators, but they seem useful in web programming when you might want to force a user to login before executing certain functions. </p>
<p>Anyway, I was following along with a flickr login example <a href="http://stuvel.eu/flickrapi/documentation/#example-using-django" rel="nofollow">here</a> that uses django and decorates a function to require the flickr login. I can't seem to get this type of decorator to work in AppEngine.</p>
<p>I've boiled it down to this:</p>
<pre><code>def require_auth(func):
def check_auth(*args, **kwargs):
print "Authenticated."
return func(*args, **kwargs)
return check_auth
@require_auth
def content():
print "Release sensitive data!"
content()
</code></pre>
<p>This code works from the commandline, but when I run it in GoogleAppEngineLauncher (OS X), I get the following error:</p>
<pre><code>check_auth() takes at least 1 argument (0 given)
</code></pre>
<p>And I'm not really sure why...</p>
<p>EDIT to include actual code:
@asperous.us I changed the definition of content() to include variable arguments, is that what you meant?
@Alex Martelli, 'print' does work within AppEngine, but still a completely fair criticism.
Like I said, I'm trying to use the flickr login from the link above. I tried to put it into my app like so:</p>
<pre><code>def require_flickr_auth(view):
def protected_view(request,*args, **kwargs):
if 'token' in request.session:
token = request.session['token']
log.info('Getting token from session: %s' % token)
else:
token = None
log.info('No token in session')
f = flickrapi.FlickrAPI(api_key, api_secret,
token=token, store_token=False)
if token:
# We have a token, but it might not be valid
log.info('Verifying token')
try:
f.auth_checkToken()
except flickrapi.FlickrError:
token = None
del request.session['token']
if not token:
# No valid token, so redirect to Flickr
log.info('Redirecting user to Flickr to get frob')
url = f.web_login_url(perms='read')
print "Redirect to %s" % url
# If the token is valid, we can call the decorated view.
log.info('Token is valid')
return view(request,*args, **kwargs)
return protected_view
@require_flickr_auth
def content(*args, **kwargs):
print 'Welcome, oh authenticated user!'
def main():
print 'Content-Type: text/plain'
content()
if __name__ == "__main__":
main()
</code></pre>
<p>When I remove the @require_flickr_auth decoration, the string 'Welcome ...' prints out just fine. Otherwise I get a big ugly AppEngine exception page with </p>
<pre><code>type 'exceptions.TypeError': protected_view() takes at least 1 argument (0 given)
</code></pre>
<p>at the bottom.</p>
| 2 | 2009-07-14T02:08:38Z | 1,123,162 | <p>@Owen, the "takes at least 1 argument" error suggests you're defining content within a class (i.e. as a method) and not as a bare function as you show -- indeed, how exactly are you trying to execute that code in GAE? I.e. what's your app.yaml &c? If you put your code exactly as you gave it in <code>silly.py</code> and in your app.yaml you have:</p>
<pre><code>handlers:
- url: /silly
script: silly.py
</code></pre>
<p>then when you visit <code>yourapp.appspot.com/silly</code> you will see absolutely nothing on either the browser or the logs (besides the <code>"GET /silly HTTP/1.1" 200 -</code> in the latter of course;-): there is no error but the <code>print</code> doesn't DO anything in particular either. So I have to imagine you tried running code different from what you're showing us...!-)</p>
| 1 | 2009-07-14T02:24:34Z | [
"python",
"google-app-engine",
"decorator"
] |
Python Function Decorators in Google App Engine | 1,123,117 | <p>I'm having trouble using python function decorators in Google's AppEngine. I'm not that familiar with decorators, but they seem useful in web programming when you might want to force a user to login before executing certain functions. </p>
<p>Anyway, I was following along with a flickr login example <a href="http://stuvel.eu/flickrapi/documentation/#example-using-django" rel="nofollow">here</a> that uses django and decorates a function to require the flickr login. I can't seem to get this type of decorator to work in AppEngine.</p>
<p>I've boiled it down to this:</p>
<pre><code>def require_auth(func):
def check_auth(*args, **kwargs):
print "Authenticated."
return func(*args, **kwargs)
return check_auth
@require_auth
def content():
print "Release sensitive data!"
content()
</code></pre>
<p>This code works from the commandline, but when I run it in GoogleAppEngineLauncher (OS X), I get the following error:</p>
<pre><code>check_auth() takes at least 1 argument (0 given)
</code></pre>
<p>And I'm not really sure why...</p>
<p>EDIT to include actual code:
@asperous.us I changed the definition of content() to include variable arguments, is that what you meant?
@Alex Martelli, 'print' does work within AppEngine, but still a completely fair criticism.
Like I said, I'm trying to use the flickr login from the link above. I tried to put it into my app like so:</p>
<pre><code>def require_flickr_auth(view):
def protected_view(request,*args, **kwargs):
if 'token' in request.session:
token = request.session['token']
log.info('Getting token from session: %s' % token)
else:
token = None
log.info('No token in session')
f = flickrapi.FlickrAPI(api_key, api_secret,
token=token, store_token=False)
if token:
# We have a token, but it might not be valid
log.info('Verifying token')
try:
f.auth_checkToken()
except flickrapi.FlickrError:
token = None
del request.session['token']
if not token:
# No valid token, so redirect to Flickr
log.info('Redirecting user to Flickr to get frob')
url = f.web_login_url(perms='read')
print "Redirect to %s" % url
# If the token is valid, we can call the decorated view.
log.info('Token is valid')
return view(request,*args, **kwargs)
return protected_view
@require_flickr_auth
def content(*args, **kwargs):
print 'Welcome, oh authenticated user!'
def main():
print 'Content-Type: text/plain'
content()
if __name__ == "__main__":
main()
</code></pre>
<p>When I remove the @require_flickr_auth decoration, the string 'Welcome ...' prints out just fine. Otherwise I get a big ugly AppEngine exception page with </p>
<pre><code>type 'exceptions.TypeError': protected_view() takes at least 1 argument (0 given)
</code></pre>
<p>at the bottom.</p>
| 2 | 2009-07-14T02:08:38Z | 1,123,174 | <p>Why</p>
<p><code>return func(*args, **kwargs)</code></p>
<p>wouldn't that execute func and then return the result?</p>
<p>If so, you shouldn't give it any arguments, since it doesn't take any. If you edited content() and added the <code>(*args, **kwargs)</code> arguments onto it, will it work?</p>
| 0 | 2009-07-14T02:28:38Z | [
"python",
"google-app-engine",
"decorator"
] |
Python Function Decorators in Google App Engine | 1,123,117 | <p>I'm having trouble using python function decorators in Google's AppEngine. I'm not that familiar with decorators, but they seem useful in web programming when you might want to force a user to login before executing certain functions. </p>
<p>Anyway, I was following along with a flickr login example <a href="http://stuvel.eu/flickrapi/documentation/#example-using-django" rel="nofollow">here</a> that uses django and decorates a function to require the flickr login. I can't seem to get this type of decorator to work in AppEngine.</p>
<p>I've boiled it down to this:</p>
<pre><code>def require_auth(func):
def check_auth(*args, **kwargs):
print "Authenticated."
return func(*args, **kwargs)
return check_auth
@require_auth
def content():
print "Release sensitive data!"
content()
</code></pre>
<p>This code works from the commandline, but when I run it in GoogleAppEngineLauncher (OS X), I get the following error:</p>
<pre><code>check_auth() takes at least 1 argument (0 given)
</code></pre>
<p>And I'm not really sure why...</p>
<p>EDIT to include actual code:
@asperous.us I changed the definition of content() to include variable arguments, is that what you meant?
@Alex Martelli, 'print' does work within AppEngine, but still a completely fair criticism.
Like I said, I'm trying to use the flickr login from the link above. I tried to put it into my app like so:</p>
<pre><code>def require_flickr_auth(view):
def protected_view(request,*args, **kwargs):
if 'token' in request.session:
token = request.session['token']
log.info('Getting token from session: %s' % token)
else:
token = None
log.info('No token in session')
f = flickrapi.FlickrAPI(api_key, api_secret,
token=token, store_token=False)
if token:
# We have a token, but it might not be valid
log.info('Verifying token')
try:
f.auth_checkToken()
except flickrapi.FlickrError:
token = None
del request.session['token']
if not token:
# No valid token, so redirect to Flickr
log.info('Redirecting user to Flickr to get frob')
url = f.web_login_url(perms='read')
print "Redirect to %s" % url
# If the token is valid, we can call the decorated view.
log.info('Token is valid')
return view(request,*args, **kwargs)
return protected_view
@require_flickr_auth
def content(*args, **kwargs):
print 'Welcome, oh authenticated user!'
def main():
print 'Content-Type: text/plain'
content()
if __name__ == "__main__":
main()
</code></pre>
<p>When I remove the @require_flickr_auth decoration, the string 'Welcome ...' prints out just fine. Otherwise I get a big ugly AppEngine exception page with </p>
<pre><code>type 'exceptions.TypeError': protected_view() takes at least 1 argument (0 given)
</code></pre>
<p>at the bottom.</p>
| 2 | 2009-07-14T02:08:38Z | 1,123,309 | <p>You're calling <code>content()</code> without any arguments, but the decorated version <code>protected_view</code> requires the <code>request</code> argument. Either add the argument to <code>content</code> or remove it from <code>protected_view</code>.</p>
<p>If you're getting that error with your simple version then I'd suspect that <code>content</code> is a class method as Alex suggested. Otherwise it looks like you're telling it to expect at least one argument, then not supplying it any.</p>
| 3 | 2009-07-14T03:26:23Z | [
"python",
"google-app-engine",
"decorator"
] |
How to lock a critical section in Django? | 1,123,200 | <p>I can't find a good clean way to lock a critical section in Django. I could use a lock or semaphore but the python implementation is for threads only, so if the production server forks then those will not be respected. Does anyone know of a way (I am thinking posix semaphores right now) to guarantee a lock across processes, or barring that a way to stop a Django server from forking.</p>
| 13 | 2009-07-14T02:44:26Z | 1,123,781 | <p>You could use simple file locking as a mutual exclusion mechanism, see my recipe <a href="http://code.activestate.com/recipes/519626/" rel="nofollow">here</a>. It won't suit all scenarios, but then you haven't said much about why you want to use this type of locking.</p>
| 4 | 2009-07-14T06:35:47Z | [
"python",
"django"
] |
How to lock a critical section in Django? | 1,123,200 | <p>I can't find a good clean way to lock a critical section in Django. I could use a lock or semaphore but the python implementation is for threads only, so if the production server forks then those will not be respected. Does anyone know of a way (I am thinking posix semaphores right now) to guarantee a lock across processes, or barring that a way to stop a Django server from forking.</p>
| 13 | 2009-07-14T02:44:26Z | 1,151,172 | <p>I ended up going with a solution I made myself involving file locking. If anyone here ends up using it remember that advisory locks and NFS don't mix well, so keep it local. Also, this is a blocking lock, if you want to mess around with loops and constantly checking back then there is instructions in the code.</p>
<pre><code>import os
import fcntl
class DjangoLock:
def __init__(self, filename):
self.filename = filename
# This will create it if it does not exist already
self.handle = open(filename, 'w')
# flock() is a blocking call unless it is bitwise ORed with LOCK_NB to avoid blocking
# on lock acquisition. This blocking is what I use to provide atomicity across forked
# Django processes since native python locks and semaphores only work at the thread level
def acquire(self):
fcntl.flock(self.handle, fcntl.LOCK_EX)
def release(self):
fcntl.flock(self.handle, fcntl.LOCK_UN)
def __del__(self):
self.handle.close()
Usage:
lock = DJangoLock('/tmp/djangolock.tmp')
lock.acquire()
try:
pass
finally:
lock.release()
</code></pre>
| 2 | 2009-07-19T23:29:59Z | [
"python",
"django"
] |
How to lock a critical section in Django? | 1,123,200 | <p>I can't find a good clean way to lock a critical section in Django. I could use a lock or semaphore but the python implementation is for threads only, so if the production server forks then those will not be respected. Does anyone know of a way (I am thinking posix semaphores right now) to guarantee a lock across processes, or barring that a way to stop a Django server from forking.</p>
| 13 | 2009-07-14T02:44:26Z | 1,151,797 | <p>You need a distributed lock manager at the point where your app suddenly needs to run on more than one service. I wrote <a href="http://github.com/dustin/elock">elock</a> for this purpose. There are <a href="http://hadoop.apache.org/zookeeper/">bigger ones</a> and others have chosen to ignore every suggestion and done the same with memcached.</p>
<p>Please don't use memcached for anything more than light advisory locking. It is designed to forget stuff.</p>
<p>I like to pretend like filesystems don't exist when I'm making web apps. Makes scale better.</p>
| 5 | 2009-07-20T05:10:29Z | [
"python",
"django"
] |
How to lock a critical section in Django? | 1,123,200 | <p>I can't find a good clean way to lock a critical section in Django. I could use a lock or semaphore but the python implementation is for threads only, so if the production server forks then those will not be respected. Does anyone know of a way (I am thinking posix semaphores right now) to guarantee a lock across processes, or barring that a way to stop a Django server from forking.</p>
| 13 | 2009-07-14T02:44:26Z | 4,317,995 | <p>If you use RDBMS, you can use its "LOCK" mechanism.
For example, while one "SELECT FOR UPDATE" transaction locks a row, the other "SELECT FOR UPDATE" transactions with the row must wait.</p>
<pre><code># You can use any Python DB API.
[SQL] BEGIN;
[SQL] SELECT col_name FROM table_name where id = 1 FOR UPDATE;
[Process some python code]
[SQL] COMMIT;
</code></pre>
| 13 | 2010-11-30T20:04:39Z | [
"python",
"django"
] |
How to lock a critical section in Django? | 1,123,200 | <p>I can't find a good clean way to lock a critical section in Django. I could use a lock or semaphore but the python implementation is for threads only, so if the production server forks then those will not be respected. Does anyone know of a way (I am thinking posix semaphores right now) to guarantee a lock across processes, or barring that a way to stop a Django server from forking.</p>
| 13 | 2009-07-14T02:44:26Z | 5,110,089 | <p>I did not write this article, but I found it supremely helpful faced with this same problem:</p>
<p><a href="http://chris-lamb.co.uk/2010/06/07/distributing-locking-python-and-redis/" rel="nofollow">http://chris-lamb.co.uk/2010/06/07/distributing-locking-python-and-redis/</a></p>
<p>Basically you use a Redis server to create a central server that exposes the locking functionality. </p>
| 2 | 2011-02-24T20:33:15Z | [
"python",
"django"
] |
How to lock a critical section in Django? | 1,123,200 | <p>I can't find a good clean way to lock a critical section in Django. I could use a lock or semaphore but the python implementation is for threads only, so if the production server forks then those will not be respected. Does anyone know of a way (I am thinking posix semaphores right now) to guarantee a lock across processes, or barring that a way to stop a Django server from forking.</p>
| 13 | 2009-07-14T02:44:26Z | 33,480,015 | <p>Use the Django builtin select_for_update function.<br>
<a href="https://docs.djangoproject.com/en/1.8/ref/models/querysets/#select-for-update">https://docs.djangoproject.com/en/1.8/ref/models/querysets/#select-for-update</a><br>
From the docs:<br>
Returns a queryset that will lock rows until the end of the transaction, generating a SELECT ... FOR UPDATE SQL statement on supported databases.</p>
<p>For example:</p>
<pre><code>entries = Entry.objects.select_for_update().filter(author=request.user)
</code></pre>
<p>All matched entries will be locked until the end of the transaction block, meaning that other transactions will be prevented from changing or acquiring locks on them.</p>
| 5 | 2015-11-02T14:33:54Z | [
"python",
"django"
] |
Django: Converting an entire set of a Model's objects into a single dictionary | 1,123,337 | <p><em>If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.</em></p>
<p>Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this:</p>
<pre><code>class DictModel(models.Model):
key = models.CharField(20)
value = models.CharField(200)
DictModel.objects.all().to_dict()
</code></pre>
<p>... with the result being a dictionary with the key/value pairs made up of records in the Model? Has anyone else seen this as being useful for them?</p>
<p>Thanks.<br />
<br />
<strong>Update</strong><br />
I just wanted to add is that my ultimate goal is to be able to do a simple variable lookup inside a Template. Something like:</p>
<pre><code>{{ DictModel.exampleKey }}
</code></pre>
<p>With a result of DictModel.objects.get(key__exact=exampleKey).value</p>
<p>Overall, though, you guys have really surprised me with how helpful allof your responses are, and how different the ways to approach it can be. Thanks a lot.
<br />
<br />
<strong>Update October 2011:</strong>
This question is the top result if you Google "django model_to_dict", which is actually pretty awful given that it solves a different problem than what I was asking.<br />
<br />
What I wanted was to be able to map all of the instances in a queryset into a single dictionary with a specified model field as the key.<br />
model_to_dict, on the other hand converts a single model instance into a dictionary.<br />
<br />
Now, my needs at the time were pretty darn specific, and probably extremely rare (I can't even remember the project I needed it for, or why). So I would be pretty surprised that anyone looking for information about model_to_dict is going to find my question actually useful. Sorry.<br />
<br />
model_to_dict seems to be a much more common usage case than I had.
<br />
<br />
<strong>Update Dec 2011:</strong><br />
I changed the title to hopefully better reflect my original intent.</p>
| 57 | 2009-07-14T03:35:53Z | 1,123,350 | <p>You are looking for the <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#values-fields">Values member of QuerySet</a> which allows you to get a list of dictionaries from your query</p>
<blockquote>
<p>Returns a ValuesQuerySet -- a QuerySet
that evaluates to a list of
dictionaries instead of model-instance
objects. Each of those dictionaries represents
an object, with the keys corresponding
to the attribute names of model
objects.</p>
</blockquote>
<pre><code>>>> Blog.objects.values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
>>> Blog.objects.values('id', 'name')
[{'id': 1, 'name': 'Beatles Blog'}]
</code></pre>
| 25 | 2009-07-14T03:42:17Z | [
"python",
"django",
"django-models",
"dictionary"
] |
Django: Converting an entire set of a Model's objects into a single dictionary | 1,123,337 | <p><em>If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.</em></p>
<p>Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this:</p>
<pre><code>class DictModel(models.Model):
key = models.CharField(20)
value = models.CharField(200)
DictModel.objects.all().to_dict()
</code></pre>
<p>... with the result being a dictionary with the key/value pairs made up of records in the Model? Has anyone else seen this as being useful for them?</p>
<p>Thanks.<br />
<br />
<strong>Update</strong><br />
I just wanted to add is that my ultimate goal is to be able to do a simple variable lookup inside a Template. Something like:</p>
<pre><code>{{ DictModel.exampleKey }}
</code></pre>
<p>With a result of DictModel.objects.get(key__exact=exampleKey).value</p>
<p>Overall, though, you guys have really surprised me with how helpful allof your responses are, and how different the ways to approach it can be. Thanks a lot.
<br />
<br />
<strong>Update October 2011:</strong>
This question is the top result if you Google "django model_to_dict", which is actually pretty awful given that it solves a different problem than what I was asking.<br />
<br />
What I wanted was to be able to map all of the instances in a queryset into a single dictionary with a specified model field as the key.<br />
model_to_dict, on the other hand converts a single model instance into a dictionary.<br />
<br />
Now, my needs at the time were pretty darn specific, and probably extremely rare (I can't even remember the project I needed it for, or why). So I would be pretty surprised that anyone looking for information about model_to_dict is going to find my question actually useful. Sorry.<br />
<br />
model_to_dict seems to be a much more common usage case than I had.
<br />
<br />
<strong>Update Dec 2011:</strong><br />
I changed the title to hopefully better reflect my original intent.</p>
| 57 | 2009-07-14T03:35:53Z | 1,123,354 | <p>use </p>
<pre><code>dict(((m.key, m.value) for m in DictModel.objects.all())
</code></pre>
<p>As suggested by Tom Leys, we do not need to get whole object, we can get only those values we need e.g.</p>
<pre><code>dict(((m['key'], m['value']) for m in DictModel.objects.values('key', 'value')))
</code></pre>
<p>and if you need all values, it is better to keep whole object in dict e.g.</p>
<pre><code>dict(((m.key, m) for m in DictModel.objects.all())
</code></pre>
| 5 | 2009-07-14T03:44:00Z | [
"python",
"django",
"django-models",
"dictionary"
] |
Django: Converting an entire set of a Model's objects into a single dictionary | 1,123,337 | <p><em>If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.</em></p>
<p>Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this:</p>
<pre><code>class DictModel(models.Model):
key = models.CharField(20)
value = models.CharField(200)
DictModel.objects.all().to_dict()
</code></pre>
<p>... with the result being a dictionary with the key/value pairs made up of records in the Model? Has anyone else seen this as being useful for them?</p>
<p>Thanks.<br />
<br />
<strong>Update</strong><br />
I just wanted to add is that my ultimate goal is to be able to do a simple variable lookup inside a Template. Something like:</p>
<pre><code>{{ DictModel.exampleKey }}
</code></pre>
<p>With a result of DictModel.objects.get(key__exact=exampleKey).value</p>
<p>Overall, though, you guys have really surprised me with how helpful allof your responses are, and how different the ways to approach it can be. Thanks a lot.
<br />
<br />
<strong>Update October 2011:</strong>
This question is the top result if you Google "django model_to_dict", which is actually pretty awful given that it solves a different problem than what I was asking.<br />
<br />
What I wanted was to be able to map all of the instances in a queryset into a single dictionary with a specified model field as the key.<br />
model_to_dict, on the other hand converts a single model instance into a dictionary.<br />
<br />
Now, my needs at the time were pretty darn specific, and probably extremely rare (I can't even remember the project I needed it for, or why). So I would be pretty surprised that anyone looking for information about model_to_dict is going to find my question actually useful. Sorry.<br />
<br />
model_to_dict seems to be a much more common usage case than I had.
<br />
<br />
<strong>Update Dec 2011:</strong><br />
I changed the title to hopefully better reflect my original intent.</p>
| 57 | 2009-07-14T03:35:53Z | 1,123,603 | <p>Does this need to create an actual dict? could you get by with only something that looked like a dict?</p>
<pre><code>class DictModelAdaptor():
def __init__(self, model):
self.model = model
def __getitem__(self, key):
return self.model.objects.get(key=key)
def __setitem__(self, key, item):
pair = self.model()
pair.key = key
pair.value = item
pair.save()
def __contains__(self, key):
...
</code></pre>
<p>You could then wrap a model in this way:</p>
<pre><code>modelDict = DictModelAdaptor(DictModel)
modelDict["name"] = "Bob Jones"
</code></pre>
<p>etc...</p>
| 15 | 2009-07-14T05:35:57Z | [
"python",
"django",
"django-models",
"dictionary"
] |
Django: Converting an entire set of a Model's objects into a single dictionary | 1,123,337 | <p><em>If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.</em></p>
<p>Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this:</p>
<pre><code>class DictModel(models.Model):
key = models.CharField(20)
value = models.CharField(200)
DictModel.objects.all().to_dict()
</code></pre>
<p>... with the result being a dictionary with the key/value pairs made up of records in the Model? Has anyone else seen this as being useful for them?</p>
<p>Thanks.<br />
<br />
<strong>Update</strong><br />
I just wanted to add is that my ultimate goal is to be able to do a simple variable lookup inside a Template. Something like:</p>
<pre><code>{{ DictModel.exampleKey }}
</code></pre>
<p>With a result of DictModel.objects.get(key__exact=exampleKey).value</p>
<p>Overall, though, you guys have really surprised me with how helpful allof your responses are, and how different the ways to approach it can be. Thanks a lot.
<br />
<br />
<strong>Update October 2011:</strong>
This question is the top result if you Google "django model_to_dict", which is actually pretty awful given that it solves a different problem than what I was asking.<br />
<br />
What I wanted was to be able to map all of the instances in a queryset into a single dictionary with a specified model field as the key.<br />
model_to_dict, on the other hand converts a single model instance into a dictionary.<br />
<br />
Now, my needs at the time were pretty darn specific, and probably extremely rare (I can't even remember the project I needed it for, or why). So I would be pretty surprised that anyone looking for information about model_to_dict is going to find my question actually useful. Sorry.<br />
<br />
model_to_dict seems to be a much more common usage case than I had.
<br />
<br />
<strong>Update Dec 2011:</strong><br />
I changed the title to hopefully better reflect my original intent.</p>
| 57 | 2009-07-14T03:35:53Z | 1,124,531 | <p>You can use the <code>python</code> <a href="http://docs.djangoproject.com/en/dev/topics/serialization">serializer</a>:</p>
<pre><code>from django.core import serializers
data = serializers.serialize('python', DictModel.objects.all())
</code></pre>
| 13 | 2009-07-14T10:19:23Z | [
"python",
"django",
"django-models",
"dictionary"
] |
Django: Converting an entire set of a Model's objects into a single dictionary | 1,123,337 | <p><em>If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.</em></p>
<p>Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this:</p>
<pre><code>class DictModel(models.Model):
key = models.CharField(20)
value = models.CharField(200)
DictModel.objects.all().to_dict()
</code></pre>
<p>... with the result being a dictionary with the key/value pairs made up of records in the Model? Has anyone else seen this as being useful for them?</p>
<p>Thanks.<br />
<br />
<strong>Update</strong><br />
I just wanted to add is that my ultimate goal is to be able to do a simple variable lookup inside a Template. Something like:</p>
<pre><code>{{ DictModel.exampleKey }}
</code></pre>
<p>With a result of DictModel.objects.get(key__exact=exampleKey).value</p>
<p>Overall, though, you guys have really surprised me with how helpful allof your responses are, and how different the ways to approach it can be. Thanks a lot.
<br />
<br />
<strong>Update October 2011:</strong>
This question is the top result if you Google "django model_to_dict", which is actually pretty awful given that it solves a different problem than what I was asking.<br />
<br />
What I wanted was to be able to map all of the instances in a queryset into a single dictionary with a specified model field as the key.<br />
model_to_dict, on the other hand converts a single model instance into a dictionary.<br />
<br />
Now, my needs at the time were pretty darn specific, and probably extremely rare (I can't even remember the project I needed it for, or why). So I would be pretty surprised that anyone looking for information about model_to_dict is going to find my question actually useful. Sorry.<br />
<br />
model_to_dict seems to be a much more common usage case than I had.
<br />
<br />
<strong>Update Dec 2011:</strong><br />
I changed the title to hopefully better reflect my original intent.</p>
| 57 | 2009-07-14T03:35:53Z | 1,124,610 | <p>You want the <code>in_bulk</code> queryset method which, according to the docs:</p>
<blockquote>
<p>Takes a list of primary-key values and
returns a dictionary mapping each
primary-key value to an instance of
the object with the given ID.</p>
</blockquote>
<p>It takes a list of IDs, so you'll need to get that first via the <code>values_list</code> method:</p>
<pre><code>ids = MyModel.objects.values_list('id', flat=True)
model_dict = MyModel.objects.in_bulk(ids)
</code></pre>
| 16 | 2009-07-14T10:39:13Z | [
"python",
"django",
"django-models",
"dictionary"
] |
Django: Converting an entire set of a Model's objects into a single dictionary | 1,123,337 | <p><em>If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.</em></p>
<p>Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this:</p>
<pre><code>class DictModel(models.Model):
key = models.CharField(20)
value = models.CharField(200)
DictModel.objects.all().to_dict()
</code></pre>
<p>... with the result being a dictionary with the key/value pairs made up of records in the Model? Has anyone else seen this as being useful for them?</p>
<p>Thanks.<br />
<br />
<strong>Update</strong><br />
I just wanted to add is that my ultimate goal is to be able to do a simple variable lookup inside a Template. Something like:</p>
<pre><code>{{ DictModel.exampleKey }}
</code></pre>
<p>With a result of DictModel.objects.get(key__exact=exampleKey).value</p>
<p>Overall, though, you guys have really surprised me with how helpful allof your responses are, and how different the ways to approach it can be. Thanks a lot.
<br />
<br />
<strong>Update October 2011:</strong>
This question is the top result if you Google "django model_to_dict", which is actually pretty awful given that it solves a different problem than what I was asking.<br />
<br />
What I wanted was to be able to map all of the instances in a queryset into a single dictionary with a specified model field as the key.<br />
model_to_dict, on the other hand converts a single model instance into a dictionary.<br />
<br />
Now, my needs at the time were pretty darn specific, and probably extremely rare (I can't even remember the project I needed it for, or why). So I would be pretty surprised that anyone looking for information about model_to_dict is going to find my question actually useful. Sorry.<br />
<br />
model_to_dict seems to be a much more common usage case than I had.
<br />
<br />
<strong>Update Dec 2011:</strong><br />
I changed the title to hopefully better reflect my original intent.</p>
| 57 | 2009-07-14T03:35:53Z | 1,677,068 | <p>You can also rely on django code already written ;).</p>
<pre><code>from django.forms.models import model_to_dict
model_to_dict(instance, fields=[], exclude=[])
</code></pre>
| 208 | 2009-11-04T22:18:09Z | [
"python",
"django",
"django-models",
"dictionary"
] |
Django: Converting an entire set of a Model's objects into a single dictionary | 1,123,337 | <p><em>If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.</em></p>
<p>Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this:</p>
<pre><code>class DictModel(models.Model):
key = models.CharField(20)
value = models.CharField(200)
DictModel.objects.all().to_dict()
</code></pre>
<p>... with the result being a dictionary with the key/value pairs made up of records in the Model? Has anyone else seen this as being useful for them?</p>
<p>Thanks.<br />
<br />
<strong>Update</strong><br />
I just wanted to add is that my ultimate goal is to be able to do a simple variable lookup inside a Template. Something like:</p>
<pre><code>{{ DictModel.exampleKey }}
</code></pre>
<p>With a result of DictModel.objects.get(key__exact=exampleKey).value</p>
<p>Overall, though, you guys have really surprised me with how helpful allof your responses are, and how different the ways to approach it can be. Thanks a lot.
<br />
<br />
<strong>Update October 2011:</strong>
This question is the top result if you Google "django model_to_dict", which is actually pretty awful given that it solves a different problem than what I was asking.<br />
<br />
What I wanted was to be able to map all of the instances in a queryset into a single dictionary with a specified model field as the key.<br />
model_to_dict, on the other hand converts a single model instance into a dictionary.<br />
<br />
Now, my needs at the time were pretty darn specific, and probably extremely rare (I can't even remember the project I needed it for, or why). So I would be pretty surprised that anyone looking for information about model_to_dict is going to find my question actually useful. Sorry.<br />
<br />
model_to_dict seems to be a much more common usage case than I had.
<br />
<br />
<strong>Update Dec 2011:</strong><br />
I changed the title to hopefully better reflect my original intent.</p>
| 57 | 2009-07-14T03:35:53Z | 2,450,865 | <p>Or were you trying to do something like:</p>
<pre><code>def someview(req):
models = MyModel.objects.all()
toTuple = lambda field: (getattr(field, 'someatt'), getattr(field, 'someotheratt'))
data = dict(map(toTuple,models))
return render_to_response(template, data)
</code></pre>
| 1 | 2010-03-15T22:18:55Z | [
"python",
"django",
"django-models",
"dictionary"
] |
Django: Converting an entire set of a Model's objects into a single dictionary | 1,123,337 | <p><em>If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.</em></p>
<p>Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this:</p>
<pre><code>class DictModel(models.Model):
key = models.CharField(20)
value = models.CharField(200)
DictModel.objects.all().to_dict()
</code></pre>
<p>... with the result being a dictionary with the key/value pairs made up of records in the Model? Has anyone else seen this as being useful for them?</p>
<p>Thanks.<br />
<br />
<strong>Update</strong><br />
I just wanted to add is that my ultimate goal is to be able to do a simple variable lookup inside a Template. Something like:</p>
<pre><code>{{ DictModel.exampleKey }}
</code></pre>
<p>With a result of DictModel.objects.get(key__exact=exampleKey).value</p>
<p>Overall, though, you guys have really surprised me with how helpful allof your responses are, and how different the ways to approach it can be. Thanks a lot.
<br />
<br />
<strong>Update October 2011:</strong>
This question is the top result if you Google "django model_to_dict", which is actually pretty awful given that it solves a different problem than what I was asking.<br />
<br />
What I wanted was to be able to map all of the instances in a queryset into a single dictionary with a specified model field as the key.<br />
model_to_dict, on the other hand converts a single model instance into a dictionary.<br />
<br />
Now, my needs at the time were pretty darn specific, and probably extremely rare (I can't even remember the project I needed it for, or why). So I would be pretty surprised that anyone looking for information about model_to_dict is going to find my question actually useful. Sorry.<br />
<br />
model_to_dict seems to be a much more common usage case than I had.
<br />
<br />
<strong>Update Dec 2011:</strong><br />
I changed the title to hopefully better reflect my original intent.</p>
| 57 | 2009-07-14T03:35:53Z | 3,428,560 | <p><code>dict((x.name, getattr(o, x.name)) for x in o._meta.fields)</code></p>
| 6 | 2010-08-06T23:49:40Z | [
"python",
"django",
"django-models",
"dictionary"
] |
Django: Converting an entire set of a Model's objects into a single dictionary | 1,123,337 | <p><em>If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.</em></p>
<p>Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this:</p>
<pre><code>class DictModel(models.Model):
key = models.CharField(20)
value = models.CharField(200)
DictModel.objects.all().to_dict()
</code></pre>
<p>... with the result being a dictionary with the key/value pairs made up of records in the Model? Has anyone else seen this as being useful for them?</p>
<p>Thanks.<br />
<br />
<strong>Update</strong><br />
I just wanted to add is that my ultimate goal is to be able to do a simple variable lookup inside a Template. Something like:</p>
<pre><code>{{ DictModel.exampleKey }}
</code></pre>
<p>With a result of DictModel.objects.get(key__exact=exampleKey).value</p>
<p>Overall, though, you guys have really surprised me with how helpful allof your responses are, and how different the ways to approach it can be. Thanks a lot.
<br />
<br />
<strong>Update October 2011:</strong>
This question is the top result if you Google "django model_to_dict", which is actually pretty awful given that it solves a different problem than what I was asking.<br />
<br />
What I wanted was to be able to map all of the instances in a queryset into a single dictionary with a specified model field as the key.<br />
model_to_dict, on the other hand converts a single model instance into a dictionary.<br />
<br />
Now, my needs at the time were pretty darn specific, and probably extremely rare (I can't even remember the project I needed it for, or why). So I would be pretty surprised that anyone looking for information about model_to_dict is going to find my question actually useful. Sorry.<br />
<br />
model_to_dict seems to be a much more common usage case than I had.
<br />
<br />
<strong>Update Dec 2011:</strong><br />
I changed the title to hopefully better reflect my original intent.</p>
| 57 | 2009-07-14T03:35:53Z | 7,327,390 | <p>Perhaps I'm missing something, but Django objects have a <code>__dict__</code> attribute which seems be what you want.</p>
| 4 | 2011-09-06T23:42:40Z | [
"python",
"django",
"django-models",
"dictionary"
] |
Django: Converting an entire set of a Model's objects into a single dictionary | 1,123,337 | <p><em>If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.</em></p>
<p>Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this:</p>
<pre><code>class DictModel(models.Model):
key = models.CharField(20)
value = models.CharField(200)
DictModel.objects.all().to_dict()
</code></pre>
<p>... with the result being a dictionary with the key/value pairs made up of records in the Model? Has anyone else seen this as being useful for them?</p>
<p>Thanks.<br />
<br />
<strong>Update</strong><br />
I just wanted to add is that my ultimate goal is to be able to do a simple variable lookup inside a Template. Something like:</p>
<pre><code>{{ DictModel.exampleKey }}
</code></pre>
<p>With a result of DictModel.objects.get(key__exact=exampleKey).value</p>
<p>Overall, though, you guys have really surprised me with how helpful allof your responses are, and how different the ways to approach it can be. Thanks a lot.
<br />
<br />
<strong>Update October 2011:</strong>
This question is the top result if you Google "django model_to_dict", which is actually pretty awful given that it solves a different problem than what I was asking.<br />
<br />
What I wanted was to be able to map all of the instances in a queryset into a single dictionary with a specified model field as the key.<br />
model_to_dict, on the other hand converts a single model instance into a dictionary.<br />
<br />
Now, my needs at the time were pretty darn specific, and probably extremely rare (I can't even remember the project I needed it for, or why). So I would be pretty surprised that anyone looking for information about model_to_dict is going to find my question actually useful. Sorry.<br />
<br />
model_to_dict seems to be a much more common usage case than I had.
<br />
<br />
<strong>Update Dec 2011:</strong><br />
I changed the title to hopefully better reflect my original intent.</p>
| 57 | 2009-07-14T03:35:53Z | 10,861,516 | <p>To get a map of all of the instances in a queryset into a single dictionary with a specified model field as the key, try doing this</p>
<pre><code>from django.forms.models import model_to_dict
from myApp.models import myModel
allObjs = myModel.objects.all()
f = {} # initialise the output
key = 'key' # one of the fields from myModel
[f.update({x[key]: x}) for x in [model_to_dict(y) for y in allObjs]]
return f
</code></pre>
| 2 | 2012-06-02T10:19:48Z | [
"python",
"django",
"django-models",
"dictionary"
] |
Django: Converting an entire set of a Model's objects into a single dictionary | 1,123,337 | <p><em>If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.</em></p>
<p>Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this:</p>
<pre><code>class DictModel(models.Model):
key = models.CharField(20)
value = models.CharField(200)
DictModel.objects.all().to_dict()
</code></pre>
<p>... with the result being a dictionary with the key/value pairs made up of records in the Model? Has anyone else seen this as being useful for them?</p>
<p>Thanks.<br />
<br />
<strong>Update</strong><br />
I just wanted to add is that my ultimate goal is to be able to do a simple variable lookup inside a Template. Something like:</p>
<pre><code>{{ DictModel.exampleKey }}
</code></pre>
<p>With a result of DictModel.objects.get(key__exact=exampleKey).value</p>
<p>Overall, though, you guys have really surprised me with how helpful allof your responses are, and how different the ways to approach it can be. Thanks a lot.
<br />
<br />
<strong>Update October 2011:</strong>
This question is the top result if you Google "django model_to_dict", which is actually pretty awful given that it solves a different problem than what I was asking.<br />
<br />
What I wanted was to be able to map all of the instances in a queryset into a single dictionary with a specified model field as the key.<br />
model_to_dict, on the other hand converts a single model instance into a dictionary.<br />
<br />
Now, my needs at the time were pretty darn specific, and probably extremely rare (I can't even remember the project I needed it for, or why). So I would be pretty surprised that anyone looking for information about model_to_dict is going to find my question actually useful. Sorry.<br />
<br />
model_to_dict seems to be a much more common usage case than I had.
<br />
<br />
<strong>Update Dec 2011:</strong><br />
I changed the title to hopefully better reflect my original intent.</p>
| 57 | 2009-07-14T03:35:53Z | 18,745,855 | <p>To get values of a models into dictionary, add below code at the place where u need that dictionary</p>
<pre><code>from models import DictModel
activity_map = dict(Plan.objects.values_list('key', 'value'))
</code></pre>
<p>activity_map is a dictionary which contains required information .</p>
| 2 | 2013-09-11T15:51:07Z | [
"python",
"django",
"django-models",
"dictionary"
] |
Django: Converting an entire set of a Model's objects into a single dictionary | 1,123,337 | <p><em>If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.</em></p>
<p>Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this:</p>
<pre><code>class DictModel(models.Model):
key = models.CharField(20)
value = models.CharField(200)
DictModel.objects.all().to_dict()
</code></pre>
<p>... with the result being a dictionary with the key/value pairs made up of records in the Model? Has anyone else seen this as being useful for them?</p>
<p>Thanks.<br />
<br />
<strong>Update</strong><br />
I just wanted to add is that my ultimate goal is to be able to do a simple variable lookup inside a Template. Something like:</p>
<pre><code>{{ DictModel.exampleKey }}
</code></pre>
<p>With a result of DictModel.objects.get(key__exact=exampleKey).value</p>
<p>Overall, though, you guys have really surprised me with how helpful allof your responses are, and how different the ways to approach it can be. Thanks a lot.
<br />
<br />
<strong>Update October 2011:</strong>
This question is the top result if you Google "django model_to_dict", which is actually pretty awful given that it solves a different problem than what I was asking.<br />
<br />
What I wanted was to be able to map all of the instances in a queryset into a single dictionary with a specified model field as the key.<br />
model_to_dict, on the other hand converts a single model instance into a dictionary.<br />
<br />
Now, my needs at the time were pretty darn specific, and probably extremely rare (I can't even remember the project I needed it for, or why). So I would be pretty surprised that anyone looking for information about model_to_dict is going to find my question actually useful. Sorry.<br />
<br />
model_to_dict seems to be a much more common usage case than I had.
<br />
<br />
<strong>Update Dec 2011:</strong><br />
I changed the title to hopefully better reflect my original intent.</p>
| 57 | 2009-07-14T03:35:53Z | 27,721,631 | <pre><code>user = mymodel.objects.all()
user.values()
</code></pre>
<p>You can also try</p>
<pre><code>user.values_list() # getting as list
</code></pre>
| 2 | 2014-12-31T13:10:27Z | [
"python",
"django",
"django-models",
"dictionary"
] |
Setting a timeout function in django | 1,123,367 | <p>So I'm creating a django app that allows a user to add a new line of text to an existing group of text lines. However I don't want multiple users adding lines to the same group of text lines concurrently. So I created a BoolField isBeingEdited that is set to True once a user decides to append a specific group. Once the Bool is True no one else can append the group until the edit is submitted, whereupon the Bool is set False again. Works alright, unless someone decides to make an edit then changes their mind or forgets about it, etc. I want isBeingEdited to flip back to False after 10 minutes or so. Is this a job for cron, or is there something easier out there? Any suggestions?</p>
| 1 | 2009-07-14T03:50:41Z | 1,123,375 | <p>Change the boolean to a "lock time"</p>
<ol>
<li>To lock the model, set the Lock time to the current time. </li>
<li>To unlock the model, set the lock time to None</li>
<li>Add an "is_locked" method. That method returns "not locked" if the current time is more than 10 minutes after the lock time. </li>
</ol>
<p>This gives you your timeout without Cron and without regular hits into the DB to check flags and unset them. Instead, the time is only checked if you are interest in wieither <em>this</em> model is locked. A Cron would likely have to check <em>all</em> models.</p>
<pre><code>from django.db import models
from datetime import datetime, timedelta
# Create your models here.
class yourTextLineGroup(models.Model):
# fields go here
lock_time = models.DateTimeField(null=True)
locked_by = models.ForeignKey()#Point me to your user model
def lock(self):
if self.is_locked(): #and code here to see if current user is not locked_by user
#exception / bad return value here
pass
self.lock_time = datetime.now()
def unlock(self):
self.lock_time = None
def is_locked(self):
return self.lock_time and datetime.now() - self.lock_time < timedelta(minutes=10)
</code></pre>
<p>Code above assumes that the caller will call the save method after calling lock or unlock.</p>
| 4 | 2009-07-14T03:56:40Z | [
"python",
"django"
] |
clipping text in python/tkinter | 1,123,463 | <p>I want to draw text on a tkinter canvas, within a previously drawn rectangle. I want to clip the text to be drawn entirely within the rectangle, hopefully by just specifying a maximum allowed width. Is there a straightforward way to do this in tkinter? If not, could I be using something else that would make it easier? Thanks</p>
<p>EDIT: "clipping" in a graphics sense, that is, draw the object (the string) as if it has enough room to be displayed in full, but only draw the portion of the object that is in the specified bounds, like this:
<img src="http://garblesnarky.net/images/pythontextclip.png" alt="alt text" /></p>
| 2 | 2009-07-14T04:45:46Z | 6,692,378 | <p>something along the lines of:</p>
<pre><code>from Tkinter import *
root = Tk()
c = Canvas(root, width=200, height=200)
c.pack()
c.create_rectangle(50,50,91,67, outline='blue')
t = Label(c, text="Hello John, Michael, Eric, ...", anchor='w')
c.create_window(51, 51, width=40, height=15, window=t, anchor='nw')
root.mainloop()
</code></pre>
<p>perhaps you could even use an Entry widget rather than a Label</p>
<p>this link could be of considerable interest:
<a href="http://effbot.org/zone/editing-canvas-text-items.htm" rel="nofollow">http://effbot.org/zone/editing-canvas-text-items.htm</a></p>
| 1 | 2011-07-14T11:21:21Z | [
"python",
"tkinter"
] |
clipping text in python/tkinter | 1,123,463 | <p>I want to draw text on a tkinter canvas, within a previously drawn rectangle. I want to clip the text to be drawn entirely within the rectangle, hopefully by just specifying a maximum allowed width. Is there a straightforward way to do this in tkinter? If not, could I be using something else that would make it easier? Thanks</p>
<p>EDIT: "clipping" in a graphics sense, that is, draw the object (the string) as if it has enough room to be displayed in full, but only draw the portion of the object that is in the specified bounds, like this:
<img src="http://garblesnarky.net/images/pythontextclip.png" alt="alt text" /></p>
| 2 | 2009-07-14T04:45:46Z | 6,929,134 | <p>Small patch over <a href="http://stackoverflow.com/questions/1123463/clipping-text-in-python-tkinter/6692378#6692378">noob oddy answer</a> (use a slider to illustrate the clipping actually works).</p>
<pre><code>from Tkinter import *
root = Tk()
c = Canvas(root, width=300, height=100)
c.pack()
r = c.create_rectangle(50,50,91,67, outline='blue')
t = Label(c, text="Hello John, Michael, Eric, ...", anchor='w')
clip = c.create_window(51, 51, height=15, window=t, anchor='nw')
def update_clipping(new_width):
x,y,w,h = c.coords(r)
c.coords(r,x,y,x+int(new_width)+1,h)
c.itemconfig(clip,width=new_width)
s = Scale(root,from_=10, to=200, orient=HORIZONTAL, command=update_clipping)
s.pack()
root.mainloop()
</code></pre>
| 0 | 2011-08-03T15:35:14Z | [
"python",
"tkinter"
] |
How do I grab an instance of a dynamic php script output? | 1,123,622 | <p>The following link outputs a different image every time you visit it:</p>
<p><a href="http://www.biglickmedia.com/art/random/index.php" rel="nofollow">http://www.biglickmedia.com/art/random/index.php</a></p>
<p>From a web browser, you can obviously right click it and save what you see. But if I were to visit this link from a command line (like through python+mechanize), how would I save the image that would output? So basically, I need a command-line method to imitate right clicking and saving the image after initially visiting the site from a web browser.</p>
<p>I can already use iMacro to do this, but I'd like a more elegant method. What can I use to accomplish this? Thanks!</p>
| 0 | 2009-07-14T05:41:16Z | 1,123,637 | <p>you might need something that creates a socket to the server and then issues a http GET request for "art/random/index.php". save the payload from the HTTP response, and then you have your data</p>
<p>what you would be creating is a simple HTTP client</p>
<p>the unix command wget does this:</p>
<pre><code>$ wget http://www.biglickmedia.com/art/random/index.php
</code></pre>
| 4 | 2009-07-14T05:45:44Z | [
"php",
"python",
"image",
"download",
"screen-scraping"
] |
How do I grab an instance of a dynamic php script output? | 1,123,622 | <p>The following link outputs a different image every time you visit it:</p>
<p><a href="http://www.biglickmedia.com/art/random/index.php" rel="nofollow">http://www.biglickmedia.com/art/random/index.php</a></p>
<p>From a web browser, you can obviously right click it and save what you see. But if I were to visit this link from a command line (like through python+mechanize), how would I save the image that would output? So basically, I need a command-line method to imitate right clicking and saving the image after initially visiting the site from a web browser.</p>
<p>I can already use iMacro to do this, but I'd like a more elegant method. What can I use to accomplish this? Thanks!</p>
| 0 | 2009-07-14T05:41:16Z | 1,123,688 | <pre><code><?php
file_put_contents('C:\\random.gif', file_get_contents('http://www.biglickmedia.com/art/random/index.php'));
?>
</code></pre>
| 1 | 2009-07-14T06:04:51Z | [
"php",
"python",
"image",
"download",
"screen-scraping"
] |
How do I grab an instance of a dynamic php script output? | 1,123,622 | <p>The following link outputs a different image every time you visit it:</p>
<p><a href="http://www.biglickmedia.com/art/random/index.php" rel="nofollow">http://www.biglickmedia.com/art/random/index.php</a></p>
<p>From a web browser, you can obviously right click it and save what you see. But if I were to visit this link from a command line (like through python+mechanize), how would I save the image that would output? So basically, I need a command-line method to imitate right clicking and saving the image after initially visiting the site from a web browser.</p>
<p>I can already use iMacro to do this, but I'd like a more elegant method. What can I use to accomplish this? Thanks!</p>
| 0 | 2009-07-14T05:41:16Z | 1,123,740 | <p>With Python and mechanize:</p>
<pre><code>import mechanize
b = mechanize.Browser()
t = b.open(url)
image_type = t.info().typeheader # mime-type of image
data = t.read() #bytes of image
open(filename, 'wb').write(data)
</code></pre>
| 1 | 2009-07-14T06:23:26Z | [
"php",
"python",
"image",
"download",
"screen-scraping"
] |
"select" on multiple Python multiprocessing Queues? | 1,123,855 | <p>What's the best way to wait (without spinning) until something is available in either one of two (multiprocessing) <a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.Queue">Queues</a>, where both reside on the same system?</p>
| 16 | 2009-07-14T06:58:17Z | 1,123,878 | <p>You could use something like the <a href="http://en.wikipedia.org/wiki/Observer%5Fpattern" rel="nofollow">Observer</a> pattern, wherein Queue subscribers are notified of state changes.</p>
<p>In this case, you could have your worker thread designated as a listener on each queue, and whenever it receives a ready signal, it can work on the new item, otherwise sleep.</p>
| 1 | 2009-07-14T07:05:52Z | [
"python",
"events",
"select",
"synchronization",
"multiprocessing"
] |
"select" on multiple Python multiprocessing Queues? | 1,123,855 | <p>What's the best way to wait (without spinning) until something is available in either one of two (multiprocessing) <a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.Queue">Queues</a>, where both reside on the same system?</p>
| 16 | 2009-07-14T06:58:17Z | 1,123,952 | <p>It doesn't look like there's an official way to handle this yet. Or at least, not based on this:</p>
<ul>
<li><a href="http://bugs.python.org/issue3831">http://bugs.python.org/issue3831</a></li>
</ul>
<p>You could try something like what this post is doing -- accessing the underlying pipe filehandles:</p>
<ul>
<li><a href="http://haltcondition.net/?p=2319">http://haltcondition.net/?p=2319</a></li>
</ul>
<p>and then use select.</p>
| 13 | 2009-07-14T07:27:44Z | [
"python",
"events",
"select",
"synchronization",
"multiprocessing"
] |
"select" on multiple Python multiprocessing Queues? | 1,123,855 | <p>What's the best way to wait (without spinning) until something is available in either one of two (multiprocessing) <a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.Queue">Queues</a>, where both reside on the same system?</p>
| 16 | 2009-07-14T06:58:17Z | 1,124,145 | <p>Seems like using threads which forward incoming items to a single Queue which you then wait on is a practical choice when using multiprocessing in a platform independent manner.</p>
<p>Avoiding the threads requires either handling low-level pipes/FDs which is both platform specific and not easy to handle consistently with the higher-level API. </p>
<p>Or you would need Queues with the ability to set callbacks which i think are the proper higher level interface to go for. I.e. you would write something like:</p>
<pre>
singlequeue = Queue()
incoming_queue1.setcallback(singlequeue.put)
incoming_queue2.setcallback(singlequeue.put)
...
singlequeue.get()
</pre>
<p>Maybe the multiprocessing package could grow this API but it's not there yet. The concept works well with py.execnet which uses the term "channel" instead of "queues", see here <a href="http://tinyurl.com/nmtr4w" rel="nofollow">http://tinyurl.com/nmtr4w</a> </p>
| 2 | 2009-07-14T08:24:14Z | [
"python",
"events",
"select",
"synchronization",
"multiprocessing"
] |
"select" on multiple Python multiprocessing Queues? | 1,123,855 | <p>What's the best way to wait (without spinning) until something is available in either one of two (multiprocessing) <a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.Queue">Queues</a>, where both reside on the same system?</p>
| 16 | 2009-07-14T06:58:17Z | 2,162,188 | <p>Actually you can use multiprocessing.Queue objects in select.select. i.e. </p>
<pre><code>que = multiprocessing.Queue()
(input,[],[]) = select.select([que._reader],[],[])
</code></pre>
<p>would select que only if it is ready to be read from. </p>
<p>No documentation about it though. I was reading the source code of the multiprocessing.queue library (at linux it's usually sth like /usr/lib/python2.6/multiprocessing/queue.py) to find it out.</p>
<p>With Queue.Queue I didn't have found any smart way to do this (and I would really love to).</p>
| 17 | 2010-01-29T13:29:15Z | [
"python",
"events",
"select",
"synchronization",
"multiprocessing"
] |
"select" on multiple Python multiprocessing Queues? | 1,123,855 | <p>What's the best way to wait (without spinning) until something is available in either one of two (multiprocessing) <a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.Queue">Queues</a>, where both reside on the same system?</p>
| 16 | 2009-07-14T06:58:17Z | 5,789,428 | <p>Not sure how well the select on a multiprocessing queue works on windows. As select on windows listens for sockets and not file handles, I suspect there could be problems.</p>
<p>My answer is to make a thread to listen to each queue in a blocking fashion, and to put the results all into a single queue listened to by the main thread, essentially multiplexing the individual queues into a single one.</p>
<p>My code for doing this is:</p>
<pre><code>"""
Allow multiple queues to be waited upon.
queue,value = multiq.select(list_of_queues)
"""
import queue
import threading
class queue_reader(threading.Thread):
def __init__(self,inq,sharedq):
threading.Thread.__init__(self)
self.inq = inq
self.sharedq = sharedq
def run(self):
while True:
data = self.inq.get()
print ("thread reads data=",data)
result = (self.inq,data)
self.sharedq.put(result)
class multi_queue(queue.Queue):
def __init__(self,list_of_queues):
queue.Queue.__init__(self)
for q in list_of_queues:
qr = queue_reader(q,self)
qr.start()
def select(list_of_queues):
outq = queue.Queue()
for q in list_of_queues:
qr = queue_reader(q,outq)
qr.start()
return outq.get()
</code></pre>
<p>The following test routine shows how to use it:</p>
<pre><code>import multiq
import queue
q1 = queue.Queue()
q2 = queue.Queue()
q3 = multiq.multi_queue([q1,q2])
q1.put(1)
q2.put(2)
q1.put(3)
q1.put(4)
res=0
while not res==4:
while not q3.empty():
res = q3.get()[1]
print ("returning result =",res)
</code></pre>
<p>Hope this helps.</p>
<p>Tony Wallace</p>
| 1 | 2011-04-26T11:10:32Z | [
"python",
"events",
"select",
"synchronization",
"multiprocessing"
] |
"select" on multiple Python multiprocessing Queues? | 1,123,855 | <p>What's the best way to wait (without spinning) until something is available in either one of two (multiprocessing) <a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.Queue">Queues</a>, where both reside on the same system?</p>
| 16 | 2009-07-14T06:58:17Z | 5,789,473 | <p>New version of above code...</p>
<p>Not sure how well the select on a multiprocessing queue works on windows. As select on windows listens for sockets and not file handles, I suspect there could be problems.</p>
<p>My answer is to make a thread to listen to each queue in a blocking fashion, and to put the results all into a single queue listened to by the main thread, essentially multiplexing the individual queues into a single one.</p>
<p>My code for doing this is:</p>
<pre><code>"""
Allow multiple queues to be waited upon.
An EndOfQueueMarker marks a queue as
"all data sent on this queue".
When this marker has been accessed on
all input threads, this marker is returned
by the multi_queue.
"""
import queue
import threading
class EndOfQueueMarker:
def __str___(self):
return "End of data marker"
pass
class queue_reader(threading.Thread):
def __init__(self,inq,sharedq):
threading.Thread.__init__(self)
self.inq = inq
self.sharedq = sharedq
def run(self):
q_run = True
while q_run:
data = self.inq.get()
result = (self.inq,data)
self.sharedq.put(result)
if data is EndOfQueueMarker:
q_run = False
class multi_queue(queue.Queue):
def __init__(self,list_of_queues):
queue.Queue.__init__(self)
self.qList = list_of_queues
self.qrList = []
for q in list_of_queues:
qr = queue_reader(q,self)
qr.start()
self.qrList.append(qr)
def get(self,blocking=True,timeout=None):
res = []
while len(res)==0:
if len(self.qList)==0:
res = (self,EndOfQueueMarker)
else:
res = queue.Queue.get(self,blocking,timeout)
if res[1] is EndOfQueueMarker:
self.qList.remove(res[0])
res = []
return res
def join(self):
for qr in self.qrList:
qr.join()
def select(list_of_queues):
outq = queue.Queue()
for q in list_of_queues:
qr = queue_reader(q,outq)
qr.start()
return outq.get()
</code></pre>
<p>The follow code is my test routine to show how it works:</p>
<pre><code>import multiq
import queue
q1 = queue.Queue()
q2 = queue.Queue()
q3 = multiq.multi_queue([q1,q2])
q1.put(1)
q2.put(2)
q1.put(3)
q1.put(4)
q1.put(multiq.EndOfQueueMarker)
q2.put(multiq.EndOfQueueMarker)
res=0
have_data = True
while have_data:
res = q3.get()[1]
print ("returning result =",res)
have_data = not(res==multiq.EndOfQueueMarker)
</code></pre>
| 1 | 2011-04-26T11:14:22Z | [
"python",
"events",
"select",
"synchronization",
"multiprocessing"
] |
"select" on multiple Python multiprocessing Queues? | 1,123,855 | <p>What's the best way to wait (without spinning) until something is available in either one of two (multiprocessing) <a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.Queue">Queues</a>, where both reside on the same system?</p>
| 16 | 2009-07-14T06:58:17Z | 21,195,494 | <p>Don't do it.</p>
<p>Put a header on the messages and send them to a common queue. This simplifies the code and will be cleaner overall. </p>
| -2 | 2014-01-17T20:42:50Z | [
"python",
"events",
"select",
"synchronization",
"multiprocessing"
] |
Socket? python -m SimpleHTTPServer | 1,124,420 | <p><strong>Problem:</strong> to get the command working <a href="http://www.commandlinefu.com/commands/view/71/serve-current-directory-tree-at-httphostname8000" rel="nofollow">here.</a> My domain is <a href="http://cs.edu.com/user/share_dir" rel="nofollow">http://cs.edu.com/user/share_dir</a>, but I cannot get the command working by typing it to a browser:</p>
<pre><code>http://cs.edu.com/user/share_dir:8000
</code></pre>
<p><strong>Question:</strong> How can I get the command working?</p>
| 3 | 2009-07-14T09:43:22Z | 1,124,467 | <p>Your URL is incorrect. The port number should be specified after the domain name:</p>
<p><a href="http://cs.edu.com:8000/">http://cs.edu.com:8000/</a></p>
<p>Some other things you should keep in mind:</p>
<ol>
<li>If this is a shared host, port 8000 might already be in use by someone else</li>
<li>The host might not be accessible from 'outside' of the network, due to firewall restrictions on non-standard ports</li>
<li>The system you see internally could map to a different system outside, so the domain/hostname could be different from what you expect.</li>
</ol>
| 5 | 2009-07-14T09:58:08Z | [
"python",
"sockets"
] |
What is the best practice in deploying application on Windows? | 1,124,667 | <p>I have an application that consists of several .dlls, .libs, .pyd (python library), .exe, .class-es.</p>
<p>What is the best practice in the deployment process?</p>
<p>I plan to put .dlls - managed into GAC and unmanaged into WinSxS folder.</p>
<p>What should I do with .libs, .exe, .class and .pyd?</p>
<p>Is it ok to put it to </p>
<pre><code>/ProgramFiles/ApplicationName/bin
/ProgramFiles/ApplicationName/lib
/ProgramFiles/ApplicationName/java
/ProgramFiles/ApplicationName/python
</code></pre>
<p>?</p>
<p>Thanks</p>
<p>Tamara</p>
| 3 | 2009-07-14T10:54:06Z | 1,124,703 | <p>The current convention seems to be </p>
<p>"/ProgramFiles/YourCompany/YourApplication/..." </p>
<p>As for how to structure things under that folder, it is really dependent on what your application is doing, and how it's structured. Do make sure to store per-user information in <a href="http://msdn.microsoft.com/en-us/library/3ak841sy%28VS.80%29.aspx" rel="nofollow">Isolated Storage</a>.</p>
| 2 | 2009-07-14T11:04:34Z | [
"python",
"windows",
"deployment"
] |
What is the best practice in deploying application on Windows? | 1,124,667 | <p>I have an application that consists of several .dlls, .libs, .pyd (python library), .exe, .class-es.</p>
<p>What is the best practice in the deployment process?</p>
<p>I plan to put .dlls - managed into GAC and unmanaged into WinSxS folder.</p>
<p>What should I do with .libs, .exe, .class and .pyd?</p>
<p>Is it ok to put it to </p>
<pre><code>/ProgramFiles/ApplicationName/bin
/ProgramFiles/ApplicationName/lib
/ProgramFiles/ApplicationName/java
/ProgramFiles/ApplicationName/python
</code></pre>
<p>?</p>
<p>Thanks</p>
<p>Tamara</p>
| 3 | 2009-07-14T10:54:06Z | 1,124,939 | <p>I agree that /ProgramFiles/CompanyName/AppName is the convention. But you might also have to look at who will install the application. More and more users are no longer given admin rights on their Windows box at work, so they can't install under ProgramFiles. So depending on your target users and how you envisage them getting your application, you might want to install it in a location they can write in (like the user's AppData). </p>
| 1 | 2009-07-14T12:02:18Z | [
"python",
"windows",
"deployment"
] |
How can I find path to given file? | 1,124,810 | <p>I have a file, for example "something.exe" and I want to find path to this file<br>
How can I do this in python?</p>
| 2 | 2009-07-14T11:30:36Z | 1,124,825 | <p>Perhaps <code>os.path.abspath()</code> would do it:</p>
<pre><code>import os
print os.path.abspath("something.exe")
</code></pre>
<p>If your <code>something.exe</code> is not in the current directory, you can pass any relative path and <code>abspath()</code> will resolve it.</p>
| 9 | 2009-07-14T11:33:23Z | [
"python"
] |
How can I find path to given file? | 1,124,810 | <p>I have a file, for example "something.exe" and I want to find path to this file<br>
How can I do this in python?</p>
| 2 | 2009-07-14T11:30:36Z | 1,124,841 | <p>use <a href="http://docs.python.org/library/os.path.html#os.path.abspath">os.path.abspath</a> to get a normalized absolutized version of the pathname<br />
use <a href="http://docs.python.org/library/os.html#os.walk">os.walk</a> to get it's location</p>
<pre><code>import os
exe = 'something.exe'
#if the exe just in current dir
print os.path.abspath(exe)
# output
# D:\python\note\something.exe
#if we need find it first
for root, dirs, files in os.walk(r'D:\python'):
for name in files:
if name == exe:
print os.path.abspath(os.path.join(root, name))
# output
# D:\python\note\something.exe
</code></pre>
| 7 | 2009-07-14T11:36:46Z | [
"python"
] |
How can I find path to given file? | 1,124,810 | <p>I have a file, for example "something.exe" and I want to find path to this file<br>
How can I do this in python?</p>
| 2 | 2009-07-14T11:30:36Z | 1,124,851 | <p>if you absolutely do not know where it is, the only way is to find it starting from root c:\</p>
<pre><code>import os
for r,d,f in os.walk("c:\\"):
for files in f:
if files == "something.exe":
print os.path.join(r,files)
</code></pre>
<p>else, if you know that there are only few places you store you exe, like your system32, then start finding it from there. you can also make use of os.environ["PATH"] if you always put your .exe in one of those directories in your PATH variable.</p>
<pre><code>for p in os.environ["PATH"].split(";"):
for r,d,f in os.walk(p):
for files in f:
if files == "something.exe":
print os.path.join(r,files)
</code></pre>
| 2 | 2009-07-14T11:38:23Z | [
"python"
] |
How can I find path to given file? | 1,124,810 | <p>I have a file, for example "something.exe" and I want to find path to this file<br>
How can I do this in python?</p>
| 2 | 2009-07-14T11:30:36Z | 1,124,862 | <p>Uh... This question is a bit unclear.</p>
<p>What do you mean "have"? Do you have the name of the file? Have you opened it? Is it a file object? Is it a file descriptor? What???</p>
<p>If it's a name, what do you mean with "find"? Do you want to search for the file in a bunch of directories? Or do you know which directory it's in?</p>
<p>If it is a file object, then you must have opened it, reasonably, and then you know the path already, although you can get the filename from fileob.name too.</p>
| 1 | 2009-07-14T11:42:19Z | [
"python"
] |
Python error when running script - "IndentationError: unindent does not match any outer indentation" | 1,124,823 | <p>I'm getting an error when I try to run my script </p>
<pre><code>Error:"IndentationError: unindent does not match any outer indentation"
</code></pre>
<p>Code snipet that throws the error:</p>
<pre><code>def update():
try:
lines = open("vbvuln.txt", "r").readlines()
except(IOError):
print "[-] Error: Check your phpvuln.txt path and permissions"
print "[-] Update Failed\n"
sys.exit(1)
try:
</code></pre>
<p>This is the actual line that occurs the error:</p>
<pre><code>print "[-] Update Failed\n"
</code></pre>
| -4 | 2009-07-14T11:33:13Z | 1,124,830 | <p>You have an empty try block with nothing underneath it. This is causing the error.</p>
<p>BTW, your <code>sys.exit(1)</code> is off-indent as well. In python, Indentation is important because this is how Python interpreter determines code blocks. So, you have to indent your code properly to get your code running.</p>
| 0 | 2009-07-14T11:35:06Z | [
"python",
"syntax",
"indentation"
] |
Python error when running script - "IndentationError: unindent does not match any outer indentation" | 1,124,823 | <p>I'm getting an error when I try to run my script </p>
<pre><code>Error:"IndentationError: unindent does not match any outer indentation"
</code></pre>
<p>Code snipet that throws the error:</p>
<pre><code>def update():
try:
lines = open("vbvuln.txt", "r").readlines()
except(IOError):
print "[-] Error: Check your phpvuln.txt path and permissions"
print "[-] Update Failed\n"
sys.exit(1)
try:
</code></pre>
<p>This is the actual line that occurs the error:</p>
<pre><code>print "[-] Update Failed\n"
</code></pre>
| -4 | 2009-07-14T11:33:13Z | 1,124,837 | <p>Put a space before <code>sys.exit(1)</code> or remove space before <code>print "[-] Error: Check your phpvuln.txt path and permissions"</code> and <code>print "[-] Update Failed\n"</code>.</p>
| 6 | 2009-07-14T11:35:58Z | [
"python",
"syntax",
"indentation"
] |
Python error when running script - "IndentationError: unindent does not match any outer indentation" | 1,124,823 | <p>I'm getting an error when I try to run my script </p>
<pre><code>Error:"IndentationError: unindent does not match any outer indentation"
</code></pre>
<p>Code snipet that throws the error:</p>
<pre><code>def update():
try:
lines = open("vbvuln.txt", "r").readlines()
except(IOError):
print "[-] Error: Check your phpvuln.txt path and permissions"
print "[-] Update Failed\n"
sys.exit(1)
try:
</code></pre>
<p>This is the actual line that occurs the error:</p>
<pre><code>print "[-] Update Failed\n"
</code></pre>
| -4 | 2009-07-14T11:33:13Z | 1,124,875 | <p>The indentation error happens where you have indented incorrectly. Which is clearly visible by the fact that you have different indentation in the line starting with "sys".</p>
| 0 | 2009-07-14T11:44:00Z | [
"python",
"syntax",
"indentation"
] |
Python error when running script - "IndentationError: unindent does not match any outer indentation" | 1,124,823 | <p>I'm getting an error when I try to run my script </p>
<pre><code>Error:"IndentationError: unindent does not match any outer indentation"
</code></pre>
<p>Code snipet that throws the error:</p>
<pre><code>def update():
try:
lines = open("vbvuln.txt", "r").readlines()
except(IOError):
print "[-] Error: Check your phpvuln.txt path and permissions"
print "[-] Update Failed\n"
sys.exit(1)
try:
</code></pre>
<p>This is the actual line that occurs the error:</p>
<pre><code>print "[-] Update Failed\n"
</code></pre>
| -4 | 2009-07-14T11:33:13Z | 1,124,878 | <p>As others have mentioned, you need to make sure that each code block has the exact same indentation.</p>
<p>What they haven't mentioned is that the <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">widely adopted convention</a> is to always use exactly 4 spaces per indentation. In your code, the <code>print</code> statements are indented using 5 spaces (most likely by accident.) So do not add another space to <code>sys.exit(1)</code>; remove the spaces from the <code>print</code> statements.</p>
<p>Revised code:</p>
<pre><code>def update():
try:
lines = open("vbvuln.txt", "r").readlines()
except (IOError):
print "[-] Error: Check your phpvuln.txt path and permissions"
print "[-] Update Failed\n"
sys.exit(1)
</code></pre>
| 3 | 2009-07-14T11:44:45Z | [
"python",
"syntax",
"indentation"
] |
Python error when running script - "IndentationError: unindent does not match any outer indentation" | 1,124,823 | <p>I'm getting an error when I try to run my script </p>
<pre><code>Error:"IndentationError: unindent does not match any outer indentation"
</code></pre>
<p>Code snipet that throws the error:</p>
<pre><code>def update():
try:
lines = open("vbvuln.txt", "r").readlines()
except(IOError):
print "[-] Error: Check your phpvuln.txt path and permissions"
print "[-] Update Failed\n"
sys.exit(1)
try:
</code></pre>
<p>This is the actual line that occurs the error:</p>
<pre><code>print "[-] Update Failed\n"
</code></pre>
| -4 | 2009-07-14T11:33:13Z | 3,866,990 | <p>A good way to maintain a standard for your indentations is to use the tab key instead of spacebar.</p>
| 1 | 2010-10-05T19:28:38Z | [
"python",
"syntax",
"indentation"
] |
Interact with a Windows console application via Python | 1,124,884 | <p>I am using python 2.5 on Windows. I wish to interact with a console process via Popen. I currently have this small snippet of code:</p>
<pre><code>p = Popen( ["console_app.exe"], stdin=PIPE, stdout=PIPE )
# issue command 1...
p.stdin.write( 'command1\n' )
result1 = p.stdout.read() # <---- we never return here
# issue command 2...
p.stdin.write( 'command2\n' )
result2 = p.stdout.read()
</code></pre>
<p>I can write to stdin but can not read from stdout. Have I missed a step? I don't want to use p.communicate( "command" )[0] as it terminates the process and I need to interact with the process dynamically over time.</p>
<p>Thanks in advance.</p>
| 7 | 2009-07-14T11:46:03Z | 1,124,911 | <p>I think you might want to try to use readline() instead?</p>
<p>Edit: sorry, misunderstoud.</p>
<p>Maybe <a href="http://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python">this</a> question can help you?</p>
| 0 | 2009-07-14T11:53:33Z | [
"python",
"windows"
] |
Interact with a Windows console application via Python | 1,124,884 | <p>I am using python 2.5 on Windows. I wish to interact with a console process via Popen. I currently have this small snippet of code:</p>
<pre><code>p = Popen( ["console_app.exe"], stdin=PIPE, stdout=PIPE )
# issue command 1...
p.stdin.write( 'command1\n' )
result1 = p.stdout.read() # <---- we never return here
# issue command 2...
p.stdin.write( 'command2\n' )
result2 = p.stdout.read()
</code></pre>
<p>I can write to stdin but can not read from stdout. Have I missed a step? I don't want to use p.communicate( "command" )[0] as it terminates the process and I need to interact with the process dynamically over time.</p>
<p>Thanks in advance.</p>
| 7 | 2009-07-14T11:46:03Z | 1,125,001 | <p>Is it possible that the console app is buffering its output in some way so that it is only being sent to stdout when the pipe is closed? If you have access to the code for the console app, maybe sticking a flush after a batch of output data might help?</p>
<p>Alternatively, is it actually writing to stderr and instead of stdout for some reason?</p>
<p>Just looked at your code again and thought of something else, I see you're sending in "command\n". Could the console app be simply waiting for a carriage return character instead of a new line? Maybe the console app is waiting for you to submit the command before it produces any output.</p>
| 0 | 2009-07-14T12:16:06Z | [
"python",
"windows"
] |
Interact with a Windows console application via Python | 1,124,884 | <p>I am using python 2.5 on Windows. I wish to interact with a console process via Popen. I currently have this small snippet of code:</p>
<pre><code>p = Popen( ["console_app.exe"], stdin=PIPE, stdout=PIPE )
# issue command 1...
p.stdin.write( 'command1\n' )
result1 = p.stdout.read() # <---- we never return here
# issue command 2...
p.stdin.write( 'command2\n' )
result2 = p.stdout.read()
</code></pre>
<p>I can write to stdin but can not read from stdout. Have I missed a step? I don't want to use p.communicate( "command" )[0] as it terminates the process and I need to interact with the process dynamically over time.</p>
<p>Thanks in advance.</p>
| 7 | 2009-07-14T11:46:03Z | 1,125,684 | <p>Had the exact same problem here. I dug into DrPython source code and stole <strong>wx.Execute()</strong> solution, which is working fine, especially if your script is already using wx. I never found correct solution on windows platform though...</p>
| 0 | 2009-07-14T14:17:23Z | [
"python",
"windows"
] |
Interact with a Windows console application via Python | 1,124,884 | <p>I am using python 2.5 on Windows. I wish to interact with a console process via Popen. I currently have this small snippet of code:</p>
<pre><code>p = Popen( ["console_app.exe"], stdin=PIPE, stdout=PIPE )
# issue command 1...
p.stdin.write( 'command1\n' )
result1 = p.stdout.read() # <---- we never return here
# issue command 2...
p.stdin.write( 'command2\n' )
result2 = p.stdout.read()
</code></pre>
<p>I can write to stdin but can not read from stdout. Have I missed a step? I don't want to use p.communicate( "command" )[0] as it terminates the process and I need to interact with the process dynamically over time.</p>
<p>Thanks in advance.</p>
| 7 | 2009-07-14T11:46:03Z | 1,127,074 | <p>Your problem here is that you are trying to control an interactive application.</p>
<p><code>stdout.read()</code> will continue reading until it has reached the end of the stream, file or pipe. Unfortunately, in case of an interactive program, the pipe is only closed then whe program exits; which is never, if the command you sent it was anything other than <code>"quit"</code>.</p>
<p>You will have to revert to reading the output of the subprocess line-by-line using <code>stdout.readline()</code>, and you'd better have a way to tell when the program is ready to accept a command, and when the command you issued to the program is finished and you can supply a new one. In case of a program like <code>cmd.exe</code>, even <code>readline()</code> won't suffice as the line that indicates a new command can be sent is not terminated by a newline, so will have to analyze the output byte-by-byte. Here's a sample script that runs <code>cmd.exe</code>, looks for the prompt, then issues a <code>dir</code> and then an <code>exit</code>:</p>
<pre><code>from subprocess import *
import re
class InteractiveCommand:
def __init__(self, process, prompt):
self.process = process
self.prompt = prompt
self.output = ""
self.wait_for_prompt()
def wait_for_prompt(self):
while not self.prompt.search(self.output):
c = self.process.stdout.read(1)
if c == "":
break
self.output += c
# Now we're at a prompt; clear the output buffer and return its contents
tmp = self.output
self.output = ""
return tmp
def command(self, command):
self.process.stdin.write(command + "\n")
return self.wait_for_prompt()
p = Popen( ["cmd.exe"], stdin=PIPE, stdout=PIPE )
prompt = re.compile(r"^C:\\.*>", re.M)
cmd = InteractiveCommand(p, prompt)
listing = cmd.command("dir")
cmd.command("exit")
print listing
</code></pre>
<p>If the timing isn't important, and interactivity for a user isn't required, it can be a lot simpler just to batch up the calls:</p>
<pre><code>from subprocess import *
p = Popen( ["cmd.exe"], stdin=PIPE, stdout=PIPE )
p.stdin.write("dir\n")
p.stdin.write("exit\n")
print p.stdout.read()
</code></pre>
| 5 | 2009-07-14T18:16:02Z | [
"python",
"windows"
] |
Interact with a Windows console application via Python | 1,124,884 | <p>I am using python 2.5 on Windows. I wish to interact with a console process via Popen. I currently have this small snippet of code:</p>
<pre><code>p = Popen( ["console_app.exe"], stdin=PIPE, stdout=PIPE )
# issue command 1...
p.stdin.write( 'command1\n' )
result1 = p.stdout.read() # <---- we never return here
# issue command 2...
p.stdin.write( 'command2\n' )
result2 = p.stdout.read()
</code></pre>
<p>I can write to stdin but can not read from stdout. Have I missed a step? I don't want to use p.communicate( "command" )[0] as it terminates the process and I need to interact with the process dynamically over time.</p>
<p>Thanks in advance.</p>
| 7 | 2009-07-14T11:46:03Z | 1,132,933 | <p>Have you tried to force windows end lines?
i.e.</p>
<pre><code>p.stdin.write( 'command1 \r\n' )
p.stdout.readline()
</code></pre>
<p>UPDATE:</p>
<p>I've just checked the solution on windows cmd.exe and it works with readline(). But it has one problem Popen's stdout.readline <strong>blocks</strong>. So if the app will ever return something without endline your app will stuck forever.</p>
<p>But there is a work around for that check out: <a href="http://code.activestate.com/recipes/440554/" rel="nofollow">http://code.activestate.com/recipes/440554/</a></p>
| 2 | 2009-07-15T17:59:19Z | [
"python",
"windows"
] |
Generic object "ownership" in Django | 1,125,006 | <p>Suppose I have the following models:</p>
<pre><code>class User(models.Model):
pass
class A(models.Model):
user = models.ForeignKey(User)
class B(models.Model):
a = models.ForeignKey(A)
</code></pre>
<p>That is, each user owns some objects of type A, and also some of type B. Now, I'm writing a generic interface that will allow the user to view any objects that it owns. In a view, of course I can't say something like "objects = model.objects.filter(user=user)", since B has no attribute 'user'. What's the best approach to take here?</p>
| 1 | 2009-07-14T12:18:08Z | 1,125,038 | <p>The way I would do it is to simply go through the object 'a' on class B. So in the view, I would do:</p>
<pre><code>objects = B.objects.get(user=a.user)
objects += A.objects.get(user=user)
</code></pre>
<p>The reason I would do it this way is because these are essentially two database queries, one to retrieve a bunch of object A's and one to retrieve a bunch of object B's. I'm not certain it's possible in Django to retrieve a list of both, simply because of the way database inheritance works.</p>
<p>You could use <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#id4" rel="nofollow">model inheritance</a> as well. This would be making a base class for both objects A and B that contains the common fields and then retrieving a list of the base classes, then convert to their proper types.</p>
<p><strong>Edit:</strong> In response to your comment, I suggest then making a base class that contains this line:</p>
<pre><code>user = models.ForeignKey(User)
</code></pre>
<p>Class A and B can then inherit from that base class, and you can thus now just get all of the objects from that class. Say your base class was called 'C':</p>
<pre><code>objects = C.objects.get(user=user)
</code></pre>
<p>That will obtain all of the C's, and you can then figure out their specific types by going through each object in objects and determining their type:</p>
<pre><code>for object in objects:
if object.A:
#code
if object.B:
#code
</code></pre>
| 0 | 2009-07-14T12:24:15Z | [
"python",
"django"
] |
Question about paths in Python | 1,125,399 | <p>let's say i have directory paths looking like this:</p>
<pre><code>this/is/the/basedir/path/a/include
this/is/the/basedir/path/b/include
this/is/the/basedir/path/a
this/is/the/basedir/path/b
</code></pre>
<p>In Python, how can i split these paths up so they will look like this instead:</p>
<pre><code>a/include
b/include
a
b
</code></pre>
<p>If i run os.path.split(path)[1] it will display:</p>
<pre><code>include
include
a
b
</code></pre>
<p>What should i be trying out here, should i be looking at some regex command or can this be done without it? Thanks in advance.</p>
<p>EDIT ALL: I solved it using regular expressions, damn handy tool :)</p>
| 1 | 2009-07-14T13:30:55Z | 1,125,426 | <p>what about <a href="http://docs.python.org/library/stdtypes.html?highlight=partition#str.partition" rel="nofollow">partition</a>?<br />
It Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.</p>
<pre><code>data = """this/is/the/basedir/path/a/include
this/is/the/basedir/path/b/include
this/is/the/basedir/path/a
this/is/the/basedir/path/b"""
for line in data.splitlines():
print line.partition("this/is/the/basedir/path/")[2]
#output
a/include
b/include
a
b
</code></pre>
<p>Updated for the new comment by author:<br />
It looks like u need rsplit for different directories by whether the directory endswith "include" of not:</p>
<pre><code>import os.path
data = """this/is/the/basedir/path/a/include
this/is/the/basedir/path/b/include
this/is/the/basedir/path/a
this/is/the/basedir/path/b"""
for line in data.splitlines():
if line.endswith('include'):
print '/'.join(line.rsplit("/",2)[-2:])
else:
print os.path.split(line)[1]
#or just
# print line.rsplit("/",1)[-1]
#output
a/include
b/include
a
b
</code></pre>
| 1 | 2009-07-14T13:34:56Z | [
"python",
"operating-system"
] |
Question about paths in Python | 1,125,399 | <p>let's say i have directory paths looking like this:</p>
<pre><code>this/is/the/basedir/path/a/include
this/is/the/basedir/path/b/include
this/is/the/basedir/path/a
this/is/the/basedir/path/b
</code></pre>
<p>In Python, how can i split these paths up so they will look like this instead:</p>
<pre><code>a/include
b/include
a
b
</code></pre>
<p>If i run os.path.split(path)[1] it will display:</p>
<pre><code>include
include
a
b
</code></pre>
<p>What should i be trying out here, should i be looking at some regex command or can this be done without it? Thanks in advance.</p>
<p>EDIT ALL: I solved it using regular expressions, damn handy tool :)</p>
| 1 | 2009-07-14T13:30:55Z | 1,125,436 | <p>Perhaps something like this, depends on how hardcoded your prefix is:</p>
<pre><code>def removePrefix(path, prefix):
plist = path.split(os.sep)
pflist = prefix.split(os.sep)
rest = plist[len(pflist):]
return os.path.join(*rest)
</code></pre>
<p>Usage:</p>
<pre><code>print removePrefix("this/is/the/basedir/path/b/include", "this/is/the/basedir/path")
b/include
</code></pre>
<p>Assuming you're on a platform where the directory separator (<code>os.sep</code>) really is the forward slash).</p>
<p>This code tries to handle paths as something a little more high-level than mere strings. It's not optimal though, you could (or should) do more cleaning and canonicalization to be safer.</p>
| 3 | 2009-07-14T13:36:03Z | [
"python",
"operating-system"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.