title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
For list unless empty in python
1,531,402
<p>I've been writing a lot of constructs like this the past couple of days:</p> <pre><code>list = get_list() if list: for i in list: pass # do something with the list else: pass # do something if the list was empty </code></pre> <p>Lot of junk and I assign the list to a real variable (keeping it in memory longer than needed). Python has simplified a lot of my code up til now... Is there a easy way to do this?</p> <p>(My understanding is that the <code>else</code> in the <code>for: else:</code> construct always triggers after it has looped, empty or not - so not what I want)</p>
12
2009-10-07T12:43:07Z
1,531,525
<p>Use a list comprehension:</p> <pre><code>def do_something(x): return x**2 list = [] result = [do_something(x) for x in list if list] print result # [] list = [1, 2, 3] result = [do_something(x) for x in list if list] print result # [1, 4, 9] </code></pre>
7
2009-10-07T13:05:42Z
[ "for-loop", "python" ]
For list unless empty in python
1,531,402
<p>I've been writing a lot of constructs like this the past couple of days:</p> <pre><code>list = get_list() if list: for i in list: pass # do something with the list else: pass # do something if the list was empty </code></pre> <p>Lot of junk and I assign the list to a real variable (keeping it in memory longer than needed). Python has simplified a lot of my code up til now... Is there a easy way to do this?</p> <p>(My understanding is that the <code>else</code> in the <code>for: else:</code> construct always triggers after it has looped, empty or not - so not what I want)</p>
12
2009-10-07T12:43:07Z
1,533,325
<p>If your actions are <strong>different</strong>, I would do:</p> <pre><code>list_ = get_list() # underscore to keep built-in list if not list_: # do something for i in list_: # # do something for each item </code></pre> <p>If your actions are <strong>similar</strong>, this is more beautiful:</p> <pre><code>for i in list_ or [None]: # do something for list item or None </code></pre> <p>or, if you might have <code>None</code> as a list element, </p> <pre><code>for i in list_ or [...]: # do something for list item or built-in constant Ellipsis </code></pre>
1
2009-10-07T18:21:44Z
[ "for-loop", "python" ]
For list unless empty in python
1,531,402
<p>I've been writing a lot of constructs like this the past couple of days:</p> <pre><code>list = get_list() if list: for i in list: pass # do something with the list else: pass # do something if the list was empty </code></pre> <p>Lot of junk and I assign the list to a real variable (keeping it in memory longer than needed). Python has simplified a lot of my code up til now... Is there a easy way to do this?</p> <p>(My understanding is that the <code>else</code> in the <code>for: else:</code> construct always triggers after it has looped, empty or not - so not what I want)</p>
12
2009-10-07T12:43:07Z
1,534,260
<p>Based on the other answers, I think the cleanest solutions are</p> <pre><code>#Handles None return from get_list for item in get_list() or []: pass #do something </code></pre> <p>or the comprehension equiv</p> <pre><code>result = [item*item for item in get_list() or []] </code></pre>
16
2009-10-07T21:21:24Z
[ "for-loop", "python" ]
For list unless empty in python
1,531,402
<p>I've been writing a lot of constructs like this the past couple of days:</p> <pre><code>list = get_list() if list: for i in list: pass # do something with the list else: pass # do something if the list was empty </code></pre> <p>Lot of junk and I assign the list to a real variable (keeping it in memory longer than needed). Python has simplified a lot of my code up til now... Is there a easy way to do this?</p> <p>(My understanding is that the <code>else</code> in the <code>for: else:</code> construct always triggers after it has looped, empty or not - so not what I want)</p>
12
2009-10-07T12:43:07Z
1,534,275
<p>I think your way is ok in general case, but you may consider this approach:</p> <pre><code>def do_something(item): pass # do something with the list def action_when_empty(): pass # do something if the list was empty # and here goes your example yourlist = get_list() or [] another_list = [do_something(x) for x in yourlist] or action_when_empty() </code></pre>
1
2009-10-07T21:23:12Z
[ "for-loop", "python" ]
For list unless empty in python
1,531,402
<p>I've been writing a lot of constructs like this the past couple of days:</p> <pre><code>list = get_list() if list: for i in list: pass # do something with the list else: pass # do something if the list was empty </code></pre> <p>Lot of junk and I assign the list to a real variable (keeping it in memory longer than needed). Python has simplified a lot of my code up til now... Is there a easy way to do this?</p> <p>(My understanding is that the <code>else</code> in the <code>for: else:</code> construct always triggers after it has looped, empty or not - so not what I want)</p>
12
2009-10-07T12:43:07Z
5,340,888
<pre><code>i = None for i in get_list(): pass # do something with the list else: if i is None: pass # do something if the list was empty </code></pre> <p>Does that help? Yes I know we are two years away from the need :-)</p>
-1
2011-03-17T15:03:36Z
[ "for-loop", "python" ]
JSON serialization of Google App Engine models
1,531,501
<p>I've been searching for quite a while with no success. My project isn't using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model) into JSON or do I need to write my own serializer? </p> <p><strong>Model:</strong></p> <pre><code>class Photo(db.Model): filename = db.StringProperty() title = db.StringProperty() description = db.StringProperty(multiline=True) date_taken = db.DateTimeProperty() date_uploaded = db.DateTimeProperty(auto_now_add=True) album = db.ReferenceProperty(Album, collection_name='photo') </code></pre>
83
2009-10-07T13:01:17Z
1,531,539
<p>Even if you are not using django as a framework, those libraries are still available for you to use. </p> <pre><code>from django.core import serializers data = serializers.serialize("xml", Photo.objects.all()) </code></pre>
3
2009-10-07T13:07:50Z
[ "python", "json", "google-app-engine" ]
JSON serialization of Google App Engine models
1,531,501
<p>I've been searching for quite a while with no success. My project isn't using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model) into JSON or do I need to write my own serializer? </p> <p><strong>Model:</strong></p> <pre><code>class Photo(db.Model): filename = db.StringProperty() title = db.StringProperty() description = db.StringProperty(multiline=True) date_taken = db.DateTimeProperty() date_uploaded = db.DateTimeProperty(auto_now_add=True) album = db.ReferenceProperty(Album, collection_name='photo') </code></pre>
83
2009-10-07T13:01:17Z
1,531,555
<p>You don't need to write your own "parser" (a parser would presumably turn JSON into a Python object), but you can still serialize your Python object yourself.</p> <p>Using <a href="http://simplejson.googlecode.com/svn/tags/simplejson-2.0.9/docs/index.html" rel="nofollow">simplejson</a>:</p> <pre><code>import simplejson as json serialized = json.dumps({ 'filename': self.filename, 'title': self.title, 'date_taken': date_taken.isoformat(), # etc. }) </code></pre>
4
2009-10-07T13:11:26Z
[ "python", "json", "google-app-engine" ]
JSON serialization of Google App Engine models
1,531,501
<p>I've been searching for quite a while with no success. My project isn't using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model) into JSON or do I need to write my own serializer? </p> <p><strong>Model:</strong></p> <pre><code>class Photo(db.Model): filename = db.StringProperty() title = db.StringProperty() description = db.StringProperty(multiline=True) date_taken = db.DateTimeProperty() date_uploaded = db.DateTimeProperty(auto_now_add=True) album = db.ReferenceProperty(Album, collection_name='photo') </code></pre>
83
2009-10-07T13:01:17Z
1,532,035
<p>A simple recursive function can be used to convert an entity (and any referents) to a nested dictionary that can be passed to <code>simplejson</code>:</p> <pre><code>import datetime import time SIMPLE_TYPES = (int, long, float, bool, dict, basestring, list) def to_dict(model): output = {} for key, prop in model.properties().iteritems(): value = getattr(model, key) if value is None or isinstance(value, SIMPLE_TYPES): output[key] = value elif isinstance(value, datetime.date): # Convert date/datetime to MILLISECONDS-since-epoch (JS "new Date()"). ms = time.mktime(value.utctimetuple()) * 1000 ms += getattr(value, 'microseconds', 0) / 1000 output[key] = int(ms) elif isinstance(value, db.GeoPt): output[key] = {'lat': value.lat, 'lon': value.lon} elif isinstance(value, db.Model): output[key] = to_dict(value) else: raise ValueError('cannot encode ' + repr(prop)) return output </code></pre>
60
2009-10-07T14:36:52Z
[ "python", "json", "google-app-engine" ]
JSON serialization of Google App Engine models
1,531,501
<p>I've been searching for quite a while with no success. My project isn't using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model) into JSON or do I need to write my own serializer? </p> <p><strong>Model:</strong></p> <pre><code>class Photo(db.Model): filename = db.StringProperty() title = db.StringProperty() description = db.StringProperty(multiline=True) date_taken = db.DateTimeProperty() date_uploaded = db.DateTimeProperty(auto_now_add=True) album = db.ReferenceProperty(Album, collection_name='photo') </code></pre>
83
2009-10-07T13:01:17Z
1,532,108
<p>For simple cases, I like the approach advocated <a href="http://skonieczny.pl/blog/it-should-just-work/post/2009/04/30/json-serialization-of-google-app-engine-models/" rel="nofollow">here</a> at the end of the article:</p> <pre><code> # after obtaining a list of entities in some way, e.g.: user = users.get_current_user().email().lower(); col = models.Entity.gql('WHERE user=:1',user).fetch(300, 0) # ...you can make a json serialization of name/key pairs as follows: json = simplejson.dumps(col, default=lambda o: {o.name :str(o.key())}) </code></pre> <p>The article also contains, at the other end of the spectrum, a complex serializer class that enriches django's (and does require <code>_meta</code> -- not sure why you're getting errors about _meta missing, perhaps the bug described <a href="http://code.google.com/p/google-app-engine-django/issues/detail?id=52" rel="nofollow">here</a>) with the ability to serialize computed properties / methods. Most of the time you serialization needs lay somewhere in between, and for those an introspective approach such as @David Wilson's may be preferable.</p>
4
2009-10-07T14:45:23Z
[ "python", "json", "google-app-engine" ]
JSON serialization of Google App Engine models
1,531,501
<p>I've been searching for quite a while with no success. My project isn't using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model) into JSON or do I need to write my own serializer? </p> <p><strong>Model:</strong></p> <pre><code>class Photo(db.Model): filename = db.StringProperty() title = db.StringProperty() description = db.StringProperty(multiline=True) date_taken = db.DateTimeProperty() date_uploaded = db.DateTimeProperty(auto_now_add=True) album = db.ReferenceProperty(Album, collection_name='photo') </code></pre>
83
2009-10-07T13:01:17Z
1,535,243
<p>If you use <a href="http://code.google.com/p/app-engine-patch/" rel="nofollow">app-engine-patch</a> it will automatically declare the <code>_meta</code> attribute for you, and then you can use <code>django.core.serializers</code> as you would normally do on django models (as in sledge's code).</p> <p>App-engine-patch has some other cool features such has an hybrid authentication (django + google accounts), and the admin part of django works.</p>
2
2009-10-08T02:05:25Z
[ "python", "json", "google-app-engine" ]
JSON serialization of Google App Engine models
1,531,501
<p>I've been searching for quite a while with no success. My project isn't using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model) into JSON or do I need to write my own serializer? </p> <p><strong>Model:</strong></p> <pre><code>class Photo(db.Model): filename = db.StringProperty() title = db.StringProperty() description = db.StringProperty(multiline=True) date_taken = db.DateTimeProperty() date_uploaded = db.DateTimeProperty(auto_now_add=True) album = db.ReferenceProperty(Album, collection_name='photo') </code></pre>
83
2009-10-07T13:01:17Z
2,305,601
<p>This is the simplest solution I found. It requires only 3 lines of codes.</p> <p>Simply add a method to your model to return a dictionary:</p> <pre><code>class DictModel(db.Model): def to_dict(self): return dict([(p, unicode(getattr(self, p))) for p in self.properties()]) </code></pre> <p>SimpleJSON now works properly:</p> <pre><code>class Photo(DictModel): filename = db.StringProperty() title = db.StringProperty() description = db.StringProperty(multiline=True) date_taken = db.DateTimeProperty() date_uploaded = db.DateTimeProperty(auto_now_add=True) album = db.ReferenceProperty(Album, collection_name='photo') from django.utils import simplejson from google.appengine.ext import webapp class PhotoHandler(webapp.RequestHandler): def get(self): photos = Photo.all() self.response.out.write(simplejson.dumps([p.to_dict() for p in photos])) </code></pre>
58
2010-02-21T10:42:46Z
[ "python", "json", "google-app-engine" ]
JSON serialization of Google App Engine models
1,531,501
<p>I've been searching for quite a while with no success. My project isn't using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model) into JSON or do I need to write my own serializer? </p> <p><strong>Model:</strong></p> <pre><code>class Photo(db.Model): filename = db.StringProperty() title = db.StringProperty() description = db.StringProperty(multiline=True) date_taken = db.DateTimeProperty() date_uploaded = db.DateTimeProperty(auto_now_add=True) album = db.ReferenceProperty(Album, collection_name='photo') </code></pre>
83
2009-10-07T13:01:17Z
2,598,073
<p>There's a method, "Model.properties()", defined for all Model classes. It returns the dict you seek.</p> <pre><code>from django.utils import simplejson class Photo(db.Model): # ... my_photo = Photo(...) simplejson.dumps(my_photo.properties()) </code></pre> <p>See <a href="http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_properties" rel="nofollow">Model properties</a> in the docs.</p>
1
2010-04-08T06:51:39Z
[ "python", "json", "google-app-engine" ]
JSON serialization of Google App Engine models
1,531,501
<p>I've been searching for quite a while with no success. My project isn't using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model) into JSON or do I need to write my own serializer? </p> <p><strong>Model:</strong></p> <pre><code>class Photo(db.Model): filename = db.StringProperty() title = db.StringProperty() description = db.StringProperty(multiline=True) date_taken = db.DateTimeProperty() date_uploaded = db.DateTimeProperty(auto_now_add=True) album = db.ReferenceProperty(Album, collection_name='photo') </code></pre>
83
2009-10-07T13:01:17Z
3,063,649
<p>To serialize models, add a custom json encoder as in the following python:</p> <pre><code>import datetime from google.appengine.api import users from google.appengine.ext import db from django.utils import simplejson class jsonEncoder(simplejson.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): return obj.isoformat() elif isinstance(obj, db.Model): return dict((p, getattr(obj, p)) for p in obj.properties()) elif isinstance(obj, users.User): return obj.email() else: return simplejson.JSONEncoder.default(self, obj) # use the encoder as: simplejson.dumps(model, cls=jsonEncoder) </code></pre> <p>This will encode:</p> <ul> <li>a date as as isoformat string (<a href="http://stackoverflow.com/questions/455580/json-datetime-between-python-and-javascript/456032#456032">per this suggestion</a>),</li> <li>a model as a dict of its properties, </li> <li>a user as his email.</li> </ul> <p>To decode the date you can use this javascript:</p> <pre><code>function decodeJsonDate(s){ return new Date( s.slice(0,19).replace('T',' ') + ' GMT' ); } // Note that this function truncates milliseconds. </code></pre> <p>Note: Thanks to user <a href="http://stackoverflow.com/users/79125/pydave">pydave</a> who edited this code to make it more readable. I had originally had used python's if/else expressions to express <code>jsonEncoder</code> in fewer lines as follows: (I've added some comments and used <code>google.appengine.ext.db.to_dict</code>, to make it clearer than the original.)</p> <pre><code>class jsonEncoder(simplejson.JSONEncoder): def default(self, obj): isa=lambda x: isinstance(obj, x) # isa(&lt;type&gt;)==True if obj is of type &lt;type&gt; return obj.isoformat() if isa(datetime.datetime) else \ db.to_dict(obj) if isa(db.Model) else \ obj.email() if isa(users.User) else \ simplejson.JSONEncoder.default(self, obj) </code></pre>
7
2010-06-17T16:39:10Z
[ "python", "json", "google-app-engine" ]
JSON serialization of Google App Engine models
1,531,501
<p>I've been searching for quite a while with no success. My project isn't using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model) into JSON or do I need to write my own serializer? </p> <p><strong>Model:</strong></p> <pre><code>class Photo(db.Model): filename = db.StringProperty() title = db.StringProperty() description = db.StringProperty(multiline=True) date_taken = db.DateTimeProperty() date_uploaded = db.DateTimeProperty(auto_now_add=True) album = db.ReferenceProperty(Album, collection_name='photo') </code></pre>
83
2009-10-07T13:01:17Z
3,588,306
<p>Mtgred's answer above worked wonderfully for me -- I slightly modified it so I could also get the key for the entry. Not as few lines of code, but it gives me the unique key:</p> <pre><code>class DictModel(db.Model): def to_dict(self): tempdict1 = dict([(p, unicode(getattr(self, p))) for p in self.properties()]) tempdict2 = {'key':unicode(self.key())} tempdict1.update(tempdict2) return tempdict1 </code></pre>
1
2010-08-27T21:38:00Z
[ "python", "json", "google-app-engine" ]
JSON serialization of Google App Engine models
1,531,501
<p>I've been searching for quite a while with no success. My project isn't using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model) into JSON or do I need to write my own serializer? </p> <p><strong>Model:</strong></p> <pre><code>class Photo(db.Model): filename = db.StringProperty() title = db.StringProperty() description = db.StringProperty(multiline=True) date_taken = db.DateTimeProperty() date_uploaded = db.DateTimeProperty(auto_now_add=True) album = db.ReferenceProperty(Album, collection_name='photo') </code></pre>
83
2009-10-07T13:01:17Z
6,829,471
<p>In the latest (1.5.2) release of the App Engine SDK, a <code>to_dict()</code> function that converts model instances to dictionaries was introduced in <code>db.py</code>. See the <a href="http://code.google.com/p/googleappengine/wiki/SdkReleaseNotes#Version_1.5.2_-_July_21,_2011">release notes</a>. </p> <p>There is no reference to this function in the documentation as of yet, but I have tried it myself and it works as expected. </p>
15
2011-07-26T11:43:18Z
[ "python", "json", "google-app-engine" ]
JSON serialization of Google App Engine models
1,531,501
<p>I've been searching for quite a while with no success. My project isn't using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model) into JSON or do I need to write my own serializer? </p> <p><strong>Model:</strong></p> <pre><code>class Photo(db.Model): filename = db.StringProperty() title = db.StringProperty() description = db.StringProperty(multiline=True) date_taken = db.DateTimeProperty() date_uploaded = db.DateTimeProperty(auto_now_add=True) album = db.ReferenceProperty(Album, collection_name='photo') </code></pre>
83
2009-10-07T13:01:17Z
9,452,999
<p>I've extended the JSON Encoder class written by <a href="http://stackoverflow.com/a/3063649">dpatru</a> to support:</p> <ul> <li>Query results properties (e.g. car.owner_set)</li> <li>ReferenceProperty - recursively turn it into JSON</li> <li><p>Filtering properties - only properties with a <code>verbose_name</code> will be encoded into JSON</p> <pre><code>class DBModelJSONEncoder(json.JSONEncoder): """Encodes a db.Model into JSON""" def default(self, obj): if (isinstance(obj, db.Query)): # It's a reference query (holding several model instances) return [self.default(item) for item in obj] elif (isinstance(obj, db.Model)): # Only properties with a verbose name will be displayed in the JSON output properties = obj.properties() filtered_properties = filter(lambda p: properties[p].verbose_name != None, properties) # Turn each property of the DB model into a JSON-serializeable entity json_dict = dict([( p, getattr(obj, p) if (not isinstance(getattr(obj, p), db.Model)) else self.default(getattr(obj, p)) # A referenced model property ) for p in filtered_properties]) json_dict['id'] = obj.key().id() # Add the model instance's ID (optional - delete this if you do not use it) return json_dict else: # Use original JSON encoding return json.JSONEncoder.default(self, obj) </code></pre></li> </ul>
2
2012-02-26T12:18:31Z
[ "python", "json", "google-app-engine" ]
JSON serialization of Google App Engine models
1,531,501
<p>I've been searching for quite a while with no success. My project isn't using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model) into JSON or do I need to write my own serializer? </p> <p><strong>Model:</strong></p> <pre><code>class Photo(db.Model): filename = db.StringProperty() title = db.StringProperty() description = db.StringProperty(multiline=True) date_taken = db.DateTimeProperty() date_uploaded = db.DateTimeProperty(auto_now_add=True) album = db.ReferenceProperty(Album, collection_name='photo') </code></pre>
83
2009-10-07T13:01:17Z
10,399,944
<p>As mentioned by <a href="http://stackoverflow.com/users/806432/fredva">http://stackoverflow.com/users/806432/fredva</a>, the to_dict works great. Here is my code i'm using.</p> <pre><code>foos = query.fetch(10) prepJson = [] for f in foos: prepJson.append(db.to_dict(f)) myJson = json.dumps(prepJson)) </code></pre>
2
2012-05-01T15:26:03Z
[ "python", "json", "google-app-engine" ]
JSON serialization of Google App Engine models
1,531,501
<p>I've been searching for quite a while with no success. My project isn't using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model) into JSON or do I need to write my own serializer? </p> <p><strong>Model:</strong></p> <pre><code>class Photo(db.Model): filename = db.StringProperty() title = db.StringProperty() description = db.StringProperty(multiline=True) date_taken = db.DateTimeProperty() date_uploaded = db.DateTimeProperty(auto_now_add=True) album = db.ReferenceProperty(Album, collection_name='photo') </code></pre>
83
2009-10-07T13:01:17Z
19,205,188
<p>To serialize a Datastore Model instance you can't use json.dumps (haven't tested but Lorenzo pointed it out). Maybe in the future the following will work.</p> <p><a href="http://docs.python.org/2/library/json.html" rel="nofollow">http://docs.python.org/2/library/json.html</a></p> <pre><code>import json string = json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) object = json.loads(self.request.body) </code></pre>
0
2013-10-06T03:43:36Z
[ "python", "json", "google-app-engine" ]
How to yank an entire block in Vim?
1,531,551
<p>Is it possible to yank an entire block of Python code in Vim?</p> <p>Be it a <code>def</code>, <code>for</code>, <code>if</code>, etc. block...</p>
17
2009-10-07T13:10:07Z
1,531,576
<p>You can yank a paragraph with <code>y}</code>. This will not yank all the methods if you have a blank line though.</p>
18
2009-10-07T13:15:24Z
[ "python", "vim" ]
How to yank an entire block in Vim?
1,531,551
<p>Is it possible to yank an entire block of Python code in Vim?</p> <p>Be it a <code>def</code>, <code>for</code>, <code>if</code>, etc. block...</p>
17
2009-10-07T13:10:07Z
1,531,578
<p>There's a vim add-on script <a href="http://www.vim.org/scripts/script.php?script%5Fid=30" rel="nofollow">python_fn.vim</a> which has, as one of its functions, a key binding to visually select a block of Python code using <code>]v</code>. You could then yank it with <code>y</code> as normal.</p>
4
2009-10-07T13:15:30Z
[ "python", "vim" ]
How to yank an entire block in Vim?
1,531,551
<p>Is it possible to yank an entire block of Python code in Vim?</p> <p>Be it a <code>def</code>, <code>for</code>, <code>if</code>, etc. block...</p>
17
2009-10-07T13:10:07Z
1,531,977
<p>I usually just use visual block mode. Shift-V, move, and 'y'ank the highlighted block. There's only so many shortcuts I can keep in memory at once :) </p>
3
2009-10-07T14:27:09Z
[ "python", "vim" ]
How to yank an entire block in Vim?
1,531,551
<p>Is it possible to yank an entire block of Python code in Vim?</p> <p>Be it a <code>def</code>, <code>for</code>, <code>if</code>, etc. block...</p>
17
2009-10-07T13:10:07Z
1,534,960
<ol> <li>Enter visual line selection by pressing 'V'</li> <li>When finished selecting the block pres 'y'</li> <li>Paste it somewhere with 'p' or 'P'</li> </ol>
3
2009-10-08T00:18:11Z
[ "python", "vim" ]
How to yank an entire block in Vim?
1,531,551
<p>Is it possible to yank an entire block of Python code in Vim?</p> <p>Be it a <code>def</code>, <code>for</code>, <code>if</code>, etc. block...</p>
17
2009-10-07T13:10:07Z
1,534,987
<p>You can combine a search with yank, so if your function ends with <code>return retval</code> you can type <code>y/return retval</code></p>
3
2009-10-08T00:32:07Z
[ "python", "vim" ]
How to yank an entire block in Vim?
1,531,551
<p>Is it possible to yank an entire block of Python code in Vim?</p> <p>Be it a <code>def</code>, <code>for</code>, <code>if</code>, etc. block...</p>
17
2009-10-07T13:10:07Z
4,533,586
<p>If you want to yank everything except the <code>{</code> use <code>yi{</code> (or <code>yi}</code>). If you to include the curly braces use <code>ya{</code> (or <code>ya}</code>). </p> <p>The <code>i</code> and <code>a</code> modifiers mean <em>in</em> and <em>all</em>. </p> <p>To yank a word no matter where in the word you are: <code>yiw</code></p> <p>To yank the contents of parentheses: <code>yi)</code>; if you want to include them, use <code>ya(</code></p> <p>You can do the same for <code>"</code> or <code>'</code> with <code>yi"</code>, <code>ya"</code> or <code>yi'</code> and <code>ya'</code>.</p> <p>Of course, you're not limited to yanking. You can delete a word with <code>diw</code> or change it with <code>ciw</code>, etc... etc...</p>
5
2010-12-26T11:01:13Z
[ "python", "vim" ]
How to yank an entire block in Vim?
1,531,551
<p>Is it possible to yank an entire block of Python code in Vim?</p> <p>Be it a <code>def</code>, <code>for</code>, <code>if</code>, etc. block...</p>
17
2009-10-07T13:10:07Z
11,173,312
<p>I made a plugin named <a href="http://www.vim.org/scripts/script.php?script_id=3997" rel="nofollow">spacebox</a> which does a Visual selection of all lines with the same or more indentation as the current line.</p> <p>With Python whitespace being the way it is, you could place your cursor on the line below <code>def</code> or <code>if</code>, and issue the command <code>:SpaceBox</code> to select your "block".</p>
1
2012-06-23T21:58:47Z
[ "python", "vim" ]
How to yank an entire block in Vim?
1,531,551
<p>Is it possible to yank an entire block of Python code in Vim?</p> <p>Be it a <code>def</code>, <code>for</code>, <code>if</code>, etc. block...</p>
17
2009-10-07T13:10:07Z
11,723,792
<p>The excellent add-on suite <a href="https://github.com/klen/python-mode">Python-mode</a> includes some <a href="https://github.com/klen/python-mode#default-keys">key commands</a> to navigate classes, methods, and function blocks.</p> <ul> <li><p>To yank a method: <kbd>y</kbd><kbd>a</kbd><kbd>M</kbd> (inner method: <kbd>y</kbd><kbd>i</kbd><kbd>M</kbd>)</p></li> <li><p>To yank a class: <kbd>y</kbd><kbd>a</kbd><kbd>C</kbd></p></li> </ul> <p>There are other handy motions, like moving from function-to-function (<kbd>]</kbd><kbd>]</kbd>). See the <a href="https://github.com/klen/python-mode#default-keys">complete list of keys</a> for more.</p>
5
2012-07-30T14:42:03Z
[ "python", "vim" ]
Double import in grok
1,531,647
<p>This is a normal case of mutual import. Suppose you have the following layout</p> <pre><code>./test.py ./one ./one/__init__.py ./one/two ./one/two/__init__.py ./one/two/m.py ./one/two/three ./one/two/three/__init__.py ./one/two/three/four ./one/two/three/four/__init__.py ./one/two/three/four/e.py ./one/two/u.py </code></pre> <p>And you have</p> <p>test.py</p> <pre><code> from one.two.three.four import e </code></pre> <p>one/two/three/four/e.py</p> <pre><code>from one.two import m </code></pre> <p>one/two/m.py</p> <pre><code>print "m" import u </code></pre> <p>one/two/u.py</p> <pre><code>print "u" import m </code></pre> <p>When you run the test.py program, you expect, of course:</p> <pre><code>python test.py m u </code></pre> <p>Which is the expected behavior. Modules have already been imported, and they are only once. In Grok, this does not happen. Suppose to have the following app.py</p> <pre><code>import os; import sys; sys.path.insert(1,os.path.dirname( os.path.realpath( __file__ ) )) import grok from one.two.three.four import e class Sample(grok.Application, grok.Container): pass </code></pre> <p>what you obtain when you run paster is:</p> <pre><code>$ bin/paster serve parts/etc/deploy.ini 2009-10-07 15:26:57,154 WARNING [root] Developer mode is enabled: this is a security risk and should NOT be enabled on production servers. Developer mode can be turned off in etc/zope.conf m u m u </code></pre> <p>What's going on in here ?</p> <p>from a pdb stack trace, both cases are imported by martian:</p> <pre><code> /Users/sbo/.buildout/eggs/martian-0.11-py2.4.egg/martian/core.py(204)grok_package() -&gt; grok_module(module_info, grokker, **kw) /Users/sbo/.buildout/eggs/martian-0.11-py2.4.egg/martian/core.py(209)grok_module() -&gt; grokker.grok(module_info.dotted_name, module_info.getModule(), /Users/sbo/.buildout/eggs/martian-0.11-py2.4.egg/martian/scan.py(118)getModule() -&gt; self._module = resolve(self.dotted_name) /Users/sbo/.buildout/eggs/martian-0.11-py2.4.egg/martian/scan.py(191)resolve() -&gt; __import__(used) </code></pre> <p>The only difference between the first case and the second one is that the first shows the progressive import of e and then of m. In the second case it directly imports m.</p> <p>Thanks for the help</p>
0
2009-10-07T13:28:17Z
1,531,809
<p>This could possibly be a side-effect of the introspection Grok does, I'm not sure.</p> <p>Try to put a pdb.set_trace() in m, and check at the stack trace to see what is importing the modules.</p>
0
2009-10-07T13:56:25Z
[ "python", "grok" ]
What are some useful non-built-in Django tags?
1,532,021
<p>I'm relatively new to Django and I'm trying to build up my toolbox for future projects. In my last project, when a built-in template tag didn't do quite what I needed, I would make a mangled mess of the template to shoe-horn in the feature. I later would find a template tag that would have saved me time and ugly code.</p> <p>So what are some useful template tags that doesn't come built into Django?</p>
3
2009-10-07T14:35:37Z
1,532,076
<p><a href="http://www.djangosnippets.org/snippets/1350/" rel="nofollow">smart-if</a>. Allows normal <code>if x &gt; y</code> constructs in templates, among other things.</p> <p>A better <code>if</code> tag is now part of Django 1.2 (see <a href="http://docs.djangoproject.com/en/dev/releases/1.2/#smart-if-tag" rel="nofollow">the release notes</a>), which is scheduled for release on <a href="http://code.djangoproject.com/wiki/Version1.2Roadmap" rel="nofollow">March 9th 2010</a>.</p>
3
2009-10-07T14:41:24Z
[ "python", "django", "favorites", "django-tagging" ]
What are some useful non-built-in Django tags?
1,532,021
<p>I'm relatively new to Django and I'm trying to build up my toolbox for future projects. In my last project, when a built-in template tag didn't do quite what I needed, I would make a mangled mess of the template to shoe-horn in the feature. I later would find a template tag that would have saved me time and ugly code.</p> <p>So what are some useful template tags that doesn't come built into Django?</p>
3
2009-10-07T14:35:37Z
1,532,097
<p>I'll start.</p> <p><a href="http://www.djangosnippets.org/snippets/1350/" rel="nofollow">http://www.djangosnippets.org/snippets/1350/</a></p> <h2>Smart {% if %} template tag</h2> <p>If you've ever found yourself needing more than a test for True, this tag is for you. It supports equality, greater than, and less than operators.</p> <h2>Simple Example</h2> <pre><code>{% block list-products %} {% if products|length &gt; 12 %} &lt;!-- Code for pagination --&gt; {% endif %} &lt;!-- Code for displaying 12 products on the page --&gt; {% endblock %} </code></pre>
4
2009-10-07T14:43:37Z
[ "python", "django", "favorites", "django-tagging" ]
What are some useful non-built-in Django tags?
1,532,021
<p>I'm relatively new to Django and I'm trying to build up my toolbox for future projects. In my last project, when a built-in template tag didn't do quite what I needed, I would make a mangled mess of the template to shoe-horn in the feature. I later would find a template tag that would have saved me time and ugly code.</p> <p>So what are some useful template tags that doesn't come built into Django?</p>
3
2009-10-07T14:35:37Z
1,532,373
<p>James Bennet's over-the-top-dynamic <a href="http://www.b-list.org/weblog/2006/jun/07/django-tips-write-better-template-tags/" rel="nofollow"><code>get_latest</code> tag</a></p> <p><strong>edit as response to jpartogi's comment</strong></p> <pre><code>class GetItemsNode(Node): def __init__(self, model, num, by, varname): self.num, self.varname = num, varname self.model = get_model(*model.split('.')) self.by = by def render(self, context): if hasattr(self.model, 'publicmgr') and not context['user'].is_authenticated(): context[self.varname] = self.model.publicmgr.all().order_by(self.by)[:self.num] else: context[self.varname] = self.model._default_manager.all().order_by(self.by)[:self.num] return '' &lt;div id="news_portlet" class="portlet"&gt; {% get_sorted_items cms.news 5 by -created_on as items %} {% include 'snippets/dl.html' %} &lt;/div&gt; &lt;div id="event_portlet" class="portlet"&gt; {% get_sorted_items cms.event 5 by date as items %} {% include 'snippets/dl.html' %} &lt;/div&gt; </code></pre> <p>I call it <code>get_sorted_items</code>, but it is based on James' blog-post</p>
1
2009-10-07T15:30:37Z
[ "python", "django", "favorites", "django-tagging" ]
What are some useful non-built-in Django tags?
1,532,021
<p>I'm relatively new to Django and I'm trying to build up my toolbox for future projects. In my last project, when a built-in template tag didn't do quite what I needed, I would make a mangled mess of the template to shoe-horn in the feature. I later would find a template tag that would have saved me time and ugly code.</p> <p>So what are some useful template tags that doesn't come built into Django?</p>
3
2009-10-07T14:35:37Z
1,543,958
<p>In come case {% autopaginate queryset %} (<a href="http://code.google.com/p/django-pagination/" rel="nofollow">http://code.google.com/p/django-pagination/</a>) is useful. For example:</p> <pre><code>#views.py obj_list = News.objects.filter(status=News.PUBLISHED) # do not use len(obj_list) - it's evaluate QuerySet obj_count = obj_list.count() </code></pre> <p><hr /></p> <pre><code>#news_index.html {% load pagination_tags %} ... # do not use {% if obj_list %} {% if obj_count %} &lt;div class="news"&gt; &lt;ul&gt; {% autopaginate obj_list 10 %} {% for item in obj_list %} &lt;li&gt;&lt;a href="..."&gt;{{ item.title }}&lt;/a&gt;&lt;/li&gt; {% endfor %} &lt;/ul&gt; &lt;/div&gt; {% paginate %} {% else %} Empty list {% endif %} </code></pre> <p>Note, that obj_list <em>must</em> be lazy - read <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#id1" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/models/querysets/#id1</a></p>
1
2009-10-09T13:58:51Z
[ "python", "django", "favorites", "django-tagging" ]
Reading HKEY CURRENT USER from the registry in Python, specifying the user
1,532,306
<p>In my application I run subprocesses under several different user accounts. I need to be able to read some of the information written to the registry by these subprocesses. Each one is writing to HKEY_CURRENT_USER, and I know the user account name that they are running under.</p> <p>In Python, how can I read values from HKEY_CURRENT_USER for a specific user? I assume I need to somehow load the registry values under the user's name, and then read them from there, but how?</p> <p>edit: Just to make sure it's clear, my Python program is running as Administrator, and I have accounts "user1", "user2", and "user3", which each have information in their own HKEY_CURRENT_USER. As Administrator, how do I read user1's HKEY_CURRENT_USER data?</p>
1
2009-10-07T15:20:19Z
1,532,868
<p>HKEY_CURRENT_USER maps to a HKEY_USERS\{id} key.</p> <p>Try finding the id by matching the HKEY_USERS{id}\Volatile Environment\USERNAME key to the username of the user (by enumerating/iterating over the {id}s that are present on the system). When you find the match just use HKEY_USERS{id} as if it was HKEY_CURRENT_USER</p>
2
2009-10-07T16:55:31Z
[ "python", "windows", "registry" ]
Reading HKEY CURRENT USER from the registry in Python, specifying the user
1,532,306
<p>In my application I run subprocesses under several different user accounts. I need to be able to read some of the information written to the registry by these subprocesses. Each one is writing to HKEY_CURRENT_USER, and I know the user account name that they are running under.</p> <p>In Python, how can I read values from HKEY_CURRENT_USER for a specific user? I assume I need to somehow load the registry values under the user's name, and then read them from there, but how?</p> <p>edit: Just to make sure it's clear, my Python program is running as Administrator, and I have accounts "user1", "user2", and "user3", which each have information in their own HKEY_CURRENT_USER. As Administrator, how do I read user1's HKEY_CURRENT_USER data?</p>
1
2009-10-07T15:20:19Z
1,532,874
<p>According to <a href="http://technet.microsoft.com/en-us/library/cc976337.aspx" rel="nofollow">MSDN</a>, <code>HKEY_CURRENT_USER</code> is a pointer to <code>HKEY_USERS/SID of the current user</code>. You can use <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">pywin32</a> to look up the SID for an account name. Once you have this, you can use open and use the registry key with the <a href="http://docs.python.org/library/%5Fwinreg.html" rel="nofollow">_winreg</a> module.</p> <pre><code>import win32security import _winreg as winreg sid = win32security.LookupAccountName(None, user_name)[0] sidstr = win32security.ConvertSidToStringSid(sid) key = winreg.OpenKey(winreg.HKEY_USERS, sidstr) # do something with the key </code></pre>
3
2009-10-07T16:56:20Z
[ "python", "windows", "registry" ]
Reading HKEY CURRENT USER from the registry in Python, specifying the user
1,532,306
<p>In my application I run subprocesses under several different user accounts. I need to be able to read some of the information written to the registry by these subprocesses. Each one is writing to HKEY_CURRENT_USER, and I know the user account name that they are running under.</p> <p>In Python, how can I read values from HKEY_CURRENT_USER for a specific user? I assume I need to somehow load the registry values under the user's name, and then read them from there, but how?</p> <p>edit: Just to make sure it's clear, my Python program is running as Administrator, and I have accounts "user1", "user2", and "user3", which each have information in their own HKEY_CURRENT_USER. As Administrator, how do I read user1's HKEY_CURRENT_USER data?</p>
1
2009-10-07T15:20:19Z
35,490,611
<p>If you don't want to install win32 stuff for Python and since you are already using subprocess, you can run built in Windows commands to get at the registry data you are looking for.</p> <p>To query the SID of a particular user:</p> <p><code>wmic useraccount where name='John' get sid</code></p> <p>Then you can use that SID to query other registry entries for that particular user:</p> <p><code>reg query HKEY_USERS\[SID]</code></p> <p>For example, if you want to know the mounted network drives for a particular user:</p> <p><code>reg query HKEY_USERS\S-1-5-21-4205028929-649740040-1951280400-500\Network /s /v RemotePath</code></p> <p>The output will look something like this:</p> <pre><code>HKEY_USERS\S-1-5-21-4205028929-649740040-1951280400-500\Network\R RemotePath REG_SZ \\MACHINENAME1\shared HKEY_USERS\S-1-5-21-4205028929-649740040-1951280400-500\Network\T RemotePath REG_SZ \\MACHINENAME2\testing HKEY_USERS\S-1-5-21-4205028929-649740040-1951280400-500\Network\V RemotePath REG_SZ \\MACHINENAME3\videos End of search: 3 match(es) found. </code></pre> <p>which should be relatively simple to parse in Python.</p> <p>References:</p> <p><a href="http://www.windows-commandline.com/get-sid-of-user/" rel="nofollow">http://www.windows-commandline.com/get-sid-of-user/</a></p> <p><a href="http://superuser.com/questions/135752/list-mapped-network-drives-from-the-command-line-to-text-file">http://superuser.com/questions/135752/list-mapped-network-drives-from-the-command-line-to-text-file</a></p>
0
2016-02-18T19:24:06Z
[ "python", "windows", "registry" ]
Why does my function "hangs"
1,532,474
<pre><code>def retCursor(): host = "localhost" user = "disappearedng" db = "gupan_crawling3" conn = MySQLdb.connect( host=host, user=user, passwd=passwd, db=db) cursor = conn.cursor() return cursor singleCur = retCursor() def checkTemplateBuilt(netlocH): """Used by crawler specifically, this check directly whether template has been built""" singleCur.execute( """SELECT templateBuilt FROM templateEnough WHERE netloc=%s""", [ netlocH]) r = singleCur.fetchone() if r: if bool( r[0]): return True return False </code></pre> <p>Hi everyone I am currently using MySQLdb. For some reason, after perhaps 30 mins of running my app comes to a complete halt. It appears that this function is blocking me. (DOn't know for what reason)</p> <pre><code>Traceback (most recent call last): File "/usr/lib/python2.6/multiprocessing/process.py", line 231, in _bootstrap self.run() File "/mount/950gb/gupan5/disappearedng_temp/code_temp_NEWBRANCH/gupan5-yahoo/crawling/templateCrawling/TemplateCrawler/crawler/crawler.py", line 117, in run self.get_check_put() File "/mount/950gb/gupan5/disappearedng_temp/code_temp_NEWBRANCH/gupan5-yahoo/crawling/templateCrawling/TemplateCrawler/crawler/crawler.py", line 66, in get_check_put if not self.checkLinkCrawlability(linkS, priority): File "/mount/950gb/gupan5/disappearedng_temp/code_temp_NEWBRANCH/gupan5-yahoo/crawling/templateCrawling/TemplateCrawler/crawler/crawler.py", line 53, in checkLinkCrawlability if checkTemplateBuilt( getNetLoc( link)): File "/mount/950gb/gupan5/disappearedng_temp/code_temp_NEWBRANCH/gupan5-yahoo/crawling/templateCrawling/TemplateCrawler/publicapi/publicfunc.py", line 71, in checkTemplateBuilt singleCur.execute( """SELECT templateBuilt FROM templateEnough WHERE netloc=%s""", [ netlocH]) File "/var/lib/python-support/python2.6/MySQLdb/cursors.py", line 153, in execute r = self._query(query) KeyboardInterrupt </code></pre> <p>Btw this is the table:</p> <pre><code>CREATE TABLE templateEnough( `netloc` INT(32) unsigned NOT NULL, `count` SMALLINT(32) unsigned NOT NULL, `templateBuilt` TINYINT(1) unsigned DEFAULT 0 NOT NULL, PRIMARY KEY ( netloc ) ) ENGINE=MEMORY DEFAULT CHARSET=utf8 ; </code></pre> <p>Any ideas? </p>
0
2009-10-07T15:46:16Z
1,532,635
<p>According to your traceback, you interrupted the script during the execution of <code>checkTemplateBuilt</code>, not <code>enoughPassedForTemplate</code>.</p> <p>I think the problem lies in a different part of the code; maybe there is an infinite loop somewhere? Maybe in the <code>run</code> function?</p>
0
2009-10-07T16:14:11Z
[ "python", "mysql" ]
Why does my function "hangs"
1,532,474
<pre><code>def retCursor(): host = "localhost" user = "disappearedng" db = "gupan_crawling3" conn = MySQLdb.connect( host=host, user=user, passwd=passwd, db=db) cursor = conn.cursor() return cursor singleCur = retCursor() def checkTemplateBuilt(netlocH): """Used by crawler specifically, this check directly whether template has been built""" singleCur.execute( """SELECT templateBuilt FROM templateEnough WHERE netloc=%s""", [ netlocH]) r = singleCur.fetchone() if r: if bool( r[0]): return True return False </code></pre> <p>Hi everyone I am currently using MySQLdb. For some reason, after perhaps 30 mins of running my app comes to a complete halt. It appears that this function is blocking me. (DOn't know for what reason)</p> <pre><code>Traceback (most recent call last): File "/usr/lib/python2.6/multiprocessing/process.py", line 231, in _bootstrap self.run() File "/mount/950gb/gupan5/disappearedng_temp/code_temp_NEWBRANCH/gupan5-yahoo/crawling/templateCrawling/TemplateCrawler/crawler/crawler.py", line 117, in run self.get_check_put() File "/mount/950gb/gupan5/disappearedng_temp/code_temp_NEWBRANCH/gupan5-yahoo/crawling/templateCrawling/TemplateCrawler/crawler/crawler.py", line 66, in get_check_put if not self.checkLinkCrawlability(linkS, priority): File "/mount/950gb/gupan5/disappearedng_temp/code_temp_NEWBRANCH/gupan5-yahoo/crawling/templateCrawling/TemplateCrawler/crawler/crawler.py", line 53, in checkLinkCrawlability if checkTemplateBuilt( getNetLoc( link)): File "/mount/950gb/gupan5/disappearedng_temp/code_temp_NEWBRANCH/gupan5-yahoo/crawling/templateCrawling/TemplateCrawler/publicapi/publicfunc.py", line 71, in checkTemplateBuilt singleCur.execute( """SELECT templateBuilt FROM templateEnough WHERE netloc=%s""", [ netlocH]) File "/var/lib/python-support/python2.6/MySQLdb/cursors.py", line 153, in execute r = self._query(query) KeyboardInterrupt </code></pre> <p>Btw this is the table:</p> <pre><code>CREATE TABLE templateEnough( `netloc` INT(32) unsigned NOT NULL, `count` SMALLINT(32) unsigned NOT NULL, `templateBuilt` TINYINT(1) unsigned DEFAULT 0 NOT NULL, PRIMARY KEY ( netloc ) ) ENGINE=MEMORY DEFAULT CHARSET=utf8 ; </code></pre> <p>Any ideas? </p>
0
2009-10-07T15:46:16Z
1,533,848
<p>There might be a lock on the table preventing the query from completing.</p>
1
2009-10-07T20:00:21Z
[ "python", "mysql" ]
Why does my function "hangs"
1,532,474
<pre><code>def retCursor(): host = "localhost" user = "disappearedng" db = "gupan_crawling3" conn = MySQLdb.connect( host=host, user=user, passwd=passwd, db=db) cursor = conn.cursor() return cursor singleCur = retCursor() def checkTemplateBuilt(netlocH): """Used by crawler specifically, this check directly whether template has been built""" singleCur.execute( """SELECT templateBuilt FROM templateEnough WHERE netloc=%s""", [ netlocH]) r = singleCur.fetchone() if r: if bool( r[0]): return True return False </code></pre> <p>Hi everyone I am currently using MySQLdb. For some reason, after perhaps 30 mins of running my app comes to a complete halt. It appears that this function is blocking me. (DOn't know for what reason)</p> <pre><code>Traceback (most recent call last): File "/usr/lib/python2.6/multiprocessing/process.py", line 231, in _bootstrap self.run() File "/mount/950gb/gupan5/disappearedng_temp/code_temp_NEWBRANCH/gupan5-yahoo/crawling/templateCrawling/TemplateCrawler/crawler/crawler.py", line 117, in run self.get_check_put() File "/mount/950gb/gupan5/disappearedng_temp/code_temp_NEWBRANCH/gupan5-yahoo/crawling/templateCrawling/TemplateCrawler/crawler/crawler.py", line 66, in get_check_put if not self.checkLinkCrawlability(linkS, priority): File "/mount/950gb/gupan5/disappearedng_temp/code_temp_NEWBRANCH/gupan5-yahoo/crawling/templateCrawling/TemplateCrawler/crawler/crawler.py", line 53, in checkLinkCrawlability if checkTemplateBuilt( getNetLoc( link)): File "/mount/950gb/gupan5/disappearedng_temp/code_temp_NEWBRANCH/gupan5-yahoo/crawling/templateCrawling/TemplateCrawler/publicapi/publicfunc.py", line 71, in checkTemplateBuilt singleCur.execute( """SELECT templateBuilt FROM templateEnough WHERE netloc=%s""", [ netlocH]) File "/var/lib/python-support/python2.6/MySQLdb/cursors.py", line 153, in execute r = self._query(query) KeyboardInterrupt </code></pre> <p>Btw this is the table:</p> <pre><code>CREATE TABLE templateEnough( `netloc` INT(32) unsigned NOT NULL, `count` SMALLINT(32) unsigned NOT NULL, `templateBuilt` TINYINT(1) unsigned DEFAULT 0 NOT NULL, PRIMARY KEY ( netloc ) ) ENGINE=MEMORY DEFAULT CHARSET=utf8 ; </code></pre> <p>Any ideas? </p>
0
2009-10-07T15:46:16Z
1,534,219
<p>Try logging the query string to a file right before you execute it. Then when you think it is hung, you can look at the query and see if it works manually</p>
1
2009-10-07T21:12:50Z
[ "python", "mysql" ]
Supporting Multiple Python Versions In Your Code?
1,532,488
<p>Today I tried using <a href="http://pybrary.net/pyPdf/">pyPdf</a> 1.12 in a script I was writing that targets Python 2.6. When running my script, and even importing pyPdf, I get complaints about deprecated functionality (md5->hashsum, sets). I'd like to contribute a patch to make this work cleanly in 2.6, but I imagine the author does not want to break compatibility for older versions (2.5 and earlier). </p> <p>Searching Google and Stack Overflow have so far turned up nothing. I feel like I have seen try/except blocks around import statements before that accomplish something similar, but can't find any examples. Is there a generally accepted best practice for supporting multiple Python versions?</p>
6
2009-10-07T15:48:28Z
1,532,524
<p>You can certainly do</p> <pre><code>try: import v26 except ImportError: import v25 </code></pre> <p><a href="http://www.diveintopython.net/file_handling/index.html#d0e14344" rel="nofollow">Dive Into Python—Using Exceptions for Other Purposes</a></p>
4
2009-10-07T15:53:59Z
[ "python", "versioning" ]
Supporting Multiple Python Versions In Your Code?
1,532,488
<p>Today I tried using <a href="http://pybrary.net/pyPdf/">pyPdf</a> 1.12 in a script I was writing that targets Python 2.6. When running my script, and even importing pyPdf, I get complaints about deprecated functionality (md5->hashsum, sets). I'd like to contribute a patch to make this work cleanly in 2.6, but I imagine the author does not want to break compatibility for older versions (2.5 and earlier). </p> <p>Searching Google and Stack Overflow have so far turned up nothing. I feel like I have seen try/except blocks around import statements before that accomplish something similar, but can't find any examples. Is there a generally accepted best practice for supporting multiple Python versions?</p>
6
2009-10-07T15:48:28Z
1,532,531
<p>There are two ways to do this:</p> <p><hr /></p> <p>(1) Just like you described: Try something and work around the exception for old versions. For example, you could try to import the <code>json</code> module and import a userland implementation if this fails:</p> <pre><code>try: import json except ImportError: import myutils.myjson as json </code></pre> <p>This is an example from Django (they use this technique often):</p> <pre><code>try: reversed except NameError: from django.utils.itercompat import reversed # Python 2.3 fallback </code></pre> <p>If the iterator <code>reversed</code> is available, they use it. Otherwise, they import their own implementation from the <code>utils</code> package.</p> <p><hr /></p> <p>(2) Explicitely compare the version of the Python interpreter:</p> <pre><code>import sys if sys.version_info &lt; (2, 6, 0): # Do stuff for old version... else: # Do 2.6+ stuff </code></pre> <p><code>sys.version_info</code> is a tuple that can easily be compared with similar version tuples.</p>
9
2009-10-07T15:55:20Z
[ "python", "versioning" ]
Supporting Multiple Python Versions In Your Code?
1,532,488
<p>Today I tried using <a href="http://pybrary.net/pyPdf/">pyPdf</a> 1.12 in a script I was writing that targets Python 2.6. When running my script, and even importing pyPdf, I get complaints about deprecated functionality (md5->hashsum, sets). I'd like to contribute a patch to make this work cleanly in 2.6, but I imagine the author does not want to break compatibility for older versions (2.5 and earlier). </p> <p>Searching Google and Stack Overflow have so far turned up nothing. I feel like I have seen try/except blocks around import statements before that accomplish something similar, but can't find any examples. Is there a generally accepted best practice for supporting multiple Python versions?</p>
6
2009-10-07T15:48:28Z
9,417,285
<p>Multiple versions of Python <em>are</em> supported here. You can a) conditionally use the newer version, which takes a little work, or b) turn off the warnings, which should really be the default (and is on newer Pythons).</p>
0
2012-02-23T16:43:32Z
[ "python", "versioning" ]
Given a string, how do I know if it needs decoding
1,532,567
<p>I'm using python's base64 module and I get a string that can be encoded or not encoded. I would like to do something like:</p> <pre><code>if isEncoded(s): output = base64.decodestring(s) else: output = s </code></pre> <p>ideas?</p>
1
2009-10-07T16:01:33Z
1,532,585
<p>You could just try it, and see what happens:</p> <pre><code>import base64 def decode_if_necessary(s): try: return base64.decodestring(s) except: return s </code></pre> <p>But you have to ask yourself: what if the original message was in fact a syntactically valid base64 string, but not meant to be one? Then "decoding" it will succeed, but the result is not the required output. So I have to ask: is this <em>really</em> what you want?</p> <p><strong>Edit:</strong> Note that <a href="http://docs.python.org/3.1/library/base64.html#base64.decodestring" rel="nofollow"><code>decodestring</code></a> is deprecated.</p>
4
2009-10-07T16:04:39Z
[ "python", "base64" ]
Given a string, how do I know if it needs decoding
1,532,567
<p>I'm using python's base64 module and I get a string that can be encoded or not encoded. I would like to do something like:</p> <pre><code>if isEncoded(s): output = base64.decodestring(s) else: output = s </code></pre> <p>ideas?</p>
1
2009-10-07T16:01:33Z
1,532,595
<p>In general, it's impossible; if you receive string 'MjMj', for example, how could you possibly know whether it's already decoded and needs to be used as is, or decoded into '23#'?</p>
10
2009-10-07T16:07:00Z
[ "python", "base64" ]
Given a string, how do I know if it needs decoding
1,532,567
<p>I'm using python's base64 module and I get a string that can be encoded or not encoded. I would like to do something like:</p> <pre><code>if isEncoded(s): output = base64.decodestring(s) else: output = s </code></pre> <p>ideas?</p>
1
2009-10-07T16:01:33Z
1,586,707
<p>You could check to see if a string <a href="https://www.theeggeadventure.com/wikimedia/index.php/IsBase64" rel="nofollow">may be base64 encoded</a>. In general, the function can predict with 75%+ accuracy is the data is encoded.</p> <pre><code>def isBase64(s): return (len(s) % 4 == 0) and re.match('^[A-Za-z0-9+/]+[=]{0,2}$', s) </code></pre>
2
2009-10-19T02:26:22Z
[ "python", "base64" ]
the fastest way to create checksum for large files in python
1,532,720
<p>i need to transfer large files across network and need to create checksum for them on hourly basis. so the speed for generating checksum is critical for me.</p> <p>somehow i can't make zlib.crc32 and zlib.adler32 working with files larger than 4GB on Windows XP Pro 64bit machine. i suspect i've hit the 32bit limitation here? using hashlib.md5 i could get a result but the problem is the speed. it takes roughly about 5 minutes to generate an md5 for 4.8GB file. task manager shows that the process is using one core only.</p> <p>my questions are:</p> <ol> <li>is there a way to make crc works on large file? i prefer to use crc than md5</li> <li>if not then is there a way to speed up the md5.hexdigest()/md5.digest? or in this case any hashlib hexdigest/digest? maybe spliting it into multi thread process? how do i do that?</li> </ol> <p>PS: i'm working on somethimg similar like an "Asset Management" system, kind of like svn but the asset consist of large compressed image files. the files have tiny bit incremental changes. the hashing/checksum is needed for detecting changes and error detection.</p>
5
2009-10-07T16:28:08Z
1,532,764
<p>You cannot possibly use more than one core to calculate MD5 hash of a large file because of the very nature of MD5: it expects a message to be broken up in chunks and fed into hashing function in strict sequence. However, you can use one thread to read a file into internal queue, and then calculate hash in a separate thread so that. I do not think though that this will give you any significant performance boost.</p> <p>The fact that it takes so long to process a big file might be due to "unbuffered" reads. Try reading, say, 16 Kb at a time and then feed the content in chunks to hashing function.</p>
0
2009-10-07T16:36:30Z
[ "python", "multithreading", "md5", "crc32", "hashlib" ]
the fastest way to create checksum for large files in python
1,532,720
<p>i need to transfer large files across network and need to create checksum for them on hourly basis. so the speed for generating checksum is critical for me.</p> <p>somehow i can't make zlib.crc32 and zlib.adler32 working with files larger than 4GB on Windows XP Pro 64bit machine. i suspect i've hit the 32bit limitation here? using hashlib.md5 i could get a result but the problem is the speed. it takes roughly about 5 minutes to generate an md5 for 4.8GB file. task manager shows that the process is using one core only.</p> <p>my questions are:</p> <ol> <li>is there a way to make crc works on large file? i prefer to use crc than md5</li> <li>if not then is there a way to speed up the md5.hexdigest()/md5.digest? or in this case any hashlib hexdigest/digest? maybe spliting it into multi thread process? how do i do that?</li> </ol> <p>PS: i'm working on somethimg similar like an "Asset Management" system, kind of like svn but the asset consist of large compressed image files. the files have tiny bit incremental changes. the hashing/checksum is needed for detecting changes and error detection.</p>
5
2009-10-07T16:28:08Z
1,532,779
<p>md5 itself can't be run in parallel. However you can md5 the file in sections (in parallel) and the take an md5 of the list of hashes.</p> <p>However that assumes that the hashing is not IO-limited, which I would suspect it is. As Anton Gogolev suggests - make sure that you're reading the file efficiently (in large power-of-2 chunks). Once you've done that, make sure the file isn't fragmented.</p> <p>Also a hash such as sha256 should be selected rather than md5 for new projects.</p> <p>Are the zlib checksums much faster than md5 for 4Gb files?</p>
0
2009-10-07T16:39:25Z
[ "python", "multithreading", "md5", "crc32", "hashlib" ]
the fastest way to create checksum for large files in python
1,532,720
<p>i need to transfer large files across network and need to create checksum for them on hourly basis. so the speed for generating checksum is critical for me.</p> <p>somehow i can't make zlib.crc32 and zlib.adler32 working with files larger than 4GB on Windows XP Pro 64bit machine. i suspect i've hit the 32bit limitation here? using hashlib.md5 i could get a result but the problem is the speed. it takes roughly about 5 minutes to generate an md5 for 4.8GB file. task manager shows that the process is using one core only.</p> <p>my questions are:</p> <ol> <li>is there a way to make crc works on large file? i prefer to use crc than md5</li> <li>if not then is there a way to speed up the md5.hexdigest()/md5.digest? or in this case any hashlib hexdigest/digest? maybe spliting it into multi thread process? how do i do that?</li> </ol> <p>PS: i'm working on somethimg similar like an "Asset Management" system, kind of like svn but the asset consist of large compressed image files. the files have tiny bit incremental changes. the hashing/checksum is needed for detecting changes and error detection.</p>
5
2009-10-07T16:28:08Z
1,532,792
<p>Did you try the <a href="http://sourceforge.net/projects/crcmod/" rel="nofollow">crc-generator</a> module?</p>
0
2009-10-07T16:43:18Z
[ "python", "multithreading", "md5", "crc32", "hashlib" ]
the fastest way to create checksum for large files in python
1,532,720
<p>i need to transfer large files across network and need to create checksum for them on hourly basis. so the speed for generating checksum is critical for me.</p> <p>somehow i can't make zlib.crc32 and zlib.adler32 working with files larger than 4GB on Windows XP Pro 64bit machine. i suspect i've hit the 32bit limitation here? using hashlib.md5 i could get a result but the problem is the speed. it takes roughly about 5 minutes to generate an md5 for 4.8GB file. task manager shows that the process is using one core only.</p> <p>my questions are:</p> <ol> <li>is there a way to make crc works on large file? i prefer to use crc than md5</li> <li>if not then is there a way to speed up the md5.hexdigest()/md5.digest? or in this case any hashlib hexdigest/digest? maybe spliting it into multi thread process? how do i do that?</li> </ol> <p>PS: i'm working on somethimg similar like an "Asset Management" system, kind of like svn but the asset consist of large compressed image files. the files have tiny bit incremental changes. the hashing/checksum is needed for detecting changes and error detection.</p>
5
2009-10-07T16:28:08Z
1,533,036
<p>It's <strong>an algorithm selection problem</strong>, rather than a library/language selection problem!</p> <p>There appears to be two points to consider primarily:</p> <ul> <li>how much would the <strong>disk I/O</strong> affect the overall performance?</li> <li>what is the expected <strong>reliability of the error detection</strong> feature?</li> </ul> <p>Apparently, the answer to the second question is something like '<em>some false negative allowed</em>' since the reliability of <em>any</em> 32 bits hash, relative to a 4Gb message, even in a moderately noisy channel, is not going to be virtually absolute.</p> <p>Assuming that I/O can be improved through multithreading, we may choose a hash that doesn't require a sequential scan of the complete message. Instead we can maybe work the file in parallel, hashing individual sections and either combining the hash values or appending them, to form a longer, more reliable error detection device.</p> <p>The next step could be to formalize this handling of files as ordered sections, and to transmit them as such (to be re-glued together at the recipient's end). This approach, along additional information about the way the files are produced (for ex. they may be exclusively modified by append, like log files), may even allow to limit the amount of hash calculation required. The added complexity of this approach needs to weighted against the desire to have zippy fast CRC calculation.</p> <p>Side note: Alder32 is <em>not</em> limited to message sizes below a particular threshold. It may just be a limit of the zlib API. (BTW, the reference I found about zlib.adler32 used a buffer, and well... this approach is to be avoided in the context of our huge messages, in favor of streamed processes: read a little from file, calculate, repeat..)</p>
4
2009-10-07T17:24:08Z
[ "python", "multithreading", "md5", "crc32", "hashlib" ]
the fastest way to create checksum for large files in python
1,532,720
<p>i need to transfer large files across network and need to create checksum for them on hourly basis. so the speed for generating checksum is critical for me.</p> <p>somehow i can't make zlib.crc32 and zlib.adler32 working with files larger than 4GB on Windows XP Pro 64bit machine. i suspect i've hit the 32bit limitation here? using hashlib.md5 i could get a result but the problem is the speed. it takes roughly about 5 minutes to generate an md5 for 4.8GB file. task manager shows that the process is using one core only.</p> <p>my questions are:</p> <ol> <li>is there a way to make crc works on large file? i prefer to use crc than md5</li> <li>if not then is there a way to speed up the md5.hexdigest()/md5.digest? or in this case any hashlib hexdigest/digest? maybe spliting it into multi thread process? how do i do that?</li> </ol> <p>PS: i'm working on somethimg similar like an "Asset Management" system, kind of like svn but the asset consist of large compressed image files. the files have tiny bit incremental changes. the hashing/checksum is needed for detecting changes and error detection.</p>
5
2009-10-07T16:28:08Z
1,533,255
<p>First, there is nothing inherent in any of the CRC algorithms that would prevent them working on an arbitrary length of data (however, a particular implementation might well impose a limit).</p> <p>However, in a file syncing application, that probably doesn't matter, as you may not want to hash the entire file when it gets large, just chunks anyway. If you hash the entire file, and the hashes at each end differ, you have to copy the entire file. If you hash fixed sized chunks, then you only have to copy the chunks whose hash has changed. If most of the changes to the files are localized (e.g. database) then this will likely require much less copying (and it' easier to spread per chunk calculations across multiple cores).</p> <p>As for the hash algorithm itself, the basic tradeoff is speed vs. lack of collisions (two different data chunks yielding the same hash). CRC-32 is fast, but with only 2^32 unique values, collisions may be seen. MD5 is much slower, but has 2^128 unique values, so collisions will almost never be seen (but are still theoretically possible). The larger hashes (SHA1, SHA256, ...) have even more unique values, but are slower still: I doubt you need them: you're worried about accidental collisions, unlike digital signature applications, where you're worried about deliberately (malicously) engineered collisions.</p> <p>It sounds like you're trying to do something very similar to what the rsync utility does. Can you just use rsync?</p>
2
2009-10-07T18:02:08Z
[ "python", "multithreading", "md5", "crc32", "hashlib" ]
the fastest way to create checksum for large files in python
1,532,720
<p>i need to transfer large files across network and need to create checksum for them on hourly basis. so the speed for generating checksum is critical for me.</p> <p>somehow i can't make zlib.crc32 and zlib.adler32 working with files larger than 4GB on Windows XP Pro 64bit machine. i suspect i've hit the 32bit limitation here? using hashlib.md5 i could get a result but the problem is the speed. it takes roughly about 5 minutes to generate an md5 for 4.8GB file. task manager shows that the process is using one core only.</p> <p>my questions are:</p> <ol> <li>is there a way to make crc works on large file? i prefer to use crc than md5</li> <li>if not then is there a way to speed up the md5.hexdigest()/md5.digest? or in this case any hashlib hexdigest/digest? maybe spliting it into multi thread process? how do i do that?</li> </ol> <p>PS: i'm working on somethimg similar like an "Asset Management" system, kind of like svn but the asset consist of large compressed image files. the files have tiny bit incremental changes. the hashing/checksum is needed for detecting changes and error detection.</p>
5
2009-10-07T16:28:08Z
1,540,992
<p>You might be hitting a size limit for files in XP. The 64-bit gives you more addressing space (removing the 2GB (or so) addressing space per application), but probably does nothing for the file size problem.</p>
1
2009-10-08T23:02:25Z
[ "python", "multithreading", "md5", "crc32", "hashlib" ]
Is there anyway to persuade python's getopt to handle optional parameters to options?
1,532,737
<p>According to the documentation on python's <code>getopt</code> (I think) the options fields should behave as the <code>getopt()</code> function. However I can't seem to enable optional parameters to my code:</p> <pre><code>#!/usr/bin/python import sys,getopt if __name__ == "__main__": try: opts, args = getopt.gnu_getopt(sys.argv[1:], "v::", ["verbose="]) except getopt.GetoptError, err: print str(err) sys.exit(1) for o,a in opts: if o in ("-v", "--verbose"): if a: verbose=int(a) else: verbose=1 print "verbosity is %d" % (verbose) </code></pre> <p>Results in:</p> <pre><code>$ ./testopt.py -v option -v requires argument $ ./testopt.py -v 1 verbosity is 1 </code></pre>
6
2009-10-07T16:30:58Z
1,532,761
<p><code>getopt</code> doesn't support optional parameters. in case of long option you could do:</p> <pre><code>$ ./testopt.py --verbose= </code></pre> <p>which will result in empty-string value.</p> <p>You could find <a href="http://code.google.com/p/argparse/"><code>argparse</code></a> module to be more flexible.</p>
7
2009-10-07T16:36:27Z
[ "python", "getopt", "getopt-long" ]
Is there anyway to persuade python's getopt to handle optional parameters to options?
1,532,737
<p>According to the documentation on python's <code>getopt</code> (I think) the options fields should behave as the <code>getopt()</code> function. However I can't seem to enable optional parameters to my code:</p> <pre><code>#!/usr/bin/python import sys,getopt if __name__ == "__main__": try: opts, args = getopt.gnu_getopt(sys.argv[1:], "v::", ["verbose="]) except getopt.GetoptError, err: print str(err) sys.exit(1) for o,a in opts: if o in ("-v", "--verbose"): if a: verbose=int(a) else: verbose=1 print "verbosity is %d" % (verbose) </code></pre> <p>Results in:</p> <pre><code>$ ./testopt.py -v option -v requires argument $ ./testopt.py -v 1 verbosity is 1 </code></pre>
6
2009-10-07T16:30:58Z
1,532,784
<p>Unfortunately, there is no way. From the <a href="http://docs.python.org/library/optparse.html" rel="nofollow">optparse docs</a>: </p> <blockquote> <p>Typically, a given option either takes an argument or it doesn’t. Lots of people want an “optional option arguments” feature, meaning that some options will take an argument if they see it, and won’t if they don’t. This is somewhat controversial, because it makes parsing ambiguous: if "-a" takes an optional argument and "-b" is another option entirely, how do we interpret "-ab"? Because of this ambiguity, optparse does not support this feature.</p> </blockquote> <p><strong>EDIT:</strong> oops, that is for the optparse module not the getopt module, but the reasoning why neither module has "optional option arguments" is the same for both.</p>
5
2009-10-07T16:40:54Z
[ "python", "getopt", "getopt-long" ]
Is there anyway to persuade python's getopt to handle optional parameters to options?
1,532,737
<p>According to the documentation on python's <code>getopt</code> (I think) the options fields should behave as the <code>getopt()</code> function. However I can't seem to enable optional parameters to my code:</p> <pre><code>#!/usr/bin/python import sys,getopt if __name__ == "__main__": try: opts, args = getopt.gnu_getopt(sys.argv[1:], "v::", ["verbose="]) except getopt.GetoptError, err: print str(err) sys.exit(1) for o,a in opts: if o in ("-v", "--verbose"): if a: verbose=int(a) else: verbose=1 print "verbosity is %d" % (verbose) </code></pre> <p>Results in:</p> <pre><code>$ ./testopt.py -v option -v requires argument $ ./testopt.py -v 1 verbosity is 1 </code></pre>
6
2009-10-07T16:30:58Z
1,533,040
<p>If you're using version 2.3 or later, you may want to try the <a href="http://docs.python.org/library/optparse.html" rel="nofollow">optparse</a> module instead, as it is "more convenient, flexible, and powerful ...", as well as newer. Alas, as Pynt answered, it doesn't seem possible to get exactly what you want.</p>
0
2009-10-07T17:25:16Z
[ "python", "getopt", "getopt-long" ]
Is there anyway to persuade python's getopt to handle optional parameters to options?
1,532,737
<p>According to the documentation on python's <code>getopt</code> (I think) the options fields should behave as the <code>getopt()</code> function. However I can't seem to enable optional parameters to my code:</p> <pre><code>#!/usr/bin/python import sys,getopt if __name__ == "__main__": try: opts, args = getopt.gnu_getopt(sys.argv[1:], "v::", ["verbose="]) except getopt.GetoptError, err: print str(err) sys.exit(1) for o,a in opts: if o in ("-v", "--verbose"): if a: verbose=int(a) else: verbose=1 print "verbosity is %d" % (verbose) </code></pre> <p>Results in:</p> <pre><code>$ ./testopt.py -v option -v requires argument $ ./testopt.py -v 1 verbosity is 1 </code></pre>
6
2009-10-07T16:30:58Z
8,528,365
<p>You can do an optional parameter with getopt like this:</p> <pre><code>import getopt import sys longopts, shortopts = getopt.getopt(sys.argv[1:], shortopts='', longopts=['env=']) argDict = dict(longopts) if argDict.has_key('--env') and argDict['--env'] == 'prod': print "production" else: print "sandbox" </code></pre> <p>Usage:</p> <pre><code>$ python scratch.py --env=prod production $ python scratch.py --env=dev sandbox $ python scratch.py sandbox </code></pre>
2
2011-12-16T00:16:04Z
[ "python", "getopt", "getopt-long" ]
Is there anyway to persuade python's getopt to handle optional parameters to options?
1,532,737
<p>According to the documentation on python's <code>getopt</code> (I think) the options fields should behave as the <code>getopt()</code> function. However I can't seem to enable optional parameters to my code:</p> <pre><code>#!/usr/bin/python import sys,getopt if __name__ == "__main__": try: opts, args = getopt.gnu_getopt(sys.argv[1:], "v::", ["verbose="]) except getopt.GetoptError, err: print str(err) sys.exit(1) for o,a in opts: if o in ("-v", "--verbose"): if a: verbose=int(a) else: verbose=1 print "verbosity is %d" % (verbose) </code></pre> <p>Results in:</p> <pre><code>$ ./testopt.py -v option -v requires argument $ ./testopt.py -v 1 verbosity is 1 </code></pre>
6
2009-10-07T16:30:58Z
27,824,336
<p>python's getopt should really support optional args, like GNU getopt by requiring '=' be used when specifying a parameter. Now you can simulate it quite easily though, with this constraint by implicitly changing --option to --option=</p> <p>I.E. you can specify that --option requires an argument, and then adjust --option to --option= as follows:</p> <pre><code>for i, opt in enumerate(sys.argv): if opt == '--option': sys.argv[i] = '--option=' elif opt == '--': break </code></pre>
0
2015-01-07T16:47:48Z
[ "python", "getopt", "getopt-long" ]
Good high-level python ftp/http lib?
1,532,760
<p>I'm looking for a good, high-level python ftp client/server library. I'm working on a project that has "evolved" a small http/ftp library on top of ftplib/urllib/urllib2 from what was originally one function, and almost none of it was designed to be built upon. So now it's time to refactor kind of seriously, and I'd like to just switch to a library. The thing I'd most like to not deal with is robust-retry logic (like, keep retrying 15 times, or keep retrying until 12pm).</p> <p>The problem that we've got right now is that we have about 10 separate <code>grab()</code> and <code>put()</code> functions. Aesthetically speaking, I'd rather have one of each with optional arguments along the lines of <code>try_until=datetime(2009, 10, 7, 19)</code> or <code>retrys=15</code>. We work with both binary and text data, so the functions would have to be reasonably smart about that. And we do way more grabbing than putting, so I can deal without the puts.</p> <p><a href="http://linux.duke.edu/projects/urlgrabber/" rel="nofollow">urlgrabber</a> looks like exactly what I want, but there doesn't seem to have been any development for the last couple years and I'm not sure how compatible it is with 2.6. Anybody got much experience with this? Or opinions?</p>
1
2009-10-07T16:36:15Z
1,533,029
<p>URLgrabber appears to be very mature, and since it's used by yum (and thus many Unix systems), I would expect it to be very stable. Python 2.x is largely backward compatible. You might encounter some warnings, but I would expect it to work suitably under Python 2.6.</p>
4
2009-10-07T17:22:31Z
[ "python", "http", "ftp" ]
Good high-level python ftp/http lib?
1,532,760
<p>I'm looking for a good, high-level python ftp client/server library. I'm working on a project that has "evolved" a small http/ftp library on top of ftplib/urllib/urllib2 from what was originally one function, and almost none of it was designed to be built upon. So now it's time to refactor kind of seriously, and I'd like to just switch to a library. The thing I'd most like to not deal with is robust-retry logic (like, keep retrying 15 times, or keep retrying until 12pm).</p> <p>The problem that we've got right now is that we have about 10 separate <code>grab()</code> and <code>put()</code> functions. Aesthetically speaking, I'd rather have one of each with optional arguments along the lines of <code>try_until=datetime(2009, 10, 7, 19)</code> or <code>retrys=15</code>. We work with both binary and text data, so the functions would have to be reasonably smart about that. And we do way more grabbing than putting, so I can deal without the puts.</p> <p><a href="http://linux.duke.edu/projects/urlgrabber/" rel="nofollow">urlgrabber</a> looks like exactly what I want, but there doesn't seem to have been any development for the last couple years and I'm not sure how compatible it is with 2.6. Anybody got much experience with this? Or opinions?</p>
1
2009-10-07T16:36:15Z
1,534,234
<p>Depending on the sort of application you are writing, you might want to consider <a href="http://twistedmatrix.com/" rel="nofollow">twisted python</a>, as it has http server and client code built in. However, it is a rather large departure from standard procedural python programming. </p> <p>The big advantage of twisted for you is that it can handle your client requests in the background, handles retries and is very scalable.</p> <p><em>Update</em></p> <p>For a quick script that interacts with servers, see this serverfault answer: <a href="http://serverfault.com/questions/66336/script-automation-login-enter-password-run-commands-save-output-locally">http://serverfault.com/questions/66336/script-automation-login-enter-password-run-commands-save-output-locally</a></p> <p>It recomends the tool <a href="http://expect.nist.gov/" rel="nofollow">expect</a></p> <blockquote> <p>Expect is a tool for automating interactive applications such as telnet, ftp, passwd, fsck, rlogin, tip, etc. Expect really makes this stuff trivial. Expect is also useful for testing these same applications. And by adding Tk, you can also wrap interactive applications in X11 GUIs.</p> <p>Expect can make easy all sorts of tasks that are prohibitively difficult with anything else. You will find that Expect is an absolutely invaluable tool - using it, you will be able to automate tasks that you've never even thought of before - and you'll be able to do this automation quickly and easily.</p> </blockquote> <p>Sounds good to me!</p>
0
2009-10-07T21:14:59Z
[ "python", "http", "ftp" ]
How to read lines from a file into a multidimensional array (or an array of lists) in python
1,532,810
<p>I have a file with a format similar to this:</p> <pre><code>a,3,4,2,1 3,2,1,a,2 </code></pre> <p>I want to read the file and create an array of lists</p> <p>in a way that:</p> <pre><code>array[0] = ['a','3','4','2','1'] array[1] = ['3','2','1','a','2'] </code></pre> <p>How can I do that?</p> <p>So far I am stuck with:</p> <pre><code>f = open('./urls-eu.csv', 'r') for line in f: arr = line.split(',') print arr </code></pre> <p>I am really new to python.</p>
3
2009-10-07T16:46:05Z
1,532,816
<p>you're almost there, you just need to do:</p> <pre><code>arr = [line.split(',') for line in open('./urls-eu.csv')] </code></pre> <p>it iteratively process file line by line, splits each line by comma and accumulates resulting lists into a list of lists. you can drop opening mode (<code>'r'</code>) since it's a default one.</p>
7
2009-10-07T16:47:42Z
[ "python", "list", "multidimensional-array" ]
How to read lines from a file into a multidimensional array (or an array of lists) in python
1,532,810
<p>I have a file with a format similar to this:</p> <pre><code>a,3,4,2,1 3,2,1,a,2 </code></pre> <p>I want to read the file and create an array of lists</p> <p>in a way that:</p> <pre><code>array[0] = ['a','3','4','2','1'] array[1] = ['3','2','1','a','2'] </code></pre> <p>How can I do that?</p> <p>So far I am stuck with:</p> <pre><code>f = open('./urls-eu.csv', 'r') for line in f: arr = line.split(',') print arr </code></pre> <p>I am really new to python.</p>
3
2009-10-07T16:46:05Z
1,532,899
<p>Batteries included:</p> <pre><code>&gt;&gt;&gt; import csv &gt;&gt;&gt; array = list( csv.reader( open( r'./urls-eu.csv' ) ) ) &gt;&gt;&gt; array[0] ['a', '3', '4', '2', '1'] &gt;&gt;&gt; array[1] ['3', '2', '1', 'a', '2'] </code></pre>
16
2009-10-07T17:00:16Z
[ "python", "list", "multidimensional-array" ]
Open IE Browser Window
1,532,884
<p>The <a href="http://docs.python.org/library/webbrowser.html"><code>webbrowser</code> library</a> provides a convenient way to launch a URL with a browser window through the <code>webbrowser.open()</code> method. Numerous browser types are available, but there does not appear to be an explicit way to launch Internet Explorer when running python on windows.</p> <p><code>WindowsDefault</code> only works if Internet Explorer is set as the default browser, which is not an assumption I can make.</p> <p>Is there a way to explicitly launch a URL into Internet Explorer without reverting to windows API calls? </p>
8
2009-10-07T16:58:10Z
1,532,945
<p>The simplest way:</p> <pre><code>import subprocess subprocess.Popen(r'"C:\Program Files\Internet Explorer\IEXPLORE.EXE" www.google.com') </code></pre>
2
2009-10-07T17:08:17Z
[ "python", "internet-explorer", "browser" ]
Open IE Browser Window
1,532,884
<p>The <a href="http://docs.python.org/library/webbrowser.html"><code>webbrowser</code> library</a> provides a convenient way to launch a URL with a browser window through the <code>webbrowser.open()</code> method. Numerous browser types are available, but there does not appear to be an explicit way to launch Internet Explorer when running python on windows.</p> <p><code>WindowsDefault</code> only works if Internet Explorer is set as the default browser, which is not an assumption I can make.</p> <p>Is there a way to explicitly launch a URL into Internet Explorer without reverting to windows API calls? </p>
8
2009-10-07T16:58:10Z
1,532,983
<p>You can always do something like</p> <pre><code>subprocess.Popen('"C:\\Program Files\\Internet Explorer\\iexplore.exe" http://www.example.com') </code></pre>
3
2009-10-07T17:13:09Z
[ "python", "internet-explorer", "browser" ]
Open IE Browser Window
1,532,884
<p>The <a href="http://docs.python.org/library/webbrowser.html"><code>webbrowser</code> library</a> provides a convenient way to launch a URL with a browser window through the <code>webbrowser.open()</code> method. Numerous browser types are available, but there does not appear to be an explicit way to launch Internet Explorer when running python on windows.</p> <p><code>WindowsDefault</code> only works if Internet Explorer is set as the default browser, which is not an assumption I can make.</p> <p>Is there a way to explicitly launch a URL into Internet Explorer without reverting to windows API calls? </p>
8
2009-10-07T16:58:10Z
1,532,990
<pre><code>&gt;&gt;&gt; ie = webbrowser.get('c:\\program files\\internet explorer\\iexplore.exe') &gt;&gt;&gt; ie.open('http://google.com') True </code></pre>
14
2009-10-07T17:14:03Z
[ "python", "internet-explorer", "browser" ]
Open IE Browser Window
1,532,884
<p>The <a href="http://docs.python.org/library/webbrowser.html"><code>webbrowser</code> library</a> provides a convenient way to launch a URL with a browser window through the <code>webbrowser.open()</code> method. Numerous browser types are available, but there does not appear to be an explicit way to launch Internet Explorer when running python on windows.</p> <p><code>WindowsDefault</code> only works if Internet Explorer is set as the default browser, which is not an assumption I can make.</p> <p>Is there a way to explicitly launch a URL into Internet Explorer without reverting to windows API calls? </p>
8
2009-10-07T16:58:10Z
1,533,016
<pre><code>iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"), "Internet Explorer\\IEXPLORE.EXE") ie = webbrowser.BackgroundBrowser(iexplore) ie.open(...) </code></pre> <p>This is what the <code>webrowser</code> module uses internally.</p>
6
2009-10-07T17:19:34Z
[ "python", "internet-explorer", "browser" ]
Open IE Browser Window
1,532,884
<p>The <a href="http://docs.python.org/library/webbrowser.html"><code>webbrowser</code> library</a> provides a convenient way to launch a URL with a browser window through the <code>webbrowser.open()</code> method. Numerous browser types are available, but there does not appear to be an explicit way to launch Internet Explorer when running python on windows.</p> <p><code>WindowsDefault</code> only works if Internet Explorer is set as the default browser, which is not an assumption I can make.</p> <p>Is there a way to explicitly launch a URL into Internet Explorer without reverting to windows API calls? </p>
8
2009-10-07T16:58:10Z
1,533,021
<p>If you plan to use the script in more than your machine, keep in mind that not everyone has a English version of Windows</p> <pre><code>import subprocess import os subprocess.Popen(r'"' + os.environ["PROGRAMFILES"] + '\Internet Explorer\IEXPLORE.EXE" www.google.com') </code></pre>
0
2009-10-07T17:20:29Z
[ "python", "internet-explorer", "browser" ]
Open IE Browser Window
1,532,884
<p>The <a href="http://docs.python.org/library/webbrowser.html"><code>webbrowser</code> library</a> provides a convenient way to launch a URL with a browser window through the <code>webbrowser.open()</code> method. Numerous browser types are available, but there does not appear to be an explicit way to launch Internet Explorer when running python on windows.</p> <p><code>WindowsDefault</code> only works if Internet Explorer is set as the default browser, which is not an assumption I can make.</p> <p>Is there a way to explicitly launch a URL into Internet Explorer without reverting to windows API calls? </p>
8
2009-10-07T16:58:10Z
11,976,103
<p>More elegant code:</p> <pre><code>import webbrowser ie = webbrowser.get(webbrowser.iexplore) ie.open('google.com') </code></pre>
15
2012-08-15T19:43:36Z
[ "python", "internet-explorer", "browser" ]
Can a WIN32 program authenticate into Django authentication system, using MYSQL?
1,533,259
<p>I have a web service with Django Framework.<br /> My friend's project is a WIN32 program and also a MS-sql server.</p> <p>The Win32 program currently has a login system that talks to a MS-sql for authentication.</p> <p>However, we would like to INTEGRATE this login system as one.</p> <p>Please answer the 2 things:</p> <ol> <li>I want scrap the MS-SQL to use only the Django authentication system on the linux server. Can the WIN32 client talk to Django using a Django API (login)?</li> <li>If not, what is the best way of combining the authentication?</li> </ol>
0
2009-10-07T02:00:40Z
1,581,622
<p>The Win32 client can act like a web client to pass the user's credentials to the server. You will want to store the session cookie you get once you are authenticated and use that cookie in all following requests</p>
1
2009-10-17T07:06:39Z
[ "python", "mysql", "windows", "django" ]
Turbogears: Can not start paster after updateing to mac osx 10.6
1,533,388
<p>After updateing to mac osx 10.6 I had to switch back to python 2.5 in order to make virtual env work. But still I can not start my turbogears project. Paster is giving this :</p> <pre><code>Traceback (most recent call last): File ".../tg2env/bin/paster", line 5, in &lt;module&gt; from pkg_resources import load_entry_point File ".../tg2env/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 657, in &lt;module&gt; File ".../tg2env/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 660, in Environment File ".../tg2env/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 55, in get_supported_platform File ".../tg2env/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 186, in get_build_platform File ".../tg2env/lib/python2.5/distutils/__init__.py", line 14, in &lt;module&gt; exec open(os.path.join(distutils_path, '__init__.py')).read() IOError: [Errno 2] No such file or directory: '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/distutils/__init__.py' </code></pre> <p>Any ideas? Thanks.</p>
0
2009-10-07T18:34:31Z
1,534,097
<p>Why did you need to switch back to 2.5 to make virtualenv work? I have upgraded to 10.6 and am happily using virtualenv in Python 2.6.</p>
0
2009-10-07T20:45:43Z
[ "python", "osx", "turbogears2" ]
Turbogears: Can not start paster after updateing to mac osx 10.6
1,533,388
<p>After updateing to mac osx 10.6 I had to switch back to python 2.5 in order to make virtual env work. But still I can not start my turbogears project. Paster is giving this :</p> <pre><code>Traceback (most recent call last): File ".../tg2env/bin/paster", line 5, in &lt;module&gt; from pkg_resources import load_entry_point File ".../tg2env/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 657, in &lt;module&gt; File ".../tg2env/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 660, in Environment File ".../tg2env/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 55, in get_supported_platform File ".../tg2env/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 186, in get_build_platform File ".../tg2env/lib/python2.5/distutils/__init__.py", line 14, in &lt;module&gt; exec open(os.path.join(distutils_path, '__init__.py')).read() IOError: [Errno 2] No such file or directory: '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/distutils/__init__.py' </code></pre> <p>Any ideas? Thanks.</p>
0
2009-10-07T18:34:31Z
1,534,121
<p>Probably eggs are installed for 2.6 distro. Please run in your terminal:</p> <pre><code>defaults write com.apple.versioner.python Version 2.5 export VERSIONER_PYTHON_VERSION=2.5 sudo easy_install virtualenv </code></pre> <p>Check out the second line, it should change python version for current terminal session.</p> <pre><code>dgl@dgl:~/ &gt; python Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51) ... dgl@dgl:~/ &gt; export VERSIONER_PYTHON_VERSION=2.5 dgl@dgl:~/ &gt; python Python 2.5.4 (r254:67916, Jul 7 2009, 23:51:24) ... </code></pre>
0
2009-10-07T20:51:34Z
[ "python", "osx", "turbogears2" ]
Turbogears: Can not start paster after updateing to mac osx 10.6
1,533,388
<p>After updateing to mac osx 10.6 I had to switch back to python 2.5 in order to make virtual env work. But still I can not start my turbogears project. Paster is giving this :</p> <pre><code>Traceback (most recent call last): File ".../tg2env/bin/paster", line 5, in &lt;module&gt; from pkg_resources import load_entry_point File ".../tg2env/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 657, in &lt;module&gt; File ".../tg2env/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 660, in Environment File ".../tg2env/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 55, in get_supported_platform File ".../tg2env/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 186, in get_build_platform File ".../tg2env/lib/python2.5/distutils/__init__.py", line 14, in &lt;module&gt; exec open(os.path.join(distutils_path, '__init__.py')).read() IOError: [Errno 2] No such file or directory: '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/distutils/__init__.py' </code></pre> <p>Any ideas? Thanks.</p>
0
2009-10-07T18:34:31Z
1,534,863
<p>As you've seen, in Snow Leopard 10.6, Apple supplies both a Python 2.6.2 (the default for <code>/usr/bin/python</code>) and a legacy Python 2.5.4 (<code>/usr/bin/python2.5</code>). The heart of both live in the <code>/System/Library/Frameworks/Python.framework</code>. In general, everything under <code>/System</code> is supplied and managed by Apple; it should not be modified by anyone else.</p> <p>If that message is to be believed, your 10.6 installation is faulty.</p> <pre><code>$ cd /System/Library/Frameworks/Python.framework/Versions $ ls -l total 8 drwxr-xr-x 5 root wheel 272 Sep 5 10:18 2.3/ drwxr-xr-x 9 root wheel 408 Sep 5 10:43 2.5/ drwxr-xr-x 9 root wheel 408 Sep 5 10:43 2.6/ lrwxr-xr-x 1 root wheel 3 Sep 5 10:18 Current@ -&gt; 2.6 $ ls -l 2.5/lib/python2.5/distutils/__init__.py -rw-r--r-- 1 root wheel 635 Jul 7 23:55 2.5/lib/python2.5/distutils/__init__.py $ /usr/bin/python2.5 Python 2.5.4 (r254:67916, Jul 7 2009, 23:51:24) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import distutils &gt;&gt;&gt; </code></pre> <p>Check to see that file exists and with the correct permissions. If not, you should figure out what else is wrong with your <code>/System</code> and consider restoring from a backup or just reinstalling Snow Leopard.</p>
0
2009-10-07T23:53:04Z
[ "python", "osx", "turbogears2" ]
Access is Denied loading a dll with ctypes on Vista
1,533,466
<p>I'm having issues with using ctypes. I'm trying to get the following project running on Vista.</p> <p><a href="http://sourceforge.net/projects/fractalfrost/" rel="nofollow">http://sourceforge.net/projects/fractalfrost/</a></p> <p>I've used the project before on Vista and had no problems. I don't see any think changed in svn that cause this I'm thinking it's something local to this machine. In fact I'm not able to load dll's with ctypes at all.</p> <pre><code>Bobby@Teresa-PC ~/fr0st-exe/fr0st/pyflam3/win32_dlls $ ls Flam4CUDA_LIB.dll cudart.dll glew32.dll libflam3.dll pthreadVC2.dll Bobby@Teresa-PC ~/fr0st-exe/fr0st/pyflam3/win32_dlls $ python Python 2.6.3 (r263rc1:75186, Oct 2 2009, 20:40:30) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from ctypes import * &gt;&gt;&gt; flam3_dll = CDLL('libflam3.dll') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "c:\Python26\lib\ctypes\__init__.py", line 353, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 5] Access is denied &gt;&gt;&gt; flam3_dll = CDLL('.\\libflam3.dll') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "c:\Python26\lib\ctypes\__init__.py", line 353, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 5] Access is denied &gt;&gt;&gt; import os &gt;&gt;&gt; flam3_dll = CDLL(os.path.abspath('libflam3.dll')) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "c:\Python26\lib\ctypes\__init__.py", line 353, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 5] Access is denied &gt;&gt;&gt; </code></pre> <p>Any ideas what would be causing this and better yet someway around it?</p>
1
2009-10-07T18:47:17Z
1,533,475
<p>I know it sounds like a silly thing, but since you didn't explicitly mention it:</p> <p>Did you check the permissions on the file you're trying to access? Perhaps you, you know, don't have read or execute access to the file.</p>
2
2009-10-07T18:50:32Z
[ "python", "windows-vista", "ctypes" ]
Python: how to show results on a web page?
1,534,070
<p>Most likely it's a dumb question for those who knows the answer, but I'm a beginner, and here it goes:</p> <p>I have a Python script which I run in a command-line with some parameter, and it prints me some results. Let's say results are some HTML code.</p> <p>I never done any Python programming for web, and couldn't figure it out... I need to have a page (OK, I know how to upload files to a server, Apache is running, Python is installed on the server...) with an edit field, which will accept that parameter, and Submit button, and I need it to "print" the results on a web page after the user submitted a proper parameter, or show any output that in a command-line situation are printed.</p> <p>I've read Dive Into Python's chapters about "HTML Processing" and "HTTP Web Services", but they do not describe what I'm looking for.</p> <p>If the answer isn't short, I would very much appreciate links to the more relevant stuff to read or maybe the key words to google for it.</p>
6
2009-10-07T20:40:37Z
1,534,088
<p>Sorry to say it, but HTTP web services <em>are</em> what you're looking for. Think of it this way - you put a form on a webpage, and a submit button. That goes to a web service that accepts the <em>request</em> and it chews on that request, and returns a <em>response</em> - which is a page of html. You never have to actually <em>save</em> the html, it is always dynamically generated, but it's a valid page of html nonetheless.</p> <p>Look at django <a href="http://www.djangoproject.com/" rel="nofollow">http://www.djangoproject.com/</a> for a high quality python based web service toolkit.</p> <p>The first step to understanding the request / response idiom is to think of the request as a specifically-formatted (defined by CGI - that is, it's a GET or POST HTML action) set of command line parameters, and the response as specifically-formatted output (HTML) that gets sent, not to stdout, but across "the wire" to some browser. Sending the request reaches out across the wire and executes the script with some parameters, and you recieve back the output - your formatted HTML page.</p>
1
2009-10-07T20:43:55Z
[ "python" ]
Python: how to show results on a web page?
1,534,070
<p>Most likely it's a dumb question for those who knows the answer, but I'm a beginner, and here it goes:</p> <p>I have a Python script which I run in a command-line with some parameter, and it prints me some results. Let's say results are some HTML code.</p> <p>I never done any Python programming for web, and couldn't figure it out... I need to have a page (OK, I know how to upload files to a server, Apache is running, Python is installed on the server...) with an edit field, which will accept that parameter, and Submit button, and I need it to "print" the results on a web page after the user submitted a proper parameter, or show any output that in a command-line situation are printed.</p> <p>I've read Dive Into Python's chapters about "HTML Processing" and "HTTP Web Services", but they do not describe what I'm looking for.</p> <p>If the answer isn't short, I would very much appreciate links to the more relevant stuff to read or maybe the key words to google for it.</p>
6
2009-10-07T20:40:37Z
1,534,091
<p>For such a simple task, you probably don't need more than CGI. Luckily Python has a built-in <code>cgi</code> module which should do what you want.</p> <p>Or you could look into some of the minimal web frameworks, such as <a href="http://webpy.org/" rel="nofollow">web.py</a>.</p>
4
2009-10-07T20:44:09Z
[ "python" ]
Python: how to show results on a web page?
1,534,070
<p>Most likely it's a dumb question for those who knows the answer, but I'm a beginner, and here it goes:</p> <p>I have a Python script which I run in a command-line with some parameter, and it prints me some results. Let's say results are some HTML code.</p> <p>I never done any Python programming for web, and couldn't figure it out... I need to have a page (OK, I know how to upload files to a server, Apache is running, Python is installed on the server...) with an edit field, which will accept that parameter, and Submit button, and I need it to "print" the results on a web page after the user submitted a proper parameter, or show any output that in a command-line situation are printed.</p> <p>I've read Dive Into Python's chapters about "HTML Processing" and "HTTP Web Services", but they do not describe what I'm looking for.</p> <p>If the answer isn't short, I would very much appreciate links to the more relevant stuff to read or maybe the key words to google for it.</p>
6
2009-10-07T20:40:37Z
1,534,133
<p>Sounds like you just need to enable <a href="http://www.modpython.org/" rel="nofollow">CGI on apache</a>, which pretty much will redirect your output to the webserver output.</p> <p>Python does have <a href="http://docs.python.org/library/cgi.html" rel="nofollow">CGI library</a> you may take a look at it.</p> <p>Here's an <a href="http://www.python.org/doc/essays/ppt/sd99east/index.htm" rel="nofollow">essay by Guido</a> ( a bit dated ) </p> <p>And an <a href="http://www.cs.virginia.edu/~lab2q/" rel="nofollow">interactive instruction</a> that looks promising.</p> <p>p.s. </p> <p>Perhaps you may also want to see Google's offering for this <a href="http://code.google.com/appengine/docs/python/gettingstarted/" rel="nofollow">Google app engine</a> ( it may not be what you want though ) </p>
2
2009-10-07T20:55:03Z
[ "python" ]
Python: how to show results on a web page?
1,534,070
<p>Most likely it's a dumb question for those who knows the answer, but I'm a beginner, and here it goes:</p> <p>I have a Python script which I run in a command-line with some parameter, and it prints me some results. Let's say results are some HTML code.</p> <p>I never done any Python programming for web, and couldn't figure it out... I need to have a page (OK, I know how to upload files to a server, Apache is running, Python is installed on the server...) with an edit field, which will accept that parameter, and Submit button, and I need it to "print" the results on a web page after the user submitted a proper parameter, or show any output that in a command-line situation are printed.</p> <p>I've read Dive Into Python's chapters about "HTML Processing" and "HTTP Web Services", but they do not describe what I'm looking for.</p> <p>If the answer isn't short, I would very much appreciate links to the more relevant stuff to read or maybe the key words to google for it.</p>
6
2009-10-07T20:40:37Z
1,534,137
<p>I agree completely with Matt -- Django is what you want. Django provides a complete solution, and really wonderful documentation that will help you get something going. If your application grows and becomes more complicated, Django can still work; Django works even for very large and very complicated web sites.</p> <p>Take a look at the free book, <a href="http://www.djangobook.com/" rel="nofollow">The Django Book</a>.</p> <p>Another plus with Django: if you do your web app in Django, you can port it to Google App Engine.</p>
0
2009-10-07T20:55:42Z
[ "python" ]
Python: how to show results on a web page?
1,534,070
<p>Most likely it's a dumb question for those who knows the answer, but I'm a beginner, and here it goes:</p> <p>I have a Python script which I run in a command-line with some parameter, and it prints me some results. Let's say results are some HTML code.</p> <p>I never done any Python programming for web, and couldn't figure it out... I need to have a page (OK, I know how to upload files to a server, Apache is running, Python is installed on the server...) with an edit field, which will accept that parameter, and Submit button, and I need it to "print" the results on a web page after the user submitted a proper parameter, or show any output that in a command-line situation are printed.</p> <p>I've read Dive Into Python's chapters about "HTML Processing" and "HTTP Web Services", but they do not describe what I'm looking for.</p> <p>If the answer isn't short, I would very much appreciate links to the more relevant stuff to read or maybe the key words to google for it.</p>
6
2009-10-07T20:40:37Z
1,534,138
<p>I've not read DIVE INTO PYTHON, so maybe what I'm saying is redundant. As Daniel said, CGI may work for you. These days this would only the case for simple stuff with a fairly low number of hits. The Python CGI module is documented <a href="http://docs.python.org/library/cgi.html" rel="nofollow">here</a>. I have always used that module for form processing and just done prints for the output. As best as I've been able to figure out, that's the usual way of doing things, but I have not done a lot of CGI with Python.</p> <p>You don't say what you're doing, so I'll state what may be obvious: Make sure you're telling the server that you're outputting a web page with your very first output being the content type followed by a blank line. Typically this is done with:</p> <pre><code>print "Content-Type: text/html" print </code></pre> <p>(For Python 2, for 3 you'll need to make your prints into function calls.) After this, you print your html, header, body, etc. tags and the actual content.</p>
0
2009-10-07T20:55:58Z
[ "python" ]
Python: how to show results on a web page?
1,534,070
<p>Most likely it's a dumb question for those who knows the answer, but I'm a beginner, and here it goes:</p> <p>I have a Python script which I run in a command-line with some parameter, and it prints me some results. Let's say results are some HTML code.</p> <p>I never done any Python programming for web, and couldn't figure it out... I need to have a page (OK, I know how to upload files to a server, Apache is running, Python is installed on the server...) with an edit field, which will accept that parameter, and Submit button, and I need it to "print" the results on a web page after the user submitted a proper parameter, or show any output that in a command-line situation are printed.</p> <p>I've read Dive Into Python's chapters about "HTML Processing" and "HTTP Web Services", but they do not describe what I'm looking for.</p> <p>If the answer isn't short, I would very much appreciate links to the more relevant stuff to read or maybe the key words to google for it.</p>
6
2009-10-07T20:40:37Z
1,534,192
<p>I think Django is overkill. If you are wanting to learn about this stuff, start from something very simple like this:</p> <p><a href="http://www.islascruz.org/html/index.php/blog/show/Python:-Simple-HTTP-Server-on-python..html" rel="nofollow">http://www.islascruz.org/html/index.php/blog/show/Python:-Simple-HTTP-Server-on-python..html</a></p> <p>You can put your code where the do_GET is.</p>
0
2009-10-07T21:06:48Z
[ "python" ]
Python: how to show results on a web page?
1,534,070
<p>Most likely it's a dumb question for those who knows the answer, but I'm a beginner, and here it goes:</p> <p>I have a Python script which I run in a command-line with some parameter, and it prints me some results. Let's say results are some HTML code.</p> <p>I never done any Python programming for web, and couldn't figure it out... I need to have a page (OK, I know how to upload files to a server, Apache is running, Python is installed on the server...) with an edit field, which will accept that parameter, and Submit button, and I need it to "print" the results on a web page after the user submitted a proper parameter, or show any output that in a command-line situation are printed.</p> <p>I've read Dive Into Python's chapters about "HTML Processing" and "HTTP Web Services", but they do not describe what I'm looking for.</p> <p>If the answer isn't short, I would very much appreciate links to the more relevant stuff to read or maybe the key words to google for it.</p>
6
2009-10-07T20:40:37Z
1,536,548
<p>A <em>current</em> method of creating simple (one-of )<code>Python</code> web page server is the <a href="http://docs.python.org/library/wsgiref.html#module-wsgiref" rel="nofollow"><code>wsgiref</code> module</a>.</p> <blockquote> <p>wsgiref is a reference implementation of the WSGI specification that can be used to add WSGI support to a web server or framework.</p> </blockquote> <p>See some <a href="http://stackoverflow.com/search?q=%5Bpython%5D+wsgiref">SO qusetions</a> (<a href="http://stackoverflow.com/search?q=%5Bpython%5D+wsgiref">http://stackoverflow.com/search?q=%5Bpython%5D+wsgiref</a>) for some code examples and more suggestions.</p> <p>The <a href="http://docs.python.org/library/wsgiref.html#examples" rel="nofollow"><code>wsgiref</code> example</a> is a good place to start:</p> <pre><code>from wsgiref.simple_server import make_server def hello_world_app(environ, start_response): status = '200 OK' # HTTP Status headers = [('Content-type', 'text/plain')] # HTTP Headers start_response(status, headers) # The returned object is going to be printed return ["Hello World"] httpd = make_server('', 8000, hello_world_app) print "Serving on port 8000..." # Serve until process is killed httpd.serve_forever() </code></pre>
0
2009-10-08T08:57:43Z
[ "python" ]
Python: how to show results on a web page?
1,534,070
<p>Most likely it's a dumb question for those who knows the answer, but I'm a beginner, and here it goes:</p> <p>I have a Python script which I run in a command-line with some parameter, and it prints me some results. Let's say results are some HTML code.</p> <p>I never done any Python programming for web, and couldn't figure it out... I need to have a page (OK, I know how to upload files to a server, Apache is running, Python is installed on the server...) with an edit field, which will accept that parameter, and Submit button, and I need it to "print" the results on a web page after the user submitted a proper parameter, or show any output that in a command-line situation are printed.</p> <p>I've read Dive Into Python's chapters about "HTML Processing" and "HTTP Web Services", but they do not describe what I'm looking for.</p> <p>If the answer isn't short, I would very much appreciate links to the more relevant stuff to read or maybe the key words to google for it.</p>
6
2009-10-07T20:40:37Z
1,537,103
<p>Whose web server? If it is a web server provided by a web hosting company or someone else and you don't have control over it, you need to ascertain in what way they support the use of Python for writing web applications. It isn't enough to know just that they have Python available.</p> <p>As pointed out by others, is likely that at least CGI scripts which use Python will be supported. CGI however is not really practical for running large Python web frameworks such as Django.</p> <p>It is possible though that the web server might also support FASTCGI. If that is the case it becomes possible to use such larger Python web frameworks as FASTCGI uses persistent processes where as CGI creates a process for each request, where the overhead of large Python web frameworks generally makes the use of CGI impractical as a result.</p> <p>If the Apache server is controlled by others using a standalone Python web server such as wsgiref and proxying to it from Apache isn't going to be doable either as you can't setup Apache to do it.</p> <p>So, find out how use of Python for web applications is supported and work out whether you are just a user of the Apache instance, or whether you have some measure of control of changing its global configuration files and restarting it. This will dictate what you can do and use.</p>
2
2009-10-08T11:04:21Z
[ "python" ]
Use different Python version with virtualenv
1,534,210
<p>I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python?</p> <p>I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary file? Or do I have to change something in respect to the libraries?</p>
501
2009-10-07T21:11:22Z
1,534,343
<p>Just use the -p flag when creating your virtualenv instance to specify the Python executable you want to use, e.g.:</p> <pre><code>virtualenv -p /usr/bin/python2.6 &lt;path/to/new/virtualenv/&gt; </code></pre>
753
2009-10-07T21:33:12Z
[ "python", "virtualenv", "virtualenvwrapper" ]
Use different Python version with virtualenv
1,534,210
<p>I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python?</p> <p>I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary file? Or do I have to change something in respect to the libraries?</p>
501
2009-10-07T21:11:22Z
1,674,444
<pre><code>virtualenv --python=/usr/bin/python2.6 &lt;path/to/myvirtualenv&gt; </code></pre>
74
2009-11-04T15:15:15Z
[ "python", "virtualenv", "virtualenvwrapper" ]
Use different Python version with virtualenv
1,534,210
<p>I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python?</p> <p>I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary file? Or do I have to change something in respect to the libraries?</p>
501
2009-10-07T21:11:22Z
6,892,302
<p>Under Windows for me this works:</p> <pre><code>virtualenv --python=c:\Python25\python.exe envname </code></pre> <p>without the <code>python.exe</code> I got <code>WindowsError: [Error 5] Access is denied</code> I have Python2.7.1 installed with virtualenv 1.6.1, and I wanted python 2.5.2.</p>
49
2011-07-31T21:04:32Z
[ "python", "virtualenv", "virtualenvwrapper" ]
Use different Python version with virtualenv
1,534,210
<p>I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python?</p> <p>I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary file? Or do I have to change something in respect to the libraries?</p>
501
2009-10-07T21:11:22Z
11,301,911
<p>These are steps when you are on shared hosting environment and need to install &amp; complie Python from source and then create venv from your Python version. For Python 2.7.9 you would do something along these lines:</p> <pre><code>mkdir ~/src wget http://www.python.org/ftp/python/2.7.9/Python-2.7.9.tgz tar -zxvf Python-2.7.9.tgz cd Python-2.7.9 mkdir ~/.localpython ./configure --prefix=$HOME/.localpython make make install </code></pre> <p><strong>virtual env</strong></p> <pre><code>cd ~/src wget https://pypi.python.org/packages/5c/79/5dae7494b9f5ed061cff9a8ab8d6e1f02db352f3facf907d9eb614fb80e9/virtualenv-15.0.2.tar.gz#md5=0ed59863994daf1292827ffdbba80a63 tar -zxvf virtualenv-15.0.2.tar.gz cd virtualenv-15.0.2/ ~/.localpython/bin/python setup.py install virtualenv ve -p $HOME/.localpython/bin/python2.7 source ve/bin/activate </code></pre> <p>Naturally this can be applicable to any situation where you want to replicate the exact environment you work and deploy on. </p>
119
2012-07-02T22:17:14Z
[ "python", "virtualenv", "virtualenvwrapper" ]
Use different Python version with virtualenv
1,534,210
<p>I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python?</p> <p>I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary file? Or do I have to change something in respect to the libraries?</p>
501
2009-10-07T21:11:22Z
20,834,097
<p>Suppose you currently have python 2.7 installed in your virtualenv. But want to make use of python3.2. You would have to update this with:</p> <pre><code>virtualenv --python=/usr/bin/python3.2 name_of_your_virtualenv </code></pre> <p>Then activate your virtualenv and type <code>python --version</code> in shell to check whether your version is now updated.</p>
9
2013-12-30T05:51:49Z
[ "python", "virtualenv", "virtualenvwrapper" ]
Use different Python version with virtualenv
1,534,210
<p>I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python?</p> <p>I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary file? Or do I have to change something in respect to the libraries?</p>
501
2009-10-07T21:11:22Z
27,972,633
<p>Mac OSX 10.6.8 (Snow Leopard):</p> <p>1) When you do <code>pip install virtualenv</code>, the pip command is associated with one of your python versions, and <code>virtualenv</code> gets installed into that version of python (you can do</p> <pre><code> $ which pip </code></pre> <p>to see what version of python that is). By default, that will be the version of python that is used for any new environment you create. However, you can specify any version of python installed on your computer to use inside a new environment with the <code>-p flag</code>: </p> <pre><code>$ virtualenv -p python3.2 my_env Running virtualenv with interpreter /usr/local/bin/python3.2 New python executable in my_env/bin/python Installing setuptools, pip...done. </code></pre> <blockquote> <p><code>virtualenv my_env</code> will create a folder in the current directory which will contain the Python executable files, and a copy of the pip [command] which you can use to install other packages.</p> </blockquote> <p><a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/">http://docs.python-guide.org/en/latest/dev/virtualenvs/</a></p> <p><code>virtualenv</code> just copies python from a location on your computer into the newly created my_env/bin/ directory. </p> <p>2) The system python is in <code>/usr/bin</code>, while the various python versions I installed were, by default, installed into:</p> <pre><code> /usr/local/bin </code></pre> <p>3) The various pythons I installed have names like <code>python2.7</code> or <code>python3.2</code>, and I can use those names rather than full paths. </p> <h3>========VIRTUALENVWRAPPER=========</h3> <p>1) I had some problems getting virtualenvwrapper to work. This is what I ended up putting in <code>~/.bash_profile</code>: </p> <pre><code>export WORKON_HOME=$HOME/.virtualenvs export PROJECT_HOME=$HOME/django_projects #Not very important -- mkproject command uses this #Added the following based on: #http://stackoverflow.com/questions/19665327/virtualenvwrapper-installation-snow-leopard-python export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python2.7 #source /usr/local/bin/virtualenvwrapper.sh source /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh </code></pre> <p>2) The <code>-p option</code> works differently with virtualenvwrapper: I have to specify the full path to the python interpreter to be used in the new environment(when I do not want to use the default python version): </p> <pre><code>$ mkvirtualenv -p /usr/local/bin/python3.2 my_env Running virtualenv with interpreter /usr/local/bin/python3 New python executable in my_env/bin/python Installing setuptools, pip...done. Usage: source deactivate removes the 'bin' directory of the environment activated with 'source activate' from PATH. </code></pre> <p>Unlike virtualenv, virtualenvwrapper will create the environment at the location specified by the $WORKON_HOME environment variable. That keeps all your environments in one place.</p>
16
2015-01-15T20:43:25Z
[ "python", "virtualenv", "virtualenvwrapper" ]
Use different Python version with virtualenv
1,534,210
<p>I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python?</p> <p>I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary file? Or do I have to change something in respect to the libraries?</p>
501
2009-10-07T21:11:22Z
32,363,907
<p>On the mac I use pyenv and virtualenvwrapper. I had to create a new virtualenv. You need homebrew which I'll assume you've installed if you're on a mac, but just for fun:</p> <pre><code>ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" brew install pyenv pyenv install 2.7.10 pyenv global 2.7.10 export PATH=/Users/{USERNAME}/.pyenv/versions/2.7.10/bin:$PATH mkvirtualenv -p ~/.pyenv/versions/2.7.10/bin/python {virtual_env_name} </code></pre> <p>I also froze my requirements first so i could simply reinstall in the new virtualenv with:</p> <pre><code>pip install -r requirements.txt </code></pre>
2
2015-09-02T22:04:10Z
[ "python", "virtualenv", "virtualenvwrapper" ]
Use different Python version with virtualenv
1,534,210
<p>I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python?</p> <p>I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary file? Or do I have to change something in respect to the libraries?</p>
501
2009-10-07T21:11:22Z
34,246,092
<p>You can call <code>virtualenv</code> with python version you want. For example:</p> <pre><code>python3 -m virtualenv venv </code></pre> <p>Or alternatively directly point to your virtualenv path. e.g. for windows:</p> <pre><code>c:\Python34\Scripts\virtualenv.exe venv </code></pre> <p>And by running:</p> <pre><code>venv/bin/python Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; </code></pre> <p>you can see the python version installed in virtual environment</p>
5
2015-12-12T23:11:12Z
[ "python", "virtualenv", "virtualenvwrapper" ]
Use different Python version with virtualenv
1,534,210
<p>I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python?</p> <p>I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary file? Or do I have to change something in respect to the libraries?</p>
501
2009-10-07T21:11:22Z
37,607,811
<p><strong>It worked for me</strong></p> <pre><code>sudo apt-get install python3-minimal virtualenv --no-site-packages --distribute -p /usr/bin/python3 ~/.virtualenvs/py3 </code></pre>
0
2016-06-03T06:53:41Z
[ "python", "virtualenv", "virtualenvwrapper" ]
Use different Python version with virtualenv
1,534,210
<p>I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python?</p> <p>I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary file? Or do I have to change something in respect to the libraries?</p>
501
2009-10-07T21:11:22Z
38,797,664
<p>The <code>-p</code> approach works well, but you do have to remember to use it every time. If your goal is to switch to a newer version of Python generally, that's a pain and can also lead to mistakes.</p> <p>Your other option is to set an environment variable that does the same thing as <code>-p</code>. Set this via your <code>~/.bashrc</code> file or wherever you manage environment variables for your login sessions:</p> <pre><code>export VIRTUALENV_PYTHON=/path/to/desired/version </code></pre> <p>Then <code>virtualenv</code> will use that any time you don't specify <code>-p</code> on the command line.</p>
0
2016-08-05T20:57:44Z
[ "python", "virtualenv", "virtualenvwrapper" ]
Use different Python version with virtualenv
1,534,210
<p>I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python?</p> <p>I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary file? Or do I have to change something in respect to the libraries?</p>
501
2009-10-07T21:11:22Z
39,574,443
<p>Even easier, by using command substitution to find python2 for you:</p> <p><code>virtualenv -p $(which python2) &lt;path/to/new/virtualenv/&gt;</code></p> <p>Or when using virtualenvwrapper : </p> <p><code>mkvirtualenv -p $(which python2) &lt;env_name&gt;</code></p>
1
2016-09-19T13:28:50Z
[ "python", "virtualenv", "virtualenvwrapper" ]
Use different Python version with virtualenv
1,534,210
<p>I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python?</p> <p>I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary file? Or do I have to change something in respect to the libraries?</p>
501
2009-10-07T21:11:22Z
39,713,544
<p>For python3 (3.5.2), use the <a href="https://docs.python.org/3/library/venv.html" rel="nofollow">new</a> <code>pyvenv</code> command.</p> <pre><code>pyvenv /path/to/new/virtual/environment </code></pre>
1
2016-09-26T22:46:36Z
[ "python", "virtualenv", "virtualenvwrapper" ]
Is there any way to affect locals at runtime?
1,534,368
<p>I actually want to create a new local. I know it sounds dubious, but I think I have a nice use case for this. Essentially my problem is that this code throws "NameError: global name 'eggs' is not defined" when I try to print eggs:</p> <pre><code>def f(): import inspect frame_who_called = inspect.stack()[1][0] frame_who_called.f_locals['eggs'] = 123 def g(): f() print(eggs) g() </code></pre> <p>I found this old thing: <a href="http://mail.python.org/pipermail/python-dev/2005-January/051018.html" rel="nofollow">http://mail.python.org/pipermail/python-dev/2005-January/051018.html</a></p> <p>Which would mean I might be able to do it using ctypes and calling some secret function, though they only talked about updating a value. But maybe there's an easier way?</p>
0
2009-10-07T21:38:37Z
1,534,421
<p>I am highly curious as to your use case. Why on Earth are you trying to poke a new local into the caller's frame, rather than simply doing something like this:</p> <pre><code>def f(): return 123 def g(): eggs = f() print(eggs) </code></pre> <p>After all, you can return a tuple with as many values as you like:</p> <pre><code>def f(): return 123, 456, 789 def g(): eggs, ham, bacon = f() print(eggs, ham, bacon) </code></pre>
3
2009-10-07T21:47:27Z
[ "python", "python-3.x", "locals" ]
Is there any way to affect locals at runtime?
1,534,368
<p>I actually want to create a new local. I know it sounds dubious, but I think I have a nice use case for this. Essentially my problem is that this code throws "NameError: global name 'eggs' is not defined" when I try to print eggs:</p> <pre><code>def f(): import inspect frame_who_called = inspect.stack()[1][0] frame_who_called.f_locals['eggs'] = 123 def g(): f() print(eggs) g() </code></pre> <p>I found this old thing: <a href="http://mail.python.org/pipermail/python-dev/2005-January/051018.html" rel="nofollow">http://mail.python.org/pipermail/python-dev/2005-January/051018.html</a></p> <p>Which would mean I might be able to do it using ctypes and calling some secret function, though they only talked about updating a value. But maybe there's an easier way?</p>
0
2009-10-07T21:38:37Z
1,534,989
<p>As Greg Hewgill mentioned in a comment on the question, I answered <a href="http://stackoverflow.com/questions/1463306/how-does-exec-work-with-locals">another question</a> about modifying <code>locals</code> in Python 3, and I'll give a bit of a recap here.</p> <p>There is a <a href="http://bugs.python.org/issue4831" rel="nofollow">post on the Python 3 bug list</a> about this issue -- it's somewhat poorly documented in the Python 3 manuals. Python 3 uses an array for locals instead of a dictionary like in Python 2 -- the advantage is a faster lookup time for local variables (Lua does this too). Basically, the array is defined at "bytecode-compile-time" and cannot be modified at runtime.</p> <p>See specifically the last paragraph in <a href="http://bugs.python.org/msg79061" rel="nofollow">Georg Brandl's post on the bug list</a> for finer details about why this cannot (and probably never will) work in Python 3.</p>
2
2009-10-08T00:32:52Z
[ "python", "python-3.x", "locals" ]
Is there any way to affect locals at runtime?
1,534,368
<p>I actually want to create a new local. I know it sounds dubious, but I think I have a nice use case for this. Essentially my problem is that this code throws "NameError: global name 'eggs' is not defined" when I try to print eggs:</p> <pre><code>def f(): import inspect frame_who_called = inspect.stack()[1][0] frame_who_called.f_locals['eggs'] = 123 def g(): f() print(eggs) g() </code></pre> <p>I found this old thing: <a href="http://mail.python.org/pipermail/python-dev/2005-January/051018.html" rel="nofollow">http://mail.python.org/pipermail/python-dev/2005-January/051018.html</a></p> <p>Which would mean I might be able to do it using ctypes and calling some secret function, though they only talked about updating a value. But maybe there's an easier way?</p>
0
2009-10-07T21:38:37Z
1,535,195
<p>In Python 2.*, you can get such code to work by defeating the normal optimization of locals:</p> <pre><code>&gt;&gt;&gt; def g(): ... exec 'pass' ... f() ... print(eggs) </code></pre> <p>The presence of an <code>exec</code> statement causes Python 2 to compile <code>g</code> in a totally non-optimized fashion, so locals are in a dict instead of in an array as they normally would be. (The performance hit can be considerable).</p> <p>This "de-optimization" does not exist in Python 3, where <code>exec</code> is not a statement any more (not even a keyword, just a function) -- even putting parentheses after it doesn't help...:</p> <pre><code>&gt;&gt;&gt; def x(): ... exec('a=23') ... print(a) ... &gt;&gt;&gt; x() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 3, in x NameError: global name 'a' is not defined &gt;&gt;&gt; </code></pre> <p>i.e., not even <code>exec</code> can now "create locals" that were not know at <code>def</code>-time (i.e., when the compiler did its pass to turn the function body into bytecode).</p> <p>Your best bet would be to give up. Second best would be to have your <code>f</code> function inject new names into the caller's <code>globals</code> -- <strong>those</strong> are still a dict, after all.</p>
1
2009-10-08T01:47:40Z
[ "python", "python-3.x", "locals" ]
Editing MP3 metadata on a file-like object in Python?
1,534,374
<p>We're generating MP3 files on the fly in Python, and need to edit the ID3 headers in-memory using a file-like object. </p> <p>All the ID3 libraries on <a href="http://pypi.python.org/pypi?%3Aaction=search&amp;term=id3&amp;submit=search" rel="nofollow">PyPI</a> <em>appear</em> to require you to pass a filesystem path as a string. I find this rather frustrating!</p> <p>Writing our generated MP3 out to disk (or ramdisk) just to add ID3 tags is unacceptable for a number of reasons, especially performance.</p> <p><em>Given the plentitude of ID3 libraries</em>, is there an ID3 library that simply works with file-like objects?</p>
3
2009-10-07T21:39:49Z
1,534,398
<p>AFAIR tags are appended to the end of file. You might want to study the format and make a simple library yourself, that should not be very difficult.</p> <p>Also, you could consider storing them temporary on a filesystem like tmpfs (ramdisk). </p>
-1
2009-10-07T21:43:54Z
[ "python", "mp3", "metadata", "id3" ]
Editing MP3 metadata on a file-like object in Python?
1,534,374
<p>We're generating MP3 files on the fly in Python, and need to edit the ID3 headers in-memory using a file-like object. </p> <p>All the ID3 libraries on <a href="http://pypi.python.org/pypi?%3Aaction=search&amp;term=id3&amp;submit=search" rel="nofollow">PyPI</a> <em>appear</em> to require you to pass a filesystem path as a string. I find this rather frustrating!</p> <p>Writing our generated MP3 out to disk (or ramdisk) just to add ID3 tags is unacceptable for a number of reasons, especially performance.</p> <p><em>Given the plentitude of ID3 libraries</em>, is there an ID3 library that simply works with file-like objects?</p>
3
2009-10-07T21:39:49Z
1,534,458
<p>Does StringIO help? <a href="http://docs.python.org/library/stringio.html" rel="nofollow">http://docs.python.org/library/stringio.html</a></p>
0
2009-10-07T21:54:47Z
[ "python", "mp3", "metadata", "id3" ]
Editing MP3 metadata on a file-like object in Python?
1,534,374
<p>We're generating MP3 files on the fly in Python, and need to edit the ID3 headers in-memory using a file-like object. </p> <p>All the ID3 libraries on <a href="http://pypi.python.org/pypi?%3Aaction=search&amp;term=id3&amp;submit=search" rel="nofollow">PyPI</a> <em>appear</em> to require you to pass a filesystem path as a string. I find this rather frustrating!</p> <p>Writing our generated MP3 out to disk (or ramdisk) just to add ID3 tags is unacceptable for a number of reasons, especially performance.</p> <p><em>Given the plentitude of ID3 libraries</em>, is there an ID3 library that simply works with file-like objects?</p>
3
2009-10-07T21:39:49Z
1,541,482
<p>Well, the answer seems to be that no such animal exists. The advantages of programming to an interface are apparently lost on the python MP3 frame hackers. We solved the problem by modifying an existing library.</p>
0
2009-10-09T02:02:28Z
[ "python", "mp3", "metadata", "id3" ]
Python object initialization bug. Or am I misunderstanding how objects work?
1,534,407
<pre><code> 1 import sys 2 3 class dummy(object): 4 def __init__(self, val): 5 self.val = val 6 7 class myobj(object): 8 def __init__(self, resources): 9 self._resources = resources 10 11 class ext(myobj): 12 def __init__(self, resources=[]): 13 #myobj.__init__(self, resources) 14 self._resources = resources 15 16 one = ext() 17 one._resources.append(1) 18 two = ext() 19 20 print one._resources 21 print two._resources 22 23 sys.exit(0) </code></pre> <p>This will print the reference to the object assigned to <code>one._resources</code> for both <code>one</code> and <code>two</code> objects. I would think that <code>two</code> would be an empty array as it is clearly setting it as such if it's not defined when creating the object. Uncommenting <code>myobj.__init__(self, resources)</code> does the same thing. Using <code>super(ext, self).__init__(resources)</code> also does the same thing.</p> <p>The only way I can get it to work is if I use the following:</p> <pre><code>two = ext(dummy(2)) </code></pre> <p>I shouldn't have to manually set the default value when creating the object to make this work. Or maybe I do. Any thoughts?</p> <p>I tried this using Python 2.5 and 2.6.</p>
1
2009-10-07T21:45:18Z
1,534,443
<p>You should change</p> <pre><code>def __init__(self, resources=[]): self._resources = resources </code></pre> <p>to</p> <pre><code>def __init__(self, resources=None): if resources is None: resources = [] self._resources = resources </code></pre> <p>and all will be better. This is a detail in the way default arguments are handled if they're mutable. There's some more information in the discussion section of <a href="http://code.activestate.com/recipes/502206/" rel="nofollow">this page</a>.</p>
7
2009-10-07T21:51:46Z
[ "python", "mutable", "arguments" ]
Python object initialization bug. Or am I misunderstanding how objects work?
1,534,407
<pre><code> 1 import sys 2 3 class dummy(object): 4 def __init__(self, val): 5 self.val = val 6 7 class myobj(object): 8 def __init__(self, resources): 9 self._resources = resources 10 11 class ext(myobj): 12 def __init__(self, resources=[]): 13 #myobj.__init__(self, resources) 14 self._resources = resources 15 16 one = ext() 17 one._resources.append(1) 18 two = ext() 19 20 print one._resources 21 print two._resources 22 23 sys.exit(0) </code></pre> <p>This will print the reference to the object assigned to <code>one._resources</code> for both <code>one</code> and <code>two</code> objects. I would think that <code>two</code> would be an empty array as it is clearly setting it as such if it's not defined when creating the object. Uncommenting <code>myobj.__init__(self, resources)</code> does the same thing. Using <code>super(ext, self).__init__(resources)</code> also does the same thing.</p> <p>The only way I can get it to work is if I use the following:</p> <pre><code>two = ext(dummy(2)) </code></pre> <p>I shouldn't have to manually set the default value when creating the object to make this work. Or maybe I do. Any thoughts?</p> <p>I tried this using Python 2.5 and 2.6.</p>
1
2009-10-07T21:45:18Z
1,534,444
<p>Your problem is that the default value is evaluated at function definition time. This means that the same list object is shared between instances. See the answer <a href="http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument">to this question</a> for more discussion.</p>
6
2009-10-07T21:51:54Z
[ "python", "mutable", "arguments" ]
Python object initialization bug. Or am I misunderstanding how objects work?
1,534,407
<pre><code> 1 import sys 2 3 class dummy(object): 4 def __init__(self, val): 5 self.val = val 6 7 class myobj(object): 8 def __init__(self, resources): 9 self._resources = resources 10 11 class ext(myobj): 12 def __init__(self, resources=[]): 13 #myobj.__init__(self, resources) 14 self._resources = resources 15 16 one = ext() 17 one._resources.append(1) 18 two = ext() 19 20 print one._resources 21 print two._resources 22 23 sys.exit(0) </code></pre> <p>This will print the reference to the object assigned to <code>one._resources</code> for both <code>one</code> and <code>two</code> objects. I would think that <code>two</code> would be an empty array as it is clearly setting it as such if it's not defined when creating the object. Uncommenting <code>myobj.__init__(self, resources)</code> does the same thing. Using <code>super(ext, self).__init__(resources)</code> also does the same thing.</p> <p>The only way I can get it to work is if I use the following:</p> <pre><code>two = ext(dummy(2)) </code></pre> <p>I shouldn't have to manually set the default value when creating the object to make this work. Or maybe I do. Any thoughts?</p> <p>I tried this using Python 2.5 and 2.6.</p>
1
2009-10-07T21:45:18Z
1,534,448
<p>From <a href="http://docs.python.org/3.1/tutorial/controlflow.html" rel="nofollow">http://docs.python.org/3.1/tutorial/controlflow.html</a>:</p> <blockquote> <p>The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.</p> </blockquote>
1
2009-10-07T21:52:40Z
[ "python", "mutable", "arguments" ]
Python object initialization bug. Or am I misunderstanding how objects work?
1,534,407
<pre><code> 1 import sys 2 3 class dummy(object): 4 def __init__(self, val): 5 self.val = val 6 7 class myobj(object): 8 def __init__(self, resources): 9 self._resources = resources 10 11 class ext(myobj): 12 def __init__(self, resources=[]): 13 #myobj.__init__(self, resources) 14 self._resources = resources 15 16 one = ext() 17 one._resources.append(1) 18 two = ext() 19 20 print one._resources 21 print two._resources 22 23 sys.exit(0) </code></pre> <p>This will print the reference to the object assigned to <code>one._resources</code> for both <code>one</code> and <code>two</code> objects. I would think that <code>two</code> would be an empty array as it is clearly setting it as such if it's not defined when creating the object. Uncommenting <code>myobj.__init__(self, resources)</code> does the same thing. Using <code>super(ext, self).__init__(resources)</code> also does the same thing.</p> <p>The only way I can get it to work is if I use the following:</p> <pre><code>two = ext(dummy(2)) </code></pre> <p>I shouldn't have to manually set the default value when creating the object to make this work. Or maybe I do. Any thoughts?</p> <p>I tried this using Python 2.5 and 2.6.</p>
1
2009-10-07T21:45:18Z
1,534,461
<p>Please read <a href="http://stackoverflow.com/questions/1495666/how-to-define-a-class-in-python/1495740#1495740">this answer</a> for a discussion of how to setup a class from <code>__init__()</code>. You have encountered a well-known quirk of Python: you are trying to set up a mutable, and your mutable is being evaluated once when <code>__init__()</code> is compiled. The standard workaround is:</p> <pre><code>class ext(myobj): def __init__(self, resources=None): if resources is None: resources = [] #myobj.__init__(self, resources) self._resources = resources </code></pre>
2
2009-10-07T21:55:07Z
[ "python", "mutable", "arguments" ]
Python object initialization bug. Or am I misunderstanding how objects work?
1,534,407
<pre><code> 1 import sys 2 3 class dummy(object): 4 def __init__(self, val): 5 self.val = val 6 7 class myobj(object): 8 def __init__(self, resources): 9 self._resources = resources 10 11 class ext(myobj): 12 def __init__(self, resources=[]): 13 #myobj.__init__(self, resources) 14 self._resources = resources 15 16 one = ext() 17 one._resources.append(1) 18 two = ext() 19 20 print one._resources 21 print two._resources 22 23 sys.exit(0) </code></pre> <p>This will print the reference to the object assigned to <code>one._resources</code> for both <code>one</code> and <code>two</code> objects. I would think that <code>two</code> would be an empty array as it is clearly setting it as such if it's not defined when creating the object. Uncommenting <code>myobj.__init__(self, resources)</code> does the same thing. Using <code>super(ext, self).__init__(resources)</code> also does the same thing.</p> <p>The only way I can get it to work is if I use the following:</p> <pre><code>two = ext(dummy(2)) </code></pre> <p>I shouldn't have to manually set the default value when creating the object to make this work. Or maybe I do. Any thoughts?</p> <p>I tried this using Python 2.5 and 2.6.</p>
1
2009-10-07T21:45:18Z
1,534,515
<p>This is a <a href="http://www.ferg.org/projects/python%5Fgotchas.html#contents%5Fitem%5F6" rel="nofollow">known</a> Python <a href="http://eli.thegreenplace.net/2009/01/16/python-insight-beware-of-mutable-default-values-for-arguments/" rel="nofollow">gotcha</a>.</p> <p>You have to avoid using a mutable object on the call of a function/method.</p> <blockquote> <p>The objects that provide the default values <strong>are not created at the time that the function/method is called</strong>. <strong>They are created at the time that the statement that defines the function is executed</strong>. (See the discussion at <a href="http://www.deadlybloodyserious.com/2008/05/default-argument-blunders/" rel="nofollow">Default arguments in Python: two easy blunders</a>: <em>"Expressions in default arguments are calculated when the function is defined, not when it’s called."</em>)</p> <p>This behavior is not a wart in the Python language. It really is a feature, not a bug. There are times when you really do want to use mutable default arguments. One thing they can do (for example) is retain a list of results from previous invocations, something that might be very handy.</p> <p>But for most programmers — especially beginning Pythonistas — this behavior is a gotcha. So for most cases we adopt the following rules.</p> <ul> <li><strong>Never use a mutable object</strong> — that is: a list, a dictionary, or a class instance — as the default value of an argument.</li> <li>Ignore rule 1 only if you really, really, REALLY know what you're doing.</li> </ul> <p>So... we plan always to follow rule #1. Now, the question is how to do it... how to code functionF in order to get the behavior that we want.</p> <p>Fortunately, the solution is straightforward. The mutable objects used as defaults are replaced by <code>None</code>, and then the arguments are tested for <code>None</code>.</p> </blockquote> <p><hr /></p> <blockquote> <p>So how can one do it correctly? One solution is <strong>avoid using mutable default values for arguments</strong>. But this is hardly satisfactory, as from time to time a new list is a useful default. There are some complex solutions like defining a decorator for functions that deep-copies all arguments. This is an overkill, and the problem can be solved easily as follows:</p> </blockquote> <pre><code>class ext(myobj): def __init__(self, resources=None): if not resources: resources = [] self._resources = resources </code></pre>
0
2009-10-07T22:08:08Z
[ "python", "mutable", "arguments" ]