title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Is non-blocking Redis pubsub possible?
7,871,526
18
2011-10-24T05:13:19Z
14,219,672
40
2013-01-08T16:32:43Z
[ "python", "redis" ]
I want to use redis' pubsub to transmit some messages, but don't want be blocked using `listen`, like the code below: ``` import redis rc = redis.Redis() ps = rc.pubsub() ps.subscribe(['foo', 'bar']) rc.publish('foo', 'hello world') for item in ps.listen(): if item['type'] == 'message': print item['chan...
If you're thinking of non-blocking, asynchronous processing, you're probably using (or should use) asynchronous framework/server. * if you're using [Tornado](http://www.tornadoweb.org/), there is [**Tornado-Redis**](https://github.com/leporo/tornado-redis). It's using native Tornado generator calls. Its [Websocket dem...
In Python, what is the difference between pass and return
7,872,611
14
2011-10-24T07:50:01Z
7,872,624
13
2011-10-24T07:51:30Z
[ "python" ]
I have seen some code in Pinax and other django apps that instead of pass, an empty return statement is used. What is the difference and would it have any effect on, for example, the django code below that I am running? The code is a signal method that automatically saves the hashtags into taggit Tag objects for a twee...
[Return](http://docs.python.org/reference/simple_stmts.html#the-return-statement) exits the current function or method. [Pass](http://docs.python.org/reference/simple_stmts.html#the-pass-statement) is a null operation and allows execution to continue at the next statement.
In Python, what is the difference between pass and return
7,872,611
14
2011-10-24T07:50:01Z
7,872,670
32
2011-10-24T07:56:00Z
[ "python" ]
I have seen some code in Pinax and other django apps that instead of pass, an empty return statement is used. What is the difference and would it have any effect on, for example, the django code below that I am running? The code is a signal method that automatically saves the hashtags into taggit Tag objects for a twee...
``` if not instance: return # will pass be better or worse here? ``` Worse. It changes the logic. `pass` actually means: Do nothing. If you would replace `return` with `pass` here, the control flow would continue, changing the semantic of the code. The purpose for `pass` is to create empty blocks, which is not po...
In Python, what is the difference between pass and return
7,872,611
14
2011-10-24T07:50:01Z
25,029,532
8
2014-07-30T05:40:29Z
[ "python" ]
I have seen some code in Pinax and other django apps that instead of pass, an empty return statement is used. What is the difference and would it have any effect on, for example, the django code below that I am running? The code is a signal method that automatically saves the hashtags into taggit Tag objects for a twee...
This illustrates some earlier answers. ``` def p(): "Executes both blocks." if 1: print(1) pass if 1: print(2) pass def r(): "Executes only the first block." if 1: print(1) return if 1: print(2) return ```
One line if-condition-assignment
7,872,838
24
2011-10-24T08:15:37Z
7,872,858
12
2011-10-24T08:17:35Z
[ "python", "if-statement" ]
I have the following code ``` num1 = 10 someBoolValue = True ``` I need to set the value of `num1` to `20` if `someBoolValue` is `True`; and do nothing otherwise. So, here is my code for that ``` num1 = 20 if someBoolValue else num1 ``` Is there someway I could avoid the `...else num1` part to make it look cleaner?...
In one line: ``` if someBoolValue: num1 = 20 ``` But don’t do that. This style is normally not expected. People prefer the longer form for clarity and consistency. ``` if someBoolValue: num1 = 20 ``` (Equally, camel caps should be avoided. So rather use `some_bool_value`.) Note that an in-line *expression* `...
One line if-condition-assignment
7,872,838
24
2011-10-24T08:15:37Z
7,872,903
12
2011-10-24T08:22:59Z
[ "python", "if-statement" ]
I have the following code ``` num1 = 10 someBoolValue = True ``` I need to set the value of `num1` to `20` if `someBoolValue` is `True`; and do nothing otherwise. So, here is my code for that ``` num1 = 20 if someBoolValue else num1 ``` Is there someway I could avoid the `...else num1` part to make it look cleaner?...
Use this: ``` num1 = 20 if someBoolValue else num1 ```
One line if-condition-assignment
7,872,838
24
2011-10-24T08:15:37Z
7,872,950
52
2011-10-24T08:27:11Z
[ "python", "if-statement" ]
I have the following code ``` num1 = 10 someBoolValue = True ``` I need to set the value of `num1` to `20` if `someBoolValue` is `True`; and do nothing otherwise. So, here is my code for that ``` num1 = 20 if someBoolValue else num1 ``` Is there someway I could avoid the `...else num1` part to make it look cleaner?...
I don't think this is possible in Python, since what you're actually trying to do probably gets expanded to something like this: ``` num1 = 20 if someBoolValue else num1 ``` If you exclude `else num1`, you'll receive a syntax error since I'm quite sure that the assignment must actually return something. As others ha...
How to compare dates in Python?
7,873,013
2
2011-10-24T08:33:24Z
7,873,056
7
2011-10-24T08:37:57Z
[ "python", "datetime", "date-comparison" ]
I'm a Python beginner. I need to see if a date has more than X days. How can I do this in Python? I have tested something like: ``` if datetime.date(2010, 1, 12) > datetime.timedelta(3): ``` I got the error: ``` TypeError: can't compare datetime.date to datetime.timedelta ``` Any clue on how to achieve this? Best...
You can't compare a [`datetime`](http://docs.python.org/py3k/library/datetime.html#date-objects) to a [`timedelta`](http://docs.python.org/py3k/library/datetime.html#timedelta-objects). A `timedelta` represents a duration, a `datetime` represents a specific point in time. The [difference](http://docs.python.org/py3k/li...
Django/Python POST
7,873,020
2
2011-10-24T08:34:03Z
7,873,080
8
2011-10-24T08:40:18Z
[ "python", "django", "post" ]
First a bit of an introduction. I will send a POST to a url and it will have either ip, mac or hostname. Now depending on which of these key' are in the QueryDict i want it to do certain calls. I.e: Output of ``` print request.POST <QueryDict: {u'ip': [u'10.1.24.178'], u'message': [u'Test'], u'client': [u'auabrthin1...
``` if 'client' in request.POST: # do something ```
utf8 codec can't decode byte 0x96 in python
7,873,556
18
2011-10-24T09:26:28Z
7,873,916
18
2011-10-24T09:58:35Z
[ "python" ]
I am trying to check if a certain word is on a page for many sites. The script runs fine for say 15 sites and then it stops. **UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 15344: invalid start byte** I did a search on stackoverflow and found many issues on it but I can't seem to understand what...
The byte at 15344 is 0x96. Presumably at position 15343 there is either a single-byte encoding of a character, or the last byte of a multiple-byte encoding, making 15344 the start of a character. 0x96 is in binary 10010110, and any byte matching the pattern 10XXXXXX (0x80 to 0xBF) can only be a second or subsequent byt...
How to convert date to timestamp using Python?
7,873,828
2
2011-10-24T09:51:26Z
7,873,893
8
2011-10-24T09:56:50Z
[ "python", "datetime-conversion" ]
I need to convert this result to timestamp: ``` >>> print (datetime.date(2010, 1, 12) + datetime.timedelta(days = 3)) 2010-01-15 ``` I need to compare the value with this timestamp: ``` >>> datetime.datetime.now() 2011-10-24 10:43:43.371294 ``` How can I achieve this?
> I need to convert this result to timestamp ``` import time mydate = datetime.date(2010, 1, 12) + datetime.timedelta(days = 3) time.mktime(mydate.timetuple()) ``` > I need to compare the value with this timestamp: ``` a = datetime.datetime(2010, 1, 12) + datetime.timedelta(days = 3) b = datetime.datetime.now() a...
How can I create a standard colorbar for a series of plots in python
7,875,688
24
2011-10-24T12:34:40Z
7,879,159
54
2011-10-24T17:03:09Z
[ "python", "matplotlib", "colorbar" ]
I using matplotlib to plot some data in python and the plots require a standard colour bar. The data consists of a series of NxM matrices containing frequency information so that a simple imshow() plot gives a 2D histogram with colour describing frequency. Each matrix contains data in different, but overlapping ranges....
Not to steal @ianilis's answer, but I wanted to add an example... There are multiple ways, but the simplest is just to specify the `vmin` and `vmax` kwargs to `imshow`. Alternately, you can make a `matplotlib.cm.Colormap` instance and specify it, but that's more complicated than necessary for simple cases. Here's a q...
How to implement a minimal class that behaves like a sequence in Python?
7,875,911
4
2011-10-24T12:52:43Z
7,876,063
7
2011-10-24T13:06:24Z
[ "python", "sequence" ]
I am looking for a sample minimal example of a class that mimics an immutable sequence in Python. ``` class MySequence() ... a = MySequence() len(a) for i in a: pass a[0] ``` What are the methods that must be implemented?
If you just want to be able to iterate over your sequence, you just need to implement the `__iter__` method returning an iterable. The easiest way to do this is to create a generator using the `yield` statement. ``` class MySequence(object): def __iter__(self): yield 1 yield 2 yield 3 for ...
What's the logical execution order of this Python decorated function?
7,875,959
4
2011-10-24T12:56:00Z
7,876,021
7
2011-10-24T13:02:20Z
[ "python", "decorator" ]
Imagine this: ``` def b1(fnc): print "b1" return fnc @b1 def a1(): print "a1" if __name__ == "__main__": a1() # will print b1 a1 ``` So, when I'm using `@b1`, a1 gets turned to `a1 = b1(a1)`, right? Then, when I say: ``` a1() ``` This turns to: ``` b1(a1) ``` And then goes into: ``` print "b1" return f...
**The decorator is only executed once. It takes a callable object and returns a callable object.** The object that it returns is used in place of `a1`. In other words, `b1` is called at the point where `a1` is defined. It prints out `"b1"` and returns `a1` unchanged. Since it returns `a1` unchanged, `b1` plays no role...
Select value from list of tuples where condition
7,876,272
17
2011-10-24T13:22:51Z
7,876,322
26
2011-10-24T13:27:20Z
[ "python", "tuples" ]
I have a list of tuples. Every tuple has 5 elements (corresponding to 5 database columns) and I'd like to make a query `select attribute1 from mylist where attribute2 = something` e.g. `personAge = select age from mylist where person_id = 10` Is it possible to query the list of tuples in some way? thank you
If you have [named tuples](http://docs.python.org/dev/library/collections.html#collections.namedtuple) you can do this: ``` results = [t.age for t in mylist if t.person_id == 10] ``` Otherwise use indexes: ``` results = [t[1] for t in mylist if t[0] == 10] ``` Or use tuple unpacking as per Nate's answer. Note that ...
Select value from list of tuples where condition
7,876,272
17
2011-10-24T13:22:51Z
7,876,353
9
2011-10-24T13:29:29Z
[ "python", "tuples" ]
I have a list of tuples. Every tuple has 5 elements (corresponding to 5 database columns) and I'd like to make a query `select attribute1 from mylist where attribute2 = something` e.g. `personAge = select age from mylist where person_id = 10` Is it possible to query the list of tuples in some way? thank you
One solution to this would be a list comprehension, with pattern matching inside your tuple: ``` >>> mylist = [(25,7),(26,9),(55,10)] >>> [age for (age,person_id) in mylist if person_id == 10] [55] ``` Another way would be using `map` and `filter`: ``` >>> map( lambda (age,_): age, filter( lambda (_,person_id): pers...
Minimum and maximum of the last 1000 values of the changing list
7,876,453
6
2011-10-24T13:36:00Z
7,876,619
7
2011-10-24T13:48:05Z
[ "python", "algorithm", "max", "min", "epsilon" ]
I'm creating an iterative algorithm (Monte Carlo method). The algorithm returns a value on every iteration, creating a stream of values. I need to analyze these values and stop the algorithm when say `1000` returned values are withing some `epsilon`. I decided to implement it calculation the `max` and `min` values of...
If you are free / willing to change your definition of `error`, you might want to consider using the `variance` instead of `(max-min)/min`. You can [compute the variance incrementally](http://stackoverflow.com/questions/5543651/computing-standard-deviation-in-a-stream/5544108#5544108). True, using this method, you are...
Standard 401 response when using HTTP auth in flask
7,877,230
9
2011-10-24T14:32:07Z
8,237,933
8
2011-11-23T06:01:33Z
[ "python", "apache2", "flask", "http-authentication", "abort" ]
In flask, I'm using the following [snippet](http://flask.pocoo.org/snippets/8/) to enable HTTP auth: ``` def authenticate(): return Response('<Why access is denied string goes here...>', 401, {'WWW-Authenticate':'Basic realm="Login Required"'}) ``` Now, in my past experience with Flask, if someone's credentials a...
Flask's `abort` comes directly from Werkzeug. It is a callable object, that raises various predefined HTTP exceptions (subclasses of `HTTPException`) on demand. Check out the code [here](https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/exceptions.py) for details. The predefined `Unauthorized` (which is mappe...
Standard 401 response when using HTTP auth in flask
7,877,230
9
2011-10-24T14:32:07Z
8,316,995
11
2011-11-29T20:04:36Z
[ "python", "apache2", "flask", "http-authentication", "abort" ]
In flask, I'm using the following [snippet](http://flask.pocoo.org/snippets/8/) to enable HTTP auth: ``` def authenticate(): return Response('<Why access is denied string goes here...>', 401, {'WWW-Authenticate':'Basic realm="Login Required"'}) ``` Now, in my past experience with Flask, if someone's credentials a...
Custom error responses are really quite easy in Flask. Create a function whose only argument is the HTTP error status code, make it return a flask.Response instance, and decorate it with [@app.errorhandler](http://flask.pocoo.org/docs/api/#flask.Flask.errorhandler). ``` @app.errorhandler(401) def custom_401(error): ...
How to send image generated by PIL to browser?
7,877,282
32
2011-10-24T14:35:43Z
7,885,108
16
2011-10-25T05:39:20Z
[ "python", "streaming", "python-imaging-library", "flask", "temporary-files" ]
I'm using flask for my application. I'd like to send an image (dynamically generated by PIL) to client without saving on disk. Any idea how to do this ?
First, you can save the image to a [tempfile](http://docs.python.org/library/tempfile.html) and remove the local file (if you have one): ``` from tempfile import NamedTemporaryFile from shutil import copyfileobj from os import remove tempFileObj = NamedTemporaryFile(mode='w+b',suffix='jpg') pilImage = open('/tmp/myfi...
How to send image generated by PIL to browser?
7,877,282
32
2011-10-24T14:35:43Z
8,436,059
7
2011-12-08T18:50:27Z
[ "python", "streaming", "python-imaging-library", "flask", "temporary-files" ]
I'm using flask for my application. I'd like to send an image (dynamically generated by PIL) to client without saving on disk. Any idea how to do this ?
It turns out that flask provides a solution (rtfm to myself!): ``` from flask import abort, send_file try: return send_file(image_file) except: abort(404) ```
How to send image generated by PIL to browser?
7,877,282
32
2011-10-24T14:35:43Z
10,170,635
96
2012-04-16T08:11:18Z
[ "python", "streaming", "python-imaging-library", "flask", "temporary-files" ]
I'm using flask for my application. I'd like to send an image (dynamically generated by PIL) to client without saving on disk. Any idea how to do this ?
Here's a version without any temp files and the like (see [here](http://flask.pocoo.org/snippets/32/)): ``` def serve_pil_image(pil_img): img_io = StringIO() pil_img.save(img_io, 'JPEG', quality=70) img_io.seek(0) return send_file(img_io, mimetype='image/jpeg') ``` To use in your code simply do ``` @...
TypeError: ‘DoesNotExist’ object is not callable
7,877,340
17
2011-10-24T14:39:12Z
7,877,717
38
2011-10-24T15:04:28Z
[ "python", "django" ]
It's not always this code chunk but this is the most recent. It seems to be random, any thoughts? ``` try: u = User.objects.get(email__iexact=useremail) except User.DoesNotExist: ... ``` Throws this error, randomly. ``` File "/srv/myapp/registration/models.py", line 23, in get_or_create_user u = User.objec...
As Chris says in the comments above, your snippet is valid. Somewhere else in your code, you may be catching exceptions incorrectly. You may have something like: ``` try: do_something() except User.MultipleObjectsReturned, User.DoesNotExist: pass ``` instead of: ``` try: do_something() except (User.Mult...
Cannot set Django to work with smtp.gmail.com
7,877,452
18
2011-10-24T14:46:10Z
7,885,950
15
2011-10-25T07:25:21Z
[ "python", "django", "smtp" ]
I've been trying to get django to work with gmail's smtp server to send mails but I always get this traceback. Any help will be most appreciated. # ----- settings.py ----- ``` EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'user@gmail.com' EMAIL_HOST_PASSWORD = 'your-password' EMAIL_PORT = 587 EMAIL_USE_TLS = Tr...
Change your settings like this : ``` EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'user' EMAIL_HOST_PASSWORD = 'your-password' EMAIL_PORT = 587 EMAIL_USE_TLS = True ``` Then try: ``` python manage.py shell >>> from django.core.mail import EmailMessage >>> email = EmailMessage('Mail Test', 'This is a test', to...
Cannot set Django to work with smtp.gmail.com
7,877,452
18
2011-10-24T14:46:10Z
7,900,850
8
2011-10-26T09:26:09Z
[ "python", "django", "smtp" ]
I've been trying to get django to work with gmail's smtp server to send mails but I always get this traceback. Any help will be most appreciated. # ----- settings.py ----- ``` EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'user@gmail.com' EMAIL_HOST_PASSWORD = 'your-password' EMAIL_PORT = 587 EMAIL_USE_TLS = Tr...
I have recently set this up and had a slightly different settings.py config. Move: ``` EMAIL_USE_TLS = True ``` to the top above EMAIL\_HOST Add: ``` DEFAULT_FROM_EMAIL = 'user@gmail.com' SERVER_EMAIL = 'user@gmail.com' ```
Can BDD testing with Lettuce replace all other forms of testing in a project?
7,877,638
7
2011-10-24T14:59:56Z
7,878,932
8
2011-10-24T16:42:51Z
[ "python", "testing", "bdd" ]
I like Lettuce, and the feel of testing with it. Could I replace all the tests ( doctests/unit tests ) in a project with Lettuce features?
In short, no. I haven't used Lettuce, but your question applies equally to other BDD frameworks such as Cucumber. This approach is considered bad practice since integration tests are slower to run and more work to maintain than unit tests. Also, a big advantage of Gherkin syntax is that it's readable by non-technica...
Python 2.7: Print thread safe
7,877,850
3
2011-10-24T15:14:41Z
7,877,918
9
2011-10-24T15:19:25Z
[ "python", "thread-safety" ]
I've seen a similar post [here](http://stackoverflow.com/questions/3029816/how-do-i-get-a-thread-safe-print-in-python-2-6) however it refers to Python 2.6 and I was hoping there was an easier way. From reading the thread it seems the best way is to just replace all my print statements with sys.stdout.write(s + '\n') ?...
``` from __future__ import print_function print = lambda x: sys.stdout.write("%s\n" % x) ``` Is a nice cheap and dirty hack.
how to check if two strings have intersection in python?
7,878,064
4
2011-10-24T15:30:39Z
7,878,165
9
2011-10-24T15:37:37Z
[ "python" ]
For example, a = "abcdefg", b = "krtol", they have no intersection, c = "hflsfjg", then a and c have intersaction. What's the easiest way to check this? just need a True or False result
``` def hasIntersection(a, b): return not set(a).isdisjoint(b) ```
How to extract an arbitrary line of values from a numpy array?
7,878,398
35
2011-10-24T15:54:47Z
7,879,057
14
2011-10-24T16:53:56Z
[ "python", "indexing", "numpy", "profile", "slice" ]
I have a numpy array that contains some image data. I would like to plot the 'profile' of a transect drawn across the image. The simplest case is a profile running parallel to the edge of the image, so if the image array is `imdat`, then the profile at a selected point `(r,c)` is simply `imdat[r]` (horizontal) or `imda...
Probably the easiest way to do this is to use [`scipy.interpolate.interp2d()`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp2d.html): ``` # construct interpolation function # (assuming your data is in the 2-d array "data") x = numpy.arange(data.shape[1]) y = numpy.arange(data.shape[0]) f...
How to extract an arbitrary line of values from a numpy array?
7,878,398
35
2011-10-24T15:54:47Z
7,880,726
54
2011-10-24T19:19:47Z
[ "python", "indexing", "numpy", "profile", "slice" ]
I have a numpy array that contains some image data. I would like to plot the 'profile' of a transect drawn across the image. The simplest case is a profile running parallel to the edge of the image, so if the image array is `imdat`, then the profile at a selected point `(r,c)` is simply `imdat[r]` (horizontal) or `imda...
@Sven's answer is the easy way, but it's rather inefficient for large arrays. If you're dealing with a relatively small array, you won't notice the difference, if you're wanting a profile from a large (e.g. >50 MB) you may want to try a couple of other approaches. You'll need to work in "pixel" coordinates for these, t...
How to extract an arbitrary line of values from a numpy array?
7,878,398
35
2011-10-24T15:54:47Z
23,846,484
12
2014-05-24T15:02:43Z
[ "python", "indexing", "numpy", "profile", "slice" ]
I have a numpy array that contains some image data. I would like to plot the 'profile' of a transect drawn across the image. The simplest case is a profile running parallel to the edge of the image, so if the image array is `imdat`, then the profile at a selected point `(r,c)` is simply `imdat[r]` (horizontal) or `imda...
I've been testing the above routines with galaxy images and think I found a small error. I think a transpose needs to be added to the otherwise great solution provided by Joe. Here is a slightly modified version of his code that reveals the error. If you run it without the transpose, you can see the profile doesn't mat...
ttk treeview: alternate row colors
7,878,730
8
2011-10-24T16:24:08Z
7,880,956
15
2011-10-24T19:36:01Z
[ "python", "treeview", "ttk" ]
How can I set a style for `treeview` widgets so that alternate rows have different background colors, for example, rows 1,3,5 have white backgrounds and rows 2,4,6 have light blue-grey backgrounds? I'd also like to set `gridlines`.
I had this same issue a few months ago. From the [tk docs](http://www.tkdocs.com/tutorial/tree.html): ``` You can assign a list of tags to each item using the "tags" item configuration option (again, when creating the item or later on). Tag configuration options can then be specified, which will then apply to all ...
read the whole file at once
7,878,844
4
2011-10-24T16:34:36Z
7,878,882
9
2011-10-24T16:37:51Z
[ "python", "file" ]
I'm trying to write a function that gets a path and returns this file's content. No error handling needed. I've came up with the following ``` def read_all_1(path): f = open(path) s = f.read() f.close() return s def read_all_2(path): with open(path) as f: return f.read() ``` My questions:...
They are both quite pythonic. To address your second question, in the second function, the file will indeed be closed automatically. That is part of the protocol used with the `with` statement. Ironically, the file is *not* guaranteed to be closed in your first example (more on why in a second). Ultimately, I would ch...
Override the {...} notation so i get an OrderedDict() instead of a dict()?
7,878,933
30
2011-10-24T16:42:54Z
7,879,023
11
2011-10-24T16:51:04Z
[ "python", "dictionary", "override", "built-in", "ordereddictionary" ]
I want to use a .py file like a config file. So using the `{...}` notation I can create a dictionary using strings as keys but the definition order is lost in a standard python dictionary. My question: is it possible to override the `{...}` notation so that I get an `OrderedDict()` instead of a `dict()`? I was hoping...
`OrderedDict` is not "standard python syntax", however, an ordered set of key-value pairs (in standard python syntax) is simply: ``` [('key1 name', 'value1'), ('key2 name', 'value2'), ('key3 name', 'value3')] ``` To explicitly get an `OrderedDict`: ``` OrderedDict([('key1 name', 'value1'), ('key2 name', 'value2'), (...
Override the {...} notation so i get an OrderedDict() instead of a dict()?
7,878,933
30
2011-10-24T16:42:54Z
7,880,276
30
2011-10-24T18:43:56Z
[ "python", "dictionary", "override", "built-in", "ordereddictionary" ]
I want to use a .py file like a config file. So using the `{...}` notation I can create a dictionary using strings as keys but the definition order is lost in a standard python dictionary. My question: is it possible to override the `{...}` notation so that I get an `OrderedDict()` instead of a `dict()`? I was hoping...
To literally get what you are asking for, you have to fiddle with the syntax tree of your file. I don't think it is advisable to do so, but I couldn't resist the temptation to try. So here we go. First, we create a module with a function `my_execfile()` that works like the built-in `execfile()`, except that all occurr...
Override the {...} notation so i get an OrderedDict() instead of a dict()?
7,878,933
30
2011-10-24T16:42:54Z
37,259,917
65
2016-05-16T17:38:52Z
[ "python", "dictionary", "override", "built-in", "ordereddictionary" ]
I want to use a .py file like a config file. So using the `{...}` notation I can create a dictionary using strings as keys but the definition order is lost in a standard python dictionary. My question: is it possible to override the `{...}` notation so that I get an `OrderedDict()` instead of a `dict()`? I was hoping...
Here's a hack that almost gives you the syntax you want: ``` class _OrderedDictMaker(object): def __getitem__(self, keys): assert isinstance(keys, tuple) assert all(isinstance(key, slice) for key in keys) return OrderedDict([(k.start, k.stop) for k in keys]) ordereddict = _OrderedDictMake...
Using anchors in python regex to get exact match
7,879,600
6
2011-10-24T17:46:25Z
7,879,653
13
2011-10-24T17:50:15Z
[ "python", "regex" ]
I need to validate a version number consisting of 'v' plus positive int, and nothing else eg "v4", "v1004" I have ``` import re pattern = "\Av(?=\d+)\W" m = re.match(pattern, "v303") if m is None: print "noMatch" else: print "match" ``` But this doesn't work! Removing the \A and \W will match for v303 but w...
Pretty straightforward. First, put anchors on your pattern: ``` "^patternhere$" ``` Now, let's put together the pattern: ``` "^v\d+$" ``` That should do it.
Is there static block in class in python
7,879,943
7
2011-10-24T18:15:34Z
7,880,038
9
2011-10-24T18:23:11Z
[ "python", "static", "block" ]
I am relatively new to python I would like to run a block of code only once for a class. Like the static block in java. for eg: ``` class ABC: execute this once for a class. ``` Is there any such options available in python? In java we write it like this. This is executed only once for a class, at the time the ...
To do this just put the code directly under the class definition (parallel to the function definitions for the class. All code directly in the class gets executed upon creation of that type in the class' namespace. Example: ``` class Test: i = 3 y = 3 * i def testF(self): print Test.y v = Test() ...
Excluding South migrations from Pylint
7,880,180
11
2011-10-24T18:36:21Z
7,880,359
15
2011-10-24T18:51:05Z
[ "python", "django", "django-south", "pylint" ]
I'm using South for migration in my Django project. When I run Pylint on my project I get a bunch of errors from the migration files. How can I exclude migration files from Pylint? I'm on a Windows system so I can't use filename exclusions in the Pylint options. I've tried to resort to adding `# pylint: disable-msg-ca...
Adding the following to the `.pylintrc` file did it. ``` [MASTER] # Add <file or directory> to the black list. It should be a base name, not a # path. You may set this option multiple times. ignore=tests.py, urls.py, migrations ```
Python executable not finding libpython shared library
7,880,454
78
2011-10-24T18:58:36Z
7,880,519
117
2011-10-24T19:03:25Z
[ "python" ]
I am installing Python 2.7 on CentOS 5. I built and installed Python as follows ``` ./configure --enable-shared --prefix=/usr/local make make install ``` When I try to run /usr/local/bin/python, I get this error message ``` /usr/local/bin/python: error while loading shared libraries: libpython2.7.so.1.0: cannot open...
Try the following: ``` LD_LIBRARY_PATH=/usr/local/lib /usr/local/bin/python ``` Replace `/usr/local/lib` with the folder where you have installed `libpython2.7.so.1.0` if it is not in `/usr/local/lib`. If this works and you want to make the changes permanent, you have two options: 1. Add `export LD_LIBRARY_PATH=/us...
Python executable not finding libpython shared library
7,880,454
78
2011-10-24T18:58:36Z
19,402,112
12
2013-10-16T11:24:02Z
[ "python" ]
I am installing Python 2.7 on CentOS 5. I built and installed Python as follows ``` ./configure --enable-shared --prefix=/usr/local make make install ``` When I try to run /usr/local/bin/python, I get this error message ``` /usr/local/bin/python: error while loading shared libraries: libpython2.7.so.1.0: cannot open...
I had the same problem and I solved it this way: If you know where libpython resides at, I supposed it would be `/usr/local/lib/libpython2.7.so.1.0` in your case, you can just create a symbolic link to it: ``` sudo ln -s /usr/local/lib/libpython2.7.so.1.0 /usr/lib/libpython2.7.so.1.0 ``` Then try running `ldd` again...
Python executable not finding libpython shared library
7,880,454
78
2011-10-24T18:58:36Z
26,657,830
38
2014-10-30T16:03:15Z
[ "python" ]
I am installing Python 2.7 on CentOS 5. I built and installed Python as follows ``` ./configure --enable-shared --prefix=/usr/local make make install ``` When I try to run /usr/local/bin/python, I get this error message ``` /usr/local/bin/python: error while loading shared libraries: libpython2.7.so.1.0: cannot open...
Putting on my gravedigger hat... The best way I've found to address this is at compile time. Since you're the one setting prefix anyway might as well tell the executable explicitly where to find its shared libraries. Unlike OpenSSL and other software packages, Python doesn't give you nice configure directives to handl...
Using deferred objects inside Twisted applications
7,880,479
4
2011-10-24T19:00:23Z
7,882,582
12
2011-10-24T22:10:10Z
[ "python", "twisted" ]
I feel like I am not understanding some things in writing Twisted applications (.tac files). Using deferred objects in .py scripts is easy by just calling `reactor.run()` at the end, but I have not seen `reactor.run()` used in any twisted application sample code. Can someone explain: 1. why `reactor.run()` is not cal...
# 1. Why is `reactor.run()` not called in example `.tac` files? `.tac` files are meant to be loaded by the "`twistd`" command-line tool, which runs the reactor for you. Running the reactor is something that's done once, by whatever bit of code is serving as the main-point for your program. Most Twisted code is effect...
Don't split double-quoted words with Python string split()?
7,881,794
8
2011-10-24T20:47:51Z
7,881,854
27
2011-10-24T20:53:08Z
[ "python", "string", "split" ]
When using the Python string function split(), does anybody have a nifty trick to treat items surrounded by double-quotes as a non-splitting word? Say I want to split only on white space and I have this: ``` >>> myStr = 'A B\t"C" DE "FE"\t\t"GH I JK L" "" ""\t"O P Q" R' >>> myStr.split() ['A', 'B', '"C"', 'DE', '"F...
You won't be able to get this behaviour with `str.split()`. If you can live with the rather complex parsing it does (like ignoring double quotes preceded by a back slash), [`shlex.split()`](http://docs.python.org/library/shlex.html) might be what you are looking for: ``` >>> shlex.split(myStr) ['A', 'B', 'C', 'DE', 'F...
matplotlib: how to change data points color based on some variable
7,881,994
26
2011-10-24T21:08:04Z
7,882,432
41
2011-10-24T21:51:22Z
[ "python", "matplotlib" ]
I have 2 variables (x,y) that change with time (t). I want to plot x vs. t and color the ticks based on the value of y. e.g. for highest values of y the tick color is dark green, for lowest value is dark red, and for intermediate values the color will be scaled in between green and red. Can this be done with matplotli...
This is what `matplotlib.pyplot.scatter` is for. As a quick example: ``` import matplotlib.pyplot as plt import numpy as np # Generate data... t = np.linspace(0, 2 * np.pi, 20) x = np.sin(t) y = np.cos(t) plt.scatter(t,x,c=y) plt.show() ``` ![enter image description here](http://i.stack.imgur.com/0SWWB.png)
What is the deal about https when using lxml?
7,882,673
10
2011-10-24T22:24:07Z
7,882,811
14
2011-10-24T22:40:01Z
[ "python", "parsing", "lxml" ]
I am using lxml to parse html files given urls. For example: ``` link = 'https://abc.com/def' htmltree = lxml.html.parse(link) ``` My code is working well for most of the cases, the ones with `http://`. However, I found for every `https://` url, lxml simply gets an *IOError*. Does anyone know the reason? And possibl...
I don't know what's happening, but I get the same errors. HTTPS is probably not supported. You can easily work around this with `urllib2`, though: ``` from lxml import html from urllib2 import urlopen html.parse(urlopen('https://duckduckgo.com')) ```
Alternative to eval in Python
7,882,987
4
2011-10-24T23:06:48Z
7,883,017
13
2011-10-24T23:11:31Z
[ "python", "eval" ]
Python `eval` is quite slow. I need to evaluate simple boolean expression with logical operators (like "True or False"). I am doing this for thousands of line of data and `eval` is a huge bottleneck in terms of performance. It's really slow.. Any alternative approaches? I tried creating a `dict` of possible expression...
``` import operator ops = { 'or': operator.or_, 'and': operator.and_ } print ops[op](True, False) ```
exporting from/importing to numpy, scipy in SQLite and HDF5 formats
7,883,646
11
2011-10-25T01:06:56Z
7,891,137
21
2011-10-25T14:48:53Z
[ "python", "sqlite", "numpy", "scipy", "hdf5" ]
There seems to be many choices for Python to interface with SQLite (sqlite3, atpy) and HDF5 (h5py, pyTables) -- I wonder if anyone has experience using these together with numpy arrays or data tables (structured/record arrays), and which of these most seamlessly integrate with "scientific" modules (numpy, scipy) for ea...
Most of it depends on your use case. I have a lot more experience dealing with the various HDF5-based methods than traditional relational databases, so I can't comment too much on SQLite libraries for python... At least as far as `h5py` vs `pyTables`, they both offer very seamless access via numpy arrays, but they're...
Where to use yield in Python best?
7,883,962
14
2011-10-25T02:11:36Z
7,883,987
38
2011-10-25T02:17:48Z
[ "python", "yield" ]
I know how `yield` works. I know permutation, think it just as a math simplicity. But what's `yield`'s true force? When should I use it? A simple and good example is better.
`yield` is best used when you have a function that returns a sequence and you want to iterate over that sequence, but you do not need to have every value in memory at once. For example, I have a python script that parses a large list of CSV files, and I want to return each line to be processed in another function. I d...
Where to use yield in Python best?
7,883,962
14
2011-10-25T02:11:36Z
7,884,206
10
2011-10-25T02:55:25Z
[ "python", "yield" ]
I know how `yield` works. I know permutation, think it just as a math simplicity. But what's `yield`'s true force? When should I use it? A simple and good example is better.
Simply put, `yield` gives you a generator. You'd use it where you would normally use a `return` in a function. As a really contrived example cut and pasted from a prompt... ``` >>> def get_odd_numbers(i): ... return range(1, i, 2) ... >>> def yield_odd_numbers(i): ... for x in range(1, i, 2): ... ...
ForeignKey to abstract class (generic relations)
7,884,359
14
2011-10-25T03:27:43Z
7,884,634
12
2011-10-25T04:14:28Z
[ "python", "django", "model-view-controller", "model" ]
I'm building a personal project with Django, to train myself (because I love Django, but I miss skills). I have the basic requirements, I know Python, I carefully read the Django book twice if not thrice. My goal is to create a simple monitoring service, with a Django-based web interface allowing me to check status of...
For a start, use Django's [multi-table inheritance](https://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance), rather than the abstract model you have currently. Your code would then become: ``` from django.db import models class Service(models.Model): port = models.PositiveIntegerField() ...
Can a Django model field's default value be defined by a function dependent on a foreign parent model?
7,884,376
7
2011-10-25T03:29:22Z
7,884,820
7
2011-10-25T04:48:23Z
[ "python", "django", "django-models" ]
I'm trying to have the default value of `Report`'s fee be based on a parent model's attributes. I don't want to do this in `save()`, because the field needs to be presented to the user if they choose to override the value before saving. Here are the three methods I've tried, in addition to passing only function pointe...
Your last example could potentially work with some work: 1. First all, you need to `__init__` on your class, not `models.Model` 2. You need to set your attribute *after* the model has been initialized 3. You need check if the model has been saved, or else your model will revert to the overridable fee every time you lo...
Bundling GTK resources with py2exe
7,884,959
11
2011-10-25T05:11:54Z
7,911,072
9
2011-10-27T02:21:44Z
[ "python", "pygtk", "py2exe" ]
I'm using Python 2.6 and PyGTK 2.22.6 from the [all-in-one installer](http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/2.24/) on Windows XP, trying to build a single-file executable (via [py2exe](http://www.py2exe.org/)) for my app. My problem is that when I run my app as a script (ie. not built into an `.exe` file...
Answering my own question here, but if anyone knows better feel free to answer too. Some of it seems quite fragile (eg. version numbers in paths), so comment or edit if you know a better way. # 1. Finding the files Firstly, I use this code to actually find the root of the GTK runtime. This is very specific to how you...
Python code generator
7,885,254
22
2011-10-25T05:59:47Z
7,886,125
15
2011-10-25T07:41:29Z
[ "python", "code-generation", "abstract-syntax-tree" ]
I want to be able to perform code generation of python given an AST description. I've done static analysis of C and built AST visitors in python, so I feel relatively comfortable manipulating a syntax tree, but I've never attempted code generation before and am trying to determine the best practice for generating pyth...
You may want to take a look at the `2to3` tool, developed by the Python code devs to automatically convert Python 2 code to Python 3 code. The tool first parses the code to a tree, and then spits out "fixed" Python 3 code from that tree. This may be a good place to start because this is an "official" Python tool endor...
defaultdict(None)
7,886,355
19
2011-10-25T08:04:24Z
7,886,386
35
2011-10-25T08:08:02Z
[ "python" ]
I wish to have a dictionary which contains a set of state transitions. I presumed that I could do this using states = defaultdict(None), but its not working as I expected. For example: ``` states = defaultdict(None) if new_state_1 != states["State 1"]: dispatch_transition() ``` I would have thought that states["S...
`defaultdict` requires a callable as argument that provides the default-value when invoked without arguments. `None` is not callable. What you want is this: ``` defaultdict(lambda: None) ```
defaultdict(None)
7,886,355
19
2011-10-25T08:04:24Z
7,886,488
8
2011-10-25T08:18:29Z
[ "python" ]
I wish to have a dictionary which contains a set of state transitions. I presumed that I could do this using states = defaultdict(None), but its not working as I expected. For example: ``` states = defaultdict(None) if new_state_1 != states["State 1"]: dispatch_transition() ``` I would have thought that states["S...
In this use case, don't use `defaultdict` at all -- a plain `dict` will do just fine: ``` states = {} if new_state_1 != states.get("State 1"): dispatch_transition() ``` The `dict.get()` method returns the value for a given key, or a default value if the key is not found. The default value defaults to `None`.
creating new python objects seems to be the same object
7,887,193
3
2011-10-25T09:23:28Z
7,887,210
10
2011-10-25T09:24:55Z
[ "python" ]
I have a problem with objects. The following code ``` class Data: def __init__(self,data=[]): self.data = data def add(self,data): self.data.extend(data) class Parent: def testa(self): a = Data() a.add('a') print a.data def testb(self): b = Data() ...
Using `[]` as a default argument to a function will only create a list once, and reuse this list on each call. See <http://docs.python.org/tutorial/controlflow.html#default-argument-values> for an explanation. Thus, both `Data` objects share the list referenced by their `self.data` member! You should modify your code ...
Calculate number of days between two dates inside Django templates
7,887,897
5
2011-10-25T10:29:04Z
7,887,958
10
2011-10-25T10:34:32Z
[ "python", "django" ]
I have two dates and want to show a message like "n days left before your trial end." where `n` is a number of days between two given dates. Is that better to do this inside views or is there a quick way to do it inside template itself?
Use [timesince](https://docs.djangoproject.com/en/dev/ref/templates/builtins/#timesince) template tag.
Trigger in sqlachemy
7,888,846
8
2011-10-25T11:52:14Z
7,890,829
9
2011-10-25T14:26:18Z
[ "python", "triggers", "sqlalchemy" ]
I have two tables related via a foreign key, here they are using Declarative Mapping ``` class Task(DeclarativeBase): __tablename__ = 'task' id = Column(Integer, primary_key=True) state = Column(Integer, default=0) obs_id = Column(Integer, ForeignKey('obs.id'), nullable=False) class Obs(DeclarativeBas...
You can create trigger in the database with [DDL class](http://www.sqlalchemy.org/docs/core/schema.html#sqlalchemy.schema.DDL): ``` update_task_state = DDL('''\ CREATE TRIGGER update_task_state UPDATE OF state ON obs BEGIN UPDATE task SET state = 2 WHERE (obs_id = old.id) and (new.state = 2); END;''') event.li...
How to remove all items from many-to-many collection in SqlAlchemy?
7,888,900
6
2011-10-25T11:56:26Z
7,889,079
17
2011-10-25T12:12:35Z
[ "python", "many-to-many", "sqlalchemy" ]
when I need to remove an object from declarative ORM many-to-many relationship, I am supposed to do this: ``` blogpost.tags.remove(tag) ``` Well. What am I supposed to do if I need to purge all these relations (not only one)? Typical situation: I'd like to set a new list of tags to my blogpost. So I need to...: 1. *...
This is the standard Python idiom for clearing a list – assigning to the “entire list” slice: ``` blogpost.tags[:] = [] ``` Instead of the empty list, you may want assign the new set of tags directly. ``` blogpost.tags[:] = new_tags ``` --- SQLAlchemy's relations are [instrumented attributes](http://www.sqla...
Guaranteeing a file close
7,888,953
5
2011-10-25T12:00:46Z
7,889,014
11
2011-10-25T12:06:07Z
[ "python" ]
I have a class where I create a file object in the constructor. This class also implements a finish() method as part of its interface and in this method I close the file object. The problem is that if I get an exception before this point, the file will not be closed. The class in question has a number of other methods ...
You could make your class a context-manager, and then wrap object creation and use of that class in a `with`-statement. See [PEP 343](http://www.python.org/dev/peps/pep-0343/) for details. To make your class a context-manager, it has to implement the methods `__enter__()` and `__exit__()`. `__enter__()` is called when...
SQLAlchemy insert or update example
7,889,183
9
2011-10-25T12:21:29Z
18,244,144
17
2013-08-14T23:45:52Z
[ "python", "sqlalchemy" ]
In Python, using SQLAlchemy, I want to insert or update a row. I tried this: ``` existing = db.session.query(Toner) for row in data: new = Toner(row[0], row[1], row[2]) ``` It does not work. How do I INSERT or UPDATE `new` into `Toner` table? I suspect it's done with merge, but I cannot understand how to do that.
assuming certain column names... **INSERT one** ``` newToner = Toner(toner_id = 1, toner_color = 'blue', toner_hex = '#0F85FF') dbsession.add(newToner) dbsession.flush() ``` **INSERT multiple** ``` newToner1 = Toner(toner_id = 1, toner_color = 'blue', ...
python - list last index
7,889,820
8
2011-10-25T13:15:49Z
7,890,373
8
2011-10-25T13:55:39Z
[ "python", "list", "indexing" ]
``` list1 = [1, 2, 33, 51] ``` I need to check is 4 the last index of the list. just like `list1.lastIndex() #=> 3` how can I do it in python?
`len(list1)-1` is definitely the way to go, but if you absolutely need a `list` that has a function that returns the last index, you could create a class that inherits from `list`. ``` class MyList(list): def last_index(self): return len(self)-1 >>> l=MyList([1, 2, 33, 51]) >>> l.last_index() 3 ```
How to pass extra arguments to callback register functions with twisted python api?
7,891,062
5
2011-10-25T14:43:36Z
7,891,302
11
2011-10-25T14:58:38Z
[ "python", "twisted" ]
I have the following python code using the twisted API. ``` def function(self,filename): def results(result): //do something for i in range(int(numbers)) : name = something that has to do with the value of i df = function_which_returns_a defer(name) df.addCallback(re...
You can pass extra arguments to a `Deferred` callback at the `Deferred.addCallback` call site by simply passing those arguments to `Deferred.addCallback`: ``` def function(self,filename): def results(result, name): # do something for i in range(int(numbers)) : name = something that has to do...
Why does setattr fail on a bound method
7,891,277
11
2011-10-25T14:56:51Z
7,891,681
23
2011-10-25T15:26:53Z
[ "python", "methods", "python-3.x", "setattr" ]
In the following, `setattr` succeeds in the first invocation, but fails in the second, with: ``` AttributeError: 'method' object has no attribute 'i' ``` Why is this, and is there a way of setting an attribute on a method such that it will only exist on one instance, not for each instance of the class? ``` class c: ...
The short answer: There is no way of adding custom attributes to bound methods. The long answer follows. In Python, there are *function objects* and *method objects*. When you define a class, the `def` statement creates a *function object* that lives within the class' namespace: ``` >>> class c: ... def m(self):...
Numpy Adding two vectors with different sizes
7,891,697
12
2011-10-25T15:28:03Z
7,891,889
13
2011-10-25T15:40:45Z
[ "python", "numpy", "linear-algebra" ]
If I have two numpy arrays of different sizes, how can I superimpose them. ``` a = numpy([0, 10, 20, 30]) b = numpy([20, 30, 40, 50, 60, 70]) ``` What is the cleanest way to add these two vectors to produce a new vector (20, 40, 60, 80, 60, 70)? This is my generic question. For background, I am specifically applying...
This could be what you are looking for ``` if len(a) < len(b): c = b.copy() c[:len(a)] += a else: c = a.copy() c[:len(b)] += b ``` basically you copy the longer one and then add in-place the shorter one
subtree with networkX
7,892,144
2
2011-10-25T16:00:44Z
7,893,497
7
2011-10-25T17:45:16Z
[ "python", "tree", "networkx", "subtree" ]
In networkX, I have a tree as DiGraph(). ``` #!/usr/bin/python # -*- coding: utf-8 -*- import networkx as nx t = nx.DiGraph() t.add_edge(1,'r') t.add_edge(2,'r') t.add_edge(3,'r') t.add_edge(4,2) t.add_edge(5,2) t.add_edge(6,5) print t.edges() ``` If a take the node 2 of tree. how I can get the subtree of 2 ? ### ...
If you mean the subtree rooted at node `2`, that's ``` from networkx.algorithms.traversal.depth_first_search import dfs_tree subtree_at_2 = dfs_tree(t, 2) ``` **Edit**: it seems you've reversed the order of nodes in your edges. In a directed tree, all paths proceed from the root to a leaf, not the other way around. ...
Sqlalchemy delete subquery
7,892,618
19
2011-10-25T16:35:52Z
7,954,618
38
2011-10-31T13:50:47Z
[ "python", "sqlalchemy" ]
I am trying to delete some child rows using a filtered query without result: ``` sl = DBSession.query(Puesto.id).filter(Puesto.locales_id == id).subquery() DBSession.query(Servicio).filter(Servicio.puestos_id.in_(sl)).delete() ``` I am getting `InvalidRequestError: Could not evaluate current criteria in Python. Speci...
After looking in the source where your exception occurs I suggest trying this: ``` sl = DBSession.query(Puesto.id).filter(Puesto.locales_id == id).subquery() DBSession.query(Servicio).filter(Servicio.puestos_id.in_(sl)) \ .delete(synchronize_session='fetch') ``` See the [documentation of the delete method](http://www...
How can I programmatically authenticate a user in Django?
7,893,451
12
2011-10-25T17:41:29Z
7,893,523
16
2011-10-25T17:47:10Z
[ "python", "django", "authentication" ]
How can I log-in the user programmatically in Django? I have the username and password of the User. Is there a method that let's me log him in?
There is no other way than "programmatically". Of course, this is [documented](https://docs.djangoproject.com/en/1.9/topics/auth/default/#how-to-log-a-user-in). ``` from django.contrib.auth import authenticate, login user = authenticate(username = username, password = password) if user is not None: login(request, ...
Python: Get URL path sections
7,894,384
16
2011-10-25T18:57:00Z
7,894,483
14
2011-10-25T19:06:28Z
[ "python", "url" ]
How do I get specific path sections from a url? For example, I want a function which operates on this: ``` http://www.mydomain.com/hithere?image=2934 ``` and returns "hithere" or operates on this: ``` http://www.mydomain.com/hithere/something/else ``` and returns the same thing ("hithere") I know this will probab...
Extract the path component of the URL with [urlparse](https://docs.python.org/2/library/urlparse.html): ``` >>> import urlparse >>> path = urlparse.urlparse('http://www.example.com/hithere/something/else').path >>> path '/hithere/something/else' ``` Split the path into components with [os.path](http://docs.python.org...
Python: Get URL path sections
7,894,384
16
2011-10-25T18:57:00Z
25,496,309
7
2014-08-26T00:33:03Z
[ "python", "url" ]
How do I get specific path sections from a url? For example, I want a function which operates on this: ``` http://www.mydomain.com/hithere?image=2934 ``` and returns "hithere" or operates on this: ``` http://www.mydomain.com/hithere/something/else ``` and returns the same thing ("hithere") I know this will probab...
The best option is to use the [`posixpath`](https://docs.python.org/3/library/undoc.html) module when working with the path component of URLs. This module has the same interface as [`os.path`](https://docs.python.org/3/library/os.path.html#module-os.path) and consistently operates on POSIX paths when used on POSIX and ...
How to loop through files and rename them in Python
7,894,472
5
2011-10-25T19:05:46Z
7,894,533
7
2011-10-25T19:10:51Z
[ "python", "filesystems", "directory-traversal" ]
I have a directory of music that has album folders as well as individual songs on each level. How can I traverse all of these files that also are encoded in different formats(mp3, wav etc)? In addition is there a way I can rename them to a format that is more consistent to my liking using regular expressions? Thanks
* `os.walk` to go over files in the directory and its sub-directories, recursively * `os.rename` to rename them The encoding of the files pays no role here, I think. You can, of course, detect their extension (use `os.path.splitext` for that) and do something based on it, but as long as you just need to rename files (...
Blog excerpt in Django
7,894,618
7
2011-10-25T19:18:12Z
7,894,695
14
2011-10-25T19:25:30Z
[ "python", "django", "blogs" ]
I am building a blog application in Django and when I display all the blogs I want to display a small blog excerpt with each entry. Can anybody tell me how can I do that? > One way to do that would be to make an extra field and store a fixed number of words for > each blog entry, let's say 20 words. But then that woul...
I suggest you use the [truncatewords](https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#truncatewords) template filter. Template example: ``` <ul> {% for blogpost in blogposts %} <li><b>{{blogpost.title}}</b>: {{blogpost.content|truncatewords:10}}</li> {% endfor %} </ul> ``` If the blog content is st...
Why doesn't the operator module have a function for logical or?
7,894,653
10
2011-10-25T19:21:40Z
7,894,701
7
2011-10-25T19:26:02Z
[ "python", "python-3.x", "bitwise-operators" ]
In Python 3, operator.or\_ is equivalent to the bitwise `|`, not the logical `or`. Why is there no operator for the logical `or`?
The logical or is a *control structure* - it decides whether code is being executed. Consider ``` 1 or 1/0 ``` This does **not** throw an error. In contrast, the following **does** throw an error, no matter how the function is implemented: ``` def logical_or(a, b): return a or b logical_or(1, 1/0) ```
Why doesn't the operator module have a function for logical or?
7,894,653
10
2011-10-25T19:21:40Z
7,894,752
17
2011-10-25T19:30:09Z
[ "python", "python-3.x", "bitwise-operators" ]
In Python 3, operator.or\_ is equivalent to the bitwise `|`, not the logical `or`. Why is there no operator for the logical `or`?
The `or` and `and` operators can't be expressed as functions because of their [short-circuiting](http://en.wikipedia.org/wiki/Short-circuit_evaluation) behavior: ``` False and some_function() True or some_function() ``` in these cases, `some_function()` is never called. A hypothetical `or_(True, some_function())`, o...
Use numpy array in shared memory for multiprocessing
7,894,791
50
2011-10-25T19:34:31Z
7,907,787
7
2011-10-26T19:26:23Z
[ "python", "numpy", "multiprocessing", "shared" ]
I would like to use a numpy array in shared memory for use with the multiprocessing module. The difficulty is using it like a numpy array, and not just as a ctypes array. ``` from multiprocessing import Process, Array import scipy def f(a): a[0] = -a[0] if __name__ == '__main__': # Create the array N = i...
The `Array` object has a `get_obj()` method associated with it, which returns the ctypes array which presents a buffer interface. I think the following should work... ``` from multiprocessing import Process, Array import scipy import numpy def f(a): a[0] = -a[0] if __name__ == '__main__': # Create the array ...
Use numpy array in shared memory for multiprocessing
7,894,791
50
2011-10-25T19:34:31Z
7,908,612
46
2011-10-26T20:36:17Z
[ "python", "numpy", "multiprocessing", "shared" ]
I would like to use a numpy array in shared memory for use with the multiprocessing module. The difficulty is using it like a numpy array, and not just as a ctypes array. ``` from multiprocessing import Process, Array import scipy def f(a): a[0] = -a[0] if __name__ == '__main__': # Create the array N = i...
To add to @unutbu's (not available anymore) and @Henry Gomersall's answers. You could use `shared_arr.get_lock()` to synchronize access when needed: ``` shared_arr = mp.Array(ctypes.c_double, N) # ... def f(i): # could be anything numpy accepts as an index such another numpy array with shared_arr.get_lock(): # syn...
Use numpy array in shared memory for multiprocessing
7,894,791
50
2011-10-25T19:34:31Z
16,753,146
7
2013-05-25T19:27:16Z
[ "python", "numpy", "multiprocessing", "shared" ]
I would like to use a numpy array in shared memory for use with the multiprocessing module. The difficulty is using it like a numpy array, and not just as a ctypes array. ``` from multiprocessing import Process, Array import scipy def f(a): a[0] = -a[0] if __name__ == '__main__': # Create the array N = i...
You can use the `sharedmem` module: <https://bitbucket.org/cleemesser/numpy-sharedmem> Here's your original code then, this time using shared memory that behaves like a NumPy array (note the additional last statement calling a NumPy `sum()` function): ``` from multiprocessing import Process import sharedmem import sc...
"Line contains NULL byte" in CSV reader (Python)
7,894,856
23
2011-10-25T19:39:15Z
7,895,086
20
2011-10-25T19:58:44Z
[ "python", "csv" ]
I'm trying to write a program that looks at a .CSV file (input.csv) and rewrites only the rows that begin with a certain element (corrected.csv), as listed in a text file (output.txt). This is what my program looks like right now: ``` import csv lines = [] with open('output.txt','r') as f: for line in f.readline...
I'm guessing you have a NUL byte in input.csv. You can test that with ``` if '\0' in open('input.csv').read(): print "you have null bytes in your input file" else: print "you don't" ``` if you do, ``` reader = csv.reader(x.replace('\0', '') for x in mycsv) ``` may get you around that. Or it may indicate you...
"Line contains NULL byte" in CSV reader (Python)
7,894,856
23
2011-10-25T19:39:15Z
9,882,004
20
2012-03-27T01:01:39Z
[ "python", "csv" ]
I'm trying to write a program that looks at a .CSV file (input.csv) and rewrites only the rows that begin with a certain element (corrected.csv), as listed in a text file (output.txt). This is what my program looks like right now: ``` import csv lines = [] with open('output.txt','r') as f: for line in f.readline...
I've solved a similar problem with an easier solution: ``` import codecs csvReader = csv.reader(codecs.open('file.csv', 'rU', 'utf-16')) ``` The key was using the codecs module to open the file with the UTF-16 encoding, there are a lot more of encodings, check the [documentation](http://docs.python.org/library/codecs...
Can I access ImageMagick API with Python?
7,895,278
28
2011-10-25T20:12:33Z
11,658,182
46
2012-07-25T20:35:27Z
[ "python", "imagemagick", "image-manipulation", "ctypes" ]
I need to use [**ImageMagick**](http://www.imagemagick.org/script/index.php) as PIL does not have the amount of image functionality available that I am looking for. However, I am wanting to use Python. The python bindings (PythonMagick) have not been updated since 2009. The only thing I have been able to find is `os.s...
I would recommend using [Wand](http://dahlia.github.com/wand/index.html) (explanations follows). I was looking for proper binding to ImageMagick library, that would: * work error/problem free * be regularly maintained and up to date * allow nice objective Python But indeed python API (binding) has too many different...
Merging a list of lists
7,895,449
5
2011-10-25T20:28:09Z
7,895,542
8
2011-10-25T20:36:16Z
[ "python", "list", "merge" ]
How do I merge a list of lists? ``` [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']] ``` into ``` ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'] ``` Even better if I can add a value on the beginning and end of each item before merging the lists, like html tags. i.e., the end result would be: ``` ['<tr>A</tr>', ...
Don't use sum(), it is slow for joining lists. Instead a [nested list comprehension](http://docs.python.org/tutorial/datastructures.html#nested-list-comprehensions) will work: ``` >>> x = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']] >>> [elem for sublist in x for elem in sublist] ['A', 'B', 'C', 'D', 'E', 'F',...
Flask and Redis
7,896,077
20
2011-10-25T21:24:35Z
7,902,669
8
2011-10-26T12:38:21Z
[ "python", "design-patterns", "orm", "redis", "flask" ]
What is best way to interact with Redis in a Flask app? Do you just import Redis and ... ``` r = redis.Redis() r.connect() ``` or is there an ORM or something I haven't seen yet?
This snippet on using Redis for server side sessions with Flask should be helpful: <http://flask.pocoo.org/snippets/75/>
Flask and Redis
7,896,077
20
2011-10-25T21:24:35Z
7,904,137
15
2011-10-26T14:28:28Z
[ "python", "design-patterns", "orm", "redis", "flask" ]
What is best way to interact with Redis in a Flask app? Do you just import Redis and ... ``` r = redis.Redis() r.connect() ``` or is there an ORM or something I haven't seen yet?
The snippet in @keybits' answer is very useful, however, I found all the information I needed from the following: <http://flask.pocoo.org/snippets/71/>
Flask and Redis
7,896,077
20
2011-10-25T21:24:35Z
13,575,034
7
2012-11-26T23:36:21Z
[ "python", "design-patterns", "orm", "redis", "flask" ]
What is best way to interact with Redis in a Flask app? Do you just import Redis and ... ``` r = redis.Redis() r.connect() ``` or is there an ORM or something I haven't seen yet?
There is a lightweight Redis ODM available called Python stdnet: <http://lsbardel.github.com/python-stdnet/overview.html> Haven't tried it yet but looks good to me. Works with Python 2.6 to 3.3 according to the documentation.
multithreading/processing in Python
7,896,321
4
2011-10-25T21:50:02Z
7,896,383
7
2011-10-25T21:56:40Z
[ "python", "multithreading" ]
Hello I am trying define values of a dictionary in parallel using multiprocessing. When the function f() is called outside "pool" the dictionary value is set correctly. In the pool call however it fails. What am I doing wrong? Thanks. ``` from multiprocessing import Pool hits={} def f(x): hits[x] = x #this will...
You spawn a bunch of subprocesses which inherit the current value of `hits`. Each subprocess get its own copy of `hits` and modifies it, then exits, dropping the process-local copy of `hits`. The intended use of `multiprocessing.Pool.map()` is to use its return value, which you are ignoring. Each process could return ...
python: how to check if a line is an empty line
7,896,495
35
2011-10-25T22:08:42Z
7,896,514
7
2011-10-25T22:10:11Z
[ "python" ]
trying to figure out how to write an if cycle to check if a line is empty. The file has many strings, and one of these is a blank line to separate from the other statements (not a ""; is a carriage return followed by another carriage return i think) ``` new statement asdasdasd asdasdasdasd new statement asdasdasdasd...
``` line.strip() == '' ``` Or, if you don't want to "eat up" lines consisting of spaces: ``` line in ('\n', '\r\n') ```
python: how to check if a line is an empty line
7,896,495
35
2011-10-25T22:08:42Z
7,896,585
47
2011-10-25T22:19:37Z
[ "python" ]
trying to figure out how to write an if cycle to check if a line is empty. The file has many strings, and one of these is a blank line to separate from the other statements (not a ""; is a carriage return followed by another carriage return i think) ``` new statement asdasdasd asdasdasdasd new statement asdasdasdasd...
If you want to ignore lines with only whitespace: ``` if not line.strip(): ... do something ``` The empty string is a False value. Or if you really want only empty lines: ``` if line in ['\n', '\r\n']: ... do something ```
Numpy vectorization algorithms to find first future element greater than current element
7,896,812
4
2011-10-25T22:52:31Z
7,896,926
9
2011-10-25T23:11:45Z
[ "python", "numpy", "vectorization" ]
I have a time series A. I want to generate another time series B, such that B[i] = j, where j is the first index greater than i such that A[j] > A[i]. is there a fast way of doing this in numpy? Thanks. [EDITED]: preferably use only O(n) of space.
Insufficiently tested, use at own risk. ``` import numpy a = numpy.random.random(100) # a_by_a[i,j] = a[i] > a[j] a_by_a = a[numpy.newaxis,:] > a[:,numpy.newaxis] # by taking the upper triangular, we ignore all cases where i < j a_by_a = numpy.triu(a_by_a) # argmax will give the first index with the highest value (1...
Python function syntax seems to be invalid, but runs
7,897,715
3
2011-10-26T01:18:33Z
7,897,733
11
2011-10-26T01:21:21Z
[ "python", "syntax", "memory-leaks" ]
All, I've run across a weird surprise in python today. The following code works, but seems to violate python's syntax. I don't know why it would work without a pass statement, or some code, but it does. ``` def test(): '''Sample docstring.''' for i in range(10): test() print "testing", i ``` I'd like to ...
There must be at least one statement in a block. A lone string literal is considered a valid statement, even if it is being used as the docstring. It should not cause any memory leaks though, since the compiler omits it in the actual code.
"Boilerplate" code in Python?
7,898,049
17
2011-10-26T02:14:38Z
7,898,069
13
2011-10-26T02:18:39Z
[ "python", "boilerplate" ]
Google has a Python tutorial, and they describe boilerplate code as "unfortunate" and provide this example: ``` #!/usr/bin/python # import modules used here -- sys is a very standard one import sys # Gather our code in a main() function def main(): print 'Hello there', sys.argv[1] # Command line args are in sys....
1. It is repetitive in the sense that it's repeated for each script that you might execute from the command line. 2. If you put your main code in a function like this, you can import the module without executing it. This is sometimes useful. It also keeps things organized a bit more. 3. Same as #2 as far as I can tell ...
Is there a Python library (or pattern) like Ruby's andand?
7,898,688
6
2011-10-26T04:18:30Z
7,898,765
9
2011-10-26T04:36:33Z
[ "python", "ruby", null, "andand" ]
For example, I have an object `x` that might be `None` or a string representation of a float. I want to do the following: ``` do_stuff_with(float(x) if x else None) ``` Except without having to type `x` twice, as with Ruby's [andand](http://andand.rubyforge.org/) library: ``` require 'andand' do_stuff_with(x.andand....
We don't have one of those but it isn't hard to roll your own: ``` def andand(x, func): return func(x) if x else None >>> x = '10.25' >>> andand(x, float) 10.25 >>> x = None >>> andand(x, float) is None True ```
How do I access the name of a given variable in python?
7,898,831
3
2011-10-26T04:50:26Z
7,898,899
8
2011-10-26T05:06:58Z
[ "python", "object" ]
I am programming in python and need to access the name I have given to an object so as to be able to pass this as a string (concatenated with another string). The reason I need to do this is that the program I am using forces me to create a global (which in my case is a dictionary) and I am writing a function to work ...
Your could do a reverse lookup of the names in globals(): ``` >>> NAME1 = 4 >>> def name_of(value): for k, v in globals().items(): if v is value: return k raise KeyError('did not find a name for %s' % value) >>> name_of(NAME1) 'NAME1' ``` If the same object has been assign...
2D Sorting with NumPy - sort 1 row and have the other follow the sorting
7,900,171
6
2011-10-26T08:11:58Z
7,901,924
12
2011-10-26T11:23:43Z
[ "python", "sorting", "numpy", "scipy" ]
Say I have a NumPy array: ``` [[4 9 2] [5 1 3]] ``` I want to sort the bottom row of this array, but have the top row follow the sorting, such that I get: ``` [[9 2 4] [1 3 5]] ``` I know that you can sort like this using the sorted() function, but that requires input and output of lists. Any ideas? Thanks so mu...
``` import numpy as np a = np.array([[4,9,2],[5,1,3]]) idx = np.argsort(a[1]) ``` Now you can use idx to index your array: ``` b=a[:,idx] ```
Python libraries for integrating Django with Facebook
7,900,313
7
2011-10-26T08:27:31Z
7,914,418
9
2011-10-27T10:06:15Z
[ "python", "django", "facebook", "facebook-graph-api" ]
I decide to write some applications using facebook and django (or even twisted, but it doesn't matter), and now I can't choose appropriate tools. I see there are many API-wrappers writed on Python exists for Facebook: * official, but seems no longer supported [Python-SDK](https://github.com/facebook/python-sdk) * new ...
I think Django Facebook is a good choice for you. But my opinion is biased. I've written it for my startup Fashiolista.com and we run it in production. (Quite huge, so most edge cases have been resolved) Django Facebook also include OpenFacebook, which is a python api client to the open graph protocol. It's the only p...
Can a Python method check if it has been called from within itself?
7,900,345
6
2011-10-26T08:31:49Z
7,900,380
11
2011-10-26T08:35:26Z
[ "python", "recursion", "introspection", "inspect" ]
Let's say I have a Python function `f` and `fhelp`. `fhelp` is designed to call itself recursively. `f` should not be called recursively. Is there a way for `f` to determine if it has been called recursively?
Use the [traceback](http://docs.python.org/library/traceback.html) module for this: ``` >>> import traceback >>> def f(depth=0): ... print depth, traceback.print_stack() ... if depth < 2: ... f(depth + 1) ... >>> f() 0 File "<stdin>", line 1, in <module> File "<stdin>", line 2, in f None 1 File "<...
extract item from list of dictionaries
7,900,882
4
2011-10-26T09:29:23Z
7,900,909
11
2011-10-26T09:32:02Z
[ "python" ]
Suppose you have a list of dictionaries like this one: ``` a = [ {'name':'pippo', 'age':'5'} , {'name':'pluto', 'age':'7'} ] ``` What do you to extract from this list only the dict where name==pluto? To make things a little bit harder, consider that I cannot do any import
List comprehension is ideal for this: ``` [d for d in a if d['name'] == 'pluto'] ```
extract item from list of dictionaries
7,900,882
4
2011-10-26T09:29:23Z
7,901,008
7
2011-10-26T09:41:59Z
[ "python" ]
Suppose you have a list of dictionaries like this one: ``` a = [ {'name':'pippo', 'age':'5'} , {'name':'pluto', 'age':'7'} ] ``` What do you to extract from this list only the dict where name==pluto? To make things a little bit harder, consider that I cannot do any import
Apart from list comprehension that other responses give it to you, you can also do it with a filter and a lambda: ``` filter(lambda x: x.get('name') == 'pluto',a) ```
Read write classes to files in an efficent way
7,900,944
2
2011-10-26T09:35:14Z
7,900,963
7
2011-10-26T09:37:34Z
[ "python", "file", "io" ]
I have want to save classes to a file in python. I want something like this, I have a similar class in python, like this C++ struct: ``` struct WebSites { char SiteName[100]; int Rank; }; ``` and I want to write something like this: ``` void write_to_binary_file(WebSites p_Data) { ...
Python has the [`pickle`](http://docs.python.org/library/pickle.html)-module that can be used to serialize objects. If you use a protocol version >= 1, the data is serialized to a binary format. You can use pickle like this: ``` class WebSites(object): def __init__(): self.SiteName = "" self.Rank =...
java's printStackTrace() equivalent in python
7,901,238
22
2011-10-26T10:05:53Z
7,901,244
32
2011-10-26T10:07:20Z
[ "java", "python" ]
In python except block, I want to print the error message but I don't want the program to stop executing, I understand that I have to do something like this ``` try: 1/0 except: print errorMessage ``` In the except part, I am looking to put something like java's `printStackTrace()`
Take a look at [`traceback.print_exc()`](http://docs.python.org/library/traceback.html#traceback.print_exc) and the rest of the [`traceback`](http://docs.python.org/library/traceback.html) module. ``` import traceback try: 1/0 except: print '>>> traceback <<<' traceback.print_exc() print '>>> end of t...