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
Django Admin: Using a custom widget for only one model field
4,176,613
41
2010-11-14T07:36:36Z
4,190,604
22
2010-11-16T02:09:50Z
[ "python", "django", "django-forms", "django-admin", "django-widget" ]
I have a [DateTimeField](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.DateTimeField) field in my model. I wanted to display it as a checkbox widget in the Django admin site. To do this, I created a custom form widget. However, I do not know how to use my custom widget for **only** this one ...
After digging into the [admin](http://code.djangoproject.com/browser/django/trunk/django/contrib/admin), [model field](http://code.djangoproject.com/browser/django/trunk/django/db/models/fields/__init__.py) and [form field](http://code.djangoproject.com/browser/django/trunk/django/forms/fields.py) code, I believe the o...
Django Admin: Using a custom widget for only one model field
4,176,613
41
2010-11-14T07:36:36Z
5,263,578
98
2011-03-10T17:42:13Z
[ "python", "django", "django-forms", "django-admin", "django-widget" ]
I have a [DateTimeField](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.DateTimeField) field in my model. I wanted to display it as a checkbox widget in the Django admin site. To do this, I created a custom form widget. However, I do not know how to use my custom widget for **only** this one ...
Create a custom ModelForm for your ModelAdmin and add 'widgets' to its Meta class, like so: ``` class StopAdminForm(forms.ModelForm): class Meta: model = Stop widgets = { 'approve_ts': ApproveStopWidget(), } fields = '__all__' class StopAdmin(admin.ModelAdmin): form = StopAdminForm ``` Done...
Is `extend` faster than `+=`?
4,176,980
9
2010-11-14T09:47:50Z
4,177,026
15
2010-11-14T10:02:46Z
[ "python", "performance", "list" ]
In python, we can concatenate lists in two ways: 1. lst.extend(another\_lst) 2. lst += another\_lst I thought `extend` would be faster than using `+=`, because it reuses the list instead of creating a new one using the other two. But when I test it out with `timeit`, it turns out that `+=` is faster, ``` >>> timeit...
EDIT: I've tested the performance and I can't replicate the differences to any significant level. --- Here's the bytecode -- thanks to @John Machin for pointing out inconsistencies. ``` >>> import dis >>> l = [1,2,3] >>> m = [4,5,6] >>> def f1(l, m): ... l.extend(m) ... >>> def f2(l,m): ... l += m ... >>> di...
Best practice for lazy loading Python modules
4,177,735
21
2010-11-14T13:47:21Z
4,177,777
14
2010-11-14T13:54:58Z
[ "python", "coding-style" ]
Occasionally I want lazy module loading in Python. Usually because I want to keep runtime requirements or start-up times low and splitting the code into sub-modules would be cumbersome. A typical use case and my currently preferred implementation is this: ``` jinja2 = None class Handler(...): ... def render_w...
``` class Handler(...): ... def render_with_jinja2(self, values, template_name): import jinja2 env = jinja2.Environment(...) ... ``` There's no need to cache the imported module; Python does that already.
Best practice for lazy loading Python modules
4,177,735
21
2010-11-14T13:47:21Z
4,177,780
35
2010-11-14T13:55:13Z
[ "python", "coding-style" ]
Occasionally I want lazy module loading in Python. Usually because I want to keep runtime requirements or start-up times low and splitting the code into sub-modules would be cumbersome. A typical use case and my currently preferred implementation is this: ``` jinja2 = None class Handler(...): ... def render_w...
There's no reason for you to keep track of imports manually -- the VM maintains a list of modules that have already been imported, and any subsequent attempts to import that module result in a quick dict lookup in sys.modules and nothing else. The difference between your code and ``` def render_with_jinja2(self, valu...
Best practice for lazy loading Python modules
4,177,735
21
2010-11-14T13:47:21Z
4,177,812
7
2010-11-14T14:02:34Z
[ "python", "coding-style" ]
Occasionally I want lazy module loading in Python. Usually because I want to keep runtime requirements or start-up times low and splitting the code into sub-modules would be cumbersome. A typical use case and my currently preferred implementation is this: ``` jinja2 = None class Handler(...): ... def render_w...
The other answers have covered the actual details but if you *are* interested in a lazy loading library, check out [apipkg](http://pypi.python.org/pypi/apipkg) which is part of the `py` package (`py.test` fame).
Infinitely Nested Dictionary in Python
4,178,249
9
2010-11-14T15:52:10Z
4,178,334
11
2010-11-14T16:09:09Z
[ "python", "dictionary", "nested" ]
Does anyone know if there's a standard class for an infinitely nestable dictionary in Python? I'm finding myself repeating this pattern: ``` d = defaultdict(lambda: defaultdict(lambda: defaultdict(int))) d['abc']['def']['xyz'] += 1 ``` If I want to add "another layer" (e.g. `d['abc']['def']['xyz']['wrt']`), I have t...
This lends itself naturally to a recursive definition. ``` >>> import collections >>> def nested_dd(): ... return collections.defaultdict(nested_dd) ... >>> foo = nested_dd() >>> foo defaultdict(<function nested_dd at 0x023F0E30>, {}) >>> foo[1][2]=3 >>> foo[1] defaultdict(<function nested_dd at 0x023F0E30>, {2: 3...
Infinitely Nested Dictionary in Python
4,178,249
9
2010-11-14T15:52:10Z
4,178,355
10
2010-11-14T16:13:35Z
[ "python", "dictionary", "nested" ]
Does anyone know if there's a standard class for an infinitely nestable dictionary in Python? I'm finding myself repeating this pattern: ``` d = defaultdict(lambda: defaultdict(lambda: defaultdict(int))) d['abc']['def']['xyz'] += 1 ``` If I want to add "another layer" (e.g. `d['abc']['def']['xyz']['wrt']`), I have t...
You can derive from `defaultdict` to get the behavior you want: ``` class InfiniteDict(defaultdict): def __init__(self): defaultdict.__init__(self, self.__class__) class Counters(InfiniteDict): def __init__(self): InfiniteDict.__init__(self) self....
Suppressing output of module calling outside library
4,178,614
4
2010-11-14T17:14:16Z
4,178,672
8
2010-11-14T17:27:10Z
[ "python", "libsvm", "pyml" ]
I have an annoying problem when using machine learning library [PyML](http://pyml.sourceforge.net). PyML uses [libsvm](http://www.csie.ntu.edu.tw/~cjlin/libsvm/) to train the SVM classifier. The problem is that libsvm outputs some text to standard output. But because that is outside of Python I cannot intercept it. I t...
Open `/dev/null` for writing, use `os.dup()` to copy stdout, and use `os.dup2()` to copy your open `/dev/null` to stdout. Use `os.dup2()` to copy your copied stdout back to the real stdout after. ``` devnull = open('/dev/null', 'w') oldstdout_fno = os.dup(sys.stdout.fileno()) os.dup2(devnull.fileno(), 1) makesomenoise...
random.randint error
4,178,648
10
2010-11-14T17:21:10Z
4,178,657
23
2010-11-14T17:24:44Z
[ "python", "python-2.x" ]
I have some code that looks something like this: ``` import random n = 0 while n <= 50: n = n+1 a = random.randint(1, 16) b = random.randint(1, 5) print n, ". ", a, "-", b, "= " ``` For some reason, when running it, I get the following error: `AttributeError: 'module' object has no attribute 'randint'`. Howe...
You have another module called "random" somewhere. Did you name your script "random.py"?
Python Named Argument is Keyword?
4,179,175
3
2010-11-14T19:21:54Z
4,179,187
10
2010-11-14T19:23:57Z
[ "python", "keyword", "named-parameters", "reserved-words" ]
So an optional parameter expected in the web POST request of an API I'm using is actually a reserved word in python too. So how do I name the param in my method call: ``` example.webrequest(x=1,y=1,z=1,from=1) ``` this fails with a syntax error due to 'from' being a keyword. How can I pass this in in such a way that ...
Pass it as a dict. ``` func(**{'as': 'foo', 'from': 'bar'}) ```
python "incrementing" a character string?
4,179,176
3
2010-11-14T19:21:58Z
4,179,181
12
2010-11-14T19:22:53Z
[ "java", "python", "character" ]
I know in java, if you have a char variable, you could do the following: ``` char a = 'a' a = a + 1 System.out.println(a) ``` This would print 'b'. I don't know the exact name of what this is, but is there any way to do this in python?
You could use ord and chr : ``` print(chr(ord('a')+1)) # b ``` More information about [ord](http://docs.python.org/library/functions.html#ord) and [chr](http://docs.python.org/library/functions.html#chr).
How to enable/disable toolbar items?
4,179,910
7
2010-11-14T21:52:41Z
4,180,745
13
2010-11-15T01:25:50Z
[ "python", "gtk", "pygtk", "toolbar" ]
How do you make a gtk.ToolButton disabled so that it is 'greyed out'? Like this: ![alt text](http://i.stack.imgur.com/XDObt.png) How do you make it enabled again?
Use the `set_sensitive` method. If all you need is to disable/enable the button, you should call the method on the button; the argument should be `True` for enabling and `False` for disabling: ``` button.set_sensitive(True) # enables the button button.set_sensitive(False) # disables the button ``` If you are dea...
Execute remote python script via SSH
4,180,390
11
2010-11-14T23:40:02Z
4,180,405
16
2010-11-14T23:43:17Z
[ "python", "ssh" ]
I want to execute a Python script on several (15+) remote machine using SSH. After invoking the script/command I need to disconnect ssh session and keep the processes running in background for as long as they are required to. I have used Paramiko and PySSH in past so have no problems using them again. Only thing I nee...
This might work, or something similar: ``` ssh user@remote.host nohup python scriptname.py & ``` Basically, have a look at the [`nohup`](http://en.wikipedia.org/wiki/Nohup) command.
Using Cython for game development?
4,180,836
11
2010-11-15T01:46:21Z
4,180,882
15
2010-11-15T02:02:52Z
[ "python", "c", "cython" ]
**How practical would it be to use Cython as the primary programming language for a game?** I am a experienced Python programmer and I absolutely love it, but I'm admittedly a novice when it comes to game programming specifically. I know that typically Python is considered too slow to do any serious game programming, ...
If you're working with a combination like that and your goal is to write a 3D game, you'd probably get better mileage out of a ready-made 3D engine with mature physics and audio bindings and a Python API like [OGRE 3D](http://www.ogre3d.org/) ([Python-OGRE](http://www.python-ogre.org/)) or [Panda3D](http://panda3d.org/...
Formatting data quantity/capacity as string
4,180,980
3
2010-11-15T02:31:15Z
4,181,263
7
2010-11-15T03:51:24Z
[ "python", "c", "readability", "stringification" ]
A common task in many programs is converting a byte count (such as from a drive capacity or file size), into a more human readable form. Consider 150000000000 bytes as being more readable as "150 GB", or "139.7 GiB". Are there any libraries that contain functionality to perform these conversions? In Python? In C? In p...
Here's a method that uses logarithms to determine the file size unit exponent: ``` from math import log byteunits = ('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB') def filesizeformat(value): exponent = int(log(value, 1024)) return "%.1f %s" % (float(value) / pow(1024, exponent), byteunits[expon...
Making Matplotlib run faster
4,181,294
5
2010-11-15T04:01:59Z
4,182,219
13
2010-11-15T07:17:47Z
[ "python", "tkinter", "matplotlib" ]
Snippet: ``` ax = Axes3D(self.fig) u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = self.prop * np.outer(np.cos(u), np.sin(v)) y = self.prop * np.outer(np.sin(u), np.sin(v)) z = self.prop * np.outer(np.ones(np.size(u)), np.cos(v)) t = ax.plot_surface(x, y, z, rstride=6, cstride=6,color='lightgr...
Really, the problem is more within `plot_surface`. There are a lot of things that can be done to improve it. For instance, the shading takes a lot of time and just by changing one line: ``` colors = [color * (0.5 + norm(v) * 0.5) for v in shade] ``` to ``` colors = np.outer(0.5+norm(shade)*0.5,color) ``` within one...
Unable to install twisted package on windows machine
4,182,419
6
2010-11-15T07:53:08Z
4,183,914
19
2010-11-15T11:32:06Z
[ "python", "windows", "twisted" ]
I have got python2.6 installed on my windows machine. tried to install twisted package but unable to install it. Also installed the zope interface On the python interpretor I get the error as : ``` >>>import twisted >>>Import Error: No Module named twisted ``` I installed the package twisted succesfully. ``` ...
The steps to install the package are as follows : 1. Install python any version . 2. Then, Install the appropriate exe <http://twistedmatrix.com/trac/wiki/Downloads> Twisted 10.1.0 for Python 2.6 ( msi | exe) or Twisted 10.1.0 for Python 2.5 ( msi | exe) 3. download the zope interface . <http://twistedmatr...
python: how to convert a string to utf-8
4,182,603
69
2010-11-15T08:26:24Z
4,182,635
104
2010-11-15T08:31:41Z
[ "python", "unicode", "utf-8" ]
I have a browser which sends utf-8 characters to my python server, but when I retrieve it from the query string, the encoding that python returns is ascii I think, how can I convert the plain string to utf-8? NOTE: the string passed from the web is already UTF-8 encoded, I just want to make python to treat it as UTF-8...
``` >>> plain_string = "Hi!" >>> unicode_string = u"Hi!" >>> type(plain_string), type(unicode_string) (<type 'str'>, <type 'unicode'>) ``` ^ This is the difference between a byte string (plain\_string) and a unicode string. ``` >>> s = "Hello!" >>> u = unicode(s, "utf-8") ``` ^ Converting to unicode and specifying t...
python: how to convert a string to utf-8
4,182,603
69
2010-11-15T08:26:24Z
4,182,757
7
2010-11-15T08:55:26Z
[ "python", "unicode", "utf-8" ]
I have a browser which sends utf-8 characters to my python server, but when I retrieve it from the query string, the encoding that python returns is ascii I think, how can I convert the plain string to utf-8? NOTE: the string passed from the web is already UTF-8 encoded, I just want to make python to treat it as UTF-8...
If I understand you correctly, you have a utf-8 encoded byte-string in your code. Converting a byte-string to a unicode string is known as decoding (unicode -> byte-string is encoding). You do that by using the [unicode](http://docs.python.org/library/functions.html#unicode) function or the [decode](http://docs.pytho...
python: how to convert a string to utf-8
4,182,603
69
2010-11-15T08:26:24Z
19,230,566
28
2013-10-07T17:00:57Z
[ "python", "unicode", "utf-8" ]
I have a browser which sends utf-8 characters to my python server, but when I retrieve it from the query string, the encoding that python returns is ascii I think, how can I convert the plain string to utf-8? NOTE: the string passed from the web is already UTF-8 encoded, I just want to make python to treat it as UTF-8...
If the methods above don't work, you can also tell Python to ignore portions of a string that it can't convert to utf-8: ``` stringnamehere.decode('utf-8', 'ignore') ```
python: how to convert a string to utf-8
4,182,603
69
2010-11-15T08:26:24Z
27,205,998
10
2014-11-29T19:13:33Z
[ "python", "unicode", "utf-8" ]
I have a browser which sends utf-8 characters to my python server, but when I retrieve it from the query string, the encoding that python returns is ascii I think, how can I convert the plain string to utf-8? NOTE: the string passed from the web is already UTF-8 encoded, I just want to make python to treat it as UTF-8...
Might be a bit overkill, but when I work with ascii and unicode in same files, repeating decode can be a pain, this is what I use: ``` def make_unicode(input): if type(input) != unicode: input = input.decode('utf-8') return input else: return input ```
'Can't set attribute' with new-style properties in Python
4,183,432
49
2010-11-15T10:27:04Z
4,183,471
10
2010-11-15T10:31:03Z
[ "python" ]
I'm trying to use new-style properties declaration: ``` class C(object): def __init__(self): self._x = 0 @property def x(self): print 'getting' return self._x @x.setter def set_x(self, value): 'setting' self._x = value if __name__ == '__main__': c = C(...
The setter method has to have the same name as the getter. Don't worry, the decorator knows how to tell them apart. ``` @x.setter def x(self, value): ... ```
'Can't set attribute' with new-style properties in Python
4,183,432
49
2010-11-15T10:27:04Z
4,183,512
64
2010-11-15T10:38:31Z
[ "python" ]
I'm trying to use new-style properties declaration: ``` class C(object): def __init__(self): self._x = 0 @property def x(self): print 'getting' return self._x @x.setter def set_x(self, value): 'setting' self._x = value if __name__ == '__main__': c = C(...
[The documentation says the following](http://docs.python.org/library/functions.html#property) about using decorator form of `property`: > Be sure to give the additional functions the same name as the original property (x in this case.) I have no idea why this is since if you use `property` as function to return an a...
Python list sort in descending order
4,183,506
98
2010-11-15T10:37:23Z
4,183,538
117
2010-11-15T10:42:12Z
[ "python", "sorting", "reverse" ]
How can I sort this list in descending order? ``` timestamp = [ "2010-04-20 10:07:30", "2010-04-20 10:07:38", "2010-04-20 10:07:52", "2010-04-20 10:08:22", "2010-04-20 10:08:22", "2010-04-20 10:09:46", "2010-04-20 10:10:37", "2010-04-20 10:10:58", "2010-04-20 10:11:50", "2010-04...
This will give you a sorted version of the array. ``` sorted(timestamp, reverse=True) ``` If you want to sort in-place: ``` timestamp.sort(reverse=True) ```
Python list sort in descending order
4,183,506
98
2010-11-15T10:37:23Z
4,183,539
7
2010-11-15T10:42:18Z
[ "python", "sorting", "reverse" ]
How can I sort this list in descending order? ``` timestamp = [ "2010-04-20 10:07:30", "2010-04-20 10:07:38", "2010-04-20 10:07:52", "2010-04-20 10:08:22", "2010-04-20 10:08:22", "2010-04-20 10:09:46", "2010-04-20 10:10:37", "2010-04-20 10:10:58", "2010-04-20 10:11:50", "2010-04...
Since your list is already in ascending order, we can simply reverse the list. ``` >>> timestamp.reverse() >>> timestamp ['2010-04-20 10:25:38', '2010-04-20 10:12:13', '2010-04-20 10:12:13', '2010-04-20 10:11:50', '2010-04-20 10:10:58', '2010-04-20 10:10:37', '2010-04-20 10:09:46', '2010-04-20 10:08:22', '2010-...
Python list sort in descending order
4,183,506
98
2010-11-15T10:37:23Z
4,183,540
123
2010-11-15T10:42:23Z
[ "python", "sorting", "reverse" ]
How can I sort this list in descending order? ``` timestamp = [ "2010-04-20 10:07:30", "2010-04-20 10:07:38", "2010-04-20 10:07:52", "2010-04-20 10:08:22", "2010-04-20 10:08:22", "2010-04-20 10:09:46", "2010-04-20 10:10:37", "2010-04-20 10:10:58", "2010-04-20 10:11:50", "2010-04...
``` timestamp.sort(key=lambda x: time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6], reverse=True) ```
Python list sort in descending order
4,183,506
98
2010-11-15T10:37:23Z
4,183,557
15
2010-11-15T10:44:45Z
[ "python", "sorting", "reverse" ]
How can I sort this list in descending order? ``` timestamp = [ "2010-04-20 10:07:30", "2010-04-20 10:07:38", "2010-04-20 10:07:52", "2010-04-20 10:08:22", "2010-04-20 10:08:22", "2010-04-20 10:09:46", "2010-04-20 10:10:37", "2010-04-20 10:10:58", "2010-04-20 10:11:50", "2010-04...
You ca simply do this: ``` timestamp.sort(reverse=True) ```
str to time in python
4,183,793
12
2010-11-15T11:18:37Z
4,183,836
14
2010-11-15T11:22:51Z
[ "python", "datetime", "strptime" ]
``` time1 = "2010-04-20 10:07:30" time2 = "2010-04-21 10:07:30" ``` How to convert the above from string to time stamp? I need to subtract the above timestamps `time2-time1`.
For Python 2.5+ ``` from datetime import datetime format = '%Y-%m-%d %H:%M:%S' print datetime.strptime(time2, format) - datetime.strptime(time1, format) # 1 day, 0:00:00 ``` **Edit:** for Python 2.4 ``` import time format = '%Y-%m-%d %H:%M:%S' print time.mktime(time.strptime(time2, format)) - time....
python: json.dumps can't handle utf-8?
4,184,108
15
2010-11-15T12:00:16Z
4,184,241
53
2010-11-15T12:20:31Z
[ "python", "json" ]
Below is the test program, including a Chinese character: ``` # -*- coding: utf-8 -*- import json j = {"d":"中", "e":"a"} json = json.dumps(j, encoding="utf-8") print json ``` Below is the result, look the json.dumps convert the utf-8 to the original numbers! ``` {"e": "a", "d": "\u4e2d"} ``` Why this is broken?...
Looks like valid JSON to me. If you want `json` to output a string that has non-ASCII characters in it then you need to pass `ensure_ascii=False` and then encode manually afterward.
python: json.dumps can't handle utf-8?
4,184,108
15
2010-11-15T12:00:16Z
4,184,289
20
2010-11-15T12:26:23Z
[ "python", "json" ]
Below is the test program, including a Chinese character: ``` # -*- coding: utf-8 -*- import json j = {"d":"中", "e":"a"} json = json.dumps(j, encoding="utf-8") print json ``` Below is the result, look the json.dumps convert the utf-8 to the original numbers! ``` {"e": "a", "d": "\u4e2d"} ``` Why this is broken?...
You should read [json.org](http://json.org). The complete JSON specification is in the white box on the right. There is nothing wrong with the generated JSON. Generators are allowed to genereate either UTF-8 strings or plain ASCII strings, where characters are escaped with the `\uXXXX` notation. In your case, the Pyth...
ImportError : No module named _sqlite3 on GAE
4,185,991
7
2010-11-15T15:40:06Z
4,186,080
8
2010-11-15T15:49:15Z
[ "python", "google-app-engine", "sqlite3" ]
While trying to start local Google App Engine (v1.3.8) Server on my Fedora 14 with Python 2.5 (installed from source) I get the importerror ``` ImportError: No module named _sqlite3 ``` I have the following package installed - sqlite, sqlite-devel, python2.5, python2.7. I did some Google and it looks like this error ...
Install `sqlite-devel` and rebuild Python.
How to display database query results of 100,000 rows or more with HTML?
4,186,384
7
2010-11-15T16:18:00Z
4,186,550
8
2010-11-15T16:31:47Z
[ "python", "html", "oracle", "coldfusion" ]
We're rewriting a website used by one of our clients. The user traffic on it is very low, less than 100 unique visitors a week. It's basically just a nice interface to their data in our databases. It allows them to query and filter on different sets of data of theirs. We're rewriting the site in Python, re-using the s...
I have done just what you are describing using the following (which works very well): **[jQuery Datatables](http://www.datatables.net/)** It enables you to do 'fetch as you scroll' pagination, so you can disable the pagination arrows in favor of a 'forever' scroll.
How do I use a relative path in a Python module when the CWD has changed?
4,187,300
15
2010-11-15T17:50:01Z
4,187,345
28
2010-11-15T17:55:19Z
[ "python", "module", "path", "relative", "getcwd" ]
I have a Python module which uses some resources in a subdirectory of the module directory. After searching around on stack overflow and finding related answers, I managed to direct the module to the resources by using something like ``` import os os.path.join(os.path.dirname(__file__), 'fonts/myfont.ttf') ``` This w...
Store the absolute path to the module directory at the very beginning of the module: ``` package_directory = os.path.dirname(os.path.abspath(__file__)) ``` Afterwards, load your resources based on this `package_directory`: ``` font_file = os.path.join(package_directory, 'fonts', 'myfont.ttf') ``` And after all, do ...
accessing variables in the debugging session with ipython and %pdb on
4,187,330
7
2010-11-15T17:53:07Z
4,187,712
9
2010-11-15T18:47:05Z
[ "python", "ipython" ]
I'm new to ipython and I am trying to use ipython to debug my code. I did: ``` [1]: %pdb Automatic pdb calling has been turned ON ``` and then ``` In [2]: %run mycode.py ``` and in the code, I have 1/0 so it raises an exception and will automatically goes into the debug session. ``` ZeroDivisionError: float divisi...
`b` is used to set break points. So whatever follows `b` is expected to be a function or line number. If you type `ipdb> help` you will see the full list of commands (reserved words). You could use, say, `x` or `y` as a variable: ``` ipdb> y = variable ``` or ``` ipdb> exec 'b = variable' ```
recursive dircmp (compare two directories to ensure they have the same files and subdirectories)
4,187,564
17
2010-11-15T18:25:29Z
6,681,395
16
2011-07-13T15:27:58Z
[ "python", "recursion" ]
From what I observe [`filecmp.dircmp`](https://docs.python.org/2/library/filecmp.html#the-dircmp-class) is *recursive, but inadequate for my needs*, at least in py2. I want to compare two directories and all their contained files. Does this exist, or do I need to build (using [`os.walk`](https://docs.python.org/2/libra...
Here's an alternative implementation of the comparison function with `filecmp` module. It uses a recursion instead of `os.walk`, so it is a little simpler. However, it does not recurse simply by using `common_dirs` and `subdirs` attributes since in that case we would be implicitly using the default "shallow" implementa...
Streaming pipes in Python
4,187,785
7
2010-11-15T18:56:12Z
4,187,841
7
2010-11-15T19:03:43Z
[ "python" ]
I'm trying to convert the output of vmstat into a CSV file using Python, so I use something like this to convert to CSV and add the date and time as coloumns: ``` vmstat 5 | python myscript.py >> vmstat.log ``` The problem I'm having is it blocks while trying to iterate sys.stdin. It seems like the input buffer doesn...
VMstat 5,does not close the stdout, so the python buffer is still waiting for more data. Use this instead: ``` for line in iter(sys.stdin.readline, ""): print line ```
PIL: Create one-dimensional histogram of image color lightness?
4,188,104
3
2010-11-15T19:34:43Z
4,199,541
8
2010-11-16T22:09:05Z
[ "python", "image-processing", "python-imaging-library", "scanning" ]
I've been working on a script, and I need it to basically: * Make the image greyscale (or bitonal, I will play with both to see which one works better). * Process each individual column and create a net intensity value for each column. * Spit the results into an ordered list. There is a really easy way to do this wit...
I see you are using numpy. I would convert the greyscale image to a numpy array first, then use numpy to sum along an axis. Bonus: You'll probably find your smoothing function runs a lot faster when you fix it to accept an 1D array as input. ``` >>> from PIL import Image >>> import numpy as np >>> i = Image.open(r'C:\...
Language choices for writing very fast abstractions interfacing with Python?
4,188,273
5
2010-11-15T19:58:17Z
4,188,289
7
2010-11-15T20:00:22Z
[ "java", "c++", "python", "boost-python" ]
I have a system currently written in Python that can be separated into backend and frontend layers. Python is too slow, so I want to rewrite the backend in a fast compiled language while keeping the frontend in Python, in a way that lets the backend functionality be called from Python. What are the best choices to do s...
C++ with [SWIG](http://www.swig.org/) can generate all of the glue code you need. So long as you avoid excessive jumps between C++ and python it'll be as fast as your C++. SWIG interfaces are usually fairly straightforward to generate unless you're doing something "odd".
How to check if an argument from commandline has been set?
4,188,467
9
2010-11-15T20:24:30Z
4,188,496
23
2010-11-15T20:27:59Z
[ "python" ]
I can call my script like this: ``` python D:\myscript.py 60 ``` And in the script I can do: ``` arg = sys.argv[1] foo(arg) ``` But how could I test if the argument has been entered in the command line call? I need to do something like this: ``` if isset(sys.argv[1]): foo(sys.argv[1]) else: print "You must...
`len(sys.argv) > 1`
How to check if an argument from commandline has been set?
4,188,467
9
2010-11-15T20:24:30Z
4,188,499
11
2010-11-15T20:28:13Z
[ "python" ]
I can call my script like this: ``` python D:\myscript.py 60 ``` And in the script I can do: ``` arg = sys.argv[1] foo(arg) ``` But how could I test if the argument has been entered in the command line call? I need to do something like this: ``` if isset(sys.argv[1]): foo(sys.argv[1]) else: print "You must...
``` if len(sys.argv) < 2: print "You must set argument!!!" ```
How to check if an argument from commandline has been set?
4,188,467
9
2010-11-15T20:24:30Z
4,188,500
19
2010-11-15T20:28:28Z
[ "python" ]
I can call my script like this: ``` python D:\myscript.py 60 ``` And in the script I can do: ``` arg = sys.argv[1] foo(arg) ``` But how could I test if the argument has been entered in the command line call? I need to do something like this: ``` if isset(sys.argv[1]): foo(sys.argv[1]) else: print "You must...
Don't use `sys.argv` for handling the command-line interface; there's a module to do that: [`argparse`](http://docs.python.org/dev/library/argparse.html). You can mark an argument as required by passing `required=True` to `add_argument`. ``` import argparse parser = argparse.ArgumentParser(description='Process some i...
How can I force urllib2 to time out?
4,188,723
5
2010-11-15T20:55:30Z
4,188,795
10
2010-11-15T21:02:47Z
[ "python", "urllib2" ]
I want to to test my application's handling of timeouts when grabbing data via urllib2, and I want to have some way to force the request to timeout. Short of finding a very very slow internet connection, what method can I use? I seem to remember an interesting application/suite for simulating these sorts of things. M...
I usually use netcat to listen on port 80 of my local machine: ``` nc -l 80 ``` Then I use <http://localhost/> as the request URL in my application. Netcat will answer at the http port but won't ever give a response, so the request is guaranteed to time out provided that you have specified a timeout in your `urllib2....
Python: How to get number of mili seconds per jiffy
4,189,123
12
2010-11-15T21:46:19Z
4,189,612
20
2010-11-15T22:44:11Z
[ "python", "linux" ]
I'd like to know the HZ of the system, i.e. how many mili seconds is one jiffy from Python code.
There is USER\_HZ ``` >>> import os >>> os.sysconf_names['SC_CLK_TCK'] 2 >>> os.sysconf(2) 100 ``` which is what the kernel uses to report time in `/proc`. From the `time(7)` manual page: > **The Software Clock, HZ, and Jiffies** > > The accuracy of various system calls that set timeouts, (e.g., > select(2), sigtim...
Tutorials on optimizing non-trivial Python applications with C extensions or Cython
4,189,328
25
2010-11-15T22:08:10Z
4,189,655
9
2010-11-15T22:50:43Z
[ "python", "c", "optimization", "cython", "python-extensions" ]
The Python community has published helpful reference material showing how to profile Python code, and the technical details of Python extensions in C or in [Cython](http://cython.org/). I am still searching for tutorials which show, however, for non-trivial Python programs, the following: 1. How to identify the hotspo...
Points 1 and 2 are just basic optimization rule of thumbs. I would be very astonished if there was anywhere the kind of tutorial you are looking for. Maybe that's why you haven't found one. My short list: * rule number one of optimization is **don't**. * rule number two **measure** * rule number three **identify the l...
What does [:] do?
4,189,446
9
2010-11-15T22:23:44Z
4,189,499
9
2010-11-15T22:30:03Z
[ "python" ]
``` return self.var[:] ``` What will that return?
Python permits you to "slice" various container types; this is a shorthand notation for taking some subcollection of an ordered collection. For instance, if you have a list ``` foo = [1,2,3,4,5] ``` and you want the second, third, and fourth elements, you can do: ``` foo[1:4] ``` If you omit one of the numbers in t...
Get process name by PID
4,189,717
21
2010-11-15T23:00:22Z
4,189,747
12
2010-11-15T23:05:18Z
[ "python", "process", "pid" ]
This should be simple, but I'm just not seeing it. If I have a process ID, how can I use that to grab info about the process such as the process name.
Try PSUtil -> <https://github.com/giampaolo/psutil> Works fine on Windows and Unix, I recall.
Get process name by PID
4,189,717
21
2010-11-15T23:00:22Z
4,189,752
16
2010-11-15T23:07:24Z
[ "python", "process", "pid" ]
This should be simple, but I'm just not seeing it. If I have a process ID, how can I use that to grab info about the process such as the process name.
Under Linux, you can read proc filesystem. File `/proc/<pid>/cmdline` contains the commandline.
How to add extra fields using django.forms Textarea
4,190,386
2
2010-11-16T01:16:55Z
4,192,500
10
2010-11-16T09:05:39Z
[ "python", "django", "django-templates", "django-forms", "django-views" ]
I am newbie in django and working on a pootle project. I would like to add bio (in textarea), interests (textarea), and profile pics (image upload). this page is looking like this: <http://pootle.locamotion.org/accounts/personal/edit/> (you might need to login to see this page) I have edited local\_apps/pootle\_profi...
Firstly, as Digitalpbk says, don't manually add columns to Django's tables. Instead, create a UserProfile model in your own app, with a OneToOneField to `auth.User`. Secondly, to add extra fields to a modelform, you need to define them explicitly at the form level: ``` class UserForm(ModelForm): ...
Python string replace for UTF-16-LE file
4,190,683
2
2010-11-16T02:28:34Z
4,191,327
7
2010-11-16T04:52:31Z
[ "python", "string" ]
Python 2.6 Using Python string.replace() seems not working for UTF-16-LE file. I think of 2 ways: 1. Find a Python module that can handle Unicode string manipulate. 2. Convert the target Unicode file to ASCII, use string.replace(), then convert it back. But I am worry about this may cause loss data. Can the communit...
You don't have a Unicode file. There is no such thing (unless you are the author of NotePad, which conflates "Unicode" and "UTF-16LE"). Please read the [Python Unicode HOWTO](http://docs.python.org/howto/unicode.html) and [Joel on Unicode](http://www.joelonsoftware.com/articles/Unicode.html). **Update** I'm glad the ...
Tracing Python warnings/errors to a line number in numpy and scipy
4,190,817
9
2010-11-16T02:54:43Z
4,190,933
16
2010-11-16T03:20:24Z
[ "python", "numpy", "scipy", "numeric", "scientific-computing" ]
I am getting the error: ``` Warning: invalid value encountered in log ``` From Python and I believe the error is thrown by numpy (using version 1.5.0). However, since I am calling the "log" function in several places, I'm not sure where the error is coming from. Is there a way to get numpy to print the line number th...
Putting `np.seterr(invalid='raise')` in your code (before the errant `log` call) will cause numpy to raise an exception instead of issuing a warning. That will give you a traceback error message and tell you the line Python was executing when the error occurred.
Python: find a duplicate in a container efficiently
4,191,171
11
2010-11-16T04:14:35Z
4,191,185
7
2010-11-16T04:18:46Z
[ "python", "algorithm", "python-3.x", "duplicates" ]
I have a container `cont`. If I want to find out if it has duplicates, I'll just check `len(cont) == len(set(cont))`. Suppose I want to find a duplicate element if it exists (just any arbitrary duplicate element). Is there any neat and efficient way to write that? [Python 3]
You can start adding them to the set and as soon as you try to add the element that is already in the set you found a duplicate.
Why has Python decided against constant references?
4,192,053
24
2010-11-16T07:42:51Z
4,192,122
8
2010-11-16T07:58:47Z
[ "python", "reference", "constants", "language-design", "language-features" ]
Note: I'm not talking about preventing the rebinding of a variable. I'm talking about preventing the modification of the memory that the variable refers to, and of any memory that can be reached from there by following the nested containers. I have a large data structure, and I want to expose it to other modules, on a...
There are many design questions about any language, the answer to most of which is "just because". It's pretty clear that constants like this would go against the ideology of Python. --- You can make a read-only class attribute, though, using [*descriptors*](http://users.rcn.com/python/download/Descriptor.htm). It's ...
Why has Python decided against constant references?
4,192,053
24
2010-11-16T07:42:51Z
4,192,159
13
2010-11-16T08:07:19Z
[ "python", "reference", "constants", "language-design", "language-features" ]
Note: I'm not talking about preventing the rebinding of a variable. I'm talking about preventing the modification of the memory that the variable refers to, and of any memory that can be reached from there by following the nested containers. I have a large data structure, and I want to expose it to other modules, on a...
It's the same as with private methods: [as consenting adults](http://mail.python.org/pipermail/tutor/2003-October/025932.html) authors of code should agree on an interface without need of force. Because really *really* enforcing the contract is *hard*, and doing it the half-assed way leads to hackish code in abundance....
Why has Python decided against constant references?
4,192,053
24
2010-11-16T07:42:51Z
4,232,486
10
2010-11-20T11:33:49Z
[ "python", "reference", "constants", "language-design", "language-features" ]
Note: I'm not talking about preventing the rebinding of a variable. I'm talking about preventing the modification of the memory that the variable refers to, and of any memory that can be reached from there by following the nested containers. I have a large data structure, and I want to expose it to other modules, on a...
In [PEP 351](http://www.python.org/dev/peps/pep-0351/), Barry Warsaw proposed a protocol for "freezing" any mutable data structure, analogous to the way that `frozenset` makes an immutable set. Frozen data structures would be hashable and so capable being used as keys in dictionaries. The proposal was [discussed on py...
"unknown column X.id" error in django using existing DB
4,192,409
7
2010-11-16T08:51:47Z
4,192,780
11
2010-11-16T09:43:02Z
[ "python", "django" ]
I am trying to create a model for an existsing DB. Using the output of `manage.py inspectdb`, My `models.py` file looks like this: ``` from django.db import models ...some more stuff here... class Scripts(models.Model): run_site = models.ForeignKey(Sites, db_column='run_site') script_name = models.CharField(...
There is always by default an [implicit `id` field as auto incrementing primary key](http://docs.djangoproject.com/en/dev/topics/db/models/#automatic-primary-key-fields) on every model. See [primary\_key in the Django docs](http://docs.djangoproject.com/en/dev/ref/models/fields/#primary-key) how to change that field to...
How to fix Python error importing ElementTree?
4,192,410
4
2010-11-16T08:51:49Z
4,192,437
7
2010-11-16T08:56:15Z
[ "python", "xml" ]
I'm beginning to learn python and here I'm trying to read from an xml file using ElementTree: ``` import sys from elementtree.ElementTree import ElementTree doc = ElementTree(file="test.xml") doc.write(sys.stdout) ``` However I get this error: File "my\_xml.py", line 2, in from elementtree.ElementTree import Element...
It should be: ``` from xml.etree.ElementTree import ElementTree ``` More information on this can be found at the [Python docs](http://docs.python.org/library/xml.etree.elementtree.html).
How to get hard disk serial number using Python
4,193,514
29
2010-11-16T11:09:43Z
4,194,146
43
2010-11-16T12:35:15Z
[ "python", "linux", "hard-drive", "serial-number", "fcntl" ]
How can I get the `serial number` of a `hard disk` drive using `Python` on `Linux`? I would like to use a Python module to do that instead of running an external program such as [`hdparm`](http://linux.die.net/man/8/hdparm). Perhaps using the [`fcntl`](http://man7.org/linux/man-pages/man2/fcntl.2.html) module?
# Linux As you suggested, [fcntl](http://docs.python.org/library/fcntl.html) is the way to do this on Linux. The C code you want to translate looks like this: ``` static struct hd_driveid hd; int fd; if ((fd = open("/dev/hda", O_RDONLY | O_NONBLOCK)) < 0) { printf("ERROR opening /dev/hda\n"); exit(1); } if ...
Django WGSI paths
4,194,243
5
2010-11-16T12:44:31Z
4,194,282
8
2010-11-16T12:50:10Z
[ "python", "django", "apache", "apache2", "wsgi" ]
I am having problems setting up wgsi with django. I'm following this <http://docs.djangoproject.com/en/dev/howto/deployment/modwsgi/> . Yet I am still really confused as to where to put the .wsgi file and if I need to set the sys.path. I have tried it both directly outside and inside the web root and I can't get anythi...
I put the wsgi at same level than settings.py, and looks like this: ``` import os import sys sys.path.insert(0,os.sep.join(os.path.abspath(__file__).split(os.sep)[:-2])) os.environ['DJANGO_SETTINGS_MODULE'] = 'yourprojectname.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHa...
python: how to get a subset of dict
4,194,365
6
2010-11-16T13:00:00Z
4,194,402
15
2010-11-16T13:05:10Z
[ "python" ]
I have a dict that has many elements, I want to write a function that can return the elements in the given index range(treat dict as array): ``` get_range(dict, begin, end): return {a new dict for all the indexes between begin and end} ``` How that can be done? EDIT: I am not asking using key filter... eg) ``` ...
**Edit:** A dictionary is *not ordered*. It is impossible to make `get_range` return the same slice whenever you have modified the dictionary. If you need deterministic result, replace your `dict` [with a `collections.OrderedDict`](http://docs.python.org/library/collections.html#collections.OrderedDict). Anyway, you c...
Python argparse: Is there a way to specify a range in nargs?
4,194,948
16
2010-11-16T14:04:50Z
4,195,302
10
2010-11-16T14:41:16Z
[ "python", "argparse" ]
I have an optional argument that supports a list of arguments itself. I mean, it should support: * -f 1 2 * -f 1 2 3 but not: * -f 1 * -f 1 2 3 4 Is there a way to force this within argparse ? Now I'm using nargs="\*", and then checking the list length. **Edit:** As requested, what I needed is being able to defin...
You could do this with a [custom action](http://docs.python.org/library/argparse.html#action): ``` import argparse def required_length(nmin,nmax): class RequiredLength(argparse.Action): def __call__(self, parser, args, values, option_string=None): if not nmin<=len(values)<=nmax: ...
How to deserialize 1GB of objects into Python faster than cPickle?
4,195,202
12
2010-11-16T14:32:32Z
4,195,787
7
2010-11-16T15:30:35Z
[ "python", "serialization", "pickle", "deserialization" ]
We've got a Python-based web server that unpickles a number of large data files on startup using `cPickle`. The data files (pickled using `HIGHEST_PROTOCOL`) are around 0.4 GB on disk and load into memory as about 1.2 GB of Python objects -- this takes about **20 seconds**. We're using Python 2.6 on 64-bit Windows mach...
Are you load()ing the pickled data directly from the file? What about to try to load the file into the memory and then do the load? I would start with trying the cStringIO(); alternatively you may try to write your own version of StringIO that would use buffer() to slice the memory which would reduce the needed copy() ...
How to deserialize 1GB of objects into Python faster than cPickle?
4,195,202
12
2010-11-16T14:32:32Z
4,195,809
16
2010-11-16T15:32:07Z
[ "python", "serialization", "pickle", "deserialization" ]
We've got a Python-based web server that unpickles a number of large data files on startup using `cPickle`. The data files (pickled using `HIGHEST_PROTOCOL`) are around 0.4 GB on disk and load into memory as about 1.2 GB of Python objects -- this takes about **20 seconds**. We're using Python 2.6 on 64-bit Windows mach...
1. Try the marshal module - it's internal (used by the byte-compiler) and intentionally not advertised much, but it is much faster. Note that it doesn't serialize arbitrary instances like pickle, only builtin types (don't remember the exact constraints, see docs). Also note that the format isn't stable. 2. If you need ...
Using POST and urllib2 to access web API
4,195,325
6
2010-11-16T14:43:19Z
4,195,412
8
2010-11-16T14:51:56Z
[ "python", "http", "post", "urllib2" ]
I am trying to access a web API using a POST technique. I AM able to access it using a GET technique, but the API owners tell me that certain functionality only works with POST. Unfortunately I can't seem to get POST working. Here's what works with GET: ``` API_URL = "http://example.com/api/" def call_api(method, **...
With `urllib2` you need to add the data to the `POST` body: ``` def call_api(method, **kwargs): url = API_URL + method req = urllib2.Request(url) if kwargs: req.add_data(urllib.urlencode(kwargs)) auth = 'Basic ' + base64.urlsafe_b64encode("%s:%s" % (USER, PASS)) req.add_header('Authorizat...
How to resize an image with OpenCV2.0 and Python2.6
4,195,453
28
2010-11-16T14:55:56Z
18,767,569
64
2013-09-12T14:51:05Z
[ "python", "image", "image-processing", "resize", "opencv" ]
I want to use OpenCV2.0 and Python2.6 to show resized images. I used and adopted the example at <http://opencv.willowgarage.com/documentation/python/cookbook.html> but unfortunately this code is for OpenCV2.1 and seem not to be working on 2.0. Here my code: ``` import os, glob import cv ulpath = "exampleshq/" for in...
If you wish to use CV2, you need to use the `resize` function. For example, this will resize both axes by half: ``` small = cv2.resize(image, (0,0), fx=0.5, fy=0.5) ``` and this will resize the image to have 100 cols (width) and 50 rows (height): ``` resized_image = cv2.resize(image, (100, 50)) ``` Another option ...
Circular Reference with python lists
4,196,329
4
2010-11-16T16:18:54Z
4,196,353
9
2010-11-16T16:21:50Z
[ "python", "list", "circular-reference" ]
Can someone explain this? ``` >>> x=x[0]=[0] >>> x [[...]] >>> x is x[0] True >>> x[0][0][0][0][0][0][0] [[...]] >>> x in x True ``` what is [...]?
That's just Python telling you that you have a circular reference; it's smart enough not to enter an infinite loop trying to print it out.
Python for-loop look-ahead
4,197,805
10
2010-11-16T18:47:50Z
4,197,836
8
2010-11-16T18:51:01Z
[ "python" ]
I have a python for loop, in which I need to look ahead one item to see if an action needs to be performed before processing. ``` for line in file: if the start of the next line == "0": perform pre-processing ... continue with normal processing ... ``` Is there any easy way to do this in p...
You can have a `prev_line` where you store previous line and process that whenever you read a line only given your condition. Something like: ``` prev_line = None for line in file: if prev_line is not None and the start of the next line == "0": perform pre-processing on prev_line ... continue ...
Python for-loop look-ahead
4,197,805
10
2010-11-16T18:47:50Z
4,197,869
15
2010-11-16T18:55:00Z
[ "python" ]
I have a python for loop, in which I need to look ahead one item to see if an action needs to be performed before processing. ``` for line in file: if the start of the next line == "0": perform pre-processing ... continue with normal processing ... ``` Is there any easy way to do this in p...
you can get any iterable to prefetch next item with this recipe: ``` from itertools import tee, islice, izip_longest def get_next(some_iterable, window=1): items, nexts = tee(some_iterable, 2) nexts = islice(nexts, window, None) return izip_longest(items, nexts) ``` Example usage: ``` for line, next_line...
Python for-loop look-ahead
4,197,805
10
2010-11-16T18:47:50Z
4,198,074
7
2010-11-16T19:21:11Z
[ "python" ]
I have a python for loop, in which I need to look ahead one item to see if an action needs to be performed before processing. ``` for line in file: if the start of the next line == "0": perform pre-processing ... continue with normal processing ... ``` Is there any easy way to do this in p...
Along the lines of nosklo's answer, I tend to use the following pattern: The function `pairwise` from the excellent [itertools recipes](http://docs.python.org/library/itertools.html#recipes) is ideal for this: ``` from itertools import tee def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b =...
How to reliably guess the encoding between MacRoman, CP1252, Latin1, UTF-8, and ASCII
4,198,804
89
2010-11-16T20:50:46Z
4,198,920
7
2010-11-16T21:02:36Z
[ "java", "python", "perl", "osx", "character-encoding" ]
At work it seems like no week ever passes without some encoding-related conniption, calamity, or catastrophe. The problem usually derives from programmers who think they can reliably process a “text” file without specifying the encoding. But you can't. So it's been decided to henceforth forbid files from ever havi...
My attempt at such a heuristic (assuming that you've ruled out ASCII and UTF-8): * If 0x7f to 0x9f don't appear at all, it's probably ISO-8859-1, because those are very rarely used control codes * If 0x91 through 0x94 appear at lot, it's probably Windows-1252, because those are the "smart quotes", by far the most like...
How to reliably guess the encoding between MacRoman, CP1252, Latin1, UTF-8, and ASCII
4,198,804
89
2010-11-16T20:50:46Z
4,200,087
10
2010-11-16T23:26:16Z
[ "java", "python", "perl", "osx", "character-encoding" ]
At work it seems like no week ever passes without some encoding-related conniption, calamity, or catastrophe. The problem usually derives from programmers who think they can reliably process a “text” file without specifying the encoding. But you can't. So it's been decided to henceforth forbid files from ever havi...
[Mozilla nsUniversalDetector](http://www.mozilla.org/projects/intl/UniversalCharsetDetection.html) (Perl bindings: [Encode::Detect](http://p3rl.org/Encode%3a%3aDetect)/[Encode::Detect::Detector](http://p3rl.org/Encode%3a%3aDetect%3a%3aDetector)) is millionfold proven.
How to reliably guess the encoding between MacRoman, CP1252, Latin1, UTF-8, and ASCII
4,198,804
89
2010-11-16T20:50:46Z
4,200,765
82
2010-11-17T01:38:46Z
[ "java", "python", "perl", "osx", "character-encoding" ]
At work it seems like no week ever passes without some encoding-related conniption, calamity, or catastrophe. The problem usually derives from programmers who think they can reliably process a “text” file without specifying the encoding. But you can't. So it's been decided to henceforth forbid files from ever havi...
First, the easy cases: ## ASCII If your data contains no bytes above 0x7F, then it's ASCII. (Or a 7-bit ISO646 encoding, but those are very obsolete.) ## UTF-8 If your data validates as UTF-8, then you can safely assume it *is* UTF-8. Due to UTF-8's strict validation rules, false positives are extremely rare. ## I...
Python list comprehension rebind names even after scope of comprehension. Is this right?
4,198,906
75
2010-11-16T21:01:00Z
4,199,344
39
2010-11-16T21:47:36Z
[ "python", "binding", "list-comprehension" ]
List comprehensions are having some unexpected interactions with scoping. Is this the expected behaviour? I've got a method: ``` def leave_room(self, uid): u = self.user_by_id(uid) r = self.rooms[u.rid] other_uids = [ouid for ouid in r.users_by_id.keys() if ouid != u.uid] other_us = [self.user_by_id(uid) for...
Yes, list comprehensions "leak" their variable in Python 2.x, just like for loops. In retrospect, this was recognized to be a mistake, and it was avoided with generator expressions. EDIT: As [Matt B. notes](https://stackoverflow.com/questions/4198906/python-list-comprehension-rebind-names-even-after-scope-of-comprehen...
Python list comprehension rebind names even after scope of comprehension. Is this right?
4,198,906
75
2010-11-16T21:01:00Z
4,199,355
100
2010-11-16T21:48:12Z
[ "python", "binding", "list-comprehension" ]
List comprehensions are having some unexpected interactions with scoping. Is this the expected behaviour? I've got a method: ``` def leave_room(self, uid): u = self.user_by_id(uid) r = self.rooms[u.rid] other_uids = [ouid for ouid in r.users_by_id.keys() if ouid != u.uid] other_us = [self.user_by_id(uid) for...
List comprehensions leak the loop control variable in Python 2 but not in Python 3. Here's Guido van Rossum (creator of Python) [explaining](http://python-history.blogspot.com/2010/06/from-list-comprehensions-to-generator.html) the history behind this: > We also made another change in Python > 3, to improve equivalenc...
Python: String formatting a regex string that uses both '%' and '{' as characters
4,199,642
4
2010-11-16T22:20:09Z
4,199,699
9
2010-11-16T22:26:54Z
[ "python", "regex" ]
I have the following regular expression, which lets me parse percentages like '20%+', '20%', or '20% - 50%' using re.split. ``` '([0-9]{1,3}[%])([+-]?)' ``` I want to use string formatting to pass the series identifiers (i.e. '+-') as an argument from config.py. ``` SERIES = '+-' ``` The two methods I've tried prod...
You can use `%%` to insert a percent-sign using the old-style formatting: ``` '([0-9]{1,3}[%%])([%s]?)' % (config.SERIES) ``` Similarly for the new-style formatting, double the braces: ``` '([0-9]{{1,3}}[%])([{0}]?)'.format(config.SERIES) ```
Python: How do I make temporary files in my test suite?
4,199,700
18
2010-11-16T22:27:02Z
4,199,712
9
2010-11-16T22:28:34Z
[ "python", "unit-testing", "testing", "temporary-files" ]
(I'm using Python 2.6 and `nose`.) I'm writing tests for my Python app. I want one test to open a new file, close it, and then delete it. Naturally, I prefer that this will happen inside a temporary directory, because I don't want to trash the user's filesystem. And, it needs to be cross-OS. How do I do it?
See the [tempfile](http://docs.python.org/library/tempfile.html) module in the standard library -- should be all you need.
Python: How do I make temporary files in my test suite?
4,199,700
18
2010-11-16T22:27:02Z
4,205,449
22
2010-11-17T14:36:25Z
[ "python", "unit-testing", "testing", "temporary-files" ]
(I'm using Python 2.6 and `nose`.) I'm writing tests for my Python app. I want one test to open a new file, close it, and then delete it. Naturally, I prefer that this will happen inside a temporary directory, because I don't want to trash the user's filesystem. And, it needs to be cross-OS. How do I do it?
FWIW using py.test you can write: ``` def test_function(tmpdir): # tmpdir is a unique-per-test-function invocation temporary directory ``` Each test function using the "tmpdir" function argument will get a clean empty directory, created as a sub directory of "/tmp/pytest-NUM" (linux, win32 has different path) whe...
fabric vs pexpect
4,200,267
15
2010-11-16T23:56:30Z
4,200,334
14
2010-11-17T00:06:25Z
[ "python", "fabric", "pexpect" ]
I've stumbled upon [pexpect](http://sourceforge.net/projects/pexpect/) and my impression is that it looks roughly similar to [fabric](http://fabfile.org/). I've tried to find some comparison, without success, so I'm asking here--in case someone has experience with both tools. Is my impression (that they are roughly eq...
I've used both. [Fabric](http://docs.fabfile.org) is more high level than pexpect, and IMHO a lot better. It depends what you're using it for, but if your use is deployment and configuration of software then Fabric is the right way to go.
what methods does `foo < bar < baz` actually invoke?
4,200,822
9
2010-11-17T01:55:02Z
4,200,854
12
2010-11-17T02:03:50Z
[ "python", "operator-overloading" ]
In python we can say: ``` if foo < bar < baz: do something. ``` and similarly, we can overload the comparision operators like: ``` class Bar: def __lt__(self, other): do something else ``` but what methods of the types of the operands of those interval comparisions are actually called? is the above ...
``` if foo < bar < baz: ``` is equivalent to ``` if foo < bar and bar < baz: ``` with one important distinction: if bar is a mutating, it will be cached. I.e.: ``` if foo < bar() < baz: ``` is equivalent to ``` tmp = bar() if foo < tmp and tmp < baz: ``` But to answer your question, it will end up being: ``` if...
How can I unshorten a URL using python?
4,201,062
7
2010-11-17T02:56:30Z
4,201,180
30
2010-11-17T03:20:28Z
[ "python", "url", "url-shortener" ]
I want to be able to take a shortened or non-shortened URL and return its un-shortened form. How can I make a python program to do this? Additional Clarification: Case 1: shortened --> unshortened Case 2: unshortened --> unshortened e.g. bit.ly/silly in the input array should be google.com in the output array ...
Send an HTTP HEAD request to the URL and look at the response code. If the code is 30x, look at the `Location` header to get the unshortened URL. Otherwise, if the code is 20x, then the URL is not redirected; you probably also want to handle error codes (4xx and 5xx) in some fashion. For example: ``` # This is for Py2...
SQLAlchemy: What's the difference between flush() and commit()?
4,201,455
199
2010-11-17T04:20:20Z
4,202,016
225
2010-11-17T06:25:24Z
[ "python", "sqlalchemy" ]
What the difference is between `flush()` and `commit()` in SQLAlchemy? I've read the docs, but am none the wiser - they seem to assume a pre-understanding that I don't have. I'm particularly interested in their impact on memory usage. I'm loading some data into a database from a series of files (around 5 million rows...
**Edited to reflect comments by zzzeek** A Session object is basically an ongoing transaction of changes to a database (update, insert, delete). These operations aren't persisted to the database until they are committed (if your program aborts for some reason in mid-session transaction, any uncommitted changes within ...
Why does domain driven design seem only popular with static languages like C♯ & Java?
4,201,846
17
2010-11-17T05:47:26Z
4,208,311
8
2010-11-17T19:27:55Z
[ "python", "domain-driven-design" ]
Domain driven design has become my architecture of choice. I've been able to find a abundance of books & tutorials for applying DDD principles within the ASP.net framework. It mostly seems inspired from what Java developers have been doing for a good while now. For my personal projects, I'm starting to lean more towar...
I think it is definitely popular elsewhere, especially functional languages. However, certain patterns associated with the Big Blue Book are not as applicable in dynamic languages and frameworks like Rails tend to lead people away from ideas of bounded context However, the true thrust of DDD being ubiquitous language ...
python 3: how to check if an object is a function?
4,202,301
9
2010-11-17T07:23:41Z
4,202,642
13
2010-11-17T08:28:42Z
[ "python", "class", "function", "python-3.x" ]
Am I correct assuming that all functions (built-in or user-defined) belong to the same class, but that class doesn't seem to be bound to any variable by default? How can I check that an object is a function? I can do this I guess: ``` def is_function(x): def tmp() pass return type(x) is type(tmp) ``` It doe...
in python2: ``` callable(fn) ``` in python3: ``` isinstance(fn, collections.Callable) ``` as Callable is an Abstract Base Class, this is equivalent to: ``` hasattr(fn, '__call__') ```
how do run syncdb without loading fixtures?
4,202,358
5
2010-11-17T07:34:03Z
20,218,080
12
2013-11-26T13:13:32Z
[ "python", "django", "django-models" ]
is there a way to run syncdb without loading fixtures? xo
`./manage.py help syncdb` suggests the following: ``` ./manage.py syncdb --no-initial-data ``` From [Django docs on initial data](https://docs.djangoproject.com/en/dev/howto/initial-data/): If you create a fixture named `initial_data.[xml/yaml/json]`, that fixture will be loaded every time you run `migrate`. This is...
Is it worth learning C/C++ before learning Python?
4,202,455
3
2010-11-17T07:54:03Z
4,202,471
7
2010-11-17T07:58:22Z
[ "c++", "python", "c" ]
I want to learn python, but I feel I should learn C or C++ to get a solid base to build on. I already know some C/C++ as well as other programming languages, which does help. So, should I master C/C++ first?
In my opinion it's better to start learning Python. I found it easier to learn then C or C++. It has libraries to do virtually anything you might need, and can do essentially anything. The only reason to use a more difficult language like C/C++ is if you need the performance or are writing code for an embedded system...
Python escape regex special characters
4,202,538
63
2010-11-17T08:09:24Z
4,202,559
98
2010-11-17T08:13:46Z
[ "python", "regex", "escaping" ]
Does Python have a function that I can use to escape special characters in a regular expression? For example, `I'm "stuck" :\` should become `I\'m \"stuck\" :\\`.
Use re.escape ``` re.escape(string) >>> re.escape('\ a.*$') '\\\\\\ a\\.\\*\\$' >>> print(re.escape('\ a.*$')) \\\ a\.\*\$ >>> re.escape('www.stackoverflow.com') 'www\\.stackoverflow\\.com' >>> print(re.escape('www.stackoverflow.com')) www\.stackoverflow\.com ``` See : <http://docs.python.org/library/re.html#module-c...
Python escape regex special characters
4,202,538
63
2010-11-17T08:09:24Z
4,202,892
8
2010-11-17T09:03:18Z
[ "python", "regex", "escaping" ]
Does Python have a function that I can use to escape special characters in a regular expression? For example, `I'm "stuck" :\` should become `I\'m \"stuck\" :\\`.
Use repr()[1:-1]. In this case, the double quotes don't need to be escaped. The [-1:1] slice is to remove the single quote from the beginning and the end. ``` >>> x = raw_input() I'm "stuck" :\ >>> print x I'm "stuck" :\ >>> print repr(x)[1:-1] I\'m "stuck" :\\ ``` Or maybe you just want to escape a phrase to paste i...
Python escape regex special characters
4,202,538
63
2010-11-17T08:09:24Z
12,012,114
12
2012-08-17T19:35:56Z
[ "python", "regex", "escaping" ]
Does Python have a function that I can use to escape special characters in a regular expression? For example, `I'm "stuck" :\` should become `I\'m \"stuck\" :\\`.
I'm surprised no one has mentioned using regular expressions via `re.sub()`: ``` import re print re.sub(r'([\"])', r'\\\1', 'it\'s "this"') # it's \"this\" print re.sub(r"([\'])", r'\\\1', 'it\'s "this"') # it\'s "this" print re.sub(r'([\" \'])', r'\\\1', 'it\'s "this"') # it\'s\ \"this\" ``` Important thing...
How do I design a class in Python?
4,203,163
129
2010-11-17T09:43:13Z
4,203,836
419
2010-11-17T11:21:51Z
[ "python", "oop", "class-design" ]
I've had some really awesome help on my previous questions [for detecting paws](http://stackoverflow.com/questions/4087919) and [toes within a paw](http://stackoverflow.com/questions/3684484), but all these solutions only work for one measurement at a time. [Now I have data](http://dl.dropbox.com/u/5207386/RAR-collect...
How to design a class. 1. Write down the words. You started to do this. Some people don't and wonder why they have problems. 2. Expand your set of words into simple statements about what these objects will be doing. That is to say, write down the various calculations you'll be doing on these things. Your short list of...
How do I design a class in Python?
4,203,163
129
2010-11-17T09:43:13Z
20,151,656
22
2013-11-22T18:09:53Z
[ "python", "oop", "class-design" ]
I've had some really awesome help on my previous questions [for detecting paws](http://stackoverflow.com/questions/4087919) and [toes within a paw](http://stackoverflow.com/questions/3684484), but all these solutions only work for one measurement at a time. [Now I have data](http://dl.dropbox.com/u/5207386/RAR-collect...
The following advices (similar to @S.Lott's advice) are from the book, [Beginning Python: From Novice to Professional](http://rads.stackoverflow.com/amzn/click/159059519X) 1. Write down a description of your problem (what should the problem do?). Underline all the nouns, verbs, and adjectives. 2. Go through the nouns,...
How do I design a class in Python?
4,203,163
129
2010-11-17T09:43:13Z
20,152,188
13
2013-11-22T18:42:31Z
[ "python", "oop", "class-design" ]
I've had some really awesome help on my previous questions [for detecting paws](http://stackoverflow.com/questions/4087919) and [toes within a paw](http://stackoverflow.com/questions/3684484), but all these solutions only work for one measurement at a time. [Now I have data](http://dl.dropbox.com/u/5207386/RAR-collect...
I like the TDD approach... So start by writing tests for what you want the behaviour to be. And write code that passes. At this point, don't worry too much about design, just get a test suite and software that passes. Don't worry if you end up with a single big ugly class, with complex methods. Sometimes, during this ...
How can I create a GzipFile instance from the “file-like object” that urllib.urlopen() returns?
4,204,604
12
2010-11-17T13:05:07Z
4,204,690
9
2010-11-17T13:14:07Z
[ "python", "gzip", "urllib" ]
I’m playing around with the Stack Overflow API using Python. I’m trying to decode the gzipped responses that the API gives. ``` import urllib, gzip url = urllib.urlopen('http://api.stackoverflow.com/1.0/badges/name') gzip.GzipFile(fileobj=url).read() ``` According to [the urllib2 documentation](http://docs.pytho...
The [urlopen docs](http://docs.python.org/library/urllib.html#urllib.urlopen) list the supported methods of the object that is returned. I recommend wrapping the object in another class that supports the methods that gzip expects. Other option: call the read method of the response object and put the result in a [Strin...
How to force a ndarray show in normal way instead of scientific notation?
4,205,259
4
2010-11-17T14:18:19Z
4,205,904
9
2010-11-17T15:22:20Z
[ "python", "arrays", "matrix", "numpy", "scientific-notation" ]
I'm trying to print a ndarray on the screen. But python always shows it in scientific notation, which I don't like. For a scalar we can use ``` >>> print '%2.4f' %(7.47212470e-01) 0.7472 ``` But how to do that for a numpy.ndarray like this : ``` [[ 7.47212470e-01 3.71730070e-01 1.16736538e-01 1.22172891e-02] ...
The [`numpy.set_string_function`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.set_string_function.html) function can be used to change the string representation of arrays. You can also use [`numpy.set_print_options`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html) to chan...
Capture keyboardinterrupt in Python without try-except
4,205,317
68
2010-11-17T14:24:51Z
4,205,386
96
2010-11-17T14:30:36Z
[ "python", "keyboardinterrupt" ]
Is there some way in Python to capture `KeyboardInterrupt` event without putting all the code inside a `try`-`except` statement? I want to cleanly exit without trace if user presses `ctrl`-`c`.
Yes, you can install an interrupt handler using the [signal module](https://docs.python.org/3/library/signal.html). ``` import signal import sys import time def signal_handler(signal, frame): print 'You pressed Ctrl+C!' sys.exit(0) signal.signal(signal.SIGINT, signal_handler) print 'Press Ctrl+C' while True:...
Capture keyboardinterrupt in Python without try-except
4,205,317
68
2010-11-17T14:24:51Z
4,205,404
22
2010-11-17T14:32:56Z
[ "python", "keyboardinterrupt" ]
Is there some way in Python to capture `KeyboardInterrupt` event without putting all the code inside a `try`-`except` statement? I want to cleanly exit without trace if user presses `ctrl`-`c`.
If all you want is to not show the traceback, make your code like this: ``` ## all your app logic here def main(): ## whatever your app does. if __name__ == "__main__": try: main() except KeyboardInterrupt: # do nothing here pass ``` (Yes, I know that this doesn't directly answer the ques...
Capture keyboardinterrupt in Python without try-except
4,205,317
68
2010-11-17T14:24:51Z
4,205,859
17
2010-11-17T15:18:34Z
[ "python", "keyboardinterrupt" ]
Is there some way in Python to capture `KeyboardInterrupt` event without putting all the code inside a `try`-`except` statement? I want to cleanly exit without trace if user presses `ctrl`-`c`.
An alternative to setting your own signal handler is to use a context-manager to catch the exception and ignore it: ``` >>> class CleanExit(object): ... def __enter__(self): ... return self ... def __exit__(self, exc_type, exc_value, exc_tb): ... if exc_type is KeyboardInterrupt: ... ...
Python - Way to recursively find and replace string in text files
4,205,854
11
2010-11-17T15:18:10Z
4,205,918
13
2010-11-17T15:23:03Z
[ "python" ]
I want to recursively search through a directory with subdirectories of text files and replace every occurrence of {$replace} within the files with the contents of a multi line string. How can this be achieved with python? **[EDIT]** So far all I have is the recursive code using os.walk to get a list of files that ar...
Check out [os.walk](http://docs.python.org/library/os.html#os.walk): ``` import os replacement = """some multi-line string""" for dname, dirs, files in os.walk("some_dir"): for fname in files: fpath = os.path.join(dname, fname) with open(fpath) as f: s = f.read() s = s.replace("...
Python - Way to recursively find and replace string in text files
4,205,854
11
2010-11-17T15:18:10Z
6,257,321
22
2011-06-06T19:57:38Z
[ "python" ]
I want to recursively search through a directory with subdirectories of text files and replace every occurrence of {$replace} within the files with the contents of a multi line string. How can this be achieved with python? **[EDIT]** So far all I have is the recursive code using os.walk to get a list of files that ar...
os.walk is great. However, it looks like you need to filer file types (which I would suggest if you are going to walk some directory). To do this, you should add `import fnmatch`. ``` import os, fnmatch def findReplace(directory, find, replace, filePattern): for path, dirs, files in os.walk(os.path.abspath(directo...
Django + apache & mod_wsgi: having to restart apache after changes
4,206,000
17
2010-11-17T15:30:08Z
4,206,117
11
2010-11-17T15:41:31Z
[ "python", "django", "apache", "mod-wsgi", "django-wsgi" ]
I configured my development server this way: Ubuntu, Apache, mod\_wsgi, Python 2.6 I work on the server from another computer connected to it. Most of the times the changes don't affect the application unless I restart Apache. In some cases the changes take effect without restarting the webserver, but after let's sa...
This blog post may help you: <http://blog.dscpl.com.au/2008/12/using-modwsgi-when-developing-django.html> ...and this: <http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode#Restarting_Daemon_Processes>
Django + apache & mod_wsgi: having to restart apache after changes
4,206,000
17
2010-11-17T15:30:08Z
4,206,134
9
2010-11-17T15:42:55Z
[ "python", "django", "apache", "mod-wsgi", "django-wsgi" ]
I configured my development server this way: Ubuntu, Apache, mod\_wsgi, Python 2.6 I work on the server from another computer connected to it. Most of the times the changes don't affect the application unless I restart Apache. In some cases the changes take effect without restarting the webserver, but after let's sa...
My suggestion is that you run the application in daemon mode. This way you won't be required to restart apache, just `touch my_handler.wsgi` and the daemon will know to restart the app. The apache httpd will not be only yours (in production) so it is fair not to restart it on every update.