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
sequence
Is there an easy way to request a URL in python and NOT follow redirects?
110,498
<p>Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple.</p>
24
2008-09-21T07:49:10Z
5,352,695
<p>This is a urllib2 handler that will not follow redirects:</p> <pre><code>class NoRedirectHandler(urllib2.HTTPRedirectHandler): def http_error_302(self, req, fp, code, msg, headers): infourl = urllib.addinfourl(fp, headers, req.get_full_url()) infourl.status = code infourl.code = code return infourl http_error_300 = http_error_302 http_error_301 = http_error_302 http_error_303 = http_error_302 http_error_307 = http_error_302 opener = urllib2.build_opener(NoRedirectHandler()) urllib2.install_opener(opener) </code></pre>
10
2011-03-18T13:33:06Z
[ "python", "http", "redirect" ]
Is there an easy way to request a URL in python and NOT follow redirects?
110,498
<p>Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple.</p>
24
2008-09-21T07:49:10Z
9,494,012
<p>The shortest way however is</p> <pre><code>class NoRedirect(urllib2.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, hdrs, newurl): pass noredir_opener = urllib2.build_opener(NoRedirect()) </code></pre>
4
2012-02-29T05:26:46Z
[ "python", "http", "redirect" ]
Is there an easy way to request a URL in python and NOT follow redirects?
110,498
<p>Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple.</p>
24
2008-09-21T07:49:10Z
10,587,613
<p>The <code>redirections</code> keyword in the <code>httplib2</code> request method is a red herring. Rather than return the first request it will raise a <code>RedirectLimit</code> exception if it receives a redirection status code. To return the inital response you need to set <code>follow_redirects</code> to <code>False</code> on the <code>Http</code> object:</p> <pre><code>import httplib2 h = httplib2.Http() h.follow_redirects = False (response, body) = h.request("http://example.com") </code></pre>
6
2012-05-14T16:45:38Z
[ "python", "http", "redirect" ]
Is there an easy way to request a URL in python and NOT follow redirects?
110,498
<p>Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple.</p>
24
2008-09-21T07:49:10Z
14,678,220
<p>Here is the <a href="http://docs.python-requests.org/en/latest/">Requests</a> way:</p> <pre><code>import requests r = requests.get('http://github.com', allow_redirects=False) print(r.status_code) </code></pre>
36
2013-02-03T22:42:27Z
[ "python", "http", "redirect" ]
Report generation
110,760
<p>I am writing a web app using TurboGears, and in that app the users must be able to generate different reports. The data the reports need is stored in a database (MySQL). The reports must be returned either as a easily printable html document, or a pdf file.</p> <p>I have previously used jasper and iReport for creating the documents, but if I can avoid having to fire up Java to create the report I would be happy.</p> <p>Ideally I would like to specify reports in a easily readable markup language and then just feed the template data with some kind of library that produces the report.</p> <p>I gladly accept any kind of hints on how I should go about generating these reports!</p>
3
2008-09-21T10:55:46Z
110,817
<p>A partial answer: the easily readable format you are looking for might be <a href="http://www.docbook.org/" rel="nofollow">DocBook</a>. From there it is very easy to go to PDF, html, RTF, etc. etc.</p>
1
2008-09-21T11:40:55Z
[ "python", "report" ]
Report generation
110,760
<p>I am writing a web app using TurboGears, and in that app the users must be able to generate different reports. The data the reports need is stored in a database (MySQL). The reports must be returned either as a easily printable html document, or a pdf file.</p> <p>I have previously used jasper and iReport for creating the documents, but if I can avoid having to fire up Java to create the report I would be happy.</p> <p>Ideally I would like to specify reports in a easily readable markup language and then just feed the template data with some kind of library that produces the report.</p> <p>I gladly accept any kind of hints on how I should go about generating these reports!</p>
3
2008-09-21T10:55:46Z
110,936
<p>You can build some fancy PDFs from Python with the <a href="http://www.reportlab.com/opensource/" rel="nofollow">ReportLab</a> toolkit.</p>
2
2008-09-21T12:45:46Z
[ "python", "report" ]
Report generation
110,760
<p>I am writing a web app using TurboGears, and in that app the users must be able to generate different reports. The data the reports need is stored in a database (MySQL). The reports must be returned either as a easily printable html document, or a pdf file.</p> <p>I have previously used jasper and iReport for creating the documents, but if I can avoid having to fire up Java to create the report I would be happy.</p> <p>Ideally I would like to specify reports in a easily readable markup language and then just feed the template data with some kind of library that produces the report.</p> <p>I gladly accept any kind of hints on how I should go about generating these reports!</p>
3
2008-09-21T10:55:46Z
111,144
<p><a href="http://appyframework.org/pod.html" rel="nofollow">Pod</a> is my favorite solution to your problem.</p>
3
2008-09-21T14:40:06Z
[ "python", "report" ]
Re-ordering entries in a model using drag-and-drop
110,774
<p>Say I have a blogging app in Django. How can i re-order the posts using a draggable table in the default admin?</p> <p>It would be best if i didn't have to add any extra fields to the model, but if i really have to i can.</p>
8
2008-09-21T11:05:29Z
110,788
<p>In model class you would probably have to add "order" field, to maintain specific order (eg. item with order = 10 is the last one and order = 1 is the first one). Then you can add a JS code in admin change_list template (see <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-media-definitions" rel="nofollow">this</a>) to maintain drag&amp;drop feature. Finally change ordering in Meta of model to something like ['order'].</p>
1
2008-09-21T11:15:01Z
[ "javascript", "python", "django" ]
Re-ordering entries in a model using drag-and-drop
110,774
<p>Say I have a blogging app in Django. How can i re-order the posts using a draggable table in the default admin?</p> <p>It would be best if i didn't have to add any extra fields to the model, but if i really have to i can.</p>
8
2008-09-21T11:05:29Z
110,830
<p>Note on the "It would be best if i didn't have to add any extra fields to the model, but if i really have to i can." </p> <p>Sorry, but order of information in a database is determined by the information itself: you always have to add a column for ordering. There's really no choice about that. </p> <p>Further, to retrieve things in this order, you'll need to specifically add <code>.order_by(x)</code> to your queries or add <code>ordering</code> to your model.</p> <pre><code>class InOrder( models.Model ): position = models.IntegerField() data = models.TextField() class Meta: ordering = [ 'position' ] </code></pre> <p>Without the additional field ordering cannot happen. It's one of the rules of relational databases.</p>
4
2008-09-21T11:49:27Z
[ "javascript", "python", "django" ]
Re-ordering entries in a model using drag-and-drop
110,774
<p>Say I have a blogging app in Django. How can i re-order the posts using a draggable table in the default admin?</p> <p>It would be best if i didn't have to add any extra fields to the model, but if i really have to i can.</p>
8
2008-09-21T11:05:29Z
111,084
<p>For working code to do this, check out <a href="http://www.djangosnippets.org/snippets/1053/">snippet 1053</a> at <a href="http://www.djangosnippets.org">djangosnippets.org</a>.</p>
5
2008-09-21T13:59:59Z
[ "javascript", "python", "django" ]
Re-ordering entries in a model using drag-and-drop
110,774
<p>Say I have a blogging app in Django. How can i re-order the posts using a draggable table in the default admin?</p> <p>It would be best if i didn't have to add any extra fields to the model, but if i really have to i can.</p>
8
2008-09-21T11:05:29Z
16,333,278
<p>There's a nice package for ordering admin objects these days</p> <p><a href="https://github.com/iambrandontaylor/django-admin-sortable" rel="nofollow">https://github.com/iambrandontaylor/django-admin-sortable</a></p> <p>Also, <a href="http://djangosuit.com/" rel="nofollow">django-suit</a> has builtin support for this</p>
3
2013-05-02T08:13:16Z
[ "javascript", "python", "django" ]
Re-ordering entries in a model using drag-and-drop
110,774
<p>Say I have a blogging app in Django. How can i re-order the posts using a draggable table in the default admin?</p> <p>It would be best if i didn't have to add any extra fields to the model, but if i really have to i can.</p>
8
2008-09-21T11:05:29Z
24,995,584
<p>You may try this snippet <a href="https://gist.github.com/barseghyanartur/1ebf927512b18dc2e5be" rel="nofollow">https://gist.github.com/barseghyanartur/1ebf927512b18dc2e5be</a> (originally based on this snippet <a href="http://djangosnippets.org/snippets/2160/" rel="nofollow">http://djangosnippets.org/snippets/2160/</a>).</p> <p>Integration is very simple.</p> <p>Your model (in models.py):</p> <pre><code>class MyModel(models.Model): name = models.CharField(max_length=255) order = models.IntegerField() # Other fields... class Meta: ordering = ('order',) </code></pre> <p>You admin (admin.py):</p> <pre><code>class MyModelAdmin(admin.ModelAdmin): fields = ('name', 'order',) # Add other fields here list_display = ('name', 'order',) list_editable = ('order',) class Media: js = ( '//code.jquery.com/jquery-1.4.2.js', '//code.jquery.com/ui/1.8.6/jquery-ui.js', 'path/to/sortable_list.js', ) </code></pre> <p>Change the JS (of the snippet) accordingly if your attributes responsible for holding the name and ordering are named differently in your model.</p>
0
2014-07-28T12:47:06Z
[ "javascript", "python", "django" ]
Dirty fields in django
110,803
<p>In my app i need to save changed values (old and new) when model gets saved. Any examples or working code?</p> <p>I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not.</p>
26
2008-09-21T11:27:24Z
110,821
<p>If you're using your own transactions (not the default admin application), you can save the before and after versions of your object. You can save the before version in the session, or you can put it in "hidden" fields in the form. Hidden fields is a security nightmare. Therefore, use the session to retain history of what's happening with this user.</p> <p>Additionally, of course, you do have to fetch the previous object so you can make changes to it. So you have several ways to monitor the differences.</p> <pre><code>def updateSomething( request, object_id ): object= Model.objects.get( id=object_id ) if request.method == "GET": request.session['before']= object form= SomethingForm( instance=object ) else request.method == "POST" form= SomethingForm( request.POST ) if form.is_valid(): # You have before in the session # You have the old object # You have after in the form.cleaned_data # Log the changes # Apply the changes to the object object.save() </code></pre>
1
2008-09-21T11:42:58Z
[ "python", "django" ]
Dirty fields in django
110,803
<p>In my app i need to save changed values (old and new) when model gets saved. Any examples or working code?</p> <p>I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not.</p>
26
2008-09-21T11:27:24Z
111,091
<p>You haven't said very much about your specific use case or needs. In particular, it would be helpful to know what you need to do with the change information (how long do you need to store it?). If you only need to store it for transient purposes, @S.Lott's session solution may be best. If you want a full audit trail of all changes to your objects stored in the DB, try this <a href="http://code.djangoproject.com/wiki/AuditTrail">AuditTrail solution</a>.</p> <p><strong>UPDATE</strong>: The AuditTrail code I linked to above is the closest I've seen to a full solution that would work for your case, though it has some limitations (doesn't work at all for ManyToMany fields). It will store all previous versions of your objects in the DB, so the admin could roll back to any previous version. You'd have to work with it a bit if you want the change to not take effect until approved.</p> <p>You could also build a custom solution based on something like @Armin Ronacher's DiffingMixin. You'd store the diff dictionary (maybe pickled?) in a table for the admin to review later and apply if desired (you'd need to write the code to take the diff dictionary and apply it to an instance).</p>
11
2008-09-21T14:04:00Z
[ "python", "django" ]
Dirty fields in django
110,803
<p>In my app i need to save changed values (old and new) when model gets saved. Any examples or working code?</p> <p>I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not.</p>
26
2008-09-21T11:27:24Z
111,364
<p>Django is currently sending all columns to the database, even if you just changed one. To change this, some changes in the database system would be necessary. This could be easily implemented on the existing code by adding a set of dirty fields to the model and adding column names to it, each time you <code>__set__</code> a column value.</p> <p>If you need that feature, I would suggest you look at the Django ORM, implement it and put a patch into the Django trac. It should be very easy to add that and it would help other users too. When you do that, add a hook that is called each time a column is set.</p> <p>If you don't want to hack on Django itself, you could copy the dict on object creation and diff it.</p> <p>Maybe with a mixin like this:</p> <pre><code>class DiffingMixin(object): def __init__(self, *args, **kwargs): super(DiffingMixin, self).__init__(*args, **kwargs) self._original_state = dict(self.__dict__) def get_changed_columns(self): missing = object() result = {} for key, value in self._original_state.iteritems(): if key != self.__dict__.get(key, missing): result[key] = value return result class MyModel(DiffingMixin, models.Model): pass </code></pre> <p>This code is untested but should work. When you call <code>model.get_changed_columns()</code> you get a dict of all changed values. This of course won't work for mutable objects in columns because the original state is a flat copy of the dict.</p>
10
2008-09-21T16:33:51Z
[ "python", "django" ]
Dirty fields in django
110,803
<p>In my app i need to save changed values (old and new) when model gets saved. Any examples or working code?</p> <p>I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not.</p>
26
2008-09-21T11:27:24Z
332,225
<p>I've found Armin's idea very useful. Here is my variation;</p> <pre><code>class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) self._original_state = self._as_dict() def _as_dict(self): return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) </code></pre> <p>Edit: I've tested this BTW.</p> <p>Sorry about the long lines. The difference is (aside from the names) it only caches local non-relation fields. In other words it doesn't cache a parent model's fields if present.</p> <p>And there's one more thing; you need to reset _original_state dict after saving. But I didn't want to overwrite save() method since most of the times we discard model instances after saving.</p> <pre><code>def save(self, *args, **kwargs): super(Klass, self).save(*args, **kwargs) self._original_state = self._as_dict() </code></pre>
18
2008-12-01T21:09:14Z
[ "python", "django" ]
Dirty fields in django
110,803
<p>In my app i need to save changed values (old and new) when model gets saved. Any examples or working code?</p> <p>I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not.</p>
26
2008-09-21T11:27:24Z
1,030,155
<p>for everyone's information, muhuk's solution fails under python2.6 as it raises an exception stating 'object.__ init __()' accepts no argument...</p> <p>edit: ho! apparently it might've been me misusing the the mixin... I didnt pay attention and declared it as the last parent and because of that the call to <strong>init</strong> ended up in the object parent rather than the next parent as it noramlly would with diamond diagram inheritance! so please disregard my comment :)</p>
-1
2009-06-23T01:03:09Z
[ "python", "django" ]
Dirty fields in django
110,803
<p>In my app i need to save changed values (old and new) when model gets saved. Any examples or working code?</p> <p>I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not.</p>
26
2008-09-21T11:27:24Z
1,716,046
<p>Continuing on Muhuk's suggestion &amp; adding Django's signals and a unique dispatch_uid you could reset the state on save without overriding save():</p> <pre><code>from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(self._reset_state, sender=self.__class__, dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__) self._reset_state() def _reset_state(self, *args, **kwargs): self._original_state = self._as_dict() def _as_dict(self): return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) </code></pre> <p>Which would clean the original state once saved without having to override save(). The code works but not sure what the performance penalty is of connecting signals at __init__</p>
3
2009-11-11T15:43:49Z
[ "python", "django" ]
Dirty fields in django
110,803
<p>In my app i need to save changed values (old and new) when model gets saved. Any examples or working code?</p> <p>I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not.</p>
26
2008-09-21T11:27:24Z
4,676,107
<p>I extended muhuk and smn's solutions to include difference checking on the primary keys for foreign key and one-to-one fields:</p> <pre><code>from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(self._reset_state, sender=self.__class__, dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__) self._reset_state() def _reset_state(self, *args, **kwargs): self._original_state = self._as_dict() def _as_dict(self): return dict([(f.attname, getattr(self, f.attname)) for f in self._meta.local_fields]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) </code></pre> <p>The only difference is in <code>_as_dict</code> I changed the last line from</p> <pre><code>return dict([ (f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel ]) </code></pre> <p>to</p> <pre><code>return dict([ (f.attname, getattr(self, f.attname)) for f in self._meta.local_fields ]) </code></pre> <p>This mixin, like the ones above, can be used like so:</p> <pre><code>class MyModel(DirtyFieldsMixin, models.Model): .... </code></pre>
3
2011-01-13T02:03:00Z
[ "python", "django" ]
Dirty fields in django
110,803
<p>In my app i need to save changed values (old and new) when model gets saved. Any examples or working code?</p> <p>I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not.</p>
26
2008-09-21T11:27:24Z
11,011,415
<p>I extended Trey Hunner's solution to support m2m relationships. Hopefully this will help others looking for a similar solution.</p> <pre><code>from django.db.models.signals import post_save DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(self._reset_state, sender=self.__class__, dispatch_uid='%s._reset_state' % self.__class__.__name__) self._reset_state() def _as_dict(self): fields = dict([ (f.attname, getattr(self, f.attname)) for f in self._meta.local_fields ]) m2m_fields = dict([ (f.attname, set([ obj.id for obj in getattr(self, f.attname).all() ])) for f in self._meta.local_many_to_many ]) return fields, m2m_fields def _reset_state(self, *args, **kwargs): self._original_state, self._original_m2m_state = self._as_dict() def get_dirty_fields(self): new_state, new_m2m_state = self._as_dict() changed_fields = dict([ (key, value) for key, value in self._original_state.iteritems() if value != new_state[key] ]) changed_m2m_fields = dict([ (key, value) for key, value in self._original_m2m_state.iteritems() if sorted(value) != sorted(new_m2m_state[key]) ]) return changed_fields, changed_m2m_fields </code></pre> <p>One may also wish to merge the two field lists. For that, replace the last line</p> <pre><code>return changed_fields, changed_m2m_fields </code></pre> <p>with</p> <pre><code>changed_fields.update(changed_m2m_fields) return changed_fields </code></pre>
6
2012-06-13T08:57:22Z
[ "python", "django" ]
Dirty fields in django
110,803
<p>In my app i need to save changed values (old and new) when model gets saved. Any examples or working code?</p> <p>I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not.</p>
26
2008-09-21T11:27:24Z
34,525,671
<p>An updated solution with m2m support (using updated <a href="https://github.com/romgar/django-dirtyfields" rel="nofollow">dirtyfields</a> and new <a href="https://docs.djangoproject.com/en/1.9/ref/models/meta/" rel="nofollow">_meta API</a> and some bug fixes), based on @Trey and @Tony's above. This has passed some basic light testing for me.</p> <pre><code>from dirtyfields import DirtyFieldsMixin class M2MDirtyFieldsMixin(DirtyFieldsMixin): def __init__(self, *args, **kwargs): super(M2MDirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect( reset_state, sender=self.__class__, dispatch_uid='{name}-DirtyFieldsMixin-sweeper'.format( name=self.__class__.__name__)) reset_state(sender=self.__class__, instance=self) def _as_dict_m2m(self): if self.pk: m2m_fields = dict([ (f.attname, set([ obj.id for obj in getattr(self, f.attname).all() ])) for f,model in self._meta.get_m2m_with_model() ]) return m2m_fields return {} def get_dirty_fields(self, check_relationship=False): changed_fields = super(M2MDirtyFieldsMixin, self).get_dirty_fields(check_relationship) new_m2m_state = self._as_dict_m2m() changed_m2m_fields = dict([ (key, value) for key, value in self._original_m2m_state.iteritems() if sorted(value) != sorted(new_m2m_state[key]) ]) changed_fields.update(changed_m2m_fields) return changed_fields def reset_state(sender, instance, **kwargs): # original state should hold all possible dirty fields to avoid # getting a `KeyError` when checking if a field is dirty or not instance._original_state = instance._as_dict(check_relationship=True) instance._original_m2m_state = instance._as_dict_m2m() </code></pre>
0
2015-12-30T08:26:30Z
[ "python", "django" ]
Dirty fields in django
110,803
<p>In my app i need to save changed values (old and new) when model gets saved. Any examples or working code?</p> <p>I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not.</p>
26
2008-09-21T11:27:24Z
34,552,017
<p>Adding a second answer because <strong>a lot has changed since the time this questions was originally posted</strong>.</p> <p>There are a number of apps in the Django world that solve this problem now. You can find a full <a href="https://www.djangopackages.com/grids/g/model-audit/" rel="nofollow">list of model auditing and history apps</a> on the Django Packages site.</p> <p>I wrote <a href="https://treyhunner.com/2011/09/django-and-model-history/" rel="nofollow">a blog post</a> comparing a few of these apps. This post is now 4 years old and it's a little dated. The different approaches for solving this problem seem to be the same though.</p> <p>The approaches:</p> <ol> <li>Store all historical changes in a serialized format (JSON?) in a single table</li> <li>Store all historical changes in a table mirroring the original for each model</li> <li>Store all historical changes in the same table as the original model (I don't recommend this)</li> </ol> <p>The <a href="https://github.com/etianen/django-reversion" rel="nofollow">django-reversion</a> package still seems to be the most popular solution to this problem. It takes the first approach: serialize changes instead of mirroring tables.</p> <p>I revived <a href="https://github.com/treyhunner/django-simple-history" rel="nofollow">django-simple-history</a> a few years back. It takes the second approach: mirror each table.</p> <p>So I would recommend <strong>using an app to solve this problem</strong>. There's a couple of popular ones that work pretty well at this point.</p> <p>Oh and if you're just looking for dirty field checking and not storing all historical changes, check out <a href="https://django-model-utils.readthedocs.org/en/latest/utilities.html#field-tracker" rel="nofollow">FieldTracker from django-model-utils</a>.</p>
3
2015-12-31T22:11:05Z
[ "python", "django" ]
Close a tkinter window?
110,923
<p>How do I end a Tkinter program? Let's say I have this code:</p> <pre><code>from Tkinter import * def quit(): # code to exit root = Tk() Button(root, text="Quit", command=quit).pack() root.mainloop() </code></pre> <p>How should I define the <code>quit</code> function?</p>
32
2008-09-21T12:40:04Z
110,929
<p>We can use:</p> <pre><code>def quit(): root.quit() </code></pre> <p>or</p> <pre><code>def quit(): root.destroy() </code></pre>
32
2008-09-21T12:44:01Z
[ "python", "tkinter" ]
Close a tkinter window?
110,923
<p>How do I end a Tkinter program? Let's say I have this code:</p> <pre><code>from Tkinter import * def quit(): # code to exit root = Tk() Button(root, text="Quit", command=quit).pack() root.mainloop() </code></pre> <p>How should I define the <code>quit</code> function?</p>
32
2008-09-21T12:40:04Z
111,011
<p>The usual method to exit a Python program:</p> <pre><code>sys.exit() </code></pre> <p>(to which you can also pass an exit status) or </p> <pre><code>raise SystemExit </code></pre> <p>will work fine in a Tkinter program.</p>
3
2008-09-21T13:24:39Z
[ "python", "tkinter" ]
Close a tkinter window?
110,923
<p>How do I end a Tkinter program? Let's say I have this code:</p> <pre><code>from Tkinter import * def quit(): # code to exit root = Tk() Button(root, text="Quit", command=quit).pack() root.mainloop() </code></pre> <p>How should I define the <code>quit</code> function?</p>
32
2008-09-21T12:40:04Z
294,199
<pre><code>import Tkinter as tk def quit(root): root.destroy() root = tk.Tk() tk.Button(root, text="Quit", command=lambda root=root:quit(root)).pack() root.mainloop() </code></pre>
11
2008-11-16T18:36:55Z
[ "python", "tkinter" ]
Close a tkinter window?
110,923
<p>How do I end a Tkinter program? Let's say I have this code:</p> <pre><code>from Tkinter import * def quit(): # code to exit root = Tk() Button(root, text="Quit", command=quit).pack() root.mainloop() </code></pre> <p>How should I define the <code>quit</code> function?</p>
32
2008-09-21T12:40:04Z
15,577,605
<pre><code>root.quit() </code></pre> <p>Above line just <strong>Bypasses</strong> the <code>root.mainloop()</code> i.e root.mainloop() will still be running in background if quit() command is executed.</p> <pre><code>root.destroy() </code></pre> <p>While destroy() command vanish out <code>root.mainloop()</code> i.e root.mainloop() stops.</p> <p>So as you just want to quit the program so you should use <code>root.destroy()</code> as it will it stop the mainloop().</p> <p>But if you want to run some infinite loop and you don't want to destroy your Tk window and want to execute some code after <code>root.mainloop()</code> line then you should use <code>root.quit()</code>. Ex:</p> <pre><code>from Tkinter import * def quit(): global root root.quit() root = Tk() while True: Button(root, text="Quit", command=quit).pack() root.mainloop() #do something </code></pre>
25
2013-03-22T18:39:54Z
[ "python", "tkinter" ]
Close a tkinter window?
110,923
<p>How do I end a Tkinter program? Let's say I have this code:</p> <pre><code>from Tkinter import * def quit(): # code to exit root = Tk() Button(root, text="Quit", command=quit).pack() root.mainloop() </code></pre> <p>How should I define the <code>quit</code> function?</p>
32
2008-09-21T12:40:04Z
18,852,907
<p>I think you wrongly understood the quit function of Tkinter, This function does not require you to define.</p> <p>First, you should modify your function as follows:</p> <pre><code>from Tkinter import * root = Tk() Button(root, text="Quit", command=root.quit).pack() root.mainloop() </code></pre> <p>Then, you should use '.pyw' suffix to save this files and double-click the '.pyw' file to run your GUI, this time, you can end the GUI with a click of the Botton, and you can also find that there will be no unpleasant DOS window.(If you run the '.py' file, the quit function will fail.)</p> <p>This is my first time to answer question in here, and my English is really very very very poor! I hope you can understand it!!! Thank you very much!!!</p>
4
2013-09-17T14:41:22Z
[ "python", "tkinter" ]
Close a tkinter window?
110,923
<p>How do I end a Tkinter program? Let's say I have this code:</p> <pre><code>from Tkinter import * def quit(): # code to exit root = Tk() Button(root, text="Quit", command=quit).pack() root.mainloop() </code></pre> <p>How should I define the <code>quit</code> function?</p>
32
2008-09-21T12:40:04Z
30,480,553
<p>try this. </p> <pre><code> self.parent.destroy() self.parent.quit() </code></pre> <p>maybe you send root like parameter to a frame that you did. so If you want to finish it you have to call your father so he can close it all, instead of closing each one of his children. </p>
-2
2015-05-27T11:00:51Z
[ "python", "tkinter" ]
Close a tkinter window?
110,923
<p>How do I end a Tkinter program? Let's say I have this code:</p> <pre><code>from Tkinter import * def quit(): # code to exit root = Tk() Button(root, text="Quit", command=quit).pack() root.mainloop() </code></pre> <p>How should I define the <code>quit</code> function?</p>
32
2008-09-21T12:40:04Z
36,854,719
<p>I'm thinking of making an RPG with Tkinter, and I find that if use a while True loop, make sure you save progress or whatever, and then use something like this:</p> <pre><code> import Tkinter root=Tkinter.Tk() def q(): exit() while True: Button(root, text="Quit", command=q).pack() root.mainloop() </code></pre> <p>Worked for me!</p> <p>It does just stop the program but the root.destroy() or root.quit() wasn't working for me. exit() worked fine!</p>
0
2016-04-26T03:23:54Z
[ "python", "tkinter" ]
Close a tkinter window?
110,923
<p>How do I end a Tkinter program? Let's say I have this code:</p> <pre><code>from Tkinter import * def quit(): # code to exit root = Tk() Button(root, text="Quit", command=quit).pack() root.mainloop() </code></pre> <p>How should I define the <code>quit</code> function?</p>
32
2008-09-21T12:40:04Z
39,130,749
<p>Use root.destroy()! Works for me just fine.</p>
-1
2016-08-24T18:38:15Z
[ "python", "tkinter" ]
Close a tkinter window?
110,923
<p>How do I end a Tkinter program? Let's say I have this code:</p> <pre><code>from Tkinter import * def quit(): # code to exit root = Tk() Button(root, text="Quit", command=quit).pack() root.mainloop() </code></pre> <p>How should I define the <code>quit</code> function?</p>
32
2008-09-21T12:40:04Z
39,174,800
<p>Illumination in case of confusion...</p> <pre><code>def quit(self): self.destroy() exit() </code></pre> <p>A) destroy() stops the mainloop and kills the window, but leaves python running</p> <p>B) exit() stops the whole process</p> <p>Just to clarify in case someone missed what destroy() was doing, and the OP also asked how to "end" a tkinter program.</p>
0
2016-08-26T21:22:15Z
[ "python", "tkinter" ]
Close a tkinter window?
110,923
<p>How do I end a Tkinter program? Let's say I have this code:</p> <pre><code>from Tkinter import * def quit(): # code to exit root = Tk() Button(root, text="Quit", command=quit).pack() root.mainloop() </code></pre> <p>How should I define the <code>quit</code> function?</p>
32
2008-09-21T12:40:04Z
39,336,070
<p>Try this:</p> <pre><code>from Tkinter import * root = Tk() Button(root, text="Quit", command=lambda:quit).pack() root.mainloop() </code></pre>
-1
2016-09-05T18:38:22Z
[ "python", "tkinter" ]
How do I handle the window close event in Tkinter?
111,155
<p>How do I handle the window close event (user clicking the 'X' button) in a Python Tkinter program?</p>
43
2008-09-21T14:46:20Z
111,160
<p>Tkinter supports a mechanism called <a href="http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm#protocols"><em>protocol handlers</em></a>. Here, the term <em>protocol</em> refers to the interaction between the application and the window manager. The most commonly used protocol is called <code>WM_DELETE_WINDOW</code>, and is used to define what happens when the user explicitly closes a window using the window manager.</p> <p>You can use the <code>protocol</code> method to <em>install a handler</em> for this protocol (the widget must be a <code>Tk</code> or <code>Toplevel</code> widget):</p> <p>Here you have a concrete example:</p> <pre><code>import tkinter as tk from tkinter import messagebox root = tk.Tk() def on_closing(): if messagebox.askokcancel("Quit", "Do you want to quit?"): root.destroy() root.protocol("WM_DELETE_WINDOW", on_closing) root.mainloop() </code></pre>
51
2008-09-21T14:51:11Z
[ "python", "events", "tkinter", "window" ]
How do I handle the window close event in Tkinter?
111,155
<p>How do I handle the window close event (user clicking the 'X' button) in a Python Tkinter program?</p>
43
2008-09-21T14:46:20Z
6,164,146
<p>Use the closeEvent</p> <pre><code>def closeEvent(self, event): # code to be executed </code></pre>
-10
2011-05-28T20:22:39Z
[ "python", "events", "tkinter", "window" ]
How do I handle the window close event in Tkinter?
111,155
<p>How do I handle the window close event (user clicking the 'X' button) in a Python Tkinter program?</p>
43
2008-09-21T14:46:20Z
14,819,661
<p>Matt has shown one classic modification of the close button.<br> The other is to have the close button minimize the window.<br> You can reproduced this behavior by having the <a href="http://effbot.org/tkinterbook/wm.htm#Tkinter.Wm.iconify-method" rel="nofollow"><em>iconify</em></a> method<br> be the <a href="http://effbot.org/tkinterbook/wm.htm#Tkinter.Wm.protocol-method" rel="nofollow"><em>protocol</em></a> method's second argument.</p> <p>Here's a working example, tested on Windows 7:</p> <pre><code># Python 3 import tkinter import tkinter.scrolledtext as scrolledtext class GUI(object): def __init__(self): root = self.root = tkinter.Tk() root.title('Test') # make the top right close button minimize (iconify) the main window root.protocol("WM_DELETE_WINDOW", root.iconify) # make Esc exit the program root.bind('&lt;Escape&gt;', lambda e: root.destroy()) # create a menu bar with an Exit command menubar = tkinter.Menu(root) filemenu = tkinter.Menu(menubar, tearoff=0) filemenu.add_command(label="Exit", command=root.destroy) menubar.add_cascade(label="File", menu=filemenu) root.config(menu=menubar) # create a Text widget with a Scrollbar attached txt = scrolledtext.ScrolledText(root, undo=True) txt['font'] = ('consolas', '12') txt.pack(expand=True, fill='both') gui = GUI() gui.root.mainloop() </code></pre> <p>In this example we give the user two new exit options:<br> the classic file menu -> Exit, and also the <kbd>Esc</kbd> button.</p>
7
2013-02-11T19:46:39Z
[ "python", "events", "tkinter", "window" ]
What is a "callable" in Python?
111,234
<p>Now that it's clear <a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">what a metaclass is</a>, there is an associated concept that I use all the time without knowing what it really means. </p> <p>I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using <code>__init__</code> and <code>__new__</code> lead to wonder what this bloody <code>__call__</code> can be used for.</p> <p>Could you give me some explanations, including examples with the magic method ?</p>
170
2008-09-21T15:34:32Z
111,251
<p>A Callable is an object that has the <code>__call__</code> method. This means you can fake callable functions or do neat things like <a href="http://www.python.org/dev/peps/pep-0309/">Partial Function Application</a> where you take a function and add something that enhances it or fills in some of the parameters, returning something that can be called in turn (known as <a href="http://en.wikipedia.org/wiki/Currying">Currying</a> in functional programming circles).</p> <p>Certain typographic errors will have the interpreter attempting to call something you did not intend, such as (for example) a string. This can produce errors where the interpreter attempts to execute a non-callable application. You can see this happening in a python interpreter by doing something like the transcript below.</p> <pre><code>[nigel@k9 ~]$ python Python 2.5 (r25:51908, Nov 6 2007, 15:55:44) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; 'aaa'() # &lt;== Here we attempt to call a string. Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'str' object is not callable &gt;&gt;&gt; </code></pre>
8
2008-09-21T15:43:15Z
[ "python", "callable" ]
What is a "callable" in Python?
111,234
<p>Now that it's clear <a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">what a metaclass is</a>, there is an associated concept that I use all the time without knowing what it really means. </p> <p>I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using <code>__init__</code> and <code>__new__</code> lead to wonder what this bloody <code>__call__</code> can be used for.</p> <p>Could you give me some explanations, including examples with the magic method ?</p>
170
2008-09-21T15:34:32Z
111,252
<p>Quite simply, a "callable" is something that can be called like a method. The built in function "callable()" will tell you whether something appears to be callable, as will checking for a <strong>call</strong> property. Functions are callable as are classes, class instances can be callable. See more about this <a href="http://docs.python.org/lib/built-in-funcs.html">here</a> and <a href="http://www.peterbe.com/plog/callable-python-objects">here</a>.</p>
5
2008-09-21T15:43:20Z
[ "python", "callable" ]
What is a "callable" in Python?
111,234
<p>Now that it's clear <a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">what a metaclass is</a>, there is an associated concept that I use all the time without knowing what it really means. </p> <p>I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using <code>__init__</code> and <code>__new__</code> lead to wonder what this bloody <code>__call__</code> can be used for.</p> <p>Could you give me some explanations, including examples with the magic method ?</p>
170
2008-09-21T15:34:32Z
111,253
<p>It's something you can put "(args)" after and expect it to work. A callable is usually a method or a class. Methods get called, classes get instantiated.</p>
0
2008-09-21T15:43:44Z
[ "python", "callable" ]
What is a "callable" in Python?
111,234
<p>Now that it's clear <a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">what a metaclass is</a>, there is an associated concept that I use all the time without knowing what it really means. </p> <p>I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using <code>__init__</code> and <code>__new__</code> lead to wonder what this bloody <code>__call__</code> can be used for.</p> <p>Could you give me some explanations, including examples with the magic method ?</p>
170
2008-09-21T15:34:32Z
111,255
<p>A callable is anything that can be called. </p> <p>The <a href="http://svn.python.org/projects/python/trunk/Objects/object.c">built-in <em>callable</em> (PyCallable_Check in objects.c)</a> checks if the argument is either:</p> <ul> <li>an instance of a class with a <em>__call__</em> method or</li> <li>is of a type that has a non null <em>tp_call</em> (c struct) member which indicates callability otherwise (such as in functions, methods etc.)</li> </ul> <p>The method named <em>__call__</em> is (<a href="http://docs.python.org/ref/callable-types.html">according to the documentation</a>)</p> <blockquote> <p>Called when the instance is ''called'' as a function</p> </blockquote> <h2>Example</h2> <pre><code>class Foo: def __call__(self): print 'called' foo_instance = Foo() foo_instance() #this is calling the __call__ method </code></pre>
181
2008-09-21T15:44:22Z
[ "python", "callable" ]
What is a "callable" in Python?
111,234
<p>Now that it's clear <a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">what a metaclass is</a>, there is an associated concept that I use all the time without knowing what it really means. </p> <p>I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using <code>__init__</code> and <code>__new__</code> lead to wonder what this bloody <code>__call__</code> can be used for.</p> <p>Could you give me some explanations, including examples with the magic method ?</p>
170
2008-09-21T15:34:32Z
111,267
<p><code>__call__</code> makes any object be callable as a function.</p> <p>This example will output 8:</p> <pre><code>class Adder(object): def __init__(self, val): self.val = val def __call__(self, val): return self.val + val func = Adder(5) print func(3) </code></pre>
5
2008-09-21T15:49:28Z
[ "python", "callable" ]
What is a "callable" in Python?
111,234
<p>Now that it's clear <a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">what a metaclass is</a>, there is an associated concept that I use all the time without knowing what it really means. </p> <p>I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using <code>__init__</code> and <code>__new__</code> lead to wonder what this bloody <code>__call__</code> can be used for.</p> <p>Could you give me some explanations, including examples with the magic method ?</p>
170
2008-09-21T15:34:32Z
111,371
<p>In Python a callable is an object which type has a <code>__call__</code> method:</p> <pre><code>&gt;&gt;&gt; class Foo: ... pass ... &gt;&gt;&gt; class Bar(object): ... pass ... &gt;&gt;&gt; type(Foo).__call__(Foo) &lt;__main__.Foo instance at 0x711440&gt; &gt;&gt;&gt; type(Bar).__call__(Bar) &lt;__main__.Bar object at 0x712110&gt; &gt;&gt;&gt; def foo(bar): ... return bar ... &gt;&gt;&gt; type(foo).__call__(foo, 42) 42 </code></pre> <p>As simple as that :)</p> <p>This of course can be overloaded:</p> <pre><code>&gt;&gt;&gt; class Foo(object): ... def __call__(self): ... return 42 ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; f() 42 </code></pre>
2
2008-09-21T16:37:09Z
[ "python", "callable" ]
What is a "callable" in Python?
111,234
<p>Now that it's clear <a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">what a metaclass is</a>, there is an associated concept that I use all the time without knowing what it really means. </p> <p>I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using <code>__init__</code> and <code>__new__</code> lead to wonder what this bloody <code>__call__</code> can be used for.</p> <p>Could you give me some explanations, including examples with the magic method ?</p>
170
2008-09-21T15:34:32Z
115,349
<p>From Python's sources <a href="http://svn.python.org/view/python/trunk/Objects/object.c?rev=64962&amp;view=markup">object.c</a>:</p> <pre class="lang-c prettyprint-override"><code>/* Test whether an object can be called */ int PyCallable_Check(PyObject *x) { if (x == NULL) return 0; if (PyInstance_Check(x)) { PyObject *call = PyObject_GetAttrString(x, "__call__"); if (call == NULL) { PyErr_Clear(); return 0; } /* Could test recursively but don't, for fear of endless recursion if some joker sets self.__call__ = self */ Py_DECREF(call); return 1; } else { return x-&gt;ob_type-&gt;tp_call != NULL; } } </code></pre> <p>It says:</p> <ol> <li>If an object is an instance of some class then it is callable <em>iff</em> it has <code>__call__</code> attribute.</li> <li>Else the object <code>x</code> is callable <em>iff</em> <code>x-&gt;ob_type-&gt;tp_call != NULL</code></li> </ol> <p>Desciption of <a href="http://docs.python.org/api/type-structs.html"><code>tp_call</code> field</a>:</p> <blockquote> <p><code>ternaryfunc tp_call</code> An optional pointer to a function that implements calling the object. This should be NULL if the object is not callable. The signature is the same as for PyObject_Call(). This field is inherited by subtypes.</p> </blockquote> <p>You can always use built-in <code>callable</code> function to determine whether given object is callable or not; or better yet just call it and catch <code>TypeError</code> later. <code>callable</code> is removed in Python 3.0 and 3.1, use <code>callable = lambda o: hasattr(o, '__call__')</code> or <code>isinstance(o, collections.Callable)</code>.</p> <p>Example, a simplistic cache implementation:</p> <pre><code>class Cached: def __init__(self, function): self.function = function self.cache = {} def __call__(self, *args): try: return self.cache[args] except KeyError: ret = self.cache[args] = self.function(*args) return ret </code></pre> <p>Usage:</p> <pre><code>@Cached def ack(x, y): return ack(x-1, ack(x, y-1)) if x*y else (x + y + 1) </code></pre> <p>Example from standard library, file <a href="http://svn.python.org/projects/python/trunk/Lib/site.py"><code>site.py</code></a>, definition of built-in <code>exit()</code> and <code>quit()</code> functions:</p> <pre><code>class Quitter(object): def __init__(self, name): self.name = name def __repr__(self): return 'Use %s() or %s to exit' % (self.name, eof) def __call__(self, code=None): # Shells like IDLE catch the SystemExit, but listen when their # stdin wrapper is closed. try: sys.stdin.close() except: pass raise SystemExit(code) __builtin__.quit = Quitter('quit') __builtin__.exit = Quitter('exit') </code></pre>
59
2008-09-22T15:04:53Z
[ "python", "callable" ]
What is a "callable" in Python?
111,234
<p>Now that it's clear <a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">what a metaclass is</a>, there is an associated concept that I use all the time without knowing what it really means. </p> <p>I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using <code>__init__</code> and <code>__new__</code> lead to wonder what this bloody <code>__call__</code> can be used for.</p> <p>Could you give me some explanations, including examples with the magic method ?</p>
170
2008-09-21T15:34:32Z
139,469
<p>A callable is an object allows you to use round parenthesis ( ) and eventually pass some parameters, just like functions.</p> <p>Every time you define a function python creates a callable object. In example, you could define the function <strong>func</strong> in these ways (it's the same):</p> <pre><code>class a(object): def __call__(self, *args): print 'Hello' func = a() # or ... def func(*args): print 'Hello' </code></pre> <p>You could use this method instead of methods like <strong>doit</strong> or <strong>run</strong>, I think it's just more clear to see obj() than obj.doit()</p>
19
2008-09-26T13:22:20Z
[ "python", "callable" ]
What is a "callable" in Python?
111,234
<p>Now that it's clear <a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">what a metaclass is</a>, there is an associated concept that I use all the time without knowing what it really means. </p> <p>I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using <code>__init__</code> and <code>__new__</code> lead to wonder what this bloody <code>__call__</code> can be used for.</p> <p>Could you give me some explanations, including examples with the magic method ?</p>
170
2008-09-21T15:34:32Z
3,665,797
<p>Good examples <a href="http://diveintopython.net/power_of_introspection/built_in_functions.html#apihelper.builtin.callable" rel="nofollow">here</a>.</p>
0
2010-09-08T08:18:48Z
[ "python", "callable" ]
What is a "callable" in Python?
111,234
<p>Now that it's clear <a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">what a metaclass is</a>, there is an associated concept that I use all the time without knowing what it really means. </p> <p>I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using <code>__init__</code> and <code>__new__</code> lead to wonder what this bloody <code>__call__</code> can be used for.</p> <p>Could you give me some explanations, including examples with the magic method ?</p>
170
2008-09-21T15:34:32Z
8,870,179
<p>to find out an object is callable or not try this</p> <pre><code>x=234 for i in dir(x): if i.startswith("__call__"): print i </code></pre> <p>there will be no output here.</p> <pre><code>def add(x,y): return x+y for i in dir(add): if i.startswith("__call__"): print i &gt;&gt;&gt;__call__ </code></pre>
-1
2012-01-15T14:00:12Z
[ "python", "callable" ]
What is a "callable" in Python?
111,234
<p>Now that it's clear <a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">what a metaclass is</a>, there is an associated concept that I use all the time without knowing what it really means. </p> <p>I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using <code>__init__</code> and <code>__new__</code> lead to wonder what this bloody <code>__call__</code> can be used for.</p> <p>Could you give me some explanations, including examples with the magic method ?</p>
170
2008-09-21T15:34:32Z
10,489,545
<p>callables implement the <code>__call__</code> special method so any object with such a method is callable.</p>
0
2012-05-07T21:40:12Z
[ "python", "callable" ]
What is a "callable" in Python?
111,234
<p>Now that it's clear <a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">what a metaclass is</a>, there is an associated concept that I use all the time without knowing what it really means. </p> <p>I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using <code>__init__</code> and <code>__new__</code> lead to wonder what this bloody <code>__call__</code> can be used for.</p> <p>Could you give me some explanations, including examples with the magic method ?</p>
170
2008-09-21T15:34:32Z
15,581,536
<p>Let me explain backwards:</p> <p>Consider this...</p> <pre><code>foo() </code></pre> <p>... as syntactic sugar for:</p> <pre><code>foo.__call__() </code></pre> <p>Where <code>foo</code> can be any object that responds to <code>__call__</code>. When I say any object, I mean it: built-in types, your own classes and their instances.</p> <p>In the case of built-in types, when you write:</p> <pre><code>int('10') unicode(10) </code></pre> <p>You're essentially doing:</p> <pre><code>int.__call__('10') unicode.__call__(10) </code></pre> <p>That's also why you don't have <code>foo = new int</code> in Python: you just make the class object return an instance of it on <code>__call__</code>. The way Python solves this is very elegant in my opinion.</p>
12
2013-03-22T23:38:33Z
[ "python", "callable" ]
What is a "callable" in Python?
111,234
<p>Now that it's clear <a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">what a metaclass is</a>, there is an associated concept that I use all the time without knowing what it really means. </p> <p>I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using <code>__init__</code> and <code>__new__</code> lead to wonder what this bloody <code>__call__</code> can be used for.</p> <p>Could you give me some explanations, including examples with the magic method ?</p>
170
2008-09-21T15:34:32Z
39,591,208
<p>To check function or method of class is callable or not that means we can call that function.</p> <pre><code>Class A: def __init__(self,val): self.val = val def bar(self): print "bar" obj = A() callable(obj.bar) True callable(obj.__init___) False def foo(): return "s" callable(foo) True callable(foo()) False </code></pre>
1
2016-09-20T10:03:37Z
[ "python", "callable" ]
How do I find out the size of a canvas item in Python/Tkinter?
111,934
<p>I want to create some text in a canvas:</p> <pre><code>myText = self.canvas.create_text(5, 5, anchor=NW, text="TEST") </code></pre> <p>Now how do I find the width and height of myText?</p>
3
2008-09-21T20:08:56Z
111,974
<pre><code>bounds = self.canvas.bbox(myText) # returns a tuple like (x1, y1, x2, y2) width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] </code></pre> <p>See the <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/canvas-methods.html">TkInter reference</a>.</p>
11
2008-09-21T20:19:34Z
[ "python", "tkinter", "tkinter-canvas" ]
How do I find out the size of a canvas item in Python/Tkinter?
111,934
<p>I want to create some text in a canvas:</p> <pre><code>myText = self.canvas.create_text(5, 5, anchor=NW, text="TEST") </code></pre> <p>Now how do I find the width and height of myText?</p>
3
2008-09-21T20:08:56Z
35,139,726
<p>This method seemed to work well if all you are interested in is the width and height of the canvas being considered, using the bounds of the box and then checking the differential works just as well if you want to do it that way.</p> <pre><code>width = myText.winfo_width() height = myText.winfo_height() </code></pre>
1
2016-02-01T20:29:43Z
[ "python", "tkinter", "tkinter-canvas" ]
Is there any way to do HTTP PUT in python
111,945
<p>I need to upload some data to a server using HTTP <code>PUT</code> in python. From my brief reading of the urllib2 docs, it only does HTTP <code>POST</code>. Is there any way to do an HTTP <code>PUT</code> in python?</p>
166
2008-09-21T20:11:05Z
111,952
<p>Have you taken a look at <a href="http://inamidst.com/proj/put/put.py" rel="nofollow">put.py</a>? I've used it in the past. You can also just hack up your own request with urllib.</p>
2
2008-09-21T20:12:49Z
[ "python", "http", "put" ]
Is there any way to do HTTP PUT in python
111,945
<p>I need to upload some data to a server using HTTP <code>PUT</code> in python. From my brief reading of the urllib2 docs, it only does HTTP <code>POST</code>. Is there any way to do an HTTP <code>PUT</code> in python?</p>
166
2008-09-21T20:11:05Z
111,968
<p>You can of course roll your own with the existing standard libraries at any level from sockets up to tweaking urllib.</p> <p><a href="http://pycurl.sourceforge.net/" rel="nofollow">http://pycurl.sourceforge.net/</a></p> <p>"PyCurl is a Python interface to libcurl."</p> <p>"libcurl is a free and easy-to-use client-side URL transfer library, ... supports ... HTTP PUT"</p> <p>"The main drawback with PycURL is that it is a relative thin layer over libcurl without any of those nice Pythonic class hierarchies. This means it has a somewhat steep learning curve unless you are already familiar with libcurl's C API. "</p>
2
2008-09-21T20:17:08Z
[ "python", "http", "put" ]
Is there any way to do HTTP PUT in python
111,945
<p>I need to upload some data to a server using HTTP <code>PUT</code> in python. From my brief reading of the urllib2 docs, it only does HTTP <code>POST</code>. Is there any way to do an HTTP <code>PUT</code> in python?</p>
166
2008-09-21T20:11:05Z
111,973
<p>You should have a look at the <a href="http://docs.python.org/lib/module-httplib.html">httplib module</a>. It should let you make whatever sort of HTTP request you want.</p>
8
2008-09-21T20:18:57Z
[ "python", "http", "put" ]
Is there any way to do HTTP PUT in python
111,945
<p>I need to upload some data to a server using HTTP <code>PUT</code> in python. From my brief reading of the urllib2 docs, it only does HTTP <code>POST</code>. Is there any way to do an HTTP <code>PUT</code> in python?</p>
166
2008-09-21T20:11:05Z
111,988
<pre><code>import urllib2 opener = urllib2.build_opener(urllib2.HTTPHandler) request = urllib2.Request('http://example.org', data='your_put_data') request.add_header('Content-Type', 'your/contenttype') request.get_method = lambda: 'PUT' url = opener.open(request) </code></pre>
197
2008-09-21T20:24:21Z
[ "python", "http", "put" ]
Is there any way to do HTTP PUT in python
111,945
<p>I need to upload some data to a server using HTTP <code>PUT</code> in python. From my brief reading of the urllib2 docs, it only does HTTP <code>POST</code>. Is there any way to do an HTTP <code>PUT</code> in python?</p>
166
2008-09-21T20:11:05Z
114,648
<p>I needed to solve this problem too a while back so that I could act as a client for a RESTful API. I settled on httplib2 because it allowed me to send PUT and DELETE in addition to GET and POST. Httplib2 is not part of the standard library but you can easily get it from the cheese shop.</p>
8
2008-09-22T12:46:40Z
[ "python", "http", "put" ]
Is there any way to do HTTP PUT in python
111,945
<p>I need to upload some data to a server using HTTP <code>PUT</code> in python. From my brief reading of the urllib2 docs, it only does HTTP <code>POST</code>. Is there any way to do an HTTP <code>PUT</code> in python?</p>
166
2008-09-21T20:11:05Z
116,122
<p>I also recommend <a href="http://code.google.com/p/httplib2/" rel="nofollow">httplib2</a> by Joe Gregario. I use this regularly instead of httplib in the standard lib.</p>
6
2008-09-22T17:05:30Z
[ "python", "http", "put" ]
Is there any way to do HTTP PUT in python
111,945
<p>I need to upload some data to a server using HTTP <code>PUT</code> in python. From my brief reading of the urllib2 docs, it only does HTTP <code>POST</code>. Is there any way to do an HTTP <code>PUT</code> in python?</p>
166
2008-09-21T20:11:05Z
3,919,484
<p>Httplib seems like a cleaner choice.</p> <pre><code>import httplib connection = httplib.HTTPConnection('1.2.3.4:1234') body_content = 'BODY CONTENT GOES HERE' connection.request('PUT', '/url/path/to/put/to', body_content) result = connection.getresponse() # Now result.status and result.reason contains interesting stuff </code></pre>
45
2010-10-12T22:13:42Z
[ "python", "http", "put" ]
Is there any way to do HTTP PUT in python
111,945
<p>I need to upload some data to a server using HTTP <code>PUT</code> in python. From my brief reading of the urllib2 docs, it only does HTTP <code>POST</code>. Is there any way to do an HTTP <code>PUT</code> in python?</p>
166
2008-09-21T20:11:05Z
8,259,648
<p>I've used a variety of python HTTP libs in the past, and I've settled on '<a href="http://docs.python-requests.org/en/latest/index.html">Requests</a>' as my favourite. Existing libs had pretty useable interfaces, but code can end up being a few lines too long for simple operations. A basic PUT in requests looks like:</p> <pre><code>payload = {'username': 'bob', 'email': '[email protected]'} &gt;&gt;&gt; r = requests.put("http://somedomain.org/endpoint", data=payload) </code></pre> <p>You can then check the response status code with:</p> <pre><code>r.status_code </code></pre> <p>or the response with:</p> <pre><code>r.content </code></pre> <p>Requests has a lot synactic sugar and shortcuts that'll make your life easier.</p>
231
2011-11-24T15:54:13Z
[ "python", "http", "put" ]
Is there any way to do HTTP PUT in python
111,945
<p>I need to upload some data to a server using HTTP <code>PUT</code> in python. From my brief reading of the urllib2 docs, it only does HTTP <code>POST</code>. Is there any way to do an HTTP <code>PUT</code> in python?</p>
166
2008-09-21T20:11:05Z
26,045,274
<p>You can use the requests library, it simplifies things a lot in comparison to taking the urllib2 approach. First install it from pip:</p> <pre><code>pip install requests </code></pre> <p>More on <a href="http://docs.python-requests.org/en/latest/user/install/" rel="nofollow">installing requests</a>.</p> <p>Then setup the put request:</p> <pre><code>import requests import json url = 'https://api.github.com/some/endpoint' payload = {'some': 'data'} # Create your header as required headers = {"content-type": "application/json", "Authorization": "&lt;auth-key&gt;" } r = requests.put(url, data=json.dumps(payload), headers=headers) </code></pre> <p>See the <a href="http://docs.python-requests.org/en/latest/user/quickstart/" rel="nofollow">quickstart for requests library</a>. I think this is a lot simpler than urllib2 but does require this additional package to be installed and imported.</p>
5
2014-09-25T18:08:52Z
[ "python", "http", "put" ]
Using Python's ftplib to get a directory listing, portably
111,954
<p>You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is:</p> <pre><code># File: ftplib-example-1.py import ftplib ftp = ftplib.FTP("www.python.org") ftp.login("anonymous", "ftplib-example-1") data = [] ftp.dir(data.append) ftp.quit() for line in data: print "-", line </code></pre> <p>Which yields:</p> <pre><code>$ python ftplib-example-1.py - total 34 - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 . - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 .. - drwxrwxr-x 2 root 4127 512 Sep 13 15:18 RCS - lrwxrwxrwx 1 root bin 11 Jun 29 14:34 README -&gt; welcome.msg - drwxr-xr-x 3 root wheel 512 May 19 1998 bin - drwxr-sr-x 3 root 1400 512 Jun 9 1997 dev - drwxrwxr-- 2 root 4127 512 Feb 8 1998 dup - drwxr-xr-x 3 root wheel 512 May 19 1998 etc ... </code></pre> <p>I guess the idea is to parse the results to get the directory listing. However this listing is directly dependent on the FTP server's way of formatting the list. It would be very messy to write code for this having to anticipate all the different ways FTP servers might format this list.</p> <p>Is there a portable way to get an array filled with the directory listing?</p> <p>(The array should only have the folder names.)</p>
35
2008-09-21T20:13:18Z
111,966
<p>Try to use <code>ftp.nlst(dir)</code>.</p> <p>However, note that if the folder is empty, it might throw an error:</p> <pre><code>files = [] try: files = ftp.nlst() except ftplib.error_perm, resp: if str(resp) == "550 No files found": print "No files in this directory" else: raise for f in files: print f </code></pre>
73
2008-09-21T20:15:59Z
[ "python", "ftp", "portability" ]
Using Python's ftplib to get a directory listing, portably
111,954
<p>You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is:</p> <pre><code># File: ftplib-example-1.py import ftplib ftp = ftplib.FTP("www.python.org") ftp.login("anonymous", "ftplib-example-1") data = [] ftp.dir(data.append) ftp.quit() for line in data: print "-", line </code></pre> <p>Which yields:</p> <pre><code>$ python ftplib-example-1.py - total 34 - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 . - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 .. - drwxrwxr-x 2 root 4127 512 Sep 13 15:18 RCS - lrwxrwxrwx 1 root bin 11 Jun 29 14:34 README -&gt; welcome.msg - drwxr-xr-x 3 root wheel 512 May 19 1998 bin - drwxr-sr-x 3 root 1400 512 Jun 9 1997 dev - drwxrwxr-- 2 root 4127 512 Feb 8 1998 dup - drwxr-xr-x 3 root wheel 512 May 19 1998 etc ... </code></pre> <p>I guess the idea is to parse the results to get the directory listing. However this listing is directly dependent on the FTP server's way of formatting the list. It would be very messy to write code for this having to anticipate all the different ways FTP servers might format this list.</p> <p>Is there a portable way to get an array filled with the directory listing?</p> <p>(The array should only have the folder names.)</p>
35
2008-09-21T20:13:18Z
111,978
<p>There's no standard for the layout of the <code>LIST</code> response. You'd have to write code to handle the most popular layouts. I'd start with Linux <code>ls</code> and Windows Server <code>DIR</code> formats. There's a lot of variety out there, though. </p> <p>Fall back to the <code>nlst</code> method (returning the result of the <code>NLST</code> command) if you can't parse the longer list. For bonus points, cheat: perhaps the longest number in the line containing a known file name is its length. </p>
2
2008-09-21T20:20:36Z
[ "python", "ftp", "portability" ]
Using Python's ftplib to get a directory listing, portably
111,954
<p>You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is:</p> <pre><code># File: ftplib-example-1.py import ftplib ftp = ftplib.FTP("www.python.org") ftp.login("anonymous", "ftplib-example-1") data = [] ftp.dir(data.append) ftp.quit() for line in data: print "-", line </code></pre> <p>Which yields:</p> <pre><code>$ python ftplib-example-1.py - total 34 - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 . - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 .. - drwxrwxr-x 2 root 4127 512 Sep 13 15:18 RCS - lrwxrwxrwx 1 root bin 11 Jun 29 14:34 README -&gt; welcome.msg - drwxr-xr-x 3 root wheel 512 May 19 1998 bin - drwxr-sr-x 3 root 1400 512 Jun 9 1997 dev - drwxrwxr-- 2 root 4127 512 Feb 8 1998 dup - drwxr-xr-x 3 root wheel 512 May 19 1998 etc ... </code></pre> <p>I guess the idea is to parse the results to get the directory listing. However this listing is directly dependent on the FTP server's way of formatting the list. It would be very messy to write code for this having to anticipate all the different ways FTP servers might format this list.</p> <p>Is there a portable way to get an array filled with the directory listing?</p> <p>(The array should only have the folder names.)</p>
35
2008-09-21T20:13:18Z
8,474,838
<p>The reliable/standardized way to parse FTP directory listing is by using MLSD command, which by now should be supported by all recent/decent FTP servers.</p> <pre><code>import ftplib f = ftplib.FTP() f.connect("localhost") f.login() ls = [] f.retrlines('MLSD', ls.append) for entry in ls: print entry </code></pre> <p>The code above will print:</p> <pre><code>modify=20110723201710;perm=el;size=4096;type=dir;unique=807g4e5a5; tests modify=20111206092323;perm=el;size=4096;type=dir;unique=807g1008e0; .xchat2 modify=20111022125631;perm=el;size=4096;type=dir;unique=807g10001a; .gconfd modify=20110808185618;perm=el;size=4096;type=dir;unique=807g160f9a; .skychart ... </code></pre> <p>Starting from python 3.3, ftplib will provide a specific method to do this:</p> <ul> <li><a href="http://bugs.python.org/issue11072">http://bugs.python.org/issue11072</a></li> <li><a href="http://hg.python.org/cpython/file/67053b135ed9/Lib/ftplib.py#l535">http://hg.python.org/cpython/file/67053b135ed9/Lib/ftplib.py#l535</a></li> </ul>
20
2011-12-12T13:10:19Z
[ "python", "ftp", "portability" ]
Using Python's ftplib to get a directory listing, portably
111,954
<p>You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is:</p> <pre><code># File: ftplib-example-1.py import ftplib ftp = ftplib.FTP("www.python.org") ftp.login("anonymous", "ftplib-example-1") data = [] ftp.dir(data.append) ftp.quit() for line in data: print "-", line </code></pre> <p>Which yields:</p> <pre><code>$ python ftplib-example-1.py - total 34 - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 . - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 .. - drwxrwxr-x 2 root 4127 512 Sep 13 15:18 RCS - lrwxrwxrwx 1 root bin 11 Jun 29 14:34 README -&gt; welcome.msg - drwxr-xr-x 3 root wheel 512 May 19 1998 bin - drwxr-sr-x 3 root 1400 512 Jun 9 1997 dev - drwxrwxr-- 2 root 4127 512 Feb 8 1998 dup - drwxr-xr-x 3 root wheel 512 May 19 1998 etc ... </code></pre> <p>I guess the idea is to parse the results to get the directory listing. However this listing is directly dependent on the FTP server's way of formatting the list. It would be very messy to write code for this having to anticipate all the different ways FTP servers might format this list.</p> <p>Is there a portable way to get an array filled with the directory listing?</p> <p>(The array should only have the folder names.)</p>
35
2008-09-21T20:13:18Z
24,090,402
<p>I happen to be stuck with an FTP server (Rackspace Cloud Sites virtual server) that doesn't seem to support MLSD. Yet I need several fields of file information, such as size and timestamp, not just the filename, so I have to use the DIR command. On this server, the output of DIR looks very much like the OP's. In case it helps anyone, here's a little Python class that parses a line of such output to obtain the filename, size and timestamp.</p> <p>import datetime</p> <pre><code>class FtpDir: def parse_dir_line(self, line): words = line.split() self.filename = words[8] self.size = int(words[4]) t = words[7].split(':') ts = words[5] + '-' + words[6] + '-' + datetime.datetime.now().strftime('%Y') + ' ' + t[0] + ':' + t[1] self.timestamp = datetime.datetime.strptime(ts, '%b-%d-%Y %H:%M') </code></pre> <p>Not very portable, I know, but easy to extend or modify to deal with various different FTP servers.</p>
0
2014-06-06T20:50:39Z
[ "python", "ftp", "portability" ]
Using Python's ftplib to get a directory listing, portably
111,954
<p>You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is:</p> <pre><code># File: ftplib-example-1.py import ftplib ftp = ftplib.FTP("www.python.org") ftp.login("anonymous", "ftplib-example-1") data = [] ftp.dir(data.append) ftp.quit() for line in data: print "-", line </code></pre> <p>Which yields:</p> <pre><code>$ python ftplib-example-1.py - total 34 - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 . - drwxrwxr-x 11 root 4127 512 Sep 14 14:18 .. - drwxrwxr-x 2 root 4127 512 Sep 13 15:18 RCS - lrwxrwxrwx 1 root bin 11 Jun 29 14:34 README -&gt; welcome.msg - drwxr-xr-x 3 root wheel 512 May 19 1998 bin - drwxr-sr-x 3 root 1400 512 Jun 9 1997 dev - drwxrwxr-- 2 root 4127 512 Feb 8 1998 dup - drwxr-xr-x 3 root wheel 512 May 19 1998 etc ... </code></pre> <p>I guess the idea is to parse the results to get the directory listing. However this listing is directly dependent on the FTP server's way of formatting the list. It would be very messy to write code for this having to anticipate all the different ways FTP servers might format this list.</p> <p>Is there a portable way to get an array filled with the directory listing?</p> <p>(The array should only have the folder names.)</p>
35
2008-09-21T20:13:18Z
28,044,376
<p>Use a library like this: <a href="http://ftputil.sschwarzer.net" rel="nofollow">http://ftputil.sschwarzer.net</a></p> <p>Everything else is "Reinventing the wheel".</p>
2
2015-01-20T11:34:50Z
[ "python", "ftp", "portability" ]
python.array versus numpy.array
111,983
<p>If you are creating a 1d array in Python is there any benefit to using the NumPy package?</p>
27
2008-09-21T20:23:02Z
112,025
<p>It all depends on what you plan to do with the array. If all you're doing is creating arrays of simple data types and doing I/O, the <a href="http://docs.python.org/lib/module-array.html">array</a> module will do just fine.</p> <p>If, on the other hand, you want to do any kind of numerical calculations, the array module doesn't provide any help with that. <a href="http://numpy.scipy.org/array_interface.shtml">NumPy</a> (and <a href="http://scipy.org">SciPy</a>) give you a wide variety of operations between arrays and special functions that are useful not only for scientific work but for things like advanced image manipulation or in general anything where you need to perform efficient calculations with large amounts of data.</p> <p>Numpy is also much more flexible, e.g. it supports arrays of any type of Python objects, and is also able to interact "natively" with your own objects if they conform to the <a href="http://numpy.scipy.org/">array interface</a>.</p>
40
2008-09-21T20:31:39Z
[ "python", "numpy" ]
How do I overlap widgets with the Tkinter pack geometry manager?
112,263
<p>I want to put a <code>Canvas</code> with an image in my window, and then I want to <em>pack</em> widgets on top of it, so the Canvas acts as a background. </p> <p>Is it possible to have two states for the <code>pack</code> manager: one for one set of widgets and another for another set?</p>
2
2008-09-21T21:45:05Z
112,337
<p>The answer to your specific question is no. You can't have two states or otherwise use pack two different ways in the same parent. </p> <p>However, what I think you want to accomplish is simple. Use the built-in features of the canvas to create an image item that is part of the canvas, then pack things into the canvas as if it were a frame. </p> <p>You can accomplish a similar thing by creating a label widget with an image, then pack your other widgets into the label.</p> <p>One advantage to using a canvas is you can easily tile an image to fill the whole canvas with a repeating background image so as the window grows the image will continue to fill the window (of course you can just use a sufficiently large original image...)</p>
2
2008-09-21T22:19:09Z
[ "python", "tkinter", "geometry", "pack", "manager" ]
How do I overlap widgets with the Tkinter pack geometry manager?
112,263
<p>I want to put a <code>Canvas</code> with an image in my window, and then I want to <em>pack</em> widgets on top of it, so the Canvas acts as a background. </p> <p>Is it possible to have two states for the <code>pack</code> manager: one for one set of widgets and another for another set?</p>
2
2008-09-21T21:45:05Z
112,397
<p>I believe that Bryan's answer is probably the best general solution. However, you may also want to look at the <a href="http://www.pythonware.com/library/tkinter/introduction/place.htm" rel="nofollow">place</a> geometry manager. The <strong>place</strong> geometry manager lets you specify the exact size and position of the widget... which can get tedious quickly, but will get the job done.</p>
1
2008-09-21T22:39:05Z
[ "python", "tkinter", "geometry", "pack", "manager" ]
How do I overlap widgets with the Tkinter pack geometry manager?
112,263
<p>I want to put a <code>Canvas</code> with an image in my window, and then I want to <em>pack</em> widgets on top of it, so the Canvas acts as a background. </p> <p>Is it possible to have two states for the <code>pack</code> manager: one for one set of widgets and another for another set?</p>
2
2008-09-21T21:45:05Z
112,432
<p>Not without swapping widget trees in and out, which I don't think can be done cleanly with Tk. Other toolkits can do this a little more elegantly.</p> <ul> <li>COM/VB/MFC can do this with an ActiveX control - you can hide/show multiple ActiveX controls in the same region. Any of the containers will let you do this by changing the child around. If you're doing a windows-specific program you may be able to accomplish it this way.</li> <li>QT will also let you do this in a similar manner.</li> <li>GTK is slightly harder.</li> </ul>
0
2008-09-21T22:48:37Z
[ "python", "tkinter", "geometry", "pack", "manager" ]
How do I overlap widgets with the Tkinter pack geometry manager?
112,263
<p>I want to put a <code>Canvas</code> with an image in my window, and then I want to <em>pack</em> widgets on top of it, so the Canvas acts as a background. </p> <p>Is it possible to have two states for the <code>pack</code> manager: one for one set of widgets and another for another set?</p>
2
2008-09-21T21:45:05Z
114,941
<blockquote> <p>... turned out to be unworkable because I wanted to add labels and more canvases to it, but I can't find any way to make their backgrounds transparent</p> </blockquote> <p>If it is acceptable to load an additional extension, take a look at <a href="http://www.tkzinc.org/tkzinc/index.php" rel="nofollow">Tkzinc</a>. From the web site, </p> <blockquote> <p>Tkzinc (historically called Zinc) widget is very similar to the Tk Canvas in that they both support structured graphics. Like the Canvas, Tkzinc implements items used to display graphical entities. Those items can be manipulated and bindings can be associated with them to implement interaction behaviors. But unlike the Canvas, Tkzinc can structure the items in a hierarchy, has support for scaling and rotation, clipping can be set for sub-trees of the item hierarchy, supports muti-contour curves. It also provides advanced rendering with the help of OpenGL, such as color gradient, antialiasing, transparencies and a triangles item. </p> </blockquote> <p>I'm currently using it on a tcl project and am quite pleased with the results. Extensions for tcl, perl, and python are available.</p>
1
2008-09-22T13:47:28Z
[ "python", "tkinter", "geometry", "pack", "manager" ]
Does anyone know of a widget for a desktop toolkit(GTK, Qt, WX) for displaying a map of US states?
112,483
<p>I'm specifically looking for one that lets me display a map of US states with each one as it's own "object" in the sense that I can control the color, on click, and on mouseover of each one individually. GTK is my personal preference, but at this point I'd settle for just about anything. The application itself will be written in Python, FWIW.</p>
1
2008-09-21T23:10:42Z
112,505
<p>You can use <a href="http://doc.trolltech.com/4.4/qgraphicsview.html" rel="nofollow">QGraphicsView</a> in PyQt. Each state is a new <code>QGraphicsItem</code>, which is either a bitmap or a path object. You just need to provide the outlines (or bitmaps) and the positions of the states. </p> <p>If you have SVGs of the states, you can use them, too.</p> <p>There is no generally accepted canvas class for GTK+.</p>
2
2008-09-21T23:17:37Z
[ "python", "qt", "gtk", "desktop" ]
Does anyone know of a widget for a desktop toolkit(GTK, Qt, WX) for displaying a map of US states?
112,483
<p>I'm specifically looking for one that lets me display a map of US states with each one as it's own "object" in the sense that I can control the color, on click, and on mouseover of each one individually. GTK is my personal preference, but at this point I'd settle for just about anything. The application itself will be written in Python, FWIW.</p>
1
2008-09-21T23:10:42Z
112,608
<p>Yes, you can use cairo, but cairo is not a canvas. You have to code behavior like mouseover/onclick yourself.</p>
-1
2008-09-22T00:04:12Z
[ "python", "qt", "gtk", "desktop" ]
Does anyone know of a widget for a desktop toolkit(GTK, Qt, WX) for displaying a map of US states?
112,483
<p>I'm specifically looking for one that lets me display a map of US states with each one as it's own "object" in the sense that I can control the color, on click, and on mouseover of each one individually. GTK is my personal preference, but at this point I'd settle for just about anything. The application itself will be written in Python, FWIW.</p>
1
2008-09-21T23:10:42Z
122,701
<p>Quick tip, if you color each state differently you can identify which one to pick from the color under mouse cursor rather than doing a complex point in polygon routine.</p>
0
2008-09-23T18:08:41Z
[ "python", "qt", "gtk", "desktop" ]
Does anyone know of a widget for a desktop toolkit(GTK, Qt, WX) for displaying a map of US states?
112,483
<p>I'm specifically looking for one that lets me display a map of US states with each one as it's own "object" in the sense that I can control the color, on click, and on mouseover of each one individually. GTK is my personal preference, but at this point I'd settle for just about anything. The application itself will be written in Python, FWIW.</p>
1
2008-09-21T23:10:42Z
146,015
<p>If you consider Qt, consider also throwing in kdelibs dependency, then you'll have marble widget, which handles maps in neat way.</p> <p>If you stick only to Qt, then QGraphicsView is a framework to go.</p> <p>(note: kdelibs != running whole kde desktop)</p>
1
2008-09-28T14:52:49Z
[ "python", "qt", "gtk", "desktop" ]
Does anyone know of a widget for a desktop toolkit(GTK, Qt, WX) for displaying a map of US states?
112,483
<p>I'm specifically looking for one that lets me display a map of US states with each one as it's own "object" in the sense that I can control the color, on click, and on mouseover of each one individually. GTK is my personal preference, but at this point I'd settle for just about anything. The application itself will be written in Python, FWIW.</p>
1
2008-09-21T23:10:42Z
146,047
<p>You can use <a href="http://qgis.org/" rel="nofollow">Quantum GIS</a>. QGIS is a Open Source Geographic Information System using the Qt Framework.</p> <p>QGIS can also be used with Python. You can either extend it with plugins written in Python or use the <a href="http://wiki.qgis.org/qgiswiki/PythonBindings" rel="nofollow">PyGIS Python bindings</a> to write your own application.</p> <p>They have a Wiki with some good <a href="http://wiki.qgis.org/qgiswiki/DevelopersCorner" rel="nofollow">informations for developers</a>.</p> <p>Maybe QGIS is to heavy for your purpose, but I add it here for completition anyway. </p>
1
2008-09-28T15:06:42Z
[ "python", "qt", "gtk", "desktop" ]
Does anyone know of a widget for a desktop toolkit(GTK, Qt, WX) for displaying a map of US states?
112,483
<p>I'm specifically looking for one that lets me display a map of US states with each one as it's own "object" in the sense that I can control the color, on click, and on mouseover of each one individually. GTK is my personal preference, but at this point I'd settle for just about anything. The application itself will be written in Python, FWIW.</p>
1
2008-09-21T23:10:42Z
302,298
<blockquote> <p>If you consider Qt, consider also throwing in kdelibs dependency, then you'll have marble widget, which handles maps in neat way.</p> </blockquote> <p>Thanks for advertizing Marble. But you are incorrect: </p> <p>The Marble Widget doesn't depend on kdelibs at all. It just depends on Qt (>=4.3).</p> <p>Additionally Marble also has just received Python bindings.</p> <p>I think that the given problem can be solved using Marble. Would just take a few days of work at max. If you have questions about Marble, feel free to ask us on our mailing list or IRC.</p> <p>Best Regards, Torsten Rahn </p>
0
2008-11-19T15:38:52Z
[ "python", "qt", "gtk", "desktop" ]
List all words in a dictionary that start with <user input>
112,532
<p>How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?</p> <p>Ex:<br /> User: "abd"<br /> Program:abdicate, abdomen, abduct...</p> <p>Thanks!</p> <p><hr /></p> <p>Edit: I'm using python, but I assume that this is a fairly language-independent problem.</p>
7
2008-09-21T23:28:06Z
112,540
<pre><code>var words = from word in dictionary where word.key.StartsWith("bla-bla-bla"); select word; </code></pre>
2
2008-09-21T23:29:51Z
[ "python", "list", "dictionary" ]
List all words in a dictionary that start with <user input>
112,532
<p>How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?</p> <p>Ex:<br /> User: "abd"<br /> Program:abdicate, abdomen, abduct...</p> <p>Thanks!</p> <p><hr /></p> <p>Edit: I'm using python, but I assume that this is a fairly language-independent problem.</p>
7
2008-09-21T23:28:06Z
112,541
<p>Try using regex to search through your list of words, e.g. /^word/ and report all matches.</p>
1
2008-09-21T23:30:13Z
[ "python", "list", "dictionary" ]
List all words in a dictionary that start with <user input>
112,532
<p>How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?</p> <p>Ex:<br /> User: "abd"<br /> Program:abdicate, abdomen, abduct...</p> <p>Thanks!</p> <p><hr /></p> <p>Edit: I'm using python, but I assume that this is a fairly language-independent problem.</p>
7
2008-09-21T23:28:06Z
112,556
<pre><code>def main(script, name): for word in open("/usr/share/dict/words"): if word.startswith(name): print word, if __name__ == "__main__": import sys main(*sys.argv) </code></pre>
2
2008-09-21T23:35:07Z
[ "python", "list", "dictionary" ]
List all words in a dictionary that start with <user input>
112,532
<p>How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?</p> <p>Ex:<br /> User: "abd"<br /> Program:abdicate, abdomen, abduct...</p> <p>Thanks!</p> <p><hr /></p> <p>Edit: I'm using python, but I assume that this is a fairly language-independent problem.</p>
7
2008-09-21T23:28:06Z
112,557
<p>One of the best ways to do this is to use a directed graph to store your dictionary. It takes a little bit of setting up, but once done it is fairly easy to then do the type of searches you are talking about.</p> <p>The nodes in the graph correspond to a letter in your word, so each node will have one incoming link and up to 26 (in English) outgoing links.</p> <p>You could also use a hybrid approach where you maintain a sorted list containing your dictionary and use the directed graph as an index into your dictionary. Then you just look up your prefix in your directed graph and then go to that point in your dictionary and spit out all words matching your search criteria.</p>
8
2008-09-21T23:35:09Z
[ "python", "list", "dictionary" ]
List all words in a dictionary that start with <user input>
112,532
<p>How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?</p> <p>Ex:<br /> User: "abd"<br /> Program:abdicate, abdomen, abduct...</p> <p>Thanks!</p> <p><hr /></p> <p>Edit: I'm using python, but I assume that this is a fairly language-independent problem.</p>
7
2008-09-21T23:28:06Z
112,559
<p>Use a <a href="http://en.wikipedia.org/wiki/Trie">trie</a>.</p> <p>Add your list of words to a trie. Each path from the root to a leaf is a valid word. A path from a root to an intermediate node represents a prefix, and the children of the intermediate node are valid completions for the prefix.</p>
10
2008-09-21T23:35:48Z
[ "python", "list", "dictionary" ]
List all words in a dictionary that start with <user input>
112,532
<p>How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?</p> <p>Ex:<br /> User: "abd"<br /> Program:abdicate, abdomen, abduct...</p> <p>Thanks!</p> <p><hr /></p> <p>Edit: I'm using python, but I assume that this is a fairly language-independent problem.</p>
7
2008-09-21T23:28:06Z
112,560
<p>If you really want to be efficient - use suffix trees or suffix arrays - <a href="http://en.wikipedia.org/wiki/Suffix_tree" rel="nofollow">wikipedia article</a>.</p> <p>Your problem is what suffix trees were designed to handle. There is even implementation for Python - <a href="http://hkn.eecs.berkeley.edu/~dyoo/python/suffix_trees/" rel="nofollow">here</a></p>
2
2008-09-21T23:36:31Z
[ "python", "list", "dictionary" ]
List all words in a dictionary that start with <user input>
112,532
<p>How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?</p> <p>Ex:<br /> User: "abd"<br /> Program:abdicate, abdomen, abduct...</p> <p>Thanks!</p> <p><hr /></p> <p>Edit: I'm using python, but I assume that this is a fairly language-independent problem.</p>
7
2008-09-21T23:28:06Z
112,562
<p>If you need to be <em>really</em> fast, use a tree:</p> <p>build an array and split the words in 26 sets based on the first letter, then split each item in 26 based on the second letter, then again.</p> <p>So if your user types "abd" you would look for Array[0][1][3] and get a list of all the words starting like that. At that point your list should be small enough to pass over to the client and use javascript to filter.</p>
1
2008-09-21T23:37:19Z
[ "python", "list", "dictionary" ]
List all words in a dictionary that start with <user input>
112,532
<p>How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?</p> <p>Ex:<br /> User: "abd"<br /> Program:abdicate, abdomen, abduct...</p> <p>Thanks!</p> <p><hr /></p> <p>Edit: I'm using python, but I assume that this is a fairly language-independent problem.</p>
7
2008-09-21T23:28:06Z
112,563
<p>If you on a debian[-like] machine, </p> <pre><code>#!/bin/bash echo -n "Enter a word: " read input grep "^$input" /usr/share/dict/words </code></pre> <p>Takes all of 0.040s on my P200.</p>
6
2008-09-21T23:37:53Z
[ "python", "list", "dictionary" ]
List all words in a dictionary that start with <user input>
112,532
<p>How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?</p> <p>Ex:<br /> User: "abd"<br /> Program:abdicate, abdomen, abduct...</p> <p>Thanks!</p> <p><hr /></p> <p>Edit: I'm using python, but I assume that this is a fairly language-independent problem.</p>
7
2008-09-21T23:28:06Z
112,587
<pre><code>egrep `read input &amp;&amp; echo ^$input` /usr/share/dict/words </code></pre> <p>oh I didn't see the Python edit, here is the same thing in python</p> <pre><code>my_input = raw_input("Enter beginning of word: ") my_words = open("/usr/share/dict/words").readlines() my_found_words = [x for x in my_words if x[0:len(my_input)] == my_input] </code></pre>
4
2008-09-21T23:50:59Z
[ "python", "list", "dictionary" ]
List all words in a dictionary that start with <user input>
112,532
<p>How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?</p> <p>Ex:<br /> User: "abd"<br /> Program:abdicate, abdomen, abduct...</p> <p>Thanks!</p> <p><hr /></p> <p>Edit: I'm using python, but I assume that this is a fairly language-independent problem.</p>
7
2008-09-21T23:28:06Z
112,598
<p>If you really want speed, use a trie/automaton. However, something that will be faster than simply scanning the whole list, given that the list of words is sorted:</p> <pre><code>from itertools import takewhile, islice import bisect def prefixes(words, pfx): return list( takewhile(lambda x: x.startswith(pfx), islice(words, bisect.bisect_right(words, pfx), len(words))) </code></pre> <p>Note that an automaton is O(1) with regard to the size of your dictionary, while this algorithm is O(log(m)) and then O(n) with regard to the number of strings that actually start with the prefix, while the full scan is O(m), with n &lt;&lt; m.</p>
4
2008-09-21T23:57:05Z
[ "python", "list", "dictionary" ]
List all words in a dictionary that start with <user input>
112,532
<p>How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?</p> <p>Ex:<br /> User: "abd"<br /> Program:abdicate, abdomen, abduct...</p> <p>Thanks!</p> <p><hr /></p> <p>Edit: I'm using python, but I assume that this is a fairly language-independent problem.</p>
7
2008-09-21T23:28:06Z
112,843
<p>If your dictionary is really big, i'd suggest indexing with a python text index (PyLucene - note that i've never used the python extension for lucene) The search would be efficient and you could even return a search 'score'.</p> <p>Also, if your dictionary is relatively static you won't even have the overhead of re-indexing very often.</p>
0
2008-09-22T02:05:02Z
[ "python", "list", "dictionary" ]
List all words in a dictionary that start with <user input>
112,532
<p>How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?</p> <p>Ex:<br /> User: "abd"<br /> Program:abdicate, abdomen, abduct...</p> <p>Thanks!</p> <p><hr /></p> <p>Edit: I'm using python, but I assume that this is a fairly language-independent problem.</p>
7
2008-09-21T23:28:06Z
114,002
<p>Don't use a bazooka to kill a fly. Use something simple just like SQLite. There are all the tools you need for every modern languages and you can just do :</p> <pre><code>"SELECT word FROM dict WHERE word LIKE "user_entry%" </code></pre> <p>It's lightning fast and a baby could do it. What's more it's portable, persistent and so easy to maintain.</p> <p>Python tuto :</p> <p><a href="http://www.initd.org/pub/software/pysqlite/doc/usage-guide.html" rel="nofollow">http://www.initd.org/pub/software/pysqlite/doc/usage-guide.html</a></p>
0
2008-09-22T09:39:15Z
[ "python", "list", "dictionary" ]
List all words in a dictionary that start with <user input>
112,532
<p>How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?</p> <p>Ex:<br /> User: "abd"<br /> Program:abdicate, abdomen, abduct...</p> <p>Thanks!</p> <p><hr /></p> <p>Edit: I'm using python, but I assume that this is a fairly language-independent problem.</p>
7
2008-09-21T23:28:06Z
306,465
<p>A linear scan is slow, but a prefix tree is probably overkill. Keeping the words sorted and using a binary search is a fast and simple compromise.</p> <pre><code>import bisect words = sorted(map(str.strip, open('/usr/share/dict/words'))) def lookup(prefix): return words[bisect.bisect_left(words, prefix):bisect.bisect_right(words, prefix+'~')] &gt;&gt;&gt; lookup('abdicat') ['abdicate', 'abdication', 'abdicative', 'abdicator'] </code></pre>
0
2008-11-20T19:04:05Z
[ "python", "list", "dictionary" ]
List all words in a dictionary that start with <user input>
112,532
<p>How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?</p> <p>Ex:<br /> User: "abd"<br /> Program:abdicate, abdomen, abduct...</p> <p>Thanks!</p> <p><hr /></p> <p>Edit: I'm using python, but I assume that this is a fairly language-independent problem.</p>
7
2008-09-21T23:28:06Z
308,443
<h2>Most Pythonic solution</h2> <pre><code># set your list of words, whatever the source words_list = ('cat', 'dog', 'banana') # get the word from the user inpuit user_word = raw_input("Enter a word:\n") # create an generator, so your output is flexible and store almost nothing in memory word_generator = (word for word in words_list if word.startswith(user_word)) # now you in, you can make anything you want with it # here we just list it : for word in word_generator : print word </code></pre> <p>Remember generators can be only used once, so turn it to a list (using list(word_generator)) or use the itertools.tee function if you expect using it more than once.</p> <h2>Best way to do it :</h2> <p>Store it into a database and use SQL to look for the word you need. If there is a lot of words in your dictionary, it will be much faster and efficient.</p> <p>Python got thousand of DB API to help you do the job ;-)</p>
0
2008-11-21T11:11:41Z
[ "python", "list", "dictionary" ]
How do I use genshi.builder to programmatically build an HTML document?
112,564
<p>I recently discovered the genshi.builder module. It reminds me of Divmod Nevow's Stan module. How would one use genshi.builder.tag to build an HTML document with a particular doctype? Or is this even a good thing to do? If not, what is the <em>right</em> way?</p>
3
2008-09-21T23:37:58Z
112,659
<p>Genshi.builder is for "programmatically generating markup streams"[1]. I believe the purpose of it is as a backend for the templating language. You're probably looking for the templating language for generating a whole page.</p> <p>You can, however do the following:</p> <pre><code>&gt;&gt;&gt; import genshi.output &gt;&gt;&gt; genshi.output.DocType('html') ('html', '-//W3C//DTD HTML 4.01//EN', 'http://www.w3.org/TR/html4/strict.dtd') </code></pre> <p>See other Doctypes here: <a href="http://genshi.edgewall.org/wiki/ApiDocs/genshi.output#genshi.output:DocType" rel="nofollow">http://genshi.edgewall.org/wiki/ApiDocs/genshi.output#genshi.output:DocType</a></p> <pre><code>[1] genshi.builder.__doc__ </code></pre>
2
2008-09-22T00:29:34Z
[ "python", "html", "templates", "genshi" ]
How do I use genshi.builder to programmatically build an HTML document?
112,564
<p>I recently discovered the genshi.builder module. It reminds me of Divmod Nevow's Stan module. How would one use genshi.builder.tag to build an HTML document with a particular doctype? Or is this even a good thing to do? If not, what is the <em>right</em> way?</p>
3
2008-09-21T23:37:58Z
112,860
<p>It's not possible to build an entire page using just <code>genshi.builder.tag</code> -- you would need to perform some surgery on the resulting stream to insert the doctype. Besides, the resulting code would look horrific. The recommended way to use Genshi is to use a separate template file, generate a stream from it, and then render that stream to the output type you want.</p> <p><code>genshi.builder.tag</code> is mostly useful for when you need to generate simple markup from within Python, such as when you're building a form or doing some sort of logic-heavy modification of the output.</p> <p>See documentation for:</p> <ul> <li><a href="http://genshi.edgewall.org/wiki/Documentation/0.5.x/templates.html" rel="nofollow">Creating and using templates</a></li> <li><a href="http://genshi.edgewall.org/wiki/Documentation/0.5.x/xml-templates.html" rel="nofollow">The XML-based template language</a></li> <li><a href="http://genshi.edgewall.org/wiki/ApiDocs/0.5.x/genshi.builder" rel="nofollow"><code>genshi.builder</code> API docs</a></li> </ul> <p>If you really want to generate a full document using only <code>builder.tag</code>, this (completely untested) code could be a good starting point:</p> <pre><code>from itertools import chain from genshi.core import DOCTYPE, Stream from genshi.output import DocType from genshi.builder import tag as t # Build the page using `genshi.builder.tag` page = t.html (t.head (t.title ("Hello world!")), t.body (t.div ("Body text"))) # Convert the page element into a stream stream = page.generate () # Chain the page stream with a stream containing only an HTML4 doctype declaration stream = Stream (chain ([(DOCTYPE, DocType.get ('html4'), None)], stream)) # Convert the stream to text using the "html" renderer (could also be xml, xhtml, text, etc) text = stream.render ('html') </code></pre> <p>The resulting page will have no whitespace in it -- it'll look normal, but you'll have a hard time reading the source code because it will be entirely on one line. Implementing appropriate filters to add whitespace is left as an exercise to the reader.</p>
4
2008-09-22T02:12:07Z
[ "python", "html", "templates", "genshi" ]
py2exe - generate single executable file
112,698
<p>I thought I heard that <a href="http://www.py2exe.org/">py2exe</a> was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used?</p> <p>Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.</p>
112
2008-09-22T00:49:12Z
112,708
<p>No, it's doesn't give you a single executable in the sense that you only have one file afterwards - but you have a directory which contains everything you need for running your program, including an exe file.</p> <p>I just wrote <a href="http://hg.diotavelli.net/sta/master/file/542689f50e63/setup.py" rel="nofollow">this setup.py</a> today. You only need to invoke <code>python setup.py py2exe</code>.</p>
-5
2008-09-22T00:53:21Z
[ "python", "packaging", "py2exe" ]
py2exe - generate single executable file
112,698
<p>I thought I heard that <a href="http://www.py2exe.org/">py2exe</a> was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used?</p> <p>Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.</p>
112
2008-09-22T00:49:12Z
112,713
<p><a href="http://www.pyinstaller.org/">PyInstaller</a> will create a single .exe file with no dependencies; use the <code>--onefile</code> option. It does this by packing all the needed shared libs into the executable, and unpacking them before it runs, just as you describe (EDIT: py2exe also has this feature, see <a href="http://stackoverflow.com/questions/112698/py2exe-generate-single-executable-file#113014">minty's answer</a>)</p> <p>I use the version of PyInstaller from svn, since the latest release (1.3) is somewhat outdated. It's been working really well for an app which depends on PyQt, PyQwt, numpy, scipy and a few more.</p>
72
2008-09-22T00:55:46Z
[ "python", "packaging", "py2exe" ]
py2exe - generate single executable file
112,698
<p>I thought I heard that <a href="http://www.py2exe.org/">py2exe</a> was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used?</p> <p>Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.</p>
112
2008-09-22T00:49:12Z
112,716
<p>I recently used py2exe to create an executable for post-review for sending reviews to ReviewBoard.</p> <p>This was the setup.py I used</p> <pre><code>from distutils.core import setup import py2exe setup(console=['post-review']) </code></pre> <p>It created a directory containing the exe file and the libraries needed. I don't think it is possible to use py2exe to get just a single .exe file. If you need that you will need to first use py2exe and then use some form of installer to make the final executable.</p> <p>One thing to take care of is that any egg files you use in your application need to be unzipped, otherwise py2exe can't include them. This is covered in the py2exe docs.</p>
-2
2008-09-22T00:56:28Z
[ "python", "packaging", "py2exe" ]
py2exe - generate single executable file
112,698
<p>I thought I heard that <a href="http://www.py2exe.org/">py2exe</a> was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used?</p> <p>Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.</p>
112
2008-09-22T00:49:12Z
113,014
<p>The way to do this using py2exe is to use the bundle_files option in your setup.py file. For a single file you will want to set <code>bundle_files</code> to 1, <code>compressed</code> to True, and set the zipfile option to None. That way it creates one compressed file for easy distribution.</p> <p>Here is a more complete description of the bundle_file option quoted directly from the <a href="http://www.py2exe.org/index.cgi/SingleFileExecutable?highlight=%28file%29|%28single%29">py2exe site</a>*</p> <blockquote> <p>Using "bundle_files" and "zipfile"</p> <p>An easier (and better) way to create single-file executables is to set bundle_files to 1 or 2, and to set zipfile to None. This approach does not require extracting files to a temporary location, which provides much faster program startup.</p> <p>Valid values for bundle_files are:</p> <ul> <li>3 (default) don't bundle </li> <li>2 bundle everything but the Python interpreter</li> <li>1 bundle everything, including the Python interpreter </li> </ul> <p>If zipfile is set to None, the files will be bundle within the executable instead of library.zip.</p> </blockquote> <p>Here is a sample setup.py:</p> <pre><code>from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = {'py2exe': {'bundle_files': 1, 'compressed': True}}, windows = [{'script': "single.py"}], zipfile = None, ) </code></pre>
150
2008-09-22T03:19:08Z
[ "python", "packaging", "py2exe" ]
py2exe - generate single executable file
112,698
<p>I thought I heard that <a href="http://www.py2exe.org/">py2exe</a> was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used?</p> <p>Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.</p>
112
2008-09-22T00:49:12Z
333,483
<p>As the other poster mention, py2exe, will generate an executable + some libraries to load. You can also have some data to add to your program.</p> <p>Next step is to use an installer, to package all this into one easy-to-use installable/unistallable program.</p> <p>I have used InnoSetup ( <a href="http://www.jrsoftware.org/isinfo.php">http://www.jrsoftware.org/isinfo.php</a> ) with delight for several years and for commercial programs, so I heartily recommend it.</p>
8
2008-12-02T09:44:45Z
[ "python", "packaging", "py2exe" ]
py2exe - generate single executable file
112,698
<p>I thought I heard that <a href="http://www.py2exe.org/">py2exe</a> was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used?</p> <p>Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.</p>
112
2008-09-22T00:49:12Z
563,909
<p>I'm told <a href="http://pypi.python.org/pypi/bbfreeze/" rel="nofollow">bbfreeze</a> will create a single file .EXE, and is newer than py2exe.</p>
1
2009-02-19T04:02:07Z
[ "python", "packaging", "py2exe" ]
py2exe - generate single executable file
112,698
<p>I thought I heard that <a href="http://www.py2exe.org/">py2exe</a> was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used?</p> <p>Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.</p>
112
2008-09-22T00:49:12Z
3,702,931
<p>You should create an installer, as mentioned before. Even though it is also possible to let py2exe bundle everything into a single executable, by setting bundle_files option to 1 and the zipfile keyword argument to None, I don't recommend this for PyGTK applications.</p> <p>That's because of GTK+ tries to load its data files (locals, themes, etc.) from the directory it was loaded from. So you have to make sure that the directory of your executable contains also the libraries used by GTK+ and the directories lib, share and etc from your installation of GTK+. Otherwise you will get problems running your application on a machine where GTK+ is not installed system-wide.</p> <p>For more details read my <a href="http://www.no-ack.org/2010/09/complete-guide-to-py2exe-for-pygtk.html" rel="nofollow">guide to py2exe for PyGTK applications</a>. It also explains how to bundle everything, but GTK+.</p>
4
2010-09-13T17:40:51Z
[ "python", "packaging", "py2exe" ]
py2exe - generate single executable file
112,698
<p>I thought I heard that <a href="http://www.py2exe.org/">py2exe</a> was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used?</p> <p>Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.</p>
112
2008-09-22T00:49:12Z
6,824,876
<p>I've been able to create a single exe file with all resources embeded into the exe. I'm building on windows. so that will explain some of the os.system calls i'm using.</p> <p>First I tried converting all my images into bitmats and then all my data files into text strings. but this caused the final exe to be very very large.</p> <p>After googleing for a week i figured out how to alter py2exe script to meet my needs.</p> <p>here is the patch link on sourceforge i submitted, please post comments so we can get it included in the next distribution.</p> <p><a href="http://sourceforge.net/tracker/index.php?func=detail&amp;aid=3334760&amp;group_id=15583&amp;atid=315583" rel="nofollow">http://sourceforge.net/tracker/index.php?func=detail&amp;aid=3334760&amp;group_id=15583&amp;atid=315583</a></p> <p>this explanes all the changes made, i've simply added a new option to the setup line. here is my setup.py.</p> <p>i'll try to comment it as best I can. Please know that my setup.py is complex do to the fact that i'm access the images by filename. so I must store a list to keep track of them.</p> <p>this is from a want-to-b screen saver I was trying to make.</p> <p>I use exec to generate my setup at run time, its easyer to cut and paste like that.</p> <pre><code>exec "setup(console=[{'script': 'launcher.py', 'icon_resources': [(0, 'ICON.ico')],\ 'file_resources': [%s], 'other_resources': [(u'INDEX', 1, resource_string[:-1])]}],\ options={'py2exe': py2exe_options},\ zipfile = None )" % (bitmap_string[:-1]) </code></pre> <p>breakdown</p> <p>script = py script i want to turn to an exe</p> <p>icon_resources = the icon for the exe</p> <p>file_resources = files I want to embed into the exe</p> <p>other_resources = a string to embed into the exe, in this case a file list.</p> <p>options = py2exe options for creating everything into one exe file</p> <p>bitmap_strings = a list of files to include</p> <p>Please note that file_resources is not a valid option untill you edit your py2exe.py file as described in the link above. </p> <p>first time i've tried to post code on this site, if I get it wrong don't flame me.</p> <pre><code>from distutils.core import setup import py2exe #@UnusedImport import os #delete the old build drive os.system("rmdir /s /q dist") #setup my option for single file output py2exe_options = dict( ascii=True, # Exclude encodings excludes=['_ssl', # Exclude _ssl 'pyreadline', 'difflib', 'doctest', 'locale', 'optparse', 'pickle', 'calendar', 'pbd', 'unittest', 'inspect'], # Exclude standard library dll_excludes=['msvcr71.dll', 'w9xpopen.exe', 'API-MS-Win-Core-LocalRegistry-L1-1-0.dll', 'API-MS-Win-Core-ProcessThreads-L1-1-0.dll', 'API-MS-Win-Security-Base-L1-1-0.dll', 'KERNELBASE.dll', 'POWRPROF.dll', ], #compressed=None, # Compress library.zip bundle_files = 1, optimize = 2 ) #storage for the images bitmap_string = '' resource_string = '' index = 0 print "compile image list" for image_name in os.listdir('images/'): if image_name.endswith('.jpg'): bitmap_string += "( " + str(index+1) + "," + "'" + 'images/' + image_name + "')," resource_string += image_name + " " index += 1 print "Starting build\n" exec "setup(console=[{'script': 'launcher.py', 'icon_resources': [(0, 'ICON.ico')],\ 'file_resources': [%s], 'other_resources': [(u'INDEX', 1, resource_string[:-1])]}],\ options={'py2exe': py2exe_options},\ zipfile = None )" % (bitmap_string[:-1]) print "Removing Trash" os.system("rmdir /s /q build") os.system("del /q *.pyc") print "Build Complete" </code></pre> <p>ok, thats it for the setup.py now the magic needed access the images. I developed this app without py2exe in mind then added it later. so you'll see access for both situations. if the image folder can't be found it tries to pull the images from the exe resources. the code will explain it. this is part of my sprite class and it uses a directx. but you can use any api you want or just access the raw data. doesn't matter.</p> <pre><code>def init(self): frame = self.env.frame use_resource_builtin = True if os.path.isdir(SPRITES_FOLDER): use_resource_builtin = False else: image_list = LoadResource(0, u'INDEX', 1).split(' ') for (model, file) in SPRITES.items(): texture = POINTER(IDirect3DTexture9)() if use_resource_builtin: data = LoadResource(0, win32con.RT_RCDATA, image_list.index(file)+1) #windll.kernel32.FindResourceW(hmod,typersc,idrsc) d3dxdll.D3DXCreateTextureFromFileInMemory(frame.device, #Pointer to an IDirect3DDevice9 interface data, #Pointer to the file in memory len(data), #Size of the file in memory byref(texture)) #ppTexture else: d3dxdll.D3DXCreateTextureFromFileA(frame.device, #@UndefinedVariable SPRITES_FOLDER + file, byref(texture)) self.model_sprites[model] = texture #else: # raise Exception("'sprites' folder is not present!") </code></pre> <p>Any questions fell free to ask.</p>
4
2011-07-26T03:20:59Z
[ "python", "packaging", "py2exe" ]
py2exe - generate single executable file
112,698
<p>I thought I heard that <a href="http://www.py2exe.org/">py2exe</a> was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used?</p> <p>Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.</p>
112
2008-09-22T00:49:12Z
31,804,023
<p>try <a href="http://cx-freeze.sourceforge.net/" rel="nofollow">c_x freeze</a> it can create a good standalone</p>
0
2015-08-04T08:13:18Z
[ "python", "packaging", "py2exe" ]