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
Truncating floats in Python
783,897
46
2009-04-23T22:56:44Z
783,914
20
2009-04-23T23:04:46Z
[ "python", "floating-point" ]
I want to remove digits from a float to have a fixed number of digits after the dot, like: ``` 1.923328437452 -> 1.923 ``` I need to output as a string to another function, not print. Also I want to ignore the lost digits, not round them.
The result of `round` is a float, so watch out: ``` >>> round(1.923328437452, 3) 1.923 >>> round(1.23456, 3) 1.2350000000000001 ``` You will be better off when using a formatted string: ``` >>> "%.3f" % 1.923328437452 '1.923' >>> "%.3f" % 1.23456 '1.235' ```
Truncating floats in Python
783,897
46
2009-04-23T22:56:44Z
783,927
53
2009-04-23T23:10:44Z
[ "python", "floating-point" ]
I want to remove digits from a float to have a fixed number of digits after the dot, like: ``` 1.923328437452 -> 1.923 ``` I need to output as a string to another function, not print. Also I want to ignore the lost digits, not round them.
First, the function, for those who just want some copy-and-paste code: ``` def truncate(f, n): '''Truncates/pads a float f to n decimal places without rounding''' s = '{}'.format(f) if 'e' in s or 'E' in s: return '{0:.{1}f}'.format(f, n) i, p, d = s.partition('.') return '.'.join([i, (d+'0...
Truncating floats in Python
783,897
46
2009-04-23T22:56:44Z
784,665
7
2009-04-24T05:46:03Z
[ "python", "floating-point" ]
I want to remove digits from a float to have a fixed number of digits after the dot, like: ``` 1.923328437452 -> 1.923 ``` I need to output as a string to another function, not print. Also I want to ignore the lost digits, not round them.
``` def trunc(num, digits): sp = str(num).split('.') return '.'.join([sp[0], sp[:digits]]) ``` This should work. It should give you the truncation you are looking for.
Truncating floats in Python
783,897
46
2009-04-23T22:56:44Z
4,176,526
11
2010-11-14T06:58:32Z
[ "python", "floating-point" ]
I want to remove digits from a float to have a fixed number of digits after the dot, like: ``` 1.923328437452 -> 1.923 ``` I need to output as a string to another function, not print. Also I want to ignore the lost digits, not round them.
``` n = 1.923328437452 str(n)[:4] ```
Python Django Template: Iterate Through List
784,124
6
2009-04-24T00:35:14Z
784,145
10
2009-04-24T00:51:21Z
[ "python", "django", "django-templates" ]
Technically it should iterate from 0 to rangeLength outputting the user name of the c[i][0].from\_user...but from looking at example online, they seem to replace the brackets with dot notation. I have the following code: ``` <div id="right_pod"> {%for i in rangeLength%} <div class="user_pod" > {{c.i.0.from_user}} ...
Do you need `i` to be an index? If not, see if the following code does what you're after: ``` <div id="right_pod"> {% for i in c %} <div class="user_pod"> {{ i.0.from_user }} </div> {% endfor %} ```
Python Django Template: Iterate Through List
784,124
6
2009-04-24T00:35:14Z
786,873
7
2009-04-24T17:37:56Z
[ "python", "django", "django-templates" ]
Technically it should iterate from 0 to rangeLength outputting the user name of the c[i][0].from\_user...but from looking at example online, they seem to replace the brackets with dot notation. I have the following code: ``` <div id="right_pod"> {%for i in rangeLength%} <div class="user_pod" > {{c.i.0.from_user}} ...
You should use the slice template filter to achieve what you want: Iterate over the object (c in this case) like so: {% for c in objects|slice:":30" %} This would make sure that you only iterate over the first 30 objects. Also, you can use the forloop.counter object to keep track of which loop iteration you're on.
Python Django Template: Iterate Through List
784,124
6
2009-04-24T00:35:14Z
788,029
13
2009-04-25T01:25:13Z
[ "python", "django", "django-templates" ]
Technically it should iterate from 0 to rangeLength outputting the user name of the c[i][0].from\_user...but from looking at example online, they seem to replace the brackets with dot notation. I have the following code: ``` <div id="right_pod"> {%for i in rangeLength%} <div class="user_pod" > {{c.i.0.from_user}} ...
Please read the entire [documentation on the template language's for loops]. First of all, that iteration (like in Python) is over objects, not indexes. Secondly, that within any for loop there is a forloop variable with two fields you'll be interested in: ``` Variable Description forloop.counter The cu...
Random strings in Python 2.6 (Is this OK?)
785,058
76
2009-04-24T09:01:29Z
785,086
131
2009-04-24T09:09:39Z
[ "python", "random", "python-2.6" ]
I've been trying to find a more pythonic way of generating random string in python that can scale as well. Typically, I see something similar to ``` ''.join(random.choice(string.letters) for i in xrange(len)) ``` It sucks if you want to generate long string. I've been thinking about random.getrandombits for a while,...
``` import os random_string = os.urandom(string_length) ```
Random strings in Python 2.6 (Is this OK?)
785,058
76
2009-04-24T09:01:29Z
12,218,477
9
2012-08-31T15:32:38Z
[ "python", "random", "python-2.6" ]
I've been trying to find a more pythonic way of generating random string in python that can scale as well. Typically, I see something similar to ``` ''.join(random.choice(string.letters) for i in xrange(len)) ``` It sucks if you want to generate long string. I've been thinking about random.getrandombits for a while,...
Sometimes a uuid is short enough and if you don't like the dashes you can always.replace('-', '') them ``` from uuid import uuid4 random_string = str(uuid4()) ``` If you want it a specific length without dashes ``` random_string_length = 16 str(uuid4()).replace('-', '')[:random_string_length] ```
Getting Python System Calls as string results
785,078
6
2009-04-24T09:07:29Z
785,149
11
2009-04-24T09:24:52Z
[ "python" ]
I'd like to use `os.system("md5sum myFile")` and have the result returned from os.system instead of just runned in a subshell where it's echoed. In short I'd like to do this: ``` resultMD5 = os.system("md5sum myFile") ``` And only have the md5sum in resultMD5 and not echoed.
[`subprocess`](http://docs.python.org/library/subprocess.html) is better than using `os.system` or `os.popen` ``` import subprocess resultMD5 = subprocess.Popen(["md5sum","myFile"],stdout=subprocess.PIPE).communicate()[0] ``` Or just calculate the md5sum yourself with the [`hashlib`](http://docs.python.org/library/ha...
Is there a way to retrieve process stats using Perl or Python?
785,810
2
2009-04-24T13:18:16Z
786,386
7
2009-04-24T15:38:56Z
[ "python", "linux", "perl", "process" ]
Is there a way to generically retrieve process stats using Perl or Python? We could keep it Linux specific. There are a few problems: I won't know the PID ahead of time, but I *can* run the process in question from the script itself. For example, I'd have no problem doing: `./myscript.pl some/process/I/want/to/get/st...
Have a look at the [Proc::ProcessTable](http://search.cpan.org/~durist/Proc-ProcessTable-0.45/ProcessTable.pm) module which returns quite a bit of information on the processes in the system. Call the "fields" method to get a list of details that you can extract from each process. I recently discovered the above module...
Basic MVT issue in Django
786,149
6
2009-04-24T14:46:45Z
786,249
7
2009-04-24T15:08:44Z
[ "python", "django", "django-templates" ]
I have a Django website as follows: * site has several views * each view has its own template to show its data * each template extends a base template * base template is the base of the site, has all the JS/CSS and the basic layout So up until now it's all good. So now we have the master head of the site (which exist...
You want to use `context_instance` and `RequestContext`s. First, add at the top of your `views.py`: ``` from django.template import RequestContext ``` Then, update all of your views to look like: ``` def someview(request, ...) ... return render_to_response('viewtemplate.html', someContext, context_instance=...
What is wrong with my attempt to do a string replace operation in Python?
786,881
2
2009-04-24T17:39:56Z
786,902
12
2009-04-24T17:46:05Z
[ "python" ]
What am I doing wrong here? ``` import re x = "The sky is red" r = re.compile ("red") y = r.sub(x, "blue") print x # Prints "The sky is red" print y # Prints "blue" ``` How do i get it to print "The sky is blue"?
The problem with your code is that there are two sub functions in the re module. One is the general one and there's one tied to regular expression objects. Your code is not following either one: The two methods are: `re.sub(pattern, repl, string[, count])` [(docs here)](http://docs.python.org/library/re.html#re.sub) ...
is it possible to define name of function's arguments dynamically?
787,262
2
2009-04-24T19:36:01Z
787,282
7
2009-04-24T19:41:33Z
[ "python", "django" ]
Now I have this code: ``` attitude = request.REQUEST['attitude'] if attitude == 'want': qs = qs.filter(attitudes__want=True) elif attitude == 'like': qs = qs.filter(attitudes__like=True) elif attitude == 'hate': qs = qs.filter(attitudes__hate=True) ...
Yes. ``` qs.filter( **{ 'attitudes__%s'%arg:True } ) ```
How to add seconds on a datetime value in Python?
787,564
8
2009-04-24T21:01:16Z
787,583
24
2009-04-24T21:06:58Z
[ "python" ]
I tried modifying the second property, but didn't work. Basically I wanna do: ``` datetime.now().second += 3 ```
Have you checked out timedeltas? ``` from datetime import datetime, timedelta x = datetime.now() + timedelta(seconds=3) x += timedelta(seconds=3) ```
Find free disk space in python on OS/X
787,776
21
2009-04-24T22:17:32Z
787,832
32
2009-04-24T22:42:45Z
[ "python", "diskspace" ]
I'm looking for the number of free bytes on my HD, but have trouble doing so on python. I've tried the following: ``` import os stat = os.statvfs(path) print stat.f_bsize * stat.f_bavail ``` But, on OS/X it gives me a 17529020874752 bytes, which is about about 1.6 TB, which would be very nice, but unfortunately not...
Try using `f_frsize` instead of `f_bsize`. ``` >>> s = os.statvfs('/') >>> (s.f_bavail * s.f_frsize) / 1024 23836592L >>> os.system('df -k /') Filesystem 1024-blocks Used Available Capacity Mounted on /dev/disk0s2 116884912 92792320 23836592 80% / ```
Find free disk space in python on OS/X
787,776
21
2009-04-24T22:17:32Z
7,285,483
17
2011-09-02T15:10:15Z
[ "python", "diskspace" ]
I'm looking for the number of free bytes on my HD, but have trouble doing so on python. I've tried the following: ``` import os stat = os.statvfs(path) print stat.f_bsize * stat.f_bavail ``` But, on OS/X it gives me a 17529020874752 bytes, which is about about 1.6 TB, which would be very nice, but unfortunately not...
On UNIX: ``` import os from collections import namedtuple _ntuple_diskusage = namedtuple('usage', 'total used free') def disk_usage(path): """Return disk usage statistics about the given path. Returned valus is a named tuple with attributes 'total', 'used' and 'free', which are the amount of total, used...
How does a threading.Thread yield the rest of its quantum in Python?
787,803
34
2009-04-24T22:29:18Z
787,810
9
2009-04-24T22:31:16Z
[ "python", "multithreading", "yield" ]
I've got a thread that's polling a piece of hardware. ``` while not hardware_is_ready(): pass process_data_from_hardware() ``` But there are other threads (and processes!) that might have things to do. If so, I don't want to burn up cpu checking the hardware every other instruction. It's been a while since I've d...
Read up on the Global Interpreter Lock (GIL). For example: <http://jessenoller.com/2009/02/01/python-threads-and-the-global-interpreter-lock/> Also: <http://www.pyzine.com/Issue001/Section_Articles/article_ThreadingGlobalInterpreter.html> Do this in your code if you must do **Busy Waiting** (e.g. polling a device). ...
How does a threading.Thread yield the rest of its quantum in Python?
787,803
34
2009-04-24T22:29:18Z
790,246
46
2009-04-26T04:39:41Z
[ "python", "multithreading", "yield" ]
I've got a thread that's polling a piece of hardware. ``` while not hardware_is_ready(): pass process_data_from_hardware() ``` But there are other threads (and processes!) that might have things to do. If so, I don't want to burn up cpu checking the hardware every other instruction. It's been a while since I've d...
`time.sleep(0)` is sufficient to yield control -- no need to use a positive epsilon. Indeed, `time.sleep(0)` MEANS "yield to whatever other thread may be ready".
Case insensitivity in Python strings
787,842
4
2009-04-24T23:42:44Z
787,881
10
2009-04-25T00:00:19Z
[ "python" ]
I know that you can use the ctypes library to perform case insensitive comparisons on strings, however I would like to perform case insensitive replacement too. Currently the only way I know to do this is with Regex's and it seems a little poor to do so via that. Is there a case insensitive version of replace()?
You can supply the flag re.IGNORECASE to functions in the re module as described in the [docs](http://docs.python.org/library/re.html). ``` matcher = re.compile(myExpression, re.IGNORECASE) ```
Python interface to PayPal - urllib.urlencode non-ASCII characters failing
787,935
20
2009-04-25T00:24:09Z
788,055
41
2009-04-25T01:45:55Z
[ "python", "unicode", "paypal", "urllib2", "urllib" ]
I am trying to implement PayPal IPN functionality. The basic protocol is as such: 1. The client is redirected from my site to PayPal's site to complete payment. He logs into his account, authorizes payment. 2. PayPal calls a page on my server passing in details as POST. Details include a person's name, address, and pa...
Try converting the params dictionary to utf-8 first... urlencode seems to like that better than unicode: ``` params = urllib.urlencode(dict([k, v.encode('utf-8')] for k, v in params.items())) ``` Of course, this assumes your input is unicode. If your input is something other than unicode, you'll want to decode it to ...
How can I optimize this Python code to generate all words with word-distance 1?
788,084
31
2009-04-25T02:20:26Z
788,094
10
2009-04-25T02:30:29Z
[ "python", "optimization", "python-2.x", "levenshtein-distance", "word-diff" ]
Profiling shows this is the slowest segment of my code for a little word game I wrote: ``` def distance(word1, word2): difference = 0 for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference def getchildren(word, wordlist): return [ w for w in wordlist...
Your function `distance` is calculating the total distance, when you really only care about distance=1. The majority of cases you'll know it's >1 within a few characters, so you could return early and save a lot of time. Beyond that, there might be a better algorithm, but I can't think of it. **Edit:** Another idea. ...
How can I optimize this Python code to generate all words with word-distance 1?
788,084
31
2009-04-25T02:20:26Z
788,461
24
2009-04-25T07:38:18Z
[ "python", "optimization", "python-2.x", "levenshtein-distance", "word-diff" ]
Profiling shows this is the slowest segment of my code for a little word game I wrote: ``` def distance(word1, word2): difference = 0 for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference def getchildren(word, wordlist): return [ w for w in wordlist...
If your wordlist is very long, might it be more efficient to generate all possible 1-letter-differences from 'word', then check which ones are in the list? I don't know any Python but there should be a suitable data structure for the wordlist allowing for log-time lookups. I suggest this because if your words are reas...
Blender- python
788,102
2
2009-04-25T02:36:16Z
790,261
7
2009-04-26T04:57:45Z
[ "python", "blender" ]
How do I point Blender to the version of python I have installed
Mark, your version of Blender should be compiled with a specific version of Python interfaced to it -- and THAT is the version of Python you need to install on your machine. The same issue surfaced back when Python 2.5 was reasonably new and Blender was still distributed with 2.4 compiled in -- see <http://www.blender....
Check to see if python script is running
788,411
60
2009-04-25T06:59:10Z
788,436
9
2009-04-25T07:16:06Z
[ "python" ]
I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it? I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay r...
There are very good packages for restarting processes on UNIX. One that has a great tutorial about building and configuring it is [monit](http://www.cyberciti.biz/tips/howto-monitor-and-restart-linux-unix-service.html). With some tweaking you can have a rock solid proven technology keeping up your daemon.
Check to see if python script is running
788,411
60
2009-04-25T06:59:10Z
789,383
59
2009-04-25T17:37:56Z
[ "python" ]
I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it? I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay r...
Drop a pidfile somewhere (e.g. /tmp). Then you can check to see if the process is running by checking to see if the PID in the file exists. Don't forget to delete the file when you shut down cleanly, and check for it when you start up. ``` #/usr/bin/env python import os import sys pid = str(os.getpid()) pidfile = "/...
Check to see if python script is running
788,411
60
2009-04-25T06:59:10Z
4,291,218
9
2010-11-27T10:41:19Z
[ "python" ]
I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it? I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay r...
Of course the example from Dan will not work as it should be. Indeed, if the script crash, rise an exception, or does not clean pid file, the script will be run multiple times. I suggest the following based from another website: This is to check if there is already a lock file existing ``` \#/usr/bin/env python imp...
Check to see if python script is running
788,411
60
2009-04-25T06:59:10Z
7,758,075
98
2011-10-13T17:36:26Z
[ "python" ]
I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it? I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay r...
A technique that is handy on a Linux system is using domain sockets: ``` import socket import sys import time def get_lock(process_name): # Without holding a reference to our socket somewhere it gets garbage # collected when the function exits get_lock._lock_socket = socket.socket(socket.AF_UNIX, socket.S...
finding substrings in python
788,699
4
2009-04-25T11:02:51Z
788,720
16
2009-04-25T11:14:49Z
[ "python", "regex", "algorithm", "substring" ]
Can you please help me to get the substrings between two characters at each occurrence For example to get all the substrings between "Q" and "E" in the given example sequence in all occurrences: ``` ex: QUWESEADFQDFSAEDFS ``` and to find the substring with minimum length.
``` import re DATA = "QUWESEADFQDFSAEDFS" # Get all the substrings between Q and E: substrings = re.findall(r'Q([^E]+)E', DATA) print "Substrings:", substrings # Sort by length, then the first one is the shortest: substrings.sort(key=lambda s: len(s)) print "Shortest substring:", substrings[0] ```
finding substrings in python
788,699
4
2009-04-25T11:02:51Z
790,231
7
2009-04-26T04:21:40Z
[ "python", "regex", "algorithm", "substring" ]
Can you please help me to get the substrings between two characters at each occurrence For example to get all the substrings between "Q" and "E" in the given example sequence in all occurrences: ``` ex: QUWESEADFQDFSAEDFS ``` and to find the substring with minimum length.
RichieHindle has it right, except that ``` substrings.sort(key=len) ``` is a better way to express it than that redundant lambda;-). If you're using Python 2.5 or later, min(substrings, key=len) will actually give you the one shortest string (the first one, if several strings tie for "shortest") quite a bit faster t...
How can I import the sqlite3 module into Python 2.4?
789,030
7
2009-04-25T14:29:03Z
955,647
13
2009-06-05T12:48:01Z
[ "python", "sqlite" ]
The sqlite3 module is included in Python version 2.5+. However, I am stuck with version 2.4. I uploaded the sqlite3 module files, added the directory to sys.path, but I get the following error when I try to import it: ``` Traceback (most recent call last): File "<stdin>", line 1, in ? File "sqlite3/__init__.py", l...
I had same problem with CentOS and python 2.4 My solution: ``` yum install python-sqlite2 ``` and try following python code ``` try: import sqlite3 except: from pysqlite2 import dbapi2 as sqlite3 ```
Why builtin functions instead of root class methods?
789,718
4
2009-04-25T21:02:33Z
789,733
13
2009-04-25T21:10:10Z
[ "python", "oop" ]
(I'm sure this is a FAQ, but also hard to google) Why does Python use abs(x) instead of x.abs? As far as I see everything abs() does besides calling `x.__abs__` could just as well be implemented in object.abs() Is it historical, because there hasn't always been a root class?
The official answer from Guido van Rossum, with additional explanation from Fredrik Lundh, is here: <http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm> In a nutshell: 1. abs(x) reads more naturally than x.abs() for most such operations 2...
Turning on debug output for python 3 urllib
789,856
13
2009-04-25T22:31:58Z
790,011
12
2009-04-26T00:34:27Z
[ "python", "http", "debugging", "python-3.x", "urllib" ]
In python 2, it was possible to get debug output from urllib by doing ``` import httplib import urllib httplib.HTTPConnection.debuglevel = 1 response = urllib.urlopen('http://example.com').read() ``` However, in python 3 it looks like this has been moved to ``` http.client.HTTPConnection.set_debuglevel(level) ``` H...
You were right the first time. You can simply add the line `http.client.HTTPConnection.debuglevel = 1` at the start of your file to turn on HTTP debugging application-wide. `urllib.request` still uses `http.client`. It seems that there's also a way to set the debuglevel for a single handler (by creating `urllib.reques...
How do I return a CSV from a Pylons app?
790,019
11
2009-04-26T00:36:32Z
790,033
12
2009-04-26T00:45:28Z
[ "python", "csv", "pylons" ]
I'm trying to return a CSV from an action in my webapp, and give the user a prompt to download the file or open it from a spreadsheet app. I can get the CSV to spit out onto the screen, but how do I change the type of the file so that the browser recognizes that this isn't supposed to be displayed as HTML? Can I use th...
To tell the browser the type of content you're giving it, you need to set the `Content-type` header to 'text/csv'. In your Pylons function, the following should do the job: `response.headers['Content-type'] = 'text/csv'`
How do I return a CSV from a Pylons app?
790,019
11
2009-04-26T00:36:32Z
790,140
9
2009-04-26T02:29:20Z
[ "python", "csv", "pylons" ]
I'm trying to return a CSV from an action in my webapp, and give the user a prompt to download the file or open it from a spreadsheet app. I can get the CSV to spit out onto the screen, but how do I change the type of the file so that the browser recognizes that this isn't supposed to be displayed as HTML? Can I use th...
PAG is correct, but furthermore if you want to suggest a name for the downloaded file you can also set `response.headers['Content-disposition'] = 'attachment; filename=suggest.csv'`
How do I return a CSV from a Pylons app?
790,019
11
2009-04-26T00:36:32Z
1,441,002
7
2009-09-17T19:56:02Z
[ "python", "csv", "pylons" ]
I'm trying to return a CSV from an action in my webapp, and give the user a prompt to download the file or open it from a spreadsheet app. I can get the CSV to spit out onto the screen, but how do I change the type of the file so that the browser recognizes that this isn't supposed to be displayed as HTML? Can I use th...
Yes, you can use the csv module for this: ``` import csv from cStringIO import StringIO ``` ... ``` def results_csv(self): response.headers['Content-Type'] = 'text/csv' s = StringIO() writer = csv.writer(s) writer.writerow(['header', 'header', 'header']) writer.writerow([123, 456, 789]) retur...
Is it possible to call a Python module from ObjC?
790,103
6
2009-04-26T01:52:07Z
791,077
12
2009-04-26T15:45:38Z
[ "python", "objective-c", "pyobjc" ]
Using PyObjC, is it possible to import a Python module, call a function and get the result as (say) a NSString? For example, doing the equivalent of the following Python code: ``` import mymodule result = mymodule.mymethod() ``` ..in pseudo-ObjC: ``` PyModule *mypymod = [PyImport module:@"mymodule"]; NSString *resu...
As mentioned in Alex Martelli's answer (although the link in the mailing-list message was broken, it should be <https://docs.python.org/extending/embedding.html#pure-embedding>).. The C way of calling.. ``` print urllib.urlopen("http://google.com").read() ``` * Add the Python.framework to your project (Right click `E...
Object class override or modify
790,560
4
2009-04-26T09:36:41Z
790,588
8
2009-04-26T10:04:12Z
[ "python" ]
Is it possible to add a method to an object class, and use it on all objects?
In Python attributes are implemented using a dictionary : ``` >>> t = test() >>> t.__dict__["foo"] = "bla" >>> t.foo 'bla' ``` But for "object", it uses a 'dictproxy' as an interface to prevent such assignement : ``` >>> object.__dict__["test"] = "test" TypeError: 'dictproxy' object does not support item assignment ...
How to synthesize sounds?
790,960
6
2009-04-26T14:37:33Z
790,973
15
2009-04-26T14:43:37Z
[ "python", "numpy", "alsa" ]
I'd like to produce sounds that would resemble audio from real instruments. The problem is that I have very little clue how to get that. What I know this far from real instruments is that sounds they output are rarely clean. But how to produce such unclean sounds? This far I've gotten to do this, it produces quite pl...
Sound synthesis is a complex topic which requires many years of study to master. It is also not an entirely solved problem, although relatively recent developments (such as physical modelling synthesis) have made progress in imitating real-world instruments. There are a number of options open to you. If you are sure ...
How to synthesize sounds?
790,960
6
2009-04-26T14:37:33Z
791,142
8
2009-04-26T16:32:34Z
[ "python", "numpy", "alsa" ]
I'd like to produce sounds that would resemble audio from real instruments. The problem is that I have very little clue how to get that. What I know this far from real instruments is that sounds they output are rarely clean. But how to produce such unclean sounds? This far I've gotten to do this, it produces quite pl...
Cheery, if you want to generate (from scratch) something that really sounds "organic", i.e. like a physical object, you're probably best off to learn a bit about how these sounds are generated. For a solid introduction, you could have a look at a book such as Fletcher and Rossings [The Physics of Musical Instruments](h...
Which JSON module can I use in Python 2.5?
791,561
61
2009-04-26T20:34:15Z
791,564
61
2009-04-26T20:35:22Z
[ "python", "json" ]
I would like to use Python's [JSON](http://docs.python.org/library/json.html) module. It was only introduced in Python 2.6 and I'm stuck with 2.5 for now. Is the particular JSON module provided with Python 2.6 available as a separate module that can be used with 2.5?
You can use [simplejson](http://pypi.python.org/pypi/simplejson). As shown by [the answer](http://stackoverflow.com/a/2119597) form [pkoch](http://stackoverflow.com/users/5128/pkoch) you can use the following import statement to get a json library depending on the installed python version: ``` try: import json ex...
Which JSON module can I use in Python 2.5?
791,561
61
2009-04-26T20:34:15Z
2,119,597
48
2010-01-22T18:41:57Z
[ "python", "json" ]
I would like to use Python's [JSON](http://docs.python.org/library/json.html) module. It was only introduced in Python 2.6 and I'm stuck with 2.5 for now. Is the particular JSON module provided with Python 2.6 available as a separate module that can be used with 2.5?
To Wells and others: > Way late here, but how can you write a script to import either json or simplejson depending on the installed python version? Here's how: ```` ``` try: import json except ImportError: import simplejson as json ``` ````
Best way to turn a list into a dict, where the keys are a value of each object?
791,708
6
2009-04-26T22:14:22Z
791,717
8
2009-04-26T22:21:48Z
[ "python" ]
I am attempting to take a list of objects, and turn that list into a dict. The dict values would be each object in the list, and the dict keys would be a value found in each object. Here is some code representing what im doing: ``` class SomeClass(object): def __init__(self, name): self.name = name obje...
``` d = dict(zip([o.name for o in object_list], object_list)) ```
Best way to turn a list into a dict, where the keys are a value of each object?
791,708
6
2009-04-26T22:14:22Z
791,722
13
2009-04-26T22:23:57Z
[ "python" ]
I am attempting to take a list of objects, and turn that list into a dict. The dict values would be each object in the list, and the dict keys would be a value found in each object. Here is some code representing what im doing: ``` class SomeClass(object): def __init__(self, name): self.name = name obje...
In python 3.0 you can use a dict comprehension: ``` {an_object.name : an_object for an_object in object_list} ``` This is also possible in Python 2, but it's a bit uglier: ``` dict([(an_object.name, an_object) for an_object in object_list]) ```
Best way to turn a list into a dict, where the keys are a value of each object?
791,708
6
2009-04-26T22:14:22Z
791,827
7
2009-04-26T23:31:40Z
[ "python" ]
I am attempting to take a list of objects, and turn that list into a dict. The dict values would be each object in the list, and the dict keys would be a value found in each object. Here is some code representing what im doing: ``` class SomeClass(object): def __init__(self, name): self.name = name obje...
If you're concerned with speed, then we can improve things slightly. Your "verbose" solution (which is really fine) creates no intermediate data structures. On the other hand, hyperboreean's solution, ``` d = dict(zip([o.name for o in object_list], object_list)) ``` creates two unnecessary lists: `[o.name for o in ob...
Can't decode utf-8 string in python on os x terminal.app
792,017
4
2009-04-27T01:47:47Z
792,139
18
2009-04-27T03:12:20Z
[ "python", "osx", "unicode", "terminal" ]
I have terminal.app set to accept utf-8 and in bash I can type unicode characters, copy and paste them, but if I start the python shell I can't and if I try to decode unicode I get errors: ``` >>> wtf = u'\xe4\xf6\xfc'.decode() Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError...
I think there is encode/decode confusion all over the place. You start with an unicode object: ``` u'\xe4\xf6\xfc' ``` This is an unicode object, the three characters are the unicode codepoints for "äöü". If you want to turn them into Utf-8, you have to **encode** them: ``` >>> u'\xe4\xf6\xfc'.encode('utf-8') '\x...
Find shortest substring
792,394
2
2009-04-27T06:08:16Z
792,419
8
2009-04-27T06:24:32Z
[ "python", "substring" ]
I have written a code to find the substring from a string. It prints all substrings. But I want a substring that ranges from length 2 to 6 and print the substring of minimum length. Please help me Program: ``` import re p=re.compile('S(.+?)N') s='ASDFANSAAAAAFGNDASMPRKYN' s1=p.findall(s) print s1 ``` output: ``` ['...
If you already have the list, you can use the [min](http://docs.python.org/library/functions.html#min) function with the [len](http://docs.python.org/library/functions.html#len) function as the second argument. ``` >>> s1 = ['DFA', 'AAAAAFG', 'MPRKY'] >>> min(s1, key=len) 'DFA' ``` **EDIT:** In the event that two a...
Is Python the right hammer for this nail? (build script)
792,629
14
2009-04-27T08:19:11Z
792,659
15
2009-04-27T08:32:34Z
[ "python", "build-process", "build-automation" ]
Currently I'm using a Windows batch file to build my software. It does things like running MSBuild, copying files, creating a ZIP file, running some tests, including the subversion revision number, etc. But the problem is, batch files are evil. So I would like to change to something better. I was planning to recreate ...
For a tool that is scripted with Python, I happen to think [Paver](http://www.blueskyonmars.com/projects/paver/) is a more easily-managed and more flexible build automator than SCons. Unlike SCons, Paver is designed for the plethora of not-compiling-programs tasks that go along with managing and distributing a software...
Is Python the right hammer for this nail? (build script)
792,629
14
2009-04-27T08:19:11Z
792,663
7
2009-04-27T08:35:01Z
[ "python", "build-process", "build-automation" ]
Currently I'm using a Windows batch file to build my software. It does things like running MSBuild, copying files, creating a ZIP file, running some tests, including the subversion revision number, etc. But the problem is, batch files are evil. So I would like to change to something better. I was planning to recreate ...
Batch files aren't evil - they've actually come quite a long way from the brain-dead days of command.com. The command language can be pretty expressive nowadays, it just requires a bit of effort on your part to learn it. Unless there's an actual *problem* with your build script that you can't fix (and, if that's the c...
String formatting in Python version earlier than 2.6
792,721
29
2009-04-27T08:57:14Z
792,740
8
2009-04-27T09:01:14Z
[ "python", "format" ]
When I run the following code in Python 2.5.2: ``` for x in range(1, 11): print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) ``` I get: ``` Traceback (most recent call last): File "<pyshell#9>", line 2, in <module> print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) AttributeError: 'str' object has no attri...
I believe that is a Python 3.0 feature, although it is in version 2.6. But if you have a version of Python below that, that type of string formatting will not work. If you are trying to print formatted strings in general, use Python's printf-style syntax through the `%` operator. For example: ``` print '%.2f' % some_...
String formatting in Python version earlier than 2.6
792,721
29
2009-04-27T08:57:14Z
792,745
42
2009-04-27T09:04:05Z
[ "python", "format" ]
When I run the following code in Python 2.5.2: ``` for x in range(1, 11): print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) ``` I get: ``` Traceback (most recent call last): File "<pyshell#9>", line 2, in <module> print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) AttributeError: 'str' object has no attri...
The `str.format` method was [introduced in Python 3.0, and backported](http://docs.python.org/3.0/whatsnew/2.6.html#pep-3101-advanced-string-formatting) to Python 2.6 and later.
String formatting in Python version earlier than 2.6
792,721
29
2009-04-27T08:57:14Z
792,776
31
2009-04-27T09:12:12Z
[ "python", "format" ]
When I run the following code in Python 2.5.2: ``` for x in range(1, 11): print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) ``` I get: ``` Traceback (most recent call last): File "<pyshell#9>", line 2, in <module> print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) AttributeError: 'str' object has no attri...
For Python versions below 2.6, use the [% operator](http://docs.python.org/library/stdtypes.html#string-formatting) to interpolate a sequence of values into a format string: ``` for x in range(1, 11): print '%2d %3d %4d' % (x, x*x, x*x*x) ``` You should also be aware that this operator can interpolate by *name* f...
String formatting in Python version earlier than 2.6
792,721
29
2009-04-27T08:57:14Z
2,201,681
7
2010-02-04T17:16:01Z
[ "python", "format" ]
When I run the following code in Python 2.5.2: ``` for x in range(1, 11): print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) ``` I get: ``` Traceback (most recent call last): File "<pyshell#9>", line 2, in <module> print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) AttributeError: 'str' object has no attri...
*Although the existing answers describe the causes and point in the direction of a fix, none of them actually provide a solution that accomplishes what the question asks.* You have two options to solve the problem. The first is to upgrade to Python 2.6 or greater, which supports the [format string construct](http://do...
psycopg2 "TypeError: not all arguments converted during string formatting"
793,679
7
2009-04-27T14:13:53Z
1,492,188
16
2009-09-29T12:14:57Z
[ "python", "postgresql", "psycopg2" ]
I'm trying to insert binary data (a whirlpool hash) into a PG table and am getting an error: ``` TypeError: not all arguments converted during string formatting ``` code: ``` cur.execute(""" INSERT INTO sessions (identity_hash, posted_on) VALUES (%s, NOW()) """, identity_hash) ``` I ...
The problem you have is that you are passing the object as second parameter: the second parameters should be either a tuple or a dict. There is no shortcut as in the % string operator. You should do: ``` cur.execute(""" INSERT INTO sessions (identity_hash, posted_on) VALUES (%s, NOW())...
Remove lines from file
793,759
3
2009-04-27T14:30:46Z
793,830
14
2009-04-27T14:43:13Z
[ "python", "perl", "text", "awk", "text-processing" ]
I am doing some text processing on a unix system. I have access to the command line on this machine and it has Python, Perl and the default text processing progams installed, awk etc. I have a text file that looks like below: ``` 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029...
With `awk`: ``` awk 'NF > 2' input_file > output_file ```
Remove lines from file
793,759
3
2009-04-27T14:30:46Z
793,865
8
2009-04-27T14:49:24Z
[ "python", "perl", "text", "awk", "text-processing" ]
I am doing some text processing on a unix system. I have access to the command line on this machine and it has Python, Perl and the default text processing progams installed, awk etc. I have a text file that looks like below: ``` 2029754527851451717 2029754527851451717 2029754527851451717 2029754527851451717 2029...
``` grep ':' filename ```
Built in python hash() function
793,761
73
2009-04-27T14:31:00Z
793,772
49
2009-04-27T14:33:54Z
[ "python", "google-app-engine", "hash" ]
Windows XP, Python 2.5: ``` hash('http://stackoverflow.com') Result: 1934711907 ``` Google App Engine (<http://shell.appspot.com/>): ``` hash('http://stackoverflow.com') Result: -5768830964305142685 ``` Why is that? How can I have a hash function which will give me same results across different platforms (Windows, ...
Use [hashlib](http://docs.python.org/library/hashlib.html?highlight=hash#module-hashlib) as `hash()` [was designed to be used to](https://docs.python.org/2/library/functions.html#hash): > quickly compare dictionary keys during a dictionary lookup and therefore does not guarantee that it will be the same across Python...
Built in python hash() function
793,761
73
2009-04-27T14:31:00Z
793,835
84
2009-04-27T14:43:44Z
[ "python", "google-app-engine", "hash" ]
Windows XP, Python 2.5: ``` hash('http://stackoverflow.com') Result: 1934711907 ``` Google App Engine (<http://shell.appspot.com/>): ``` hash('http://stackoverflow.com') Result: -5768830964305142685 ``` Why is that? How can I have a hash function which will give me same results across different platforms (Windows, ...
As stated in the documentation, built-in hash() function is *not* designed for storing resulting hashes somewhere externally. It is used to provide object's hash value, to store them in dictionaries and so on. It's also implementation-specific (GAE uses a modified version of Python). Check out: ``` >>> class Foo: ... ...
Built in python hash() function
793,761
73
2009-04-27T14:31:00Z
3,979,894
32
2010-10-20T16:02:17Z
[ "python", "google-app-engine", "hash" ]
Windows XP, Python 2.5: ``` hash('http://stackoverflow.com') Result: 1934711907 ``` Google App Engine (<http://shell.appspot.com/>): ``` hash('http://stackoverflow.com') Result: -5768830964305142685 ``` Why is that? How can I have a hash function which will give me same results across different platforms (Windows, ...
The response is absolutely no surprise: in fact ``` In [1]: -5768830964305142685L & 0xffffffff Out[1]: 1934711907L ``` so if you want to get reliable responses **on ASCII strings**, just get the lower 32 bits as `uint`. The hash function for strings is 32-bit-safe and *almost* portable. On the other side, you can't ...
Built in python hash() function
793,761
73
2009-04-27T14:31:00Z
5,467,932
9
2011-03-29T04:36:02Z
[ "python", "google-app-engine", "hash" ]
Windows XP, Python 2.5: ``` hash('http://stackoverflow.com') Result: 1934711907 ``` Google App Engine (<http://shell.appspot.com/>): ``` hash('http://stackoverflow.com') Result: -5768830964305142685 ``` Why is that? How can I have a hash function which will give me same results across different platforms (Windows, ...
Hash results varies between 32bit and 64bit platforms If a calculated hash shall be the same on both platforms consider using ``` def hash32(value): return hash(value) & 0xffffffff ```
Built in python hash() function
793,761
73
2009-04-27T14:31:00Z
33,763,349
9
2015-11-17T17:29:46Z
[ "python", "google-app-engine", "hash" ]
Windows XP, Python 2.5: ``` hash('http://stackoverflow.com') Result: 1934711907 ``` Google App Engine (<http://shell.appspot.com/>): ``` hash('http://stackoverflow.com') Result: -5768830964305142685 ``` Why is that? How can I have a hash function which will give me same results across different platforms (Windows, ...
Most answers suggest this is because of different platforms, but there is more to it. From [the documentation of `object.__hash__(self)`](https://docs.python.org/3.5/reference/datamodel.html#object.__hash__): > By default, the `__hash__()` values of `str`, `bytes` and > `datetime` objects are “salted” with an unpr...
Returning an object vs returning a tuple
794,132
11
2009-04-27T15:48:48Z
795,805
12
2009-04-28T00:34:52Z
[ "python", "design" ]
I am developing in python a file class that can read and write a file, containing a list of xyz coordinates. In my program, I already have a Coord3D class to hold xyz coordinates. My question is relative to the design of a getCoordinate(index) method. Should I return a tuple of floats, or a Coord3D object? In the fir...
Compromise solution: Instead of a class, make Coord3D a [`namedtuple`](http://docs.python.org/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields) and return that :-) Usage: ``` Coord3D = namedtuple('Coord3D', 'x y z') def getCoordinate(index): # do stuff, creating variables x, y, z...
Python list comprehension - access last created element?
794,774
11
2009-04-27T18:46:27Z
794,871
10
2009-04-27T19:12:32Z
[ "python" ]
Is it possible to access the previous element generated in a list comprehension. I am working on some toy encryption stuff. Given the key as an arbitrarily large integer, an initialization value, and a list of elements as the message to encrypt. I need to xor each element with the previous ciphered element and the key...
There isn't a good, Pythonic way to do this with a list comprehension. The best way to think about list comprehensions is as a replacement for `map` and `filter`. In other words, you'd use a list comprehension whenever you need to take a list and * Use its elements as input for some expression (e.g. squaring the eleme...
How to convert datetime to string in python in django
794,995
4
2009-04-27T19:42:52Z
795,000
11
2009-04-27T19:44:51Z
[ "python", "django" ]
I have a datetime object at my model. I am sending it to the view, but in html i don't know what to write in order to format it. I am trying ``` {{ item.date.strftime("%Y-%m-%d")|escape }} ``` but I get ``` TemplateSyntaxError: Could not parse some characters: item.date.strftime|("%Y-%m-%d")||escape ``` when I am ...
Try using the built-in Django [date format filter](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date) instead: ``` {{ item.date|date:"Y M d" }} ```
How to perform common post-initialization tasks in inherited Python classes?
795,190
4
2009-04-27T20:38:03Z
795,877
8
2009-04-28T01:17:47Z
[ "python", "inheritance", "initialization" ]
The initialization process of group of classes that share a common parent can be divided into three parts: common part1, class-specific part, common part2. Currently the first two parts are called from the \_\_init\_\_ function of each child class, but the second common part has to be called separately For example: ``...
Template Method Design Pattern to the rescue: ``` class BaseClass: def __init__(self, specifics=None): print 'base __init__' self.common1() if specifics is not None: specifics() self.finalizeInitialization() def common1(self): print 'common 1' def final...
How to compare value of 2 fields in Django QuerySet?
795,310
7
2009-04-27T21:13:51Z
795,322
15
2009-04-27T21:17:30Z
[ "python", "django", "model" ]
I have a django model like this: ``` class Player(models.Model): name = models.CharField() batting = models.IntegerField() bowling = models.IntegerField() ``` What would be the Django QuerySet equivalent of the following SQL? ``` SELECT * FROM player WHERE batting > bowling; ```
In django 1.1 you can do the following: ``` players = Player.objects.filter(batting__gt=F('bowling')) ``` See the [other question](http://stackoverflow.com/questions/433294/column-comparison-in-django-queries) for details
Google AppEngine: how to count a database's entries beyond 1000?
795,817
12
2009-04-28T00:44:43Z
796,588
14
2009-04-28T07:15:18Z
[ "python", "google-app-engine", "count" ]
**Duplicate of** ["how does one get a count of rows in a datastore model in google appengine?"](http://stackoverflow.com/questions/751124/how-does-one-get-a-count-of-rows-in-a-datastore-model-in-google-appengine) --- I want to know how many users I have. Previously, I achieved this with the following code: ``` users...
It is indeed a duplicate and the other post describes how to theoretically do it, but I'd like to stress that you should really not be doing counts this way. The reason being that BigTable by its distributed nature is really bad for aggregates. What you probably want to do is add a transactional counter to that entity,...
Can't subtract offset-naive and offset-aware datetimes
796,008
105
2009-04-28T02:28:08Z
796,019
133
2009-04-28T02:36:07Z
[ "python", "postgresql", "datetime", "timezone" ]
I have a timezone aware `timestamptz` field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age. The problem I'm having is that both `datetime.datetime.now()` and `datetime.datetime.utcnow()` seem to return timezone unaware timestamps, which results in me ge...
have you tried to remove the timezone awareness? from <http://pytz.sourceforge.net/> ``` naive = dt.replace(tzinfo=None) ``` may have to add time zone conversion as well.
Can't subtract offset-naive and offset-aware datetimes
796,008
105
2009-04-28T02:28:08Z
25,662,061
27
2014-09-04T09:37:14Z
[ "python", "postgresql", "datetime", "timezone" ]
I have a timezone aware `timestamptz` field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age. The problem I'm having is that both `datetime.datetime.now()` and `datetime.datetime.utcnow()` seem to return timezone unaware timestamps, which results in me ge...
The correct solution is to *add* the timezone info e.g., to get the current time as an aware datetime object in Python 3: ``` from datetime import datetime, timezone now = datetime.now(timezone.utc) ``` On older Python versions, you could define the `utc` tzinfo object yourself (example from datetime docs): ``` fro...
Can't subtract offset-naive and offset-aware datetimes
796,008
105
2009-04-28T02:28:08Z
30,971,376
16
2015-06-22T02:28:47Z
[ "python", "postgresql", "datetime", "timezone" ]
I have a timezone aware `timestamptz` field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age. The problem I'm having is that both `datetime.datetime.now()` and `datetime.datetime.utcnow()` seem to return timezone unaware timestamps, which results in me ge...
I know some people use Django specifically as an interface to abstract this type of database interaction. Django provides utilities that can be used for this: ``` from django.utils import timezone now_aware = timezone.now() ``` You do need to set up a basic Django settings infrastructure, even if you are just using t...
How to limit choice field options based on another choice field in django admin
796,466
9
2009-04-28T06:28:14Z
796,567
10
2009-04-28T07:07:33Z
[ "javascript", "python", "django", "django-admin" ]
I have the following models: ``` class Category(models.Model): name = models.CharField(max_length=40) class Item(models.Model): name = models.CharField(max_length=40) category = models.ForeignKey(Category) class Demo(models.Model): name = models.CharField(max_length=40) category = models.ForeignK...
Here is some javascript (JQuery based) to change the item option values when category changes: ``` <script charset="utf-8" type="text/javascript"> $(function(){ $("select#id_category").change(function(){ $.getJSON("/items/",{id: $(this).val(), view: 'json'}, function(j) { var options = '<option val...
Python "protected" attributes
797,771
21
2009-04-28T12:55:50Z
797,814
52
2009-04-28T13:03:31Z
[ "python" ]
How do I access a private attribute of a parent class from a subclass (without making it public)?
My understanding of Python convention is * \_member is protected * \_\_member is private Options for if you control the parent class * Make it protected instead of private since that seems like what you really want * Use a getter (@property def \_protected\_access\_to\_member...) to limit the protected access ...
Python "protected" attributes
797,771
21
2009-04-28T12:55:50Z
21,217,121
13
2014-01-19T13:06:06Z
[ "python" ]
How do I access a private attribute of a parent class from a subclass (without making it public)?
Some language designers subscribe to the following assumption: > *"Many programmers are irresponsible, dim-witted, or both."* These language designers will feel tempted to protect programmers from each other by introducing a `private` specifier into their language. Shortly later they recognize that this is often too ...
Django caching - can it be done pre-emptively?
797,773
4
2009-04-28T12:56:05Z
797,882
8
2009-04-28T13:17:09Z
[ "python", "django", "caching" ]
I have a Django view, which receives part of its data from an external website, which I parse using urllib2/BeautifulSoup. This operation is rather expensive so I cache it using the low-level cache API, for ~5 minutes. However, each user which accesses the site after the cached data expires will receive a significant ...
So you want to schedule something to run at a regular interval? At the cost of some CPU time, you can use [this simple app](http://code.google.com/p/django-cron/wiki/Install). Alternatively, if you can use it, the [cron job](http://www.thesitewizard.com/general/set-cron-job.shtml) for every 5 minutes is: ``` */5 * * ...
Algorithm for neatly indenting SQL statements (Python implementation would be nice)
798,180
19
2009-04-28T14:14:24Z
798,417
33
2009-04-28T14:59:12Z
[ "python", "sql", "coding-style", "indentation", "pretty-print" ]
I'd like to reformat some SQL statements that are a single string with newlines in to something that's much easier to read. I don't personally know of a good coding style for indenting SQL - how should nested queries / where clauses / left joins / etc by represented to maximise readability? Has anyone seen a pretty-p...
You can try [sqlparse](http://python-sqlparse.googlecode.com). It's a Python module that provides simple SQL formatting. A online demo is available [here](http://sqlformat.appspot.com).
How to call a Perl script from Python, piping input to it?
798,413
6
2009-04-28T14:58:34Z
798,425
9
2009-04-28T15:00:49Z
[ "python", "perl", "domainkeys", "dkim" ]
I'm hacking some support for DomainKeys and DKIM into an open source email marketing program, which uses a python script to send the actual emails via SMTP. I decided to go the quick and dirty route, and just write a perl script that accepts an email message from STDIN, signs it, then returns it signed. What I would l...
[os.popen()](http://docs.python.org/library/os.html#os.popen) will return a tuple with the stdin and stdout of the subprocess.
How to call a Perl script from Python, piping input to it?
798,413
6
2009-04-28T14:58:34Z
798,534
10
2009-04-28T15:25:57Z
[ "python", "perl", "domainkeys", "dkim" ]
I'm hacking some support for DomainKeys and DKIM into an open source email marketing program, which uses a python script to send the actual emails via SMTP. I decided to go the quick and dirty route, and just write a perl script that accepts an email message from STDIN, signs it, then returns it signed. What I would l...
Use [subprocess](http://docs.python.org/library/subprocess.html). Here is the Python script: ``` #!/usr/bin/python import subprocess var = "world" pipe = subprocess.Popen(["./x.pl", var], stdout=subprocess.PIPE) result = pipe.stdout.read() print result ``` And here is the Perl script: ``` #!/usr/bin/perl use s...
What is the correct (or best) way to subclass the Python set class, adding a new instance variable?
798,442
5
2009-04-28T15:05:21Z
804,973
11
2009-04-30T01:01:00Z
[ "python", "subclass", "set", "instance-variables" ]
I'm implementing an object that is almost identical to a set, but requires an extra instance variable, so I am subclassing the built-in set object. What is the best way to make sure that the value of this variable is copied when one of my objects is copied? Using the old sets module, the following code worked perfectl...
My favorite way to wrap methods of a built-in collection: ``` class Fooset(set): def __init__(self, s=(), foo=None): super(Fooset,self).__init__(s) if foo is None and hasattr(s, 'foo'): foo = s.foo self.foo = foo @classmethod def _wrap_methods(cls, names): def...
All combinations of a list of lists
798,854
95
2009-04-28T16:44:47Z
798,893
168
2009-04-28T16:54:56Z
[ "python", "combinations" ]
I'm basically looking for a python version of [Combination of `List<List<int>>`](http://stackoverflow.com/questions/545703/combination-of-listlistint) Given a list of lists, I need a new list that gives all the possible combinations of items between the lists. ``` [[1,2,3],[4,5,6],[7,8,9,10]] -> [[1,4,7],[1,4,8],...,...
you need [`itertools.product`](https://docs.python.org/2/library/itertools.html#itertools.product): ``` >>> import itertools >>> a = [[1,2,3],[4,5,6],[7,8,9,10]] >>> list(itertools.product(*a)) [(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 4, 10), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 5, 10), (1, 6, 7), (1, 6, 8), (1, 6, 9), (...
All combinations of a list of lists
798,854
95
2009-04-28T16:44:47Z
798,894
17
2009-04-28T16:55:04Z
[ "python", "combinations" ]
I'm basically looking for a python version of [Combination of `List<List<int>>`](http://stackoverflow.com/questions/545703/combination-of-listlistint) Given a list of lists, I need a new list that gives all the possible combinations of items between the lists. ``` [[1,2,3],[4,5,6],[7,8,9,10]] -> [[1,4,7],[1,4,8],...,...
The most elegant solution is to use [itertools.product](https://docs.python.org/2/library/itertools.html#itertools.product) in python 2.6. If you aren't using Python 2.6, the docs for itertools.product actually show an equivalent function to do the product the "manual" way: ``` def product(*args, **kwds): # produ...
All combinations of a list of lists
798,854
95
2009-04-28T16:44:47Z
798,908
10
2009-04-28T16:58:13Z
[ "python", "combinations" ]
I'm basically looking for a python version of [Combination of `List<List<int>>`](http://stackoverflow.com/questions/545703/combination-of-listlistint) Given a list of lists, I need a new list that gives all the possible combinations of items between the lists. ``` [[1,2,3],[4,5,6],[7,8,9,10]] -> [[1,4,7],[1,4,8],...,...
``` listOLists = [[1,2,3],[4,5,6],[7,8,9,10]] for list in itertools.product(*listOLists): print list; ``` I hope you find that as elegant as I did when I first encountered it.
Python exceptions: call same function for any Exception
799,293
4
2009-04-28T18:35:33Z
799,315
15
2009-04-28T18:42:01Z
[ "python", "exception" ]
Notice in the code below that `foobar()` is called if any Exception is thrown. Is there a way to do this without using the same line in every Exception? ``` try: foo() except(ErrorTypeA): bar() foobar() except(ErrorTypeB): baz() foobar() except(SwineFlu): print 'You have caught Swine Flu!' foobar() excep...
``` success = False try: foo() success = True except(A): bar() except(B): baz() except(C): bay() finally: if not success: foobar() ```
Python exceptions: call same function for any Exception
799,293
4
2009-04-28T18:35:33Z
799,323
11
2009-04-28T18:43:22Z
[ "python", "exception" ]
Notice in the code below that `foobar()` is called if any Exception is thrown. Is there a way to do this without using the same line in every Exception? ``` try: foo() except(ErrorTypeA): bar() foobar() except(ErrorTypeB): baz() foobar() except(SwineFlu): print 'You have caught Swine Flu!' foobar() excep...
You can use a dictionary to map exceptions against functions to call: ``` exception_map = { ErrorTypeA : bar, ErrorTypeB : baz } try: try: somthing() except tuple(exception_map), e: # this catches only the exceptions in the map exception_map[type(e)]() # calls the related function raise...
Python html output (first attempt), several questions (code included)
799,479
2
2009-04-28T19:27:29Z
799,586
8
2009-04-28T20:00:40Z
[ "javascript", "python" ]
While I have been playing with python for a few months now (just a hobbyist), I know very little about web programming (a little html, zero javascript, etc). That said, I have a current project that is making me look at web programming for the first time. This led me to ask: <http://stackoverflow.com/questions/731470/...
It would not be overkill to use a framework for something like this; python frameworks tend to be very light and easy to work with, and would make it much easier for you to add features to your tiny site. But neither is it required; I'll assume you're doing this for learning purposes and talk about how I would change t...
Getting name of windows computer running python script?
799,767
45
2009-04-28T20:49:11Z
799,782
9
2009-04-28T20:53:12Z
[ "python", "windows", "networking" ]
Basically, I have a couple Windows computers on my network that will be running a python script. A different set of configuration options should be used in the script depending on which computer is running this script. How would I get that computer name in the python script? Let's say the script was running on a comp...
From <https://mail.python.org/pipermail/python-list/2006-April/397494.html> ``` import os os.getenv('COMPUTERNAME') ```
Getting name of windows computer running python script?
799,767
45
2009-04-28T20:49:11Z
799,783
15
2009-04-28T20:53:25Z
[ "python", "windows", "networking" ]
Basically, I have a couple Windows computers on my network that will be running a python script. A different set of configuration options should be used in the script depending on which computer is running this script. How would I get that computer name in the python script? Let's say the script was running on a comp...
``` import socket socket.gethostname() ```
Getting name of windows computer running python script?
799,767
45
2009-04-28T20:49:11Z
799,799
83
2009-04-28T20:57:22Z
[ "python", "windows", "networking" ]
Basically, I have a couple Windows computers on my network that will be running a python script. A different set of configuration options should be used in the script depending on which computer is running this script. How would I get that computer name in the python script? Let's say the script was running on a comp...
It turns out there are three options (including the two already answered earlier): ``` >>> import platform >>> import socket >>> import os >>> platform.node() 'DARK-TOWER' >>> socket.gethostname() 'DARK-TOWER' >>> os.environ['COMPUTERNAME'] 'DARK-TOWER' ```
How to get all of the immediate subdirectories in Python
800,197
63
2009-04-28T22:59:11Z
800,201
115
2009-04-28T23:02:06Z
[ "python", "file" ]
I'm trying to write a simple Python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions). I'm getting bogged down by trying to get the list of subdirectories.
``` import os def get_immediate_subdirectories(a_dir): return [name for name in os.listdir(a_dir) if os.path.isdir(os.path.join(a_dir, name))] ```
How to get all of the immediate subdirectories in Python
800,197
63
2009-04-28T22:59:11Z
800,203
7
2009-04-28T23:02:46Z
[ "python", "file" ]
I'm trying to write a simple Python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions). I'm getting bogged down by trying to get the list of subdirectories.
[`os.walk`](http://www.python.org/doc/2.5.4/lib/os-file-dir.html) is your friend in this situation. Straight from the documentation: > walk() generates the file names in a directory tree, by walking the tree either top down or bottom up. For each directory in the tree rooted at directory top (including top itself), i...
How to get all of the immediate subdirectories in Python
800,197
63
2009-04-28T22:59:11Z
17,460,317
11
2013-07-04T00:47:48Z
[ "python", "file" ]
I'm trying to write a simple Python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions). I'm getting bogged down by trying to get the list of subdirectories.
``` import os, os.path ``` **To get (full-path) immediate sub-directories in a directory:** ``` def SubDirPath (d): return filter(os.path.isdir, [os.path.join(d,f) for f in os.listdir(d)]) ``` **To get the latest (newest) sub-directory:** ``` def LatestDirectory (d): return max(SubDirPath(d), key=os.path.ge...
How to get all of the immediate subdirectories in Python
800,197
63
2009-04-28T22:59:11Z
18,278,257
23
2013-08-16T16:41:50Z
[ "python", "file" ]
I'm trying to write a simple Python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions). I'm getting bogged down by trying to get the list of subdirectories.
Why has no one mentioned [`glob`](https://docs.python.org/2/library/glob.html)? `glob` lets you use Unix-style pathname expansion, and is my go to function for almost everything that needs to find more than one path name. It makes it very easy: ``` from glob import glob paths = glob('*/') ``` Note that `glob` will re...
Django equivalent of PHP's form value array/associative array
801,354
42
2009-04-29T08:04:10Z
802,053
57
2009-04-29T12:03:36Z
[ "python", "django", "forms", "html-form" ]
In PHP, I would do this to get `name` as an array. ``` <input type"text" name="name[]" /> <input type"text" name="name[]" /> ``` Or if I wanted to get `name` as an associative array: ``` <input type"text" name="name[first]" /> <input type"text" name="name[last]" /> ``` What is the Django equivalent for such things?
[Check out the QueryDict documentation](http://docs.djangoproject.com/en/dev/ref/request-response/#querydict-objects), particularly the usage of [`QueryDict.getlist(key)`](http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict.getlist). Since request.POST and request.GET in the view are insta...
Django equivalent of PHP's form value array/associative array
801,354
42
2009-04-29T08:04:10Z
4,746,016
17
2011-01-20T10:34:39Z
[ "python", "django", "forms", "html-form" ]
In PHP, I would do this to get `name` as an array. ``` <input type"text" name="name[]" /> <input type"text" name="name[]" /> ``` Or if I wanted to get `name` as an associative array: ``` <input type"text" name="name[first]" /> <input type"text" name="name[last]" /> ``` What is the Django equivalent for such things?
Sorry for digging this up, but Django has an utils.datastructures.DotExpandedDict. Here's a piece of it's docs: ``` >>> d = DotExpandedDict({'person.1.firstname': ['Simon'], \ 'person.1.lastname': ['Willison'], \ 'person.2.firstname': ['Adrian'], \ 'person.2.lastname': ['Holovaty']}) >>> d {'pe...
How to put timedelta in django model?
801,912
20
2009-04-29T11:26:47Z
801,963
27
2009-04-29T11:40:52Z
[ "python", "django", "model" ]
With inspectdb I was able to get a "interval" field from postgres into django. In Django, it was a TextField. The object that I retrieved was indeed a timedelta object! Now I want to put this timedelta object in a new model. What's the best way to do this? Because putting a timedelta in a TextField results in the str ...
You can trivially normalize a timedelta to a single floating-point number in days or seconds. Here's the "Normalize to Days" version. ``` float(timedelta.days) + float(timedelta.seconds) / float(86400) ``` You can trivially turn a floating-point number into a timedelta. ``` >>> datetime.timedelta(2.5) datetime.time...
How to put timedelta in django model?
801,912
20
2009-04-29T11:26:47Z
10,576,547
7
2012-05-14T01:16:07Z
[ "python", "django", "model" ]
With inspectdb I was able to get a "interval" field from postgres into django. In Django, it was a TextField. The object that I retrieved was indeed a timedelta object! Now I want to put this timedelta object in a new model. What's the best way to do this? Because putting a timedelta in a TextField results in the str ...
First, define your model: ``` class TimeModel(models.Model): time = models.FloatField() ``` To store a timedelta object: ``` # td is a timedelta object TimeModel.objects.create(time=td.total_seconds()) ``` To get the timedelta object out of the database: ``` # Assume the previously created TimeModel object has...
How to put timedelta in django model?
801,912
20
2009-04-29T11:26:47Z
29,516,197
38
2015-04-08T13:35:20Z
[ "python", "django", "model" ]
With inspectdb I was able to get a "interval" field from postgres into django. In Django, it was a TextField. The object that I retrieved was indeed a timedelta object! Now I want to put this timedelta object in a new model. What's the best way to do this? Because putting a timedelta in a TextField results in the str ...
Since Django 1.8 you can use [DurationField](https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.DurationField).
Changing user agent on urllib2.urlopen
802,134
75
2009-04-29T12:32:36Z
802,146
50
2009-04-29T12:34:30Z
[ "python", "urllib2", "user-agent" ]
How can I download a webpage with a user agent other than the default one on urllib2.urlopen?
[Setting the User-Agent](http://www.diveintopython.net/http_web_services/user_agent.html) from everyone's favorite [Dive Into Python](http://diveintopython.net/). The short story: You can use [Request.add\_header](http://docs.python.org/library/urllib2.html#urllib2.Request.add_header) to do this. You can also pass th...
Changing user agent on urllib2.urlopen
802,134
75
2009-04-29T12:32:36Z
802,246
89
2009-04-29T12:56:46Z
[ "python", "urllib2", "user-agent" ]
How can I download a webpage with a user agent other than the default one on urllib2.urlopen?
I [answered](http://stackoverflow.com/a/762007/3790126) a [similar question](http://stackoverflow.com/questions/761978/send-headers-along-in-python) a couple weeks ago. There is example code in that question, but basically you can do something like this: (Note the capitalization of `User-Agent` as of [RFC 2616](https:...
Changing user agent on urllib2.urlopen
802,134
75
2009-04-29T12:32:36Z
5,196,160
72
2011-03-04T15:58:58Z
[ "python", "urllib2", "user-agent" ]
How can I download a webpage with a user agent other than the default one on urllib2.urlopen?
``` headers = { 'User-Agent' : 'Mozilla/5.0' } req = urllib2.Request('www.example.com', None, headers) html = urllib2.urlopen(req).read() ``` Or, a bit shorter: ``` req = urllib2.Request('www.example.com', headers={ 'User-Agent': 'Mozilla/5.0' }) html = urllib2.urlopen(req).read() ```
Changing user agent on urllib2.urlopen
802,134
75
2009-04-29T12:32:36Z
8,994,498
8
2012-01-24T21:32:26Z
[ "python", "urllib2", "user-agent" ]
How can I download a webpage with a user agent other than the default one on urllib2.urlopen?
All these should work in theory, but (with Python 2.7.2 on Windows at least) any time you send a custom User-agent header, urllib2 doesn't send that header. If you don't try to send a User-agent header, it sends the default Python / urllib2 None of these methods seem to work for adding User-agent but they work for oth...