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
How to read a file line by line into a list with Python
3,277,503
891
2010-07-18T22:25:01Z
3,277,516
909
2010-07-18T22:28:32Z
[ "python", "string", "file" ]
How do I read every line of a file in Python and store each line as an element in list? I want to read the file line by line and each line is appended to the end of the list.
``` with open(fname) as f: content = f.readlines() ``` I'm guessing that you meant [`list`](http://docs.python.org/glossary.html#term-list) and not array.
How to read a file line by line into a list with Python
3,277,503
891
2010-07-18T22:25:01Z
17,166,344
18
2013-06-18T10:17:33Z
[ "python", "string", "file" ]
How do I read every line of a file in Python and store each line as an element in list? I want to read the file line by line and each line is appended to the end of the list.
Another option is [`numpy.genfromtxt`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html), e.g: ``` import numpy as np data = np.genfromtxt("yourfile.dat",delimiter="\n") ``` This will make `data` a numpy array with as many rows as are in your file
How to read a file line by line into a list with Python
3,277,503
891
2010-07-18T22:25:01Z
19,639,084
27
2013-10-28T15:40:52Z
[ "python", "string", "file" ]
How do I read every line of a file in Python and store each line as an element in list? I want to read the file line by line and each line is appended to the end of the list.
This should encapsulate the open command. ``` array = [] with open("file.txt", "r") as f: for line in f: array.append(line) ```
How to read a file line by line into a list with Python
3,277,503
891
2010-07-18T22:25:01Z
20,147,869
15
2013-11-22T14:57:48Z
[ "python", "string", "file" ]
How do I read every line of a file in Python and store each line as an element in list? I want to read the file line by line and each line is appended to the end of the list.
If you'd like to read a file from the command line or from stdin, you can also use the `fileinput` module: ``` # reader.py import fileinput content = [] for line in fileinput.input(): content.append(line.strip()) fileinput.close() ``` Pass files to it like so: ``` $ python reader.py textfile.txt ``` Read more...
How to read a file line by line into a list with Python
3,277,503
891
2010-07-18T22:25:01Z
21,073,824
11
2014-01-12T10:58:04Z
[ "python", "string", "file" ]
How do I read every line of a file in Python and store each line as an element in list? I want to read the file line by line and each line is appended to the end of the list.
``` f = open("your_file.txt",'r') out = f.readlines() # will append in the list out ``` Now variable out is a list (array) of what you want. You could either do: ``` for line in out: print line ``` or ``` for line in f: print line ``` you'll get the same results.
How to read a file line by line into a list with Python
3,277,503
891
2010-07-18T22:25:01Z
22,123,823
82
2014-03-02T04:22:39Z
[ "python", "string", "file" ]
How do I read every line of a file in Python and store each line as an element in list? I want to read the file line by line and each line is appended to the end of the list.
If you want the `\n` included: ``` with open(fname) as f: content = f.readlines() ``` If you do not want `\n` included: ``` with open(fname) as f: content = f.read().splitlines() ```
How to read a file line by line into a list with Python
3,277,503
891
2010-07-18T22:25:01Z
23,889,306
17
2014-05-27T12:21:01Z
[ "python", "string", "file" ]
How do I read every line of a file in Python and store each line as an element in list? I want to read the file line by line and each line is appended to the end of the list.
Here's one more option by using list comprehensions on files; ``` lines = [line.rstrip() for line in open('file.txt')] ``` This should be more efficient way as the most of the work is done inside the Python interpreter.
How to read a file line by line into a list with Python
3,277,503
891
2010-07-18T22:25:01Z
27,583,116
22
2014-12-20T18:31:22Z
[ "python", "string", "file" ]
How do I read every line of a file in Python and store each line as an element in list? I want to read the file line by line and each line is appended to the end of the list.
**Clean and Pythonic Way of Reading the Lines of a File Into a List** --- First and foremost, you should focus on opening your file and reading its contents in an efficient and pythonic way. Here is an example of the way I personally DO NOT prefer: ``` infile = open('my_file.txt', 'r') # Open the file for reading. ...
How to read a file line by line into a list with Python
3,277,503
891
2010-07-18T22:25:01Z
28,358,149
11
2015-02-06T03:34:48Z
[ "python", "string", "file" ]
How do I read every line of a file in Python and store each line as an element in list? I want to read the file line by line and each line is appended to the end of the list.
**The simplest way to do it** A simple way is to: 1. Read the whole file as a string 2. Split the string line by line In one line, that would give: ``` lines = open('C:/path/file.txt').read().splitlines() ```
How to read a file line by line into a list with Python
3,277,503
891
2010-07-18T22:25:01Z
29,740,172
19
2015-04-20T05:53:10Z
[ "python", "string", "file" ]
How do I read every line of a file in Python and store each line as an element in list? I want to read the file line by line and each line is appended to the end of the list.
As simple as it can get: ``` for line in open("myfile.txt") : print line.rstrip('\n') # .rstrip('\n') removes the line break ```
How to read a file line by line into a list with Python
3,277,503
891
2010-07-18T22:25:01Z
35,622,867
41
2016-02-25T09:13:38Z
[ "python", "string", "file" ]
How do I read every line of a file in Python and store each line as an element in list? I want to read the file line by line and each line is appended to the end of the list.
You could simply do the following, as has been suggested: ``` with open('/your/path/file') as f: my_lines = f.readlines() ``` Note that this approach has 2 downsides: 1) You store all the lines in memory. In the general case, this is a very bad idea. The file could be very large, and you could run out of memory....
How deploy Flask application on Webfaction?
3,277,657
11
2010-07-18T23:21:13Z
6,264,592
16
2011-06-07T11:36:52Z
[ "python", "flask" ]
Anybody know how to deploy a simple Flask application on Webfaction? I know Webfaction support mod\_wsgi and I read the guide on the Flask site but still I can't make my app working. Anybody have a working configuration? **UPDATE** to answer a comment by Graham Dumpleton. I get a 500 Internal server error. Apache doe...
I got it working with the following procedure: * create and app named 'myapp' of type mod\_wsgi 3.3/Python 2.7. Webfaction will create the following folders: ``` myapp |- apache2 |- htdocs ``` * Webfaction will also automatically create a simple script `index.py` in your `htdocs` directory. Check ...
Initial Data for Django Inline Formsets
3,278,043
6
2010-07-19T01:59:40Z
3,280,608
16
2010-07-19T11:27:15Z
[ "python", "django", "forms", "inline-formset" ]
I have put together a form to save a recipe. It makes use of a form and an inline formset. I have users with text files containing recipes and they would like to cut and paste the data to make entry easier. I have worked out how to populate the form portion after processing the raw text input but I cannot figure out ho...
My first suggestion would be to take the simple way out: save the `Recipe` and `RecipeIngredient`s, then use the resulting `Recipe` as your instance when making the `FormSet`. You may want to add a "reviewed" boolean field to your recipes to indicate whether the formsets were then approved by the user. However, if you...
Difference between __getattr__ vs __getattribute__
3,278,077
210
2010-07-19T02:11:19Z
3,278,093
14
2010-07-19T02:18:53Z
[ "python" ]
I am trying to understand when to use `__getattr__` or `__getattribute__`. The [documentation](http://docs.python.org/reference/datamodel.html?highlight=__getattribute__#object.__getattribute__) mentions `__getattribute__` applies to new-style classes. What are new-style classes?
New-style classes inherit from `object`, or from another new style class: ``` class SomeObject(object): pass class SubObject(SomeObject): pass ``` Old-style classes don't: ``` class SomeObject: pass ``` This only applies to Python 2 - in Python 3 all the above will create new-style classes. See *[9. C...
Difference between __getattr__ vs __getattribute__
3,278,077
210
2010-07-19T02:11:19Z
3,278,104
258
2010-07-19T02:22:00Z
[ "python" ]
I am trying to understand when to use `__getattr__` or `__getattribute__`. The [documentation](http://docs.python.org/reference/datamodel.html?highlight=__getattribute__#object.__getattribute__) mentions `__getattribute__` applies to new-style classes. What are new-style classes?
A key difference between `__getattr__` and `__getattribute__` is that `__getattr__` is only invoked if the attribute wasn't found the usual ways. It's good for implementing a fallback for missing attributes, and is probably the one of two you want. `__getattribute__` is invoked before looking at the actual attributes ...
Difference between __getattr__ vs __getattribute__
3,278,077
210
2010-07-19T02:11:19Z
18,821,412
13
2013-09-16T06:11:50Z
[ "python" ]
I am trying to understand when to use `__getattr__` or `__getattribute__`. The [documentation](http://docs.python.org/reference/datamodel.html?highlight=__getattribute__#object.__getattribute__) mentions `__getattribute__` applies to new-style classes. What are new-style classes?
This is just an example based on @Ned Batchelder explanation. `__getattr__` example: ``` class Foo(object): def __getattr__(self, attr): print "looking up", attr value = 42 self.__dict__[attr] = value return value f = Foo() print f.x #output >>> looking up x 42 f.x = 3 print f.x...
Doc, rtf and txt reader in python
3,278,850
5
2010-07-19T06:22:59Z
3,278,898
7
2010-07-19T06:33:51Z
[ "python", "python-3.x" ]
Like `csv.reader()` are there any other functions which can read `.rtf`, `.txt`, `.doc` files in Python?
You can read a text file with ``` txt = open("file.txt").read() ``` Try [PyRTF](http://pyrtf.sourceforge.net/) for RTF files. I would think that reading MS Word .doc files are pretty unlikely unless you are on Windows and you can use some of the native MS interfaces for reading those files. [This article](http://www....
Stand-alone fabfile for fabric?
3,278,880
8
2010-07-19T06:31:12Z
6,401,485
12
2011-06-19T08:58:56Z
[ "python", "fabric" ]
Is it possible to make the fabfile stand-alone? I'm not very fond of running the external tool 'fab'. If I manage to get the fabfile standalone I can run the file from within the (Eclipse / Pydev) IDE, easily debug it, use project configurations and paths etc. Why doesn't this work: ``` from fabric.api import run ...
I eventually found the solution (and it is really simple!). In my fabfile, I added: ``` from fabric.main import main if __name__ == '__main__': import sys sys.argv = ['fab', '-f', __file__, 'update_server'] main() ``` I hope this helps people...
How can I compare a date and a datetime in Python?
3,278,999
33
2010-07-19T06:58:08Z
3,279,015
62
2010-07-19T07:02:54Z
[ "python" ]
Here's a little snippet that I'm trying execute: ``` >>> from datetime import * >>> item_date = datetime.strptime('7/16/10', "%m/%d/%y") >>> from_date = date.today()-timedelta(days=3) >>> print type(item_date) <type 'datetime.datetime'> >>> print type(from_date) <type 'datetime.date'> >>> if item_date > from_date: ......
Use [the `.date()` method](http://docs.python.org/library/datetime.html#datetime.datetime.date) to convert a datetime to a date: ``` if item_date.date() > from_date: ``` Alternatively, you could use [`datetime.today()`](http://docs.python.org/library/datetime.html#datetime.datetime.today) instead of `date.today()`. Y...
Python Chain getattr as a string
3,279,082
4
2010-07-19T07:16:17Z
3,283,072
15
2010-07-19T16:46:12Z
[ "python", "getattr" ]
``` import amara def chain_attribute_call(obj, attlist): """ Allows to execute chain attribute calls """ splitted_attrs = attlist.split(".") current_dom = obj for attr in splitted_attrs: current_dom = getattr(current_dom, attr) return current_dom doc = amara.parse("sample.xml") prin...
you could also use: ``` from operator import attrgetter attrgetter('x.y.z')(doc) ```
Invert colormap in matplotlib
3,279,560
85
2010-07-19T08:44:21Z
3,280,732
174
2010-07-19T11:45:51Z
[ "python", "matplotlib" ]
I would like to know how to simply reverse the color order of a given colormap in order to use it with plot\_surface.
The standard colormaps also all have reversed versions. They have the same names with `_r` tacked on to the end. ([Documentation here.](http://matplotlib.org/api/pyplot_summary.html?highlight=colormaps#matplotlib.pyplot.colormaps))
Invert colormap in matplotlib
3,279,560
85
2010-07-19T08:44:21Z
17,127,875
10
2013-06-15T21:04:48Z
[ "python", "matplotlib" ]
I would like to know how to simply reverse the color order of a given colormap in order to use it with plot\_surface.
In matplotlib a color map isn't a list, but it contains the list of its colors as `colormap.colors`. And the module `matplotlib.colors` provides a function `ListedColormap()` to generate a color map from a list. So you can reverse any color map by doing ``` colormap_r = ListedColormap(colormap.colors[::-1]) ```
Python implementation of Jenkins Hash?
3,279,615
12
2010-07-19T08:55:40Z
4,594,659
9
2011-01-04T14:27:45Z
[ "python", "hash" ]
Does there exist a native Python implementation of the [Jenkins hash](http://burtleburtle.net/bob/hash/doobs.html) algorithm(s)? I need a hash algorithm that takes an arbitrary string and turns it into an 32-bit integer. For a given string, it must guarantee to return the same integer across platforms. I have looked ...
This native python-code should give you the same hash as the original lookup3.c ``` # Need to constrain U32 to only 32 bits using the & 0xffffffff # since Python has no native notion of integers limited to 32 bit # http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex '''Original copyright...
How to use a custom __init__ of an app engine Python model class properly?
3,279,833
8
2010-07-19T09:30:08Z
3,280,270
15
2010-07-19T10:34:57Z
[ "python", "google-app-engine" ]
I'm trying to implement a delayed blog post deletion scheme. So instead of an annoying *Are you sure?*, you get a 2 minute time frame to cancel deletion. I want to track What will be deleted When with a db.Model class (*DeleteQueueItem*), as I found no way to delete a task from the queue and suspect I can query what's...
Generally, you shouldn't try and override the **init** method of Model classes. While it's possible to get right, the correct constructor behaviour is fairly complex, and may even change between releases, breaking your code (though we try to avoid doing so!). Part of the reason for this is that the constructor has to b...
Content-based routing with RabbitMQ and Python
3,280,676
6
2010-07-19T11:37:51Z
3,458,295
14
2010-08-11T12:41:13Z
[ "python", "routing", "rabbitmq", "amqp" ]
Is it possible with RabbitMQ and Python to do content-based routing? The AMQP standard and RabbitMQ claims to support content-based routing, but are there any libraries for Python which support specifying content-based bindings etc.? The library I am currently using (py-amqplib <http://barryp.org/software/py-amqplib/...
The answer is "yes", but there's more to it... :) Let's first agree on what content-based routing means. There are two possible meanings. Some people say that it is based on the *header* portion of a message. Others say it's based on the *data* portion of a message. If we take the first definition, these are more or ...
Automatically call all functions matching a certain pattern in python
3,281,300
3
2010-07-19T13:13:34Z
3,281,405
7
2010-07-19T13:24:12Z
[ "python", "automation" ]
In python I have many functions likes the ones below. I would like to run all the functions whose name matches `setup_*` without having to explicitly call them from main. The order in which the functions are run is not important. How can I do this in python? ``` def setup_1(): .... def setup_2(): .... def se...
``` def setup_1(): print('1') def setup_2(): print('2') def setup_3(): print('3') if __name__ == '__main__': for func in (val for key,val in vars().items() if key.startswith('setup_')): func() ``` yields ``` # 1 # 3 # 2 ```
Best way to install python packages locally for development
3,281,495
18
2010-07-19T13:33:29Z
3,281,590
11
2010-07-19T13:45:31Z
[ "python", "installation" ]
Being new to the python games I seem to have missed out on some knowledge on how you can develop on a program but also keep it in your live environment. Programs like gpodder can be run directly from the source checkout which is really handy however others want to be "installed" to run. A lot of programs are distribu...
Install: <http://pypi.python.org/pypi/virtualenv> to set up a localized virtual environment for your libraries, and: <http://pypi.python.org/pypi/setuptools> i.e. "easy\_install" to install new things.
python - list operations
3,281,898
11
2010-07-19T14:21:17Z
3,281,922
19
2010-07-19T14:23:06Z
[ "python", "list" ]
Given a list of unsorted numbers, I want to find the smallest number larger than N (if any). In C#, I'd do something like this (checks omitted) : ``` var x = list.Where(i => i > N).Min(); ``` What's a short, READABLE way to do this in Python?
``` >>> l = [4, 5, 12, 0, 3, 7] >>> min(x for x in l if x > 5) 7 ```
How to convert a Python string representing bytes into actual bytes?
3,282,678
2
2010-07-19T15:50:44Z
3,282,691
8
2010-07-19T15:52:03Z
[ "python" ]
I have a string like: "01030009" and I want to get another string (because in Python 2.x we use strings for bytes) newString which will produce this result: ``` for a in newString: print ord(a) 0 1 0 3 0 0 0 9 ``` Thanks
``` ''.join(chr(int(x)) for x in oldString) ``` `chr` is the inverse of `ord`.
Get key with the least value from a dictionary
3,282,823
116
2010-07-19T16:11:25Z
3,282,871
24
2010-07-19T16:16:01Z
[ "python", "dictionary", "minimum" ]
If I have a Python dictionary, how do I get the key to the entry which contains the minimum value? I was thinking about something to do with the `min()` function... Given the input: ``` {320:1, 321:0, 322:3} ``` It would return `321`.
Here's an answer that actually gives the solution the OP asked for: ``` >>> d = {320:1, 321:0, 322:3} >>> d.items() [(320, 1), (321, 0), (322, 3)] >>> # find the minimum by comparing the second element of each tuple >>> min(d.items(), key=lambda x: x[1]) (321, 0) ``` Using [`d.iteritems()`](http://docs.python.org/li...
Get key with the least value from a dictionary
3,282,823
116
2010-07-19T16:11:25Z
3,282,904
222
2010-07-19T16:21:26Z
[ "python", "dictionary", "minimum" ]
If I have a Python dictionary, how do I get the key to the entry which contains the minimum value? I was thinking about something to do with the `min()` function... Given the input: ``` {320:1, 321:0, 322:3} ``` It would return `321`.
Best: `min(d, key=d.get)` -- no reason to interpose a useless `lambda` indirection layer or extract items or keys!
2 digit years using strptime() is not able to parse birthdays very well
3,283,209
5
2010-07-19T17:04:13Z
3,283,229
11
2010-07-19T17:07:45Z
[ "python", "strptime", "2-digit-year" ]
Consider the following birthdays (as `dob`): * 1-Jun-68 * 1-Jun-69 When parsed with Python’s `datetime.strptime(dob, '%d-%b-%y')` will yield: * `datetime.datetime(2068, 6, 1, 0, 0)` * `datetime.datetime(1969, 6, 1, 0, 0)` Well of course they’re supposed to be born in the same decade but now it’s not even in t...
If you're always using it for birthdays, just subtract 100 if the year is after now: ``` if d > datetime.now(): d = datetime(d.year - 100, d.month, d.day) ```
finding out absolute path to a file from python
3,283,306
12
2010-07-19T17:17:22Z
3,283,326
13
2010-07-19T17:19:13Z
[ "python", "filesystems", "io" ]
if I have a file test.py that resides in some directory, how can I find out from test.py what directory it is in? os.path.curdir will give the current directory but not the directory where the file lives. If I invoke test.py from some directory "foo", os.curdir will return foo but not the path of test.py. thanks.
the answer is to use: ``` __file__ ``` which returns a relative path. ``` os.path.abspath(__file__) ``` can be used to get the full path.
finding out absolute path to a file from python
3,283,306
12
2010-07-19T17:17:22Z
3,283,336
11
2010-07-19T17:20:19Z
[ "python", "filesystems", "io" ]
if I have a file test.py that resides in some directory, how can I find out from test.py what directory it is in? os.path.curdir will give the current directory but not the directory where the file lives. If I invoke test.py from some directory "foo", os.curdir will return foo but not the path of test.py. thanks.
Here's how to get the directory of the current file: ``` import os os.path.abspath(os.path.dirname(__file__)) ```
Python "NoneType is not callable" error
3,283,441
4
2010-07-19T17:32:16Z
3,283,495
8
2010-07-19T17:38:16Z
[ "python", "types" ]
I have a function that looks like the following, with a whole lot of optional parameters. One of these parameters, somewhere amidst all the others, is `text`. I handle `text` specially because if it is a boolean, then I want to run to do something based on that. If it's not (which means it's just a string), then I do ...
I guess you have an argument called `type` somewhere, I can easily reproduce your error with the following code: ``` >>> type('abc') <class 'str'> >>> type = None >>> type('abc') Traceback (most recent call last): File "<pyshell#62>", line 1, in <module> type('abc') TypeError: 'NoneType' object is not callable `...
Fetch an email with imaplib but do not mark it as SEEN
3,283,460
15
2010-07-19T17:34:05Z
3,283,791
11
2010-07-19T18:15:26Z
[ "python", "gmail", "imaplib" ]
I want to parse some emails from a user 's inbox but when I do: ``` typ, msg_data = imap_conn.fetch(uid, '(RFC822)') ``` It marks the email as SEEN or read. This is not the desired functionality. Do you know how can I keep the email at its previous stare either SEEN or NOT SEEN?
The following should work: ``` typ, msg_data = imap_conn.fetch(uid, '(BODY.PEEK[HEADER])') ``` or `BODY.PEEK[TEXT]`, etc.
Fetch an email with imaplib but do not mark it as SEEN
3,283,460
15
2010-07-19T17:34:05Z
3,956,110
25
2010-10-18T01:38:49Z
[ "python", "gmail", "imaplib" ]
I want to parse some emails from a user 's inbox but when I do: ``` typ, msg_data = imap_conn.fetch(uid, '(RFC822)') ``` It marks the email as SEEN or read. This is not the desired functionality. Do you know how can I keep the email at its previous stare either SEEN or NOT SEEN?
You might also set read\_only to true when selecting the folder. .select('Inbox', readonly=True)
Is this an acceptable pythonic idiom?
3,283,479
4
2010-07-19T17:36:50Z
3,283,523
12
2010-07-19T17:41:02Z
[ "python" ]
I have a class that assists in importing a special type of file, and a 'factory' class that allows me to do these in batch. The factory class uses a generator so the client can iterate through the importers. My question is, did I use the iterator correctly? Is this an acceptable idiom? I've just started using Python. ...
You could make one thing a little simpler: Instead of `try`...`finally`, use a `with` block: ``` with open(file, "rb") as fh: yield FileParser(fh) ``` This will close the file for you automatically as soon as the `with` block is left.
Is this an acceptable pythonic idiom?
3,283,479
4
2010-07-19T17:36:50Z
3,283,570
7
2010-07-19T17:47:34Z
[ "python" ]
I have a class that assists in importing a special type of file, and a 'factory' class that allows me to do these in batch. The factory class uses a generator so the client can iterate through the importers. My question is, did I use the iterator correctly? Is this an acceptable idiom? I've just started using Python. ...
It's absolutely fine to have a method that's a generator, as you do. I would recommend making all your classes new-style (if you're on Python 2, either set `__metaclass__ = type` at the start of your module, or add `(object)` to all your base-less `class` statements), because legacy classes are "evil";-); and, for clar...
Can I format a variable in python?
3,283,621
2
2010-07-19T17:53:41Z
3,283,638
8
2010-07-19T17:56:37Z
[ "python" ]
Is there a way of formating a variable? For example, I'd like to automate the creation of a variable named *M\_color*, where *M* is a string of value "bingo". The final result would be *bingo\_color*. What should I do if the value of M changes during the execution?
The best solution for this kind of problem is to use dictionaries: ``` color_of = {} M = "bingo" color_of[M] = "red" print(color_of[M]) ```
Decode Hex String in Python 3
3,283,984
16
2010-07-19T18:44:40Z
3,284,069
26
2010-07-19T18:54:44Z
[ "python", "python-3.x" ]
In Python 2, converting the hexadecimal form of a string into the corresponding unicode was straightforward: ``` comments.decode("hex") ``` where the variable 'comments' is a part of a line in a file (the rest of the line does *not* need to be converted, as it is represented only in ASCII. Now in Python 3, however, ...
Something like: ``` >>> bytes.fromhex('4a4b4c').decode('utf-8') 'JKL' ``` Just put the actual encoding you are using.
python dictionary, keeping a count of integers
3,283,990
2
2010-07-19T18:45:13Z
3,284,027
8
2010-07-19T18:49:39Z
[ "python", "dictionary" ]
I am trying to count a list of say, integers. I have a list of numbers in a csv file I am able to read in, that looks something like 4,245,34,99,340,... What I am doing is trying to return is a dictionary with key:value pairs where the key is an integer value from the csv file, and the value is the number of times it a...
Sounds like what you want is a Counter object: <http://docs.python.org/library/collections.html#counter-objects> Also I think you may want to use the CSV module: <http://docs.python.org/library/csv.html> Using the built-in modules should make it a lot easier :) To get the rows something like this should work: `...
How to switch backends in matplotlib / Python
3,285,193
33
2010-07-19T21:20:59Z
6,372,226
24
2011-06-16T12:57:25Z
[ "python", "matplotlib" ]
I am struggling with the following issue. I need to generate reports that consists of a collection of charts. All these charts, except one, are made using Matplotlib default backend (TkAgg). One chart needs to be made using the Cairo backend, the reason is that I am plotting an igraph graph and that can only be plotted...
There is an "experimental" feature : ``` import matplotlib.pyplot as p p.switch_backend('newbackend') ``` taken from [matplotlib doc](http://matplotlib.sourceforge.net/api/matplotlib_configuration_api.html). > Switch the default backend to newbackend. This feature is > **experimental**, and is only expected to work ...
How to switch backends in matplotlib / Python
3,285,193
33
2010-07-19T21:20:59Z
14,763,330
9
2013-02-07T23:48:06Z
[ "python", "matplotlib" ]
I am struggling with the following issue. I need to generate reports that consists of a collection of charts. All these charts, except one, are made using Matplotlib default backend (TkAgg). One chart needs to be made using the Cairo backend, the reason is that I am plotting an igraph graph and that can only be plotted...
Why not just use the [`reload`](http://docs.python.org/2/library/functions.html#reload) built-in function ([`importlib.reload`](https://docs.python.org/3/library/importlib.html#importlib.reload) in Python 3)? ``` import matplotlib matplotlib.use('agg') matplotlib = reload(matplotlib) matplotlib.use('cairo.png') ```
CSV, DictWriter, unicode and utf-8
3,285,578
4
2010-07-19T22:24:54Z
3,285,637
9
2010-07-19T22:35:18Z
[ "python", "unicode", "csv", "utf-8" ]
I am having problems with the DictWriter and non-ascii characters. A short version of my problem: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- import codecs import csv f = codecs.open("test.csv", 'w', 'utf-8') writer = csv.DictWriter(f, ['field1'], delimiter='\t') writer.writerow({'field1':u'Ã¥'.encode('utf-8')...
The object you obtain with `codecs.open` wants a **unicode** string in its `write` method -- that's the whole point. `csv.DictWriter` of course is calling that method with a utf8-encoded byte string instead, whence the exception. Change `f`'s creation to `f = open("test.csv", 'wb')` (taking `codecs` out of the picture...
How to dynamically compose and access class attributes in Python?
3,286,089
10
2010-07-20T00:18:20Z
3,286,173
14
2010-07-20T00:38:16Z
[ "python" ]
I have a Python class that have attributes named: date1, date2, date3, etc. During runtime, I have a variable i, which is an integer. What I want to do is to access the appropriate date attribute in run time based on the value of i. For example, if i == 1, I want to access myobject.date1 if i == 2, I want to acces...
You can use `getattr()` to access a property when you don't know its name until runtime: ``` obj = myobject() i = 7 date7 = getattr(obj, 'date%d' % i) # same as obj.date7 ``` If you keep your numbered classes in a module called `foo`, you can use `getattr()` again to access them by number. ``` foo.py: class Class1...
Calling a python method from C/C++, and extracting its return value
3,286,448
26
2010-07-20T01:54:41Z
3,310,608
34
2010-07-22T15:33:17Z
[ "c++", "python", "c", "python-c-api", "python-embedding" ]
I'd like to call a custom function that is defined in a python module from C. I have some preliminary code to do that, but it just prints the output to stdout. **mytest.py** ``` import math def myabs(x): return math.fabs(x) ``` **test.cpp** ``` #include <Python.h> int main() { Py_Initialize(); PyRun_S...
As explained before, using PyRun\_SimpleString seems to be a bad idea. You should definitely use the methods provided by the C-API (http://docs.python.org/c-api/). Reading the introduction is the first thing to do to understand the way it works. First, you have to learn about PyObject that is the basic object for th...
Calling a python method from C/C++, and extracting its return value
3,286,448
26
2010-07-20T01:54:41Z
24,687,260
9
2014-07-10T22:21:13Z
[ "c++", "python", "c", "python-c-api", "python-embedding" ]
I'd like to call a custom function that is defined in a python module from C. I have some preliminary code to do that, but it just prints the output to stdout. **mytest.py** ``` import math def myabs(x): return math.fabs(x) ``` **test.cpp** ``` #include <Python.h> int main() { Py_Initialize(); PyRun_S...
Here is a sample code I wrote (with the help of various online sources) to send a string to a Python code, then return a value. Here is the C code `call_function.c`: ``` #include <Python.h> #include <stdlib.h> int main() { // Set PYTHONPATH TO working directory setenv("PYTHONPATH",".",1); PyObject *pName, *...
return SQL table as JSON in python
3,286,525
16
2010-07-20T02:16:01Z
3,286,575
10
2010-07-20T02:33:20Z
[ "python", "sql", "json" ]
I'm playing around with a little web app in web.py, and am setting up a url to return a JSON object. What's the best way to convert a SQL table to JSON using python?
More information about how you'll be working with your data before transferring it would help a ton. The json module provides dump(s) and load(s) methods that'll help if you're using 2.6 or newer: <http://docs.python.org/library/json.html>. -- EDITED -- Without knowing which libraries you're using I can't tell you fo...
return SQL table as JSON in python
3,286,525
16
2010-07-20T02:16:01Z
3,286,841
10
2010-07-20T03:39:40Z
[ "python", "sql", "json" ]
I'm playing around with a little web app in web.py, and am setting up a url to return a JSON object. What's the best way to convert a SQL table to JSON using python?
Personally I prefer [SQLObject](http://www.sqlobject.org/) for this sort of thing. I adapted some quick-and-dirty test code I had to get this: ``` import simplejson from sqlobject import * # Replace this with the URI for your actual database connection = connectionForURI('sqlite:/:memory:') sqlhub.processConnection ...
return SQL table as JSON in python
3,286,525
16
2010-07-20T02:16:01Z
3,287,775
35
2010-07-20T07:16:36Z
[ "python", "sql", "json" ]
I'm playing around with a little web app in web.py, and am setting up a url to return a JSON object. What's the best way to convert a SQL table to JSON using python?
Here is a really nice example of [a pythonic way to do that](http://github.com/mitsuhiko/flask/blob/master/examples/minitwit/minitwit.py): ``` import json import psycopg2 def db(database_name='pepe'): return psycopg2.connect(database=database_name) def query_db(query, args=(), one=False): cur = db().cursor()...
Convert string timestamp (with timezone offset) to local time. . ? python
3,286,817
7
2010-07-20T03:34:48Z
3,286,853
8
2010-07-20T03:42:20Z
[ "python", "datetime", "timezone" ]
I am trying to convert a string timestamp into a proper datetime object. The problem I am having is that there is a timezone offset and everything I am doing doesn't seem to work. Ultimately I want to convert the string timestamp into a datetime object in my machines timezone. ``` # string timestamp date = u"Fri...
The [dateutil](http://labix.org/python-dateutil) package is handy for parsing date/times: ``` In [10]: date = u"Fri, 16 Jul 2010 07:08:23 -0700" In [11]: from dateutil.parser import parse In [12]: parse(date) Out[12]: datetime.datetime(2010, 7, 16, 7, 8, 23, tzinfo=tzoffset(None, -25200)) ``` Finally, to convert in...
Cron and virtualenv
3,287,038
119
2010-07-20T04:33:15Z
3,287,063
131
2010-07-20T04:40:58Z
[ "python", "django", "cron", "virtualenv" ]
I am trying to run a Django management command from cron. I am using virtualenv to keep my project sandboxed. I have seen examples here and elsewhere that show running management commands from within virtualenv's like: ``` 0 3 * * * source /home/user/project/env/bin/activate && /home/user/project/manage.py command ar...
You should be able to do this by using the `python` in your virtual environment: ``` /home/my/virtual/bin/python /home/my/project/manage.py command arg ``` EDIT: If your django project isn't in the PYTHONPATH, then you'll need to switch to the right directory: ``` cd /home/my/project && /home/my/virtual/bin/python ....
Cron and virtualenv
3,287,038
119
2010-07-20T04:33:15Z
7,031,758
44
2011-08-11T19:33:35Z
[ "python", "django", "cron", "virtualenv" ]
I am trying to run a Django management command from cron. I am using virtualenv to keep my project sandboxed. I have seen examples here and elsewhere that show running management commands from within virtualenv's like: ``` 0 3 * * * source /home/user/project/env/bin/activate && /home/user/project/manage.py command ar...
Running `source` from a cronfile won't work as cron uses `/bin/sh` as its default shell, which doesn't support `source`. You need to set the SHELL environment variable to be `/bin/bash`: ``` SHELL=/bin/bash */10 * * * * root source /path/to/virtualenv/bin/activate && /path/to/build/manage.py some_command > /dev/null `...
Cron and virtualenv
3,287,038
119
2010-07-20T04:33:15Z
13,832,915
9
2012-12-12T04:42:01Z
[ "python", "django", "cron", "virtualenv" ]
I am trying to run a Django management command from cron. I am using virtualenv to keep my project sandboxed. I have seen examples here and elsewhere that show running management commands from within virtualenv's like: ``` 0 3 * * * source /home/user/project/env/bin/activate && /home/user/project/manage.py command ar...
Rather than mucking around with virtualenv-specific shebangs, just prepend `PATH` onto the crontab. From an activated virtualenv, run these three commands and python scripts should just work: ``` $ echo "PATH=$PATH" > myserver.cron $ crontab -l >> myserver.cron $ crontab myserver.cron ``` The crontab's first line sh...
Download a spreadsheet from Google Docs using Python
3,287,651
23
2010-07-20T06:52:09Z
3,376,067
15
2010-07-30T23:28:24Z
[ "python", "google-docs", "google-docs-api", "gdata-python-client" ]
Can you produce a Python example of how to download a Google Docs spreadsheet given its key and worksheet ID (`gid`)? I can't. I've scoured versions 1, 2 and 3 of the API. I'm having no luck, I can't figure out their compilcated ATOM-like feeds API, the `gdata.docs.service.DocsService._DownloadFile` private method say...
You might try using the AuthSub method described in the [Exporting Spreadsheets](http://code.google.com/apis/documents/docs/1.0/developers_guide_python.html#DownloadingSpreadsheets) section of the documentation. Get a separate login token for the spreadsheets service and substitue that for the export. Adding this to t...
Download a spreadsheet from Google Docs using Python
3,287,651
23
2010-07-20T06:52:09Z
9,006,155
15
2012-01-25T16:22:34Z
[ "python", "google-docs", "google-docs-api", "gdata-python-client" ]
Can you produce a Python example of how to download a Google Docs spreadsheet given its key and worksheet ID (`gid`)? I can't. I've scoured versions 1, 2 and 3 of the API. I'm having no luck, I can't figure out their compilcated ATOM-like feeds API, the `gdata.docs.service.DocsService._DownloadFile` private method say...
In case anyone comes across this looking for a quick fix, here's [another (currently) working solution](https://gist.github.com/1650271) that doesn't rely on the gdata client library: ``` #!/usr/bin/python import re, urllib, urllib2 class Spreadsheet(object): def __init__(self, key): super(Spreadsheet, s...
Download a spreadsheet from Google Docs using Python
3,287,651
23
2010-07-20T06:52:09Z
18,296,318
22
2013-08-18T06:22:42Z
[ "python", "google-docs", "google-docs-api", "gdata-python-client" ]
Can you produce a Python example of how to download a Google Docs spreadsheet given its key and worksheet ID (`gid`)? I can't. I've scoured versions 1, 2 and 3 of the API. I'm having no luck, I can't figure out their compilcated ATOM-like feeds API, the `gdata.docs.service.DocsService._DownloadFile` private method say...
The <https://github.com/burnash/gspread> library is a newer, simpler way to interact with Google Spreadsheets, rather than the old answers to this that suggest the `gdata` library which is not only too low-level, but is also overly-complicated. You will also need to create and download (in JSON format) a Service Accou...
How can I get fields in an original order?
3,288,107
7
2010-07-20T08:17:15Z
3,288,801
15
2010-07-20T09:53:20Z
[ "python", "django", "introspection" ]
I have a code like: ``` class Ordered(object): x = 0 z = 0 b = 0 a = 0 print(dir(Ordered)) ``` it prints: ``` [ ......., a, b, x, z] ``` How can I get fields in an original order: x, z, b, a? I've seen similar behavior in Django Models.
As mentioned above, if you want to keep things simple, just use a eg `_ordering` attribute, which manually keeps track of ordering. Otherwise, here is a metaclass approach (like the one Django uses), which creates an ordering attribute automatically. **Recording the original ordering** Classes don't keep track of the...
How do I get integers from a tuple in Python?
3,288,250
2
2010-07-20T08:37:40Z
3,288,270
21
2010-07-20T08:39:39Z
[ "python", "tuples" ]
I have a tuple with two numbers in it, I need to get both numbers. The first number is the x-coordinate, while the second is the y-coordinate. My pseudo code is my idea about how to go about it, however I'm not quite sure how to make it work. pseudo code: ``` tuple = (46, 153) string = str(tuple) ss = string.search()...
``` int1, int2 = tuple ```
How do I get integers from a tuple in Python?
3,288,250
2
2010-07-20T08:37:40Z
3,288,281
16
2010-07-20T08:40:44Z
[ "python", "tuples" ]
I have a tuple with two numbers in it, I need to get both numbers. The first number is the x-coordinate, while the second is the y-coordinate. My pseudo code is my idea about how to go about it, however I'm not quite sure how to make it work. pseudo code: ``` tuple = (46, 153) string = str(tuple) ss = string.search()...
The other way is to use array subscripts: ``` int1 = tuple[0] int2 = tuple[1] ``` This is useful if you find you only need to access one member of the tuple at some point.
Good tutorial/example of SFTP server in Twisted Conch?
3,288,377
3
2010-07-20T08:54:21Z
3,295,974
7
2010-07-21T02:55:31Z
[ "python", "twisted" ]
can anyone recommend a good example or tutorial of how to add SFTP capabilities to a Twisted Conch SSH server? Is it possible to run an Conch SFTP server that I can connect to using other SFTP clients? I'm just getting started with Twisted. Thanks.
Probably the best existing example of doing this is in the code in Twisted Conch itself for setting up a normal filesystem-backed SFTP server. You can find the basic code for hooking up the SFTP subsystem in `twisted/conch/unix.py`, in `UnixConchUser.__init__`. Then, if you look in `twisted/conch/ssh/filetransfer.py` t...
Multiprocessing: How to use Pool.map on a function defined in a class?
3,288,595
114
2010-07-20T09:25:32Z
3,289,815
7
2010-07-20T12:21:24Z
[ "python", "multiprocessing", "pickle" ]
When I run something like: ``` from multiprocessing import Pool p = Pool(5) def f(x): return x*x p.map(f, [1,2,3]) ``` it works fine. However, putting this as a function of a class: ``` class calculate(object): def run(self): def f(x): return x*x p = Pool() return p.ma...
Functions defined in classes (even within functions within classes) don't really pickle. However, this works: ``` def f(x): return x*x class calculate(object): def run(self): p = Pool() return p.map(f, [1,2,3]) cl = calculate() print cl.run() ```
Multiprocessing: How to use Pool.map on a function defined in a class?
3,288,595
114
2010-07-20T09:25:32Z
3,336,182
36
2010-07-26T15:11:41Z
[ "python", "multiprocessing", "pickle" ]
When I run something like: ``` from multiprocessing import Pool p = Pool(5) def f(x): return x*x p.map(f, [1,2,3]) ``` it works fine. However, putting this as a function of a class: ``` class calculate(object): def run(self): def f(x): return x*x p = Pool() return p.ma...
There is currently no solution to your problem, as far as I know: the function that you give to `map()` must be accessible through an import of your module. This is why robert's code works: the function `f()` can be obtained by importing the following code: ``` def f(x): return x*x class Calculate(object): de...
Multiprocessing: How to use Pool.map on a function defined in a class?
3,288,595
114
2010-07-20T09:25:32Z
5,792,404
47
2011-04-26T15:10:23Z
[ "python", "multiprocessing", "pickle" ]
When I run something like: ``` from multiprocessing import Pool p = Pool(5) def f(x): return x*x p.map(f, [1,2,3]) ``` it works fine. However, putting this as a function of a class: ``` class calculate(object): def run(self): def f(x): return x*x p = Pool() return p.ma...
I also was annoyed by restrictions on what sort of functions pool.map could accept. I wrote the following to circumvent this. It appears to work, even for recursive use of parmap. ``` from multiprocessing import Process, Pipe from itertools import izip def spawn(f): def fun(pipe,x): pipe.send(f(x)) ...
Multiprocessing: How to use Pool.map on a function defined in a class?
3,288,595
114
2010-07-20T09:25:32Z
6,020,833
11
2011-05-16T17:08:06Z
[ "python", "multiprocessing", "pickle" ]
When I run something like: ``` from multiprocessing import Pool p = Pool(5) def f(x): return x*x p.map(f, [1,2,3]) ``` it works fine. However, putting this as a function of a class: ``` class calculate(object): def run(self): def f(x): return x*x p = Pool() return p.ma...
I've also struggled with this. I had functions as data members of a class, as a simplified example: ``` from multiprocessing import Pool import itertools pool = Pool() class Example(object): def __init__(self, my_add): self.f = my_add def add_lists(self, list1, list2): # Needed to do somethi...
Multiprocessing: How to use Pool.map on a function defined in a class?
3,288,595
114
2010-07-20T09:25:32Z
10,525,471
17
2012-05-09T23:18:22Z
[ "python", "multiprocessing", "pickle" ]
When I run something like: ``` from multiprocessing import Pool p = Pool(5) def f(x): return x*x p.map(f, [1,2,3]) ``` it works fine. However, putting this as a function of a class: ``` class calculate(object): def run(self): def f(x): return x*x p = Pool() return p.ma...
The solution by mrule is correct but has a bug: if the child sends back a large amount of data, it can fill the pipe's buffer, blocking on the child's `pipe.send()`, while the parent is waiting for the child to exit on `pipe.join()`. The solution is to read the child's data before `join()`ing the child. Furthermore the...
Multiprocessing: How to use Pool.map on a function defined in a class?
3,288,595
114
2010-07-20T09:25:32Z
16,071,616
58
2013-04-17T22:51:47Z
[ "python", "multiprocessing", "pickle" ]
When I run something like: ``` from multiprocessing import Pool p = Pool(5) def f(x): return x*x p.map(f, [1,2,3]) ``` it works fine. However, putting this as a function of a class: ``` class calculate(object): def run(self): def f(x): return x*x p = Pool() return p.ma...
I could not use the codes posted so far for three reasons. 1. The codes using "multiprocessing.Pool" do not work with lambda expressions. 2. The codes not using "multiprocessing.Pool" spawn as many processes as there are work items. 3. All codes iterate through the whole input list before doing the actual work. 2.) i...
Multiprocessing: How to use Pool.map on a function defined in a class?
3,288,595
114
2010-07-20T09:25:32Z
21,345,308
14
2014-01-25T01:15:44Z
[ "python", "multiprocessing", "pickle" ]
When I run something like: ``` from multiprocessing import Pool p = Pool(5) def f(x): return x*x p.map(f, [1,2,3]) ``` it works fine. However, putting this as a function of a class: ``` class calculate(object): def run(self): def f(x): return x*x p = Pool() return p.ma...
Multiprocessing and pickling is broken and limited unless you jump outside the standard library. If you use a fork of `multiprocessing` called `pathos.multiprocesssing`, you can directly use classes and class methods in multiprocessing's `map` functions. This is because `dill` is used instead of `pickle` or `cPickle`,...
Maximum level of recursion in Python
3,289,430
25
2010-07-20T11:30:10Z
3,289,437
30
2010-07-20T11:31:06Z
[ "python", "recursion" ]
What's the maximum level of recursion and how do I change it in Python?
The default is 1000 levels deep and you can change that using the `setrecursionlimit` function in the `sys` module. ***Warning:*** Beware that some operating systems may start running into problems if you go much higher due to limited stack space.
null object in Python?
3,289,601
469
2010-07-20T11:53:41Z
3,289,606
663
2010-07-20T11:54:27Z
[ "python", null ]
How do I refer to the null object in Python?
In Python, the 'null' object is the singleton `None`. The best way to check things for "Noneness" is to use the identity operator, `is`: ``` if foo is None: ... ```
null object in Python?
3,289,601
469
2010-07-20T11:53:41Z
3,289,624
29
2010-07-20T11:56:34Z
[ "python", null ]
How do I refer to the null object in Python?
It's not called null as in other languages, but [`None`](http://docs.python.org/library/constants.html?highlight=none#None). There is always only one instance of this object, so you can check for equivalence with `x is None` (identity comparison) instead of `x == None`, if you want.
null object in Python?
3,289,601
469
2010-07-20T11:53:41Z
15,185,044
15
2013-03-03T11:11:50Z
[ "python", null ]
How do I refer to the null object in Python?
In Python, to represent the absence of a value, you can use the *None* value (*types.NoneType.None*) for objects and *""* (or *len() == 0*) for strings. Therefore: ``` if yourObject is None: # if yourObject == None: ... if yourString == "": # if yourString.len() == 0: ... ``` Regarding the difference betwe...
lists in python, with references
3,289,822
2
2010-07-20T12:22:34Z
3,289,904
7
2010-07-20T12:34:00Z
[ "python", "list", "reference", "copy" ]
How do I copy the contents of a list and not just a reference to the list in Python?
Look at the [`copy` module](http://docs.python.org/library/copy.html#module-copy), and notice the difference between shallow and deep copies: > The difference between **shallow and deep copying** is only relevant for compound objects (objects that contain other objects, like lists or class instances): > > * A **shallo...
Read from a log file as it's being written using python
3,290,292
26
2010-07-20T13:16:22Z
3,290,355
22
2010-07-20T13:22:47Z
[ "python", "file", "logging", "file-io", "monitoring" ]
I'm trying to find a nice way to read a log file in real time using python. I'd like to process lines from a log file one at a time as it is written. Somehow I need to keep trying to read the file until it is created and then continue to process lines until I terminate the process. Is there an appropriate way to do thi...
Take a look at [this PDF](http://www.dabeaz.com/generators/Generators.pdf) starting at page 38, ~slide I-77 and you'll find all the info you need. Of course the rest of the slides are amazing, too, but those specifically deal with your issue: ``` import time def follow(thefile): thefile.seek(0,2) # Go to the end o...
Read from a log file as it's being written using python
3,290,292
26
2010-07-20T13:16:22Z
3,290,359
15
2010-07-20T13:23:16Z
[ "python", "file", "logging", "file-io", "monitoring" ]
I'm trying to find a nice way to read a log file in real time using python. I'd like to process lines from a log file one at a time as it is written. Somehow I need to keep trying to read the file until it is created and then continue to process lines until I terminate the process. Is there an appropriate way to do thi...
You could try with something like this: ``` import time while 1: where = file.tell() line = file.readline() if not line: time.sleep(1) file.seek(where) else: print line, # already has newline ``` Example was extracted from [here](http://code.activestate.com/recipes/157035-tail...
urllib2 and json
3,290,522
52
2010-07-20T13:40:00Z
3,290,647
15
2010-07-20T13:53:50Z
[ "python", "json", "urllib2" ]
can anyone point out a tutorial that shows me how to do a POST request using urllib2 with the data being in JSON format?
Example - sending some data encoded as JSON as a POST data: ``` import json import urllib2 data = json.dumps([1, 2, 3]) f = urllib2.urlopen(url, data) response = f.read() f.close() ```
urllib2 and json
3,290,522
52
2010-07-20T13:40:00Z
4,998,300
104
2011-02-14T23:00:40Z
[ "python", "json", "urllib2" ]
can anyone point out a tutorial that shows me how to do a POST request using urllib2 with the data being in JSON format?
Messa's answer only works if the server isn't bothering to check the content-type header. You'll need to specify a content-type header if you want it to really work. Here's Messa's answer modified to include a content-type header: ``` import json import urllib2 data = json.dumps([1, 2, 3]) req = urllib2.Request(url, d...
urllib2 and json
3,290,522
52
2010-07-20T13:40:00Z
7,606,288
24
2011-09-30T05:31:07Z
[ "python", "json", "urllib2" ]
can anyone point out a tutorial that shows me how to do a POST request using urllib2 with the data being in JSON format?
Whatever urllib is using to figure out Content-Length seems to get confused by json, so you have to calculate that yourself. ``` import json import urllib2 data = json.dumps([1, 2, 3]) clen = len(data) req = urllib2.Request(url, data, {'Content-Type': 'application/json', 'Content-Length': clen}) f = urllib2.urlopen(re...
urllib2 and json
3,290,522
52
2010-07-20T13:40:00Z
8,349,805
7
2011-12-01T23:23:04Z
[ "python", "json", "urllib2" ]
can anyone point out a tutorial that shows me how to do a POST request using urllib2 with the data being in JSON format?
To read json response use `json.loads()`. Here is the sample. ``` import json import urllib import urllib2 post_params = { 'foo' : bar } params = urllib.urlencode(post_params) response = urllib2.urlopen(url, params) json_response = json.loads(response.read()) ```
Python: what does "...".encode("utf8") fix?
3,291,123
8
2010-07-20T14:41:40Z
3,291,290
8
2010-07-20T14:56:22Z
[ "python", "unicode", "internationalization", "urlencode", "utf-8" ]
I wanted to url encode a python string and got exceptions with hebrew strings. I couldn't fix it and started doing some guess oriented programming. Finally, doing `mystr = mystr.encode("utf8")` before sending it to the url encoder saved the day. Can somebody explain what happened? What does .encode("utf8") do? My orig...
You original string was a unicode object containing raw [Unicode](http://en.wikipedia.org/wiki/Unicode) code points, after encoding it as UTF-8 it is a normal byte string that contains [UTF-8](http://en.wikipedia.org/wiki/UTF-8) encoded data. The URL encoder seems to expect a byte string, so that it can URL-encode one...
Python: what does "...".encode("utf8") fix?
3,291,123
8
2010-07-20T14:41:40Z
3,291,374
12
2010-07-20T15:05:15Z
[ "python", "unicode", "internationalization", "urlencode", "utf-8" ]
I wanted to url encode a python string and got exceptions with hebrew strings. I couldn't fix it and started doing some guess oriented programming. Finally, doing `mystr = mystr.encode("utf8")` before sending it to the url encoder saved the day. Can somebody explain what happened? What does .encode("utf8") do? My orig...
> My original string was a unicode string anyways (i.e. prefixed by a u) ...which is the problem. It wasn't a "string", as such, but a "Unicode object". It contains a sequence of Unicode code points. These code points must, of course, have some internal representation that Python knows about, but whatever that is is a...
JSON module for python 2.4?
3,291,682
20
2010-07-20T15:35:36Z
3,291,937
22
2010-07-20T15:59:36Z
[ "python", "json", "python-2.4" ]
I'm accustomed to doing `import json` in Python 2.6, however I now need to write some code for Python 2.4. Is there a JSON library with a similar interface that is available for Python 2.4?
The `json` module in Python 2.6 is mostly the same as the `simplejson` third-party module, which is available for Python 2.4 as well. You can just do: ``` try: import json except ImportError: import simplejson as json ```
JSON module for python 2.4?
3,291,682
20
2010-07-20T15:35:36Z
11,244,834
22
2012-06-28T12:38:19Z
[ "python", "json", "python-2.4" ]
I'm accustomed to doing `import json` in Python 2.6, however I now need to write some code for Python 2.4. Is there a JSON library with a similar interface that is available for Python 2.4?
Now, a few years later, simplejson does only support python 2.5+. No more simplejson for systems stuck on 2.4. Even though it is not supported, you may find older packages on pypi. 2.0.9 or 2.1.0 should work. ``` pip install simplejson==2.1.0 ``` (I could not comment on the chosen answer, but this just bit me hard, s...
Are accessors in Python ever justified?
3,292,631
9
2010-07-20T17:26:49Z
3,292,757
8
2010-07-20T17:42:26Z
[ "python", "inheritance", "interface", "attributes", "abstract-class" ]
I realize that in most cases, it's preferred in Python to just access attributes directly, since there's no real concept of encapsulation like there is in Java and the like. However, I'm wondering if there aren't any exceptions, particularly with abstract classes that have disparate implementations. Let's say I'm writ...
> Note: I've considered properties, but I don't think they're a cleaner solution. [But they are.](http://docs.python.org/library/functions.html#property) By using properties, you'll have the class signature you want, while being able to use the property as an attribute itself. ``` def _get_id(self): return self._i...
Python - convert list of tuples to string
3,292,643
14
2010-07-20T17:28:05Z
3,292,660
20
2010-07-20T17:30:16Z
[ "python", "list", "string-formatting", "tuples" ]
Which is the most pythonic way to convert a list of tuples to string? I have: ``` [(1,2), (3,4)] ``` and I want: ``` "(1,2), (3,4)" ``` My solution to this has been: ``` l=[(1,2),(3,4)] s="" for t in l: s += "(%s,%s)," % t s = s[:-1] ``` Is there a more pythonic way to do this?
You can try something like this ([see also on ideone.com](http://ideone.com/VfbJp)): ``` myList = [(1,2),(3,4)] print ",".join("(%s,%s)" % tup for tup in myList) # (1,2),(3,4) ```
Python - convert list of tuples to string
3,292,643
14
2010-07-20T17:28:05Z
3,292,703
19
2010-07-20T17:34:55Z
[ "python", "list", "string-formatting", "tuples" ]
Which is the most pythonic way to convert a list of tuples to string? I have: ``` [(1,2), (3,4)] ``` and I want: ``` "(1,2), (3,4)" ``` My solution to this has been: ``` l=[(1,2),(3,4)] s="" for t in l: s += "(%s,%s)," % t s = s[:-1] ``` Is there a more pythonic way to do this?
you might want to use something such simple as: ``` >>> l = [(1,2), (3,4)] >>> str(l).strip('[]') '(1, 2), (3, 4)' ``` .. which is handy, but not guaranteed to work correctly
Python - convert list of tuples to string
3,292,643
14
2010-07-20T17:28:05Z
3,293,466
9
2010-07-20T19:13:07Z
[ "python", "list", "string-formatting", "tuples" ]
Which is the most pythonic way to convert a list of tuples to string? I have: ``` [(1,2), (3,4)] ``` and I want: ``` "(1,2), (3,4)" ``` My solution to this has been: ``` l=[(1,2),(3,4)] s="" for t in l: s += "(%s,%s)," % t s = s[:-1] ``` Is there a more pythonic way to do this?
How about: ``` >>> tups = [(1, 2), (3, 4)] >>> ', '.join(map(str, tups)) '(1, 2), (3, 4)' ```
Sum fields in sqlAlchemy
3,292,752
6
2010-07-20T17:41:28Z
3,294,597
10
2010-07-20T21:40:58Z
[ "python", "sqlalchemy" ]
I recently upgraded to the most recent version of sqlalchemy and some of my code no longer works. I'm having difficulty finding how to fix it and could use a hand. Previously the query appeared as so. ``` self.db.query(Drive).filter(Drive.package_id==package.package_id)\ .filter(Drive.wipe_end!=None).sum(Drive.wi...
I believe you need the sum() function in the "func" package: ``` from sqlalchemy import func cursor = self.db.query(func.sum(Drive.wipe_end - Drive.wipe_start)).filter(Drive.package_id==package.package_id).filter(Drive.wipe_end!=None) total = cursor.scalar() ```
My function takes negative time to complete. What in the world happened?
3,292,865
3
2010-07-20T17:55:14Z
3,292,921
17
2010-07-20T18:05:04Z
[ "python", "time", "timing" ]
I'm posing this question mostly out of curiosity. I've written some code that is doing some very time intensive work. So, before executing my workhorse function, I wrapped it up in a couple of calls to time.clock(). It looks something like this: ``` t1 = time.clock() print this_function_takes_forever(how_long_paramete...
The [Python docs](http://docs.python.org/library/time.html#time.clock) say: > On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name The [manpa...
python dbus problem
3,293,172
2
2010-07-20T18:35:13Z
3,293,262
8
2010-07-20T18:46:52Z
[ "python", "dbus" ]
I have a problem with dbus and python. Running python from the command line, telling it `import dbus` and then `systembus = dbus.SystemBus()` results in no errors, nor does running a program written by a friend which also uses the exact same code. However, when running a program I'm trying to write, I get this error: ...
The obvious problem is that when you are importing `dbus`, it is not getting all the methods with it. In both your program and your friend's, do `print dbus.__file__`. This will show what .pyc it is using. If they are different, you are not importing the correct dbus module. I'm going to guess that you are actually i...
Iterating over dictionaries using for loops in Python
3,294,889
1,056
2010-07-20T22:27:42Z
3,294,897
27
2010-07-20T22:29:15Z
[ "python", "dictionary" ]
I am a bit puzzled by the following code: ``` d = {'x': 1, 'y': 2, 'z': 3} for key in d: print key, 'corresponds to', d[key] ``` What I don't understand is the `key` portion. How does Python recognize that it needs only to read the key from the dictionary? Is `key` a special word in Python? Or is it simply a var...
When you iterate through dictionaries using the `for .. in ..`-syntax, it always iterates over the keys (the values are accessible using `dictionary[key]`). To iterate over key-value pairs, use `for k,v in s.iteritems()`.
Iterating over dictionaries using for loops in Python
3,294,889
1,056
2010-07-20T22:27:42Z
3,294,899
1,973
2010-07-20T22:29:33Z
[ "python", "dictionary" ]
I am a bit puzzled by the following code: ``` d = {'x': 1, 'y': 2, 'z': 3} for key in d: print key, 'corresponds to', d[key] ``` What I don't understand is the `key` portion. How does Python recognize that it needs only to read the key from the dictionary? Is `key` a special word in Python? Or is it simply a var...
`key` is just a variable name. ``` for key in d: ``` will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following: For Python 2.x: ``` for key, value in d.iteritems(): ``` For Python 3.x: ``` for key, value in d.items(): ``` To test ...
Iterating over dictionaries using for loops in Python
3,294,889
1,056
2010-07-20T22:27:42Z
3,294,969
12
2010-07-20T22:42:58Z
[ "python", "dictionary" ]
I am a bit puzzled by the following code: ``` d = {'x': 1, 'y': 2, 'z': 3} for key in d: print key, 'corresponds to', d[key] ``` What I don't understand is the `key` portion. How does Python recognize that it needs only to read the key from the dictionary? Is `key` a special word in Python? Or is it simply a var...
This is a very common looping idiom. `in` is an operator. For when to use `for key in dict` and when it must be `for key in dict.keys()` see [David Goodger's Idiomatic Python article](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#use-in-where-possible-1).
Iterating over dictionaries using for loops in Python
3,294,889
1,056
2010-07-20T22:27:42Z
3,295,279
25
2010-07-20T23:49:27Z
[ "python", "dictionary" ]
I am a bit puzzled by the following code: ``` d = {'x': 1, 'y': 2, 'z': 3} for key in d: print key, 'corresponds to', d[key] ``` What I don't understand is the `key` portion. How does Python recognize that it needs only to read the key from the dictionary? Is `key` a special word in Python? Or is it simply a var...
`key` is simply a variable. You can do this: ``` d = {'x': 1, 'y': 2, 'z': 3} for my_var in d: print my_var, 'corresponds to', d[my_var] ``` ... or better, ``` d = {'x': 1, 'y': 2, 'z': 3} for the_key, the_value in d.iteritems(): print the_key, 'corresponds to', the_value ``` **EDIT** Changed the var nam...
Iterating over dictionaries using for loops in Python
3,294,889
1,056
2010-07-20T22:27:42Z
3,295,295
225
2010-07-20T23:52:08Z
[ "python", "dictionary" ]
I am a bit puzzled by the following code: ``` d = {'x': 1, 'y': 2, 'z': 3} for key in d: print key, 'corresponds to', d[key] ``` What I don't understand is the `key` portion. How does Python recognize that it needs only to read the key from the dictionary? Is `key` a special word in Python? Or is it simply a var...
It's not that key is a special word, but that dictionaries implement the iterator protocol. You could do this in your class, e.g. see [this question](http://stackoverflow.com/questions/19151/build-a-basic-python-iterator/24377#24377) for how to build class iterators. In the case of dictionaries, it's implemented at th...
Iterating over dictionaries using for loops in Python
3,294,889
1,056
2010-07-20T22:27:42Z
3,295,662
86
2010-07-21T01:27:03Z
[ "python", "dictionary" ]
I am a bit puzzled by the following code: ``` d = {'x': 1, 'y': 2, 'z': 3} for key in d: print key, 'corresponds to', d[key] ``` What I don't understand is the `key` portion. How does Python recognize that it needs only to read the key from the dictionary? Is `key` a special word in Python? Or is it simply a var...
Iterating over a `dict` iterates through its keys in no particular order, as you can see here: ``` >>> d = {'x': 1, 'y': 2, 'z': 3} >>> list(d) ['y', 'x', 'z'] >>> d.keys() ['y', 'x', 'z'] ``` For your example, it is a better idea to use `dict.items()`: ``` >>> d.items() [('y', 2), ('x', 1), ('z', 3)] ``` This giv...
Where should utility functions live in Django?
3,295,268
25
2010-07-20T23:45:14Z
3,295,933
14
2010-07-21T02:46:27Z
[ "python", "django", "structure" ]
Where should utility functions live in Django? Functions like custom encrypting/decrypting a number, sending tweets, sending email, verifying object ownership, custom input validation, etc. Repetitive and custom stuff that I use in a number of places in my app. I'm definitely breaking DRY right now. I saw some demos w...
Different [question](http://stackoverflow.com/questions/3224902/django-what-is-the-most-ideal-place-to-store-project-specific-middleware/3224926#3224926) but same answer: > My usual layout for a django site is: > > ``` > projects/ > templates/ > common/ > local/ > ``` > > Where: > > * projects contains your main proje...
Python unittest and discovery
3,295,386
22
2010-07-21T00:13:54Z
3,295,615
21
2010-07-21T01:16:49Z
[ "python", "unit-testing", "discovery" ]
I have directories, which contain files named like: `test_foo.py` Each file is a test case. I would like to 1) Run all the tests in a directory from the command line. I am using `unittest2`, since we are running Python 2.5.1. From one of these directories I tried typing this at the command line: ``` python -m unitt...
Give how you're trying to use `unittest2` from the command line on Python `< 2.7`, I think you may have missed [the note on the `unittest2` PyPI page](http://pypi.python.org/pypi/unittest2): > Note > > Command line usage > > In Python 2.7 you invoke the unittest > command line features (including test > discover) with...
Python unittest and discovery
3,295,386
22
2010-07-21T00:13:54Z
6,672,873
30
2011-07-13T00:35:46Z
[ "python", "unit-testing", "discovery" ]
I have directories, which contain files named like: `test_foo.py` Each file is a test case. I would like to 1) Run all the tests in a directory from the command line. I am using `unittest2`, since we are running Python 2.5.1. From one of these directories I tried typing this at the command line: ``` python -m unitt...
I ran into the same issue when running `python -m unittest discover`. Here is a good check list to verify your setup. `Nose` is more flexible with the allowed configurations, but not necessarily better. 1. Make sure all files/dirs start with `test`. Do **not** use `test-something.py`, since that is not a valid python ...