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
Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?
18,946,662
482
2013-09-22T17:24:13Z
18,947,663
13
2013-09-22T19:02:57Z
[ "python", "performance", "jit", "pypy", "cpython" ]
I've been hearing a lot about the [PyPy](http://en.wikipedia.org/wiki/PyPy) project. They claim it is 6.3 times faster than the [CPython](http://en.wikipedia.org/wiki/CPython) interpreter on [their site](http://speed.pypy.org). Whenever we talk about dynamic languages like Python, speed is one of the top issues. To so...
I did a small benchmark on this topic. While many of the other posters have made good points about compatibility, my experience has been that PyPy isn't that much faster for just moving around bits. For many uses of Python, it really only exists to translate bits between two or more services. For example, not many web ...
Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?
18,946,662
482
2013-09-22T17:24:13Z
18,949,049
81
2013-09-22T21:42:22Z
[ "python", "performance", "jit", "pypy", "cpython" ]
I've been hearing a lot about the [PyPy](http://en.wikipedia.org/wiki/PyPy) project. They claim it is 6.3 times faster than the [CPython](http://en.wikipedia.org/wiki/CPython) interpreter on [their site](http://speed.pypy.org). Whenever we talk about dynamic languages like Python, speed is one of the top issues. To so...
That site does **not** claim PyPy is 6.3 times faster than CPython. To quote: > The geometric average of all benchmarks is 0.16 or 6.3 times faster than CPython This is a **very** different statement to the blanket statement you made, and when you understand the difference, you'll understand at least one set of reaso...
Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?
18,946,662
482
2013-09-22T17:24:13Z
18,949,652
7
2013-09-22T23:01:58Z
[ "python", "performance", "jit", "pypy", "cpython" ]
I've been hearing a lot about the [PyPy](http://en.wikipedia.org/wiki/PyPy) project. They claim it is 6.3 times faster than the [CPython](http://en.wikipedia.org/wiki/CPython) interpreter on [their site](http://speed.pypy.org). Whenever we talk about dynamic languages like Python, speed is one of the top issues. To so...
CPython has reference counting and garbage collection, PyPy has garbage collection only. So objects tend to be deleted earlier and `__del__` is called in a more predictable way in CPython. Some software relies on this behavior, thus they are not ready for migrating to PyPy. Some other software works with both, but us...
Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?
18,946,662
482
2013-09-22T17:24:13Z
18,958,181
12
2013-09-23T11:32:27Z
[ "python", "performance", "jit", "pypy", "cpython" ]
I've been hearing a lot about the [PyPy](http://en.wikipedia.org/wiki/PyPy) project. They claim it is 6.3 times faster than the [CPython](http://en.wikipedia.org/wiki/CPython) interpreter on [their site](http://speed.pypy.org). Whenever we talk about dynamic languages like Python, speed is one of the top issues. To so...
*Q: If PyPy can solve these great challenges (speed, memory consumption, parallelism) in comparison to CPython, what are its weaknesses that are preventing wider adoption?* A: First, there is little evidence that the PyPy team can solve the speed problem **in general**. Long-term evidence is showing that PyPy runs cer...
Using python multiprocessing Pool in the terminal and in code modules for Django or Flask
18,947,876
12
2013-09-22T19:27:57Z
18,962,804
23
2013-09-23T15:10:36Z
[ "python", "django", "flask", "multiprocessing", "pool" ]
When using multiprocessing.Pool in python with the following code, there is some bizarre behavior. ``` from multiprocessing import Pool p = Pool(3) def f(x): return x threads = [p.apply_async(f, [i]) for i in range(20)] for t in threads: try: print(t.get(timeout=1)) except Exception: pass ``` I get the follow...
## Pools must be initialized after the definitions of functions to be run on them The inscrutable text from the python docs means that at the time the pool is defined, the surrounding module is imported by the threads in the pool. In the case of the python terminal, this means all and only code you have run so far. S...
Running Python code in Vim
18,948,491
37
2013-09-22T20:35:08Z
18,948,530
48
2013-09-22T20:38:49Z
[ "python", "vim" ]
I am writing Python code using Vim, and every time I want to run my code, I type this inside Vim: ``` :w !python ``` This gets frustrating, so I was looking for a quicker method to run Python code inside Vim. Executing Python scripts from a terminal maybe? I am using Linux.
how about adding an `autocmd`, when `FileType python`, create a mapping: ``` nnoremap <buffer> <F9> :exec '!python' shellescape(@%, 1)<cr> ``` then you could press `<F9>` to execute the current buffer with `python`
Running Python code in Vim
18,948,491
37
2013-09-22T20:35:08Z
25,038,733
8
2014-07-30T13:55:32Z
[ "python", "vim" ]
I am writing Python code using Vim, and every time I want to run my code, I type this inside Vim: ``` :w !python ``` This gets frustrating, so I was looking for a quicker method to run Python code inside Vim. Executing Python scripts from a terminal maybe? I am using Linux.
I have this in my .vimrc file: ``` nnoremap <silent> <F5> :!clear;python %<CR> ``` When I'm done editing a Python script, I press `<Esc>` and then `<F5>`. The script is saved and then executed in a blank screen.
Pymongo $addToSet fails to work
18,948,521
2
2013-09-22T20:37:47Z
18,950,392
8
2013-09-23T01:01:00Z
[ "python", "database", "mongodb", "pymongo" ]
I am trying to make a simple database in PyMongo. It creates trigrams and utilises those as keys. The values are the words in which the trigramkey occurs; so: ``` {"trigram":"#ha","words":["hahaha","harley","mahalo"]} etc. ``` I am looping through the set of trigrams that are found and create them as keys. The proble...
Unless you use the `upsert` option, an `update` will only modify existing docs, not create them. Try this instead: ``` db["Terms"].update( { "trigram":trigram }, { "$addToSet":{"words":word} }, upsert=True) ``` By using the `upsert` option, it will create the doc if missing, otherwise just update the existing...
class method generates "TypeError: ... got multiple values for keyword argument ..."
18,950,054
50
2013-09-23T00:08:45Z
18,950,055
65
2013-09-23T00:08:45Z
[ "python", "class", "python-2.7", "methods" ]
If I define a class method with a keyword argument thus: ``` class foo(object): def foodo(thing=None, thong='not underwear'): print thing if thing else "nothing" print 'a thong is',thong ``` calling the method generates a `TypeError`: ``` myfoo = foo() myfoo.foodo(thing="something") ... TypeError: foodo(...
The problem is that the first argument passed to class methods in python is always a copy of the class instance on which the method is called, typically labelled `self`. If the class is declared thus: ``` class foo(object): def foodo(self, thing=None, thong='not underwear'): print thing if thing else "nothing" ...
class method generates "TypeError: ... got multiple values for keyword argument ..."
18,950,054
50
2013-09-23T00:08:45Z
24,943,359
33
2014-07-24T20:27:57Z
[ "python", "class", "python-2.7", "methods" ]
If I define a class method with a keyword argument thus: ``` class foo(object): def foodo(thing=None, thong='not underwear'): print thing if thing else "nothing" print 'a thong is',thong ``` calling the method generates a `TypeError`: ``` myfoo = foo() myfoo.foodo(thing="something") ... TypeError: foodo(...
Thanks for the instructive posts. I'd just like to keep a note that if you're getting "TypeError: foodo() got multiple values for keyword argument 'thing'", it may also be that you're mistakenly passing the 'self' as a parameter when calling the function (probably because you copied the line from the class declaration ...
class method generates "TypeError: ... got multiple values for keyword argument ..."
18,950,054
50
2013-09-23T00:08:45Z
31,822,875
9
2015-08-05T03:20:54Z
[ "python", "class", "python-2.7", "methods" ]
If I define a class method with a keyword argument thus: ``` class foo(object): def foodo(thing=None, thong='not underwear'): print thing if thing else "nothing" print 'a thong is',thong ``` calling the method generates a `TypeError`: ``` myfoo = foo() myfoo.foodo(thing="something") ... TypeError: foodo(...
This might be obvious, but it might help someone who has never seen it before. This also happens for regular functions if you mistakenly assign a parameter by position and explicitly by name. ``` >>> def foodo(thing=None, thong='not underwear'): ... print thing if thing else "nothing" ... print 'a thong is',th...
How to jump out of a dead loop automatically in Python?
18,950,913
4
2013-09-23T02:21:15Z
18,950,946
7
2013-09-23T02:26:26Z
[ "python" ]
I have a "do..., until..." structure in Python as follows: ``` while True: if foo() == bar(): break ``` It works fine (jumps out in the end) in most of the cases. However, in some of the cases where the condition is never met, it will get stuck there. Figuring out what are these cases is kind of difficul...
``` import time loop_start = time.time() while time.time() - loop_start <= 1: if foo() == bar(): break ```
What happened on March 16th 1984?
18,950,963
11
2013-09-23T02:29:39Z
18,952,645
7
2013-09-23T06:01:28Z
[ "python", "timezone", "pypy", "mktime" ]
I am trying to figure out what's special about March 16th, 1984. On a virtual machine I am using (nothing special about it), Python (as well as [PyPy](http://en.wikipedia.org/wiki/PyPy)) crashes when trying to use mktime with what seems to be a perfectly reasonable time struct. ``` $ pypy Python 2.7.3 (f66246c46ca30b2...
Your machine thinks that there was a daylight savings transition between midnight on 15th March 1984 and midnight on 17th March 1984, given that the difference between 448326000.0 and 448156800.0 is 47 hours, not 48. But so far as I can tell, no such transition occurred on that day in France. And I'm not sure how you ...
What happened on March 16th 1984?
18,950,963
11
2013-09-23T02:29:39Z
18,958,502
7
2013-09-23T11:50:19Z
[ "python", "timezone", "pypy", "mktime" ]
I am trying to figure out what's special about March 16th, 1984. On a virtual machine I am using (nothing special about it), Python (as well as [PyPy](http://en.wikipedia.org/wiki/PyPy)) crashes when trying to use mktime with what seems to be a perfectly reasonable time struct. ``` $ pypy Python 2.7.3 (f66246c46ca30b2...
Aha! Mystery solved (since OP finally figured out the time zone "at fault"). I found this: <http://www.timeanddate.com/worldclock/timezone.html?n=60&syear=1980> ``` 1980 No time changes 1981 No time changes 1982 No time changes 1983 No time changes 1984 Time zone change on Friday, March 16, 198...
Are there any reasons not to use an ordered dictionary?
18,951,143
34
2013-09-23T02:56:25Z
18,951,209
69
2013-09-23T03:04:23Z
[ "python", "dictionary", "python-3.x", "ordereddictionary" ]
I'm referring to the [OrderedDict](http://docs.python.org/2/library/collections.html#collections.OrderedDict) from the `collections` module. If it has the added functionality of being orderable, which I realize may often not be necessary but even so, are there any downsides? Is it slower? Is it missing any functionali...
`OrderedDict` is a subclass of `dict`, and needs more memory to keep track of the order in which keys are added. This isn't trivial. The implementation adds a second `dict` under the covers, and a doubly-linked list of all the keys (that's the part that remembers the order), and a bunch of weakref proxies. It's not a *...
Use Distance Matrix in scipy.cluster.hierarchy.linkage()?
18,952,587
14
2013-09-23T05:56:26Z
18,954,990
13
2013-09-23T08:40:23Z
[ "python", "scipy", "hierarchical-clustering" ]
I have a distance matrix n\*n `M` where `M_ij` is the distance between `object_i` and `object_j`. So as expected, it takes the following form: ``` / 0 M_01 M_02 ... M_0n\ | M_10 0 M_12 ... M_1n | | M_20 M_21 0 ... M2_n | | ... | \ ...
It seems that indeed we cannot directly pass the redundant square matrix in, although the documentation claims we can do so. To benefit anyone who faces the same problem in the future, I write my solution as an additional answer here. So the copy-and-paste guys can just proceed with the clustering. Use the following ...
Upload a file using boto
18,952,684
5
2013-09-23T06:05:31Z
18,953,291
8
2013-09-23T06:51:14Z
[ "python", "boto" ]
``` import boto conn = boto.connect_s3('', '') mybucket = conn.get_bucket('data_report_321') ``` I can download the file from a bucket using the following code. ``` for b in mybucket: print b.name b.get_contents_to_filename('0000_part_00', headers=None, cb=None, num_cb=10, torrent=False, version_id=None, ...
Both [send\_file](https://boto.readthedocs.org/en/latest/ref/s3.html#boto.s3.key.Key.send_file) and [set\_contents\_from\_file](https://boto.readthedocs.org/en/latest/ref/s3.html#boto.s3.key.Key.set_contents_from_file) take a `File` object for first argument. If you would like to pass a string you should see [set\_cont...
Valueerror : I/O operation on closed file
18,952,716
23
2013-09-23T06:08:21Z
18,952,732
35
2013-09-23T06:09:02Z
[ "python", "csv", "io" ]
``` import csv with open('v.csv', 'w') as csvfile: cwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) for w, c in p.iteritems(): cwriter.writerow(w + c) ``` Here, p is a dictionary, w and c both are strings. When I try to write in the file it reports error : Valueerr...
Indent correctly; `for` statement should be inside `with` block: ``` import csv with open('v.csv', 'w') as csvfile: cwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) for w, c in p.iteritems(): cwriter.writerow(w + c) ``` Outside the `with` block, the file is ...
How to process images of a video, frame by frame in video streaming using Opencv python
18,954,889
17
2013-09-23T08:34:51Z
18,957,214
7
2013-09-23T10:40:46Z
[ "python", "opencv", "video", "video-streaming" ]
I am a beginner in OpenCV. I want to do some image processing on the frames of a video which is being uploaded to my server. I just want to read the available frames and write them in a directory. And wait for other part of the video to be uploaded and write the frames to the directory. And I should wait for each frame...
In openCV's documentation there is an [example](http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html) for getting video frame by frame. It is written in c++ but it is very easy to port the example to python - you can search for each fumction documentation to see how to call them in pytho...
How to process images of a video, frame by frame in video streaming using Opencv python
18,954,889
17
2013-09-23T08:34:51Z
19,082,750
16
2013-09-29T20:08:42Z
[ "python", "opencv", "video", "video-streaming" ]
I am a beginner in OpenCV. I want to do some image processing on the frames of a video which is being uploaded to my server. I just want to read the available frames and write them in a directory. And wait for other part of the video to be uploaded and write the frames to the directory. And I should wait for each frame...
After reading the documentation of [`VideoCapture`](http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture). I figured out that you can tell `VideoCapture`, which frame to process next time we call [`VideoCapture.read()`](http://docs.opencv.org/modules/highgui/doc/reading_and_...
Interpolating one time series onto another in pandas
18,955,250
5
2013-09-23T08:54:39Z
18,956,276
7
2013-09-23T09:49:25Z
[ "python", "numpy", "pandas" ]
I have one set of values measured at regular times. Say: ``` import pandas as pd import numpy as np rng = pd.date_range('2013-01-01', periods=12, freq='H') data = pd.Series(np.random.randn(len(rng)), index=rng) ``` And another set of more arbitrary times, for example, (in reality these times are not a regular sequenc...
You can concatenate the two time series and sort by index. Since the values in the second series are `NaN` you can `interpolate` and the just select out the values that represent the points from the second series: ``` pd.concat([data, ts]).sort_index().interpolate().reindex(ts.index) ``` or ``` pd.concat([data, ts...
Get random key:value pairs from dictionary in python
18,955,554
4
2013-09-23T09:11:13Z
18,955,679
12
2013-09-23T09:19:02Z
[ "python", "csv", "random", "dictionary" ]
I'm trying to pull out a random set of key-value pairs from a dictionary I made from a csv file. The dictionary contains information for genes, with the gene name being the dictionary key, and a list of numbers (related to gene expression etc.) being the value. ``` # python 2.7.5 import csv import random genes_csv = ...
If you want to get random `K` elements from dictionary `D` you simply use ``` import random random.sample( D.items(), K ) ``` and that's all you need. From the Python's documentation: > random.**sample**(*population*, *k*) > > Return a *k* length list of unique elements > chosen from the *population* sequence. Used...
"SSLError: The read operation timed out" when using pip
18,958,508
13
2013-09-23T11:50:28Z
19,334,551
26
2013-10-12T13:08:26Z
[ "python", "pip" ]
Whenever I try to install something with `pip` I get the following error: ``` Downloading/unpacking Django>=1.5.1,<1.6 (from -r requirements.txt (line 1))   Downloading Django-1.5.4.tar.gz (8.1MB): 8.0MB downloaded Cleaning up... Exception: Traceback (most recent call last):   File "/vagrant/venv/local/lib/python2.7/s...
try (note the --default): ``` pip --default-timeout=100 install django ``` if it still doesn't work, you can manually download [django1.5.4](https://www.djangoproject.com/download/1.5.4/tarball/) and: <https://docs.djangoproject.com/en/dev/topics/install/#installing-an-official-release-manually> **similar questions...
Running coverage inside virtualenv
18,959,072
13
2013-09-23T12:18:32Z
18,960,025
10
2013-09-23T13:05:10Z
[ "python", "virtualenv", "coverage.py", "python-coverage" ]
I recently stumbled upon some issue with running coverage measurements within virtual environment. I do not remember similar issues in the past, nor I was able to find solution on the web. Basically, when I am trying to run test suite in virtualenv, it works fine. But as soon, as I try to do it using `coverage`, it fa...
`pip install coverage` in your new venv ``` [alex@gesa ~]$ virtualenv venv [alex@gesa ~]$ source venv/bin/activate (venv)[alex@gesa ~]$ pip install coverage (venv)[alex@gesa ~]$ echo 'import sys; print(sys.executable)' > test.py (venv)[alex@gesa ~]$ python test.py /home/alex/venv/bin/python (venv)[alex@gesa ~]$ covera...
Running coverage inside virtualenv
18,959,072
13
2013-09-23T12:18:32Z
23,377,188
9
2014-04-29T23:39:48Z
[ "python", "virtualenv", "coverage.py", "python-coverage" ]
I recently stumbled upon some issue with running coverage measurements within virtual environment. I do not remember similar issues in the past, nor I was able to find solution on the web. Basically, when I am trying to run test suite in virtualenv, it works fine. But as soon, as I try to do it using `coverage`, it fa...
I had to leave my virtualenv after installing coverage and reactivate it to get coverage to work. ``` [alex@gesa ~]$ virtualenv --no-site-packages venv [alex@gesa ~]$ source venv/bin/activate (venv)[alex@gesa ~]$ pip install coverage (venv)[alex@gesa ~]$ deactivate [alex@gesa ~]$ source venv/bin/activate ```
Python os.stat(file_name).st_size versus os.path.getsize(file_name)
18,962,166
4
2013-09-23T14:39:41Z
18,962,257
10
2013-09-23T14:43:59Z
[ "python", "python-2.6" ]
I've got two pieces of code that are both meant to do the same thing -- sit in a loop until a file is done being written to. They are both mainly used for files coming in via FTP/SCP. One version of the code does it using `os.stat()[stat.ST_SIZE]`: ``` size1,size2 = 1,0 while size1 != size2: size1 = os.stat(file_na...
In CPython 2.6 and 2.7, `os.path.getsize()` is implemented as follows: ``` def getsize(filename): """Return the size of a file, reported by os.stat().""" return os.stat(filename).st_size ``` From this, it seems pretty clear that there is no reason to expect the two approaches to behave differently (except per...
Convert string in to dictionary
18,962,207
3
2013-09-23T14:41:42Z
18,962,230
7
2013-09-23T14:42:47Z
[ "python", "json", "serialization", "dictionary", "pickle" ]
I know It's looks like a dumb question, but anyway. I'm trying to convert string representation of dictionary back in to dictionary. My workflow is the following: ``` d = {1:2} s = str(d) ``` When I do: ``` dict(s) ``` I get: > > ValueError: dictionary update sequence element #0 has length 1; 2 is required And ...
Try using [`ast.literal_eval()`](http://docs.python.org/library/ast.html), it's the safest way: ``` import ast ast.literal_eval('{1:2}') => '{1:2}' ``` From the linked documentation: > Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the f...
Convert string in to dictionary
18,962,207
3
2013-09-23T14:41:42Z
18,962,262
10
2013-09-23T14:44:20Z
[ "python", "json", "serialization", "dictionary", "pickle" ]
I know It's looks like a dumb question, but anyway. I'm trying to convert string representation of dictionary back in to dictionary. My workflow is the following: ``` d = {1:2} s = str(d) ``` When I do: ``` dict(s) ``` I get: > > ValueError: dictionary update sequence element #0 has length 1; 2 is required And ...
If you want a portable string representation, use `s = json.dumps(d)` which can then be reloaded using `json.loads(s)` However, this is limited to JSON-compatible types. If you just want to use it within python the most powerful option is [`pickle`](http://docs.python.org/2/library/pickle.html) (be careful: never unpi...
How do I run tox in a project that has no setup.py?
18,962,403
28
2013-09-23T14:50:46Z
18,985,263
38
2013-09-24T15:04:28Z
[ "python", "unit-testing", "distutils", "tox" ]
I would like to use `tox` to run my unittests in two virtualenvs, since my application has to support 2 different Python versions. My problem is that `tox` requires a `setup.py`, but I have none since my application is not a module and has its own installer. For now I don't want to go through the hassle of automating ...
After digging inside the source code, I found a scarcely documented option in tox.ini that skips sdist: ``` [tox] skipsdist = BOOL # defaults to false ``` Setting this to `True` I got what I wanted, saving me the effort of writing a meaningful `setup.py`
How do I run tox in a project that has no setup.py?
18,962,403
28
2013-09-23T14:50:46Z
26,938,095
16
2014-11-14T20:13:11Z
[ "python", "unit-testing", "distutils", "tox" ]
I would like to use `tox` to run my unittests in two virtualenvs, since my application has to support 2 different Python versions. My problem is that `tox` requires a `setup.py`, but I have none since my application is not a module and has its own installer. For now I don't want to go through the hassle of automating ...
If you have an application (with a `requirements.txt`), rather than a project that you are going to distribute (which would have a `setup.py` instead), your `tox.ini` should look something like this: ``` [tox] skipsdist = True [testenv] deps = -r{toxinidir}/requirements.txt ``` Found this answer originally here: <ht...
Https with Http in Flask Python
18,962,418
7
2013-09-23T14:51:50Z
18,962,456
7
2013-09-23T14:54:04Z
[ "python", "http", "https", "flask" ]
I have a client server application. I managed to make them connect over https using SSl encryption using this ``` context = SSL.Context(SSL.SSLv3_METHOD) context.use_privatekey_file('/path_to_key/key.key') context.use_certificate_file('/path_to_cert/cert.crt') app.run(use_reloader=True, host='0.0.0.0',...
First big thing: don't use the built in web server in flask to do any heavy lifting. You should use a real web server like apache (mod\_wsgi) nginex + gunicore, etc. These servers have documentation on how to run http and https simultaneously.
OSError: [Errno 2] No such file or directory while using python subprocess in Django
18,962,785
47
2013-09-23T15:09:41Z
18,962,815
115
2013-09-23T15:11:08Z
[ "python", "django", "subprocess" ]
I am trying to run a program to make some system calls inside python code using subprocess.call() ... Which throws the following error , traceback ``` Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/lib/python2.7/subprocess.py", line 493, in call return Popen(*pope...
Use `shell=True` if you're passing a string to `subprocess.call`. From [docs](http://docs.python.org/2/library/subprocess.html#frequently-used-arguments): > If passing a single string, either `shell` must be `True` or > else the string must simply name the program to be executed without > specifying any arguments. `...
django file upload: [Errno 13] Permission denied: '/static'
18,963,494
4
2013-09-23T15:45:20Z
18,963,573
7
2013-09-23T15:49:41Z
[ "python", "django", "apache", "mod-wsgi", "permission-denied" ]
I am trying to upload several files in django. On my local maching where I use the djangos build in server everything works fine but on my productivity server I get this error: ``` [Errno 13] Permission denied: '/static' ``` There are many questions about this issue but nothing I found worked for me. In my case it ha...
Your Apache configuration for the uploaded media: ``` Alias /media /var/www/webpage/webpage/ ``` is not in-sync with your Django settings: ``` # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/var/www/example.com/media/" MEDIA_ROOT = '' # URL that handles the media served ...
factory_boy objects seem to lack primary keys
18,963,526
5
2013-09-23T15:47:16Z
18,965,006
12
2013-09-23T17:09:32Z
[ "python", "django", "django-models", "factory-boy" ]
When I create factory\_boy objects, the object doesn't appear to have a primary key and I'm not sure why. Here's my model and factory: ``` # models.py from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): # UserProfile is a subset table of User. They have a 1:1...
For django support you need to use `DjangoModelFactory`: <https://factoryboy.readthedocs.org/en/latest/orms.html#the-djangomodelfactory-subclass>
Error Pickling in Python: io.UnsupportedOperation: read
18,963,949
3
2013-09-23T16:08:18Z
18,964,012
9
2013-09-23T16:11:24Z
[ "python", "pickle" ]
I am trying to learn how to `pickle` and save an object in python. However, when I use the [sample code](http://www.astrobetter.com/python-tip-storing-data/) below I get the following error: `io.UnsupportedOperation: read` which traces back to `favorite_color = pickle.load(f_myfile)`. I cannot find a good explanation o...
Change: ``` # Read from file f_myfile = open('myfile.pickle', 'wb') ``` to: ``` f_myfile = open('myfile.pickle', 'rb') ``` and you can see the dict obj you've pickled.
GetUserTimeline always returns my own timeline
18,964,216
5
2013-09-23T16:22:20Z
18,965,443
7
2013-09-23T17:36:21Z
[ "python", "python-2.7", "twitter", "timeline" ]
I am using python-twitter library, but I am unable to get the timeline of a specified user. Example ``` print [s.text for s in api.GetUserTimeline('@BarackObama')] ``` returns: ``` [u'test'] ``` which is my last tweet (api is the object returned by tweeter.Api(...)). Can someone help me with this? **EDIT**: The c...
Try this instead (screen\_name will accept `@BarackObama`, `BarackObama` or `barackobama`): ``` print [s.text for s in api.GetUserTimeline(screen_name='@BarackObama')] ``` (c.f. [`GetUserTimeline` test code in twitter\_test.py](https://github.com/bear/python-twitter/blob/master/twitter_test.py#L386) - which is to say...
Python BeautifulSoup scrape tables
18,966,368
9
2013-09-23T18:35:13Z
18,966,444
13
2013-09-23T18:40:00Z
[ "python", "html", "web-scraping", "beautifulsoup", "html-parsing" ]
I am trying to create a table scrape with BeautifulSoup. I wrote this Python code: ``` import urllib2 from bs4 import BeautifulSoup url = "http://dofollow.netsons.org/table1.htm" # change to whatever your url is page = urllib2.urlopen(url).read() soup = BeautifulSoup(page) for i in soup.find_all('form'): print...
Loop over table rows (`tr` tag) and get the text of cells (`td` tag) inside: ``` for tr in soup.find_all('tr')[2:]: tds = tr.find_all('td') print "Nome: %s, Cognome: %s, Email: %s" % \ (tds[0].text, tds[1].text, tds[2].text) ``` prints: ``` Nome:  Massimo, Cognome:  Allegri, Email:  Allegri.Mass...
Pip freeze vs. pip list
18,966,564
30
2013-09-23T18:46:13Z
18,966,632
31
2013-09-23T18:49:47Z
[ "python", "python-2.7", "python-3.x", "pip" ]
A comparison of outputs reveals differences: ``` user@user-VirtualBox:~$ pip list feedparser (5.1.3) pip (1.4.1) setuptools (1.1.5) wsgiref (0.1.2) user@user-VirtualBox:~$ pip freeze feedparser==5.1.3 wsgiref==0.1.2 ``` Pip's documentation states ``` freeze Output installed packages in requireme...
When you are using a `virtualenv`, you can specify a `requirements.txt` file to install all the dependencies. A typical usage: ``` $ pip install -r requirements.txt ``` The packages need to be in a specific format for `pip` to understand, which is ``` feedparser==5.1.3 wsgiref==0.1.2 django==1.4.2 ... ``` That is ...
Pip freeze vs. pip list
18,966,564
30
2013-09-23T18:46:13Z
28,330,159
9
2015-02-04T19:50:16Z
[ "python", "python-2.7", "python-3.x", "pip" ]
A comparison of outputs reveals differences: ``` user@user-VirtualBox:~$ pip list feedparser (5.1.3) pip (1.4.1) setuptools (1.1.5) wsgiref (0.1.2) user@user-VirtualBox:~$ pip freeze feedparser==5.1.3 wsgiref==0.1.2 ``` Pip's documentation states ``` freeze Output installed packages in requireme...
To answer the second part of this question, the two packages shown in `pip list` but not `pip freeze` are `setuptools` (which is easy\_install) and `pip` itself. It looks like `pip freeze` just doesn't list packages that pip itself depends on. You may use the `--all` flag to show also those packages.
Convert string to list. Python [string.split() acting weird]
18,966,798
11
2013-09-23T19:01:25Z
18,966,807
19
2013-09-23T19:02:31Z
[ "python", "string", "list", "split" ]
``` temp = "['a','b','c']" print type(temp) #string output = ['a','b','c'] print type(output) #list ``` so i have this temporary string which is basically a list in string format . . . i'm trying to turn it back into a list but i'm not sure a simple way to do it . i know one way but i'd rather not use regex if i use...
Use [`ast.literal_eval()`](http://docs.python.org/2/library/ast.html#ast.literal_eval): > Safely evaluate an expression node or a Unicode or Latin-1 encoded > string containing a Python expression. The string or node provided may > only consist of the following Python literal structures: strings, > numbers, tuples, li...
Add a prefix to all Flask routes
18,967,441
30
2013-09-23T19:39:27Z
18,967,744
32
2013-09-23T19:57:47Z
[ "python", "routes", "flask" ]
I have a prefix that I want to add to every route. Right now I add a constant to the route at every definition. Is there a way to do this automatically? ``` PREFIX = "/abc/123" @app.route(PREFIX + "/") def index_page(): return "This is a website about burritos" @app.route(PREFIX + "/about") def about_page(): ret...
The answer depends on how you are serving this application. ## Sub-mounted inside of another WSGI container Assuming that you are going to run this application inside of a WSGI container (mod\_wsgi, uwsgi, gunicorn, etc); you need to actually *mount, at that prefix* the application as a sub-part of that WSGI containe...
Add a prefix to all Flask routes
18,967,441
30
2013-09-23T19:39:27Z
18,969,161
33
2013-09-23T21:24:12Z
[ "python", "routes", "flask" ]
I have a prefix that I want to add to every route. Right now I add a constant to the route at every definition. Is there a way to do this automatically? ``` PREFIX = "/abc/123" @app.route(PREFIX + "/") def index_page(): return "This is a website about burritos" @app.route(PREFIX + "/about") def about_page(): ret...
You can put your routes in a blueprint: ``` bp = Blueprint('burritos', __name__, template_folder='templates') @bp.route("/") def index_page(): return "This is a website about burritos" @bp.route("/about") def about_page(): return "This is a website about burritos" ``` Then you register t...
Add a prefix to all Flask routes
18,967,441
30
2013-09-23T19:39:27Z
36,033,627
7
2016-03-16T10:57:05Z
[ "python", "routes", "flask" ]
I have a prefix that I want to add to every route. Right now I add a constant to the route at every definition. Is there a way to do this automatically? ``` PREFIX = "/abc/123" @app.route(PREFIX + "/") def index_page(): return "This is a website about burritos" @app.route(PREFIX + "/about") def about_page(): ret...
All you have to do is to write a middleware to make the following changes: 1. modify `PATH_INFO` to handle the prefixed url. 2. modify `SCRIPT_NAME` to generate the prefixed url. Like this: ``` class PrefixMiddleware(object): def __init__(self, app, prefix=''): self.app = app self.prefix = prefi...
Floats print differently when shown in dictionary - python
18,967,687
3
2013-09-23T19:55:06Z
18,967,830
7
2013-09-23T20:04:05Z
[ "python", "dictionary", "numbers", "key" ]
I'm creating a dictionary with this simple code: ``` pixel_histogram = {} min_value = -0.2 max_value = 0.2 interval_size = (math.fabs(min_value) + math.fabs(max_value))/bins for i in range(bins): key = min_value+(i*interval_size) print key pixel_histogram[key] = 0 print pixel_histogram ``` But I'm a ...
Python's `print` statement uses `str()` on the item being printed. For floating-point values, `str()` will print up to certain number of decimal values. When printing a dictionary, the `print` statement is calling `str()` on the dictionary object. The dictionary, in its `__str__()` method definition, uses `repr()` on ...
Deleting items in a list in python
18,967,756
2
2013-09-23T19:58:25Z
18,967,773
10
2013-09-23T19:59:43Z
[ "python", "list", "python-2.7" ]
Tried deleting items in a list, no success. ``` >>> r = [1,2,3,4,5] >>> for i in r: if i<3: del i >>> print r [1, 2, 3, 4, 5] ``` I even tried filtering it, ``` >>> def f(i): True if i>2 else False >>> print list(filter(f,r)) [] ``` I do not understand why the first one is not working. And I don...
Use a list comprehension instead: ``` [i for i in r if i >= 3] ``` and retain instead of delete. Your filter never *returned* the test; so you always return `None` instead and that's false in a boolean context. The following works just fine: ``` def f(i): return i > 2 ``` Your initial attempt failed because `d...
Paramiko: Port Forwarding Around A NAT Router
18,968,069
10
2013-09-23T20:18:04Z
19,039,769
11
2013-09-26T22:27:51Z
[ "python", "ssh", "paramiko" ]
## Configuration * **LOCAL:** A local machine that will create an ssh connection and issue commands on a REMOTE box. * **PROXY:** An EC-2 instance with ssh access to both LOCAL and REMOTE. * **REMOTE:** A remote machine sitting behind a NAT Router (inaccessible by LOCAL, but will open a connection to PROXY and allow L...
A detailed explanation of what Paramiko is doing "under the hood" can be found at [@bitprohet's blog here](http://bitprophet.org/blog/2012/11/05/gateway-solutions/). Assuming the configuration above, the code I have working looks something like this: ``` from paramiko import SSHClient # Set up the proxy (forwarding ...
Construct two dimensional numpy array from indices and values of a one dimensional array
18,968,660
6
2013-09-23T20:53:24Z
18,968,810
12
2013-09-23T21:01:57Z
[ "python", "numpy" ]
Say I've got ``` Y = np.array([2, 0, 1, 1]) ``` From this I want to obtain a matrix X with shape `(len(Y), 3)`. In this particular case, the first row of X should have a one on the second index and zero otherwhise. The second row of X should have a one on the 0 index and zero otherwise. To be explicit: ``` X = np.ar...
Maybe: ``` >>> Y = np.array([2, 0, 1, 1]) >>> X = np.zeros((len(Y), 3)) >>> X[np.arange(len(Y)), Y] = 1 >>> X array([[ 0., 0., 1.], [ 1., 0., 0.], [ 0., 1., 0.], [ 0., 1., 0.]]) ```
Parsing Data From Long to Wide Format in Python
18,969,034
2
2013-09-23T21:14:57Z
19,328,258
7
2013-10-11T22:31:25Z
[ "python", "parsing", "pandas", "reshape" ]
I'm wondering what the best way to parse long form data into wide for is in python. I've previously been doing this sort of task in R but it really is taking to long as my files can be upwards of 1 gb. Here is some dummy data: ``` Sequence Position Strand Score Gene1 0 + 1 Gene1 1 + 0.25 ...
Both of these solutions seem like overkill when you can do it with pandas in a one-liner: ``` In [7]: df Out[7]: Sequence Position Strand Score 0 Gene1 0 + 1.00 1 Gene1 1 + 0.25 2 Gene1 0 - 1.00 3 Gene1 1 - 0.50 4 Gene2 0 + ...
Android Market API - Python ImportError: No module named google.protobuf
18,969,358
19
2013-09-23T21:38:33Z
21,488,362
27
2014-01-31T19:23:05Z
[ "python", "google-play" ]
Based on [Python-API](https://github.com/liato/android-market-api-py) the requirements I have configured and installed the protocol buffers (as mentioned in <http://worthynote.blogspot.com/2011/05/protobuf-compiler-on-mac.html> ) and python 2.7. When I ran the command ``` python examples.py ``` and still faced the er...
Use [pip](http://www.pip-installer.org/): ``` sudo pip install protobuf ``` I had the same problem, which is how I found your question, and this fixed it.
Wallis' formula for pi
18,969,881
3
2013-09-23T22:20:51Z
18,969,900
7
2013-09-23T22:22:53Z
[ "python", "python-2.7" ]
``` def wallis(n): pi = 0.0 for i in range(n): left = (2 * i)/(2 * i - 1) right = (2 * i)/(2 * i + 1) total = left * right pi = pi + total return pi print wallis(1000) print wallis(10000) print wallis(100000) ``` I copied the formula exactly but I keep getting 0 as the ou...
Python is doing integer division, and truncates the decimals. This is because both values to division are integers. Convert one of the numbers to a float to get a floating point value in return. ``` left = float(2 * i)/(2 * i - 1) right = float(2 * i)/(2 * i + 1) ``` OR, as @kindall points out, you can change the con...
Python equivalent to Ruby Array.each method
18,970,196
10
2013-09-23T22:49:55Z
18,970,204
12
2013-09-23T22:50:47Z
[ "python", "ruby" ]
In Python what is equivalent to Ruby's Array.each method? Does Python have a nice and short closure/lambda syntax for it? ``` [1,2,3].each do |x| puts x end ```
The most idiomatic: ``` for x in [1,2,3]: print x ```
Python equivalent to Ruby Array.each method
18,970,196
10
2013-09-23T22:49:55Z
18,970,233
24
2013-09-23T22:54:31Z
[ "python", "ruby" ]
In Python what is equivalent to Ruby's Array.each method? Does Python have a nice and short closure/lambda syntax for it? ``` [1,2,3].each do |x| puts x end ```
> Does Python have a nice and short closure/lambda syntax for it? Yes, but you don't want it in this case. The closest equivalent to that Ruby code is: ``` new_values = map(print, [1, 2, 3]) ``` That looks pretty nice when you already have a function lying around, like `print`. When you just have some arbitrary exp...
What's the most pythonic and elegant way to separate logic of a class and its parent if child class is determined by construction logic?
18,971,275
4
2013-09-24T00:53:12Z
18,971,381
8
2013-09-24T01:07:35Z
[ "python", "class", "inheritance" ]
I want to construct classes from strings such as `"red apple"`. This would create an instance of class `Apple`, which is a subclass of `Fruit`. The thing is, `color` attribute should belong to `Fruit`, not `Apple`. Therefore, the natural way of creating the object seem to me to be: 1. parse the string 2. create `Fruit...
I would pull the creation logic out of the classes completely: 1. parse the string 2. determine the object to create 3. create object So using the following code: ``` class Fruit(object): def __init__(self, color): self.color = color def observe(self): print "Looks like a tasty %s fruit" % s...
Python socket server/client programming
18,971,777
10
2013-09-24T01:55:43Z
18,972,039
11
2013-09-24T02:31:46Z
[ "python", "sockets", "client" ]
So I am just getting into python and trying out some stuff. To start, I am making a server that does simple stuff like "GET"s stored text, "STORE"s new text over the old stored text, and "TRANSLATE"s lowercase text into uppercase. But I have a few questions. Here is my code so far: ``` import socket HOST = '' # Sym...
I see that you're quite new to Python. You can try to find some code example, and you **should** also learn how to interpret the error message. The error message will give you the line number where you should look at. You should consider that line or previous line, as the error may be caused by previous mistakes. Anyw...
Image segmentation based on edge pixel map
18,972,932
27
2013-09-24T04:24:08Z
19,510,366
47
2013-10-22T06:18:53Z
[ "python", "opencv", "image-processing", "edge-detection", "image-segmentation" ]
I have trained a classifier in Python for classifying pixels in an image of cells as edge or non edge. I've used it successfully on a few image datasets but am running into problems with this particular dataset, which seems pretty ambiguous even to the human eye. I don't know of any existing automated technique that ca...
Very nice work on boundary detection. I used to work on similar segmentation problems. ### Theory: Once you obtained your edge map where `e(i,j)` indicates the "edge-iness" degree of pixel `i,j` you would like a segmentation of the image that would respect the edge map as possible. In order to formulate this "respe...
Setting Different Bar color in matplotlib Python
18,973,404
25
2013-09-24T05:13:17Z
18,973,430
29
2013-09-24T05:15:19Z
[ "python", "matplotlib", "pandas", "bar-chart" ]
Supposely, I have the bar chart as below: ![BarPlot](http://i.stack.imgur.com/wy1lP.png) Any ideas on how to set different colors for each carrier? As for example, AK would be Red, GA would be Green, etc? I am using Pandas and matplotlib in Python ``` >>> f=plt.figure() >>> ax=f.add_subplot(1,1,1) >>> ax.bar([1,2,3...
Simple, just use `.set_color` ``` >>> barlist=plt.bar([1,2,3,4], [1,2,3,4]) >>> barlist[0].set_color('r') >>> plt.show() ``` ![enter image description here](http://i.stack.imgur.com/SYCFW.png) For your new question, not much harder either, just need to find the bar from your axis, an example: ``` >>> f=plt.figure()...
Setting Different Bar color in matplotlib Python
18,973,404
25
2013-09-24T05:13:17Z
18,975,065
13
2013-09-24T07:04:44Z
[ "python", "matplotlib", "pandas", "bar-chart" ]
Supposely, I have the bar chart as below: ![BarPlot](http://i.stack.imgur.com/wy1lP.png) Any ideas on how to set different colors for each carrier? As for example, AK would be Red, GA would be Green, etc? I am using Pandas and matplotlib in Python ``` >>> f=plt.figure() >>> ax=f.add_subplot(1,1,1) >>> ax.bar([1,2,3...
I assume you are using Series.plot() to plot your data. If you look at the docs for Series.plot() here: <http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.plot.html> there is no *color* parameter listed where you might be able to set the colors for your bar graph. However, the Series.plot() docs state...
os.mkdir(path) returns OSError when directory does not exist
18,973,418
10
2013-09-24T05:14:22Z
18,973,480
12
2013-09-24T05:19:10Z
[ "python", "system", "mkdir" ]
I am calling os.mkdir to create a folder with a certain set of generated data. However, even though the path I specify has not been created, the os.mkdir(path) raises an OSError that the path already exists. For example, I call: ``` os.mkdir(test) ``` This call results in `OSError: [Errno 17] File exists: 'test'` ev...
Just check if the path exist. if not create it ``` if not os.path.exists(test): os.makedirs(test) ```
os.mkdir(path) returns OSError when directory does not exist
18,973,418
10
2013-09-24T05:14:22Z
22,718,321
14
2014-03-28T16:30:46Z
[ "python", "system", "mkdir" ]
I am calling os.mkdir to create a folder with a certain set of generated data. However, even though the path I specify has not been created, the os.mkdir(path) raises an OSError that the path already exists. For example, I call: ``` os.mkdir(test) ``` This call results in `OSError: [Errno 17] File exists: 'test'` ev...
Greg's answer is correct but doesn't go far enough. `OSError` has sub-error conditions, and you don't want to suppress them all every time. It's prudent to trap just **expected** OS errors. Do additional checking before you decide to suppress the exception, like this: ``` import errno try: os.mkdir(dirname) exce...
How to compile OpenCV for iOS7 (arm64)
18,976,893
2
2013-09-24T08:49:15Z
22,564,796
8
2014-03-21T16:54:10Z
[ "python", "ios", "opencv", "ios7" ]
Compiling Xcode Project fails with following errors: ['missing required architecture arm64 in file /Users/*\**/Git/ocr/opencv2.framework/opencv2'](http://pastebin.com/WC9Tbe8L) It works well, if i change Architectures(under Build Settings) to (armv7, armv7s) instead of (armv7, armv7s). How to change the opencv python...
The latest OpenCV iOS framework supports 64 bit by default It can be downloaded at: [OpenCV download page](http://opencv.org/downloads.html)
Sending post data from angularjs to django as JSON and not as raw content
18,979,111
16
2013-09-24T10:28:51Z
18,981,965
39
2013-09-24T12:43:39Z
[ "python", "django", "angularjs", "http-post" ]
I have a request like this: ``` $http({ method: 'POST', url: '/url/', data: 'test=data' }) ``` In my django views: ``` class SomeClass(View): def get(self, request): return HttpResponse("Hello") def post(self, request): print request.post print request.body retu...
When calling ajax, you recieve encoded json string in request body, so you need to decode it using python's json module to get python dict: ``` json.loads(request.body) ```
Sending post data from angularjs to django as JSON and not as raw content
18,979,111
16
2013-09-24T10:28:51Z
19,710,743
11
2013-10-31T15:35:16Z
[ "python", "django", "angularjs", "http-post" ]
I have a request like this: ``` $http({ method: 'POST', url: '/url/', data: 'test=data' }) ``` In my django views: ``` class SomeClass(View): def get(self, request): return HttpResponse("Hello") def post(self, request): print request.post print request.body retu...
In my case works something like ``` $http({ url: '/url/', method: "POST", data: $.param(params), headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } }) ``` Or more nice variant: ``` app.config ($httpProvider) -> ... $httpProvider.defaults.headers.post['...
Boto s3 get_metadata
18,979,199
7
2013-09-24T10:33:01Z
18,981,298
13
2013-09-24T12:12:46Z
[ "python", "amazon-s3", "metadata", "amazon", "boto" ]
Trying to get meta\_data that i have set on all my items in an s3 bucket. Which can be seen in the screenshot and below is the code I'm using. The two get\_metadata calls return None. Any idea's ![enter image description here](http://i.stack.imgur.com/mzIq8.png) > > > boto.Version > > > '2.5.2' ``` amazon_connection...
bucket.list() does not return metadata. try this instead: ``` for key in bucket.list(): akey = bucket.get_key(key.name) print akey.get_metadata("company") ```
How to append in a json file in Python?
18,980,039
9
2013-09-24T11:12:21Z
18,980,132
24
2013-09-24T11:16:50Z
[ "python", "json" ]
I have the a json file whose contents is `{"67790": {"1": {"kwh": 319.4}}}`. Now I create a dictionary `a_dict` which I need to append it into the json file. I tried the following but was not able to do it correctly. Where I'm going wrong? ``` with open(DATA_FILENAME, 'a') as f: json_obj = json.dump(a_dict, json.lo...
Assuming you have a `test.json` file with the following content: ``` {"67790": {"1": {"kwh": 319.4}}} ``` Then, the code below will `load` the json file, update the data inside using `dict.update()` and `dump` into the `test.json` file: ``` import json a_dict = {'new_key': 'new_value'} with open('test.json') as f:...
Difference between except: and except Exception as e: in Python
18,982,610
30
2013-09-24T13:11:41Z
18,982,726
36
2013-09-24T13:16:29Z
[ "python", "python-3.x" ]
Both the following snippets of code do the same thing. They catch every exception and execute the code in the `except:` block Snippet 1 - ``` try: #some code that may throw an exception except: #exception handling code ``` Snippet 2 - ``` try: #some code that may throw an exception except Exception as e...
In the second you can access the attributes of the exception object: ``` >>> def catch(): ... try: ... asd() ... except Exception as e: ... print e.message, e.args ... >>> catch() global name 'asd' is not defined ("global name 'asd' is not defined",) ``` But it doesn't catch `BaseException` o...
Difference between except: and except Exception as e: in Python
18,982,610
30
2013-09-24T13:11:41Z
18,982,754
13
2013-09-24T13:17:35Z
[ "python", "python-3.x" ]
Both the following snippets of code do the same thing. They catch every exception and execute the code in the `except:` block Snippet 1 - ``` try: #some code that may throw an exception except: #exception handling code ``` Snippet 2 - ``` try: #some code that may throw an exception except Exception as e...
``` except: ``` accepts **all** exceptions, whereas ``` except Exception as e: ``` only accepts exceptions that you're *meant* to catch. Here's an example of one that you're not meant to catch: ``` >>> try: ... input() ... except: ... pass ... >>> try: ... input() ... except Exception as e: ... pa...
Python 2.7 : Write to file instantly
18,984,092
13
2013-09-24T14:16:01Z
18,984,120
9
2013-09-24T14:17:18Z
[ "python", "python-2.7" ]
I realized that when I write into a file using python it wait until the end of my Python file to execute it: ``` outputFile = open("./outputFile.txt","a") outputFile.write("First") print "Now you have 10sec to see that outputFile.txt is still the same as before" time.sleep(10) outputFile.write("Second") print "Now if ...
Force it with the `flush()` function, add ``` outputFile.flush() ``` at the end of your code.
Python 2.7 : Write to file instantly
18,984,092
13
2013-09-24T14:16:01Z
18,984,187
21
2013-09-24T14:19:22Z
[ "python", "python-2.7" ]
I realized that when I write into a file using python it wait until the end of my Python file to execute it: ``` outputFile = open("./outputFile.txt","a") outputFile.write("First") print "Now you have 10sec to see that outputFile.txt is still the same as before" time.sleep(10) outputFile.write("Second") print "Now if ...
You can use `flush()` or you can set the file object to be unbuffered. Details on using that parameter for `open()` [here](http://docs.python.org/2/library/functions.html#open). So you would change your open call to - ``` outputFile = open("./outputFile.txt", "a", 0) ```
error using L-BFGS-B in scipy
18,985,048
2
2013-09-24T14:55:28Z
18,985,916
7
2013-09-24T15:32:24Z
[ "python", "optimization", "scipy" ]
I get some puzzling result when using the 'L-BFGS-B' method in scipy.optimize.minimize: ``` import scipy.optimize as optimize import numpy as np def testFun(): prec = 1e3 func0 = lambda x: (float(x[0]*prec)/prec+0.5)**2+(float(x[1]*prec)/prec-0.3)**2 func1 = lambda x: (float(round(x[0]*prec))/prec+0.5)**...
BFGS method is one of those method that relies on not only the function value, but also the gradient and Hessian (think of it as first and second derivative if you wish). In your `func1()`, once you have `round()` in it, the gradient is no longer continuous. BFGS method therefore fails right after the 1st iteration (th...
Regex related to * and + in python
18,987,394
2
2013-09-24T16:43:02Z
18,987,446
9
2013-09-24T16:45:44Z
[ "python", "regex" ]
I am new to python. I didnt understand the behaviour of these program in python. ``` import re sub="dear" pat="[aeiou]+" m=re.search(pat,sub) print(m.group()) ``` This prints "ea" ``` import re sub="dear" pat="[aeiou]*" m=re.search(pat,sub) print(m.group()) ``` This doesnt prints anything. I know + matches 1 or mo...
> This doesnt prints anything. Not exactly. It prints an empty string which you just of course you didn't notice, as it's not visible. Try using this code instead: ``` l = re.findall(pat, sub) print l ``` this will print: ``` ['', 'ea', '', ''] ``` --- **Why this behaviour?** This is because when you use `*` qua...
Can I optionally include one element in a list without an else statement in python?
18,988,805
2
2013-09-24T18:02:25Z
18,988,829
7
2013-09-24T18:03:59Z
[ "python", "list", "syntax" ]
I know you can do something like this in python: ``` >>> conditional = False >>> x = [1 if conditional else 2, 3, 4] [ 2, 3, 4 ] ``` but how would I do something like this? ``` >>> conditional = False >>> x = [1 if conditional, 3, 4] [ 3, 4 ] ``` That is, I don't want to substitute the `1` for another number. I wan...
Use concatenation: ``` x = ([1] if conditional else []) + [3, 4] ``` In other words, generate a sublist that either has the optional element in it, or is empty. Demo: ``` >>> conditional = False >>> ([1] if conditional else []) + [3, 4] [3, 4] >>> conditional = True >>> ([1] if conditional else []) + [3, 4] [1, 3, ...
Python - Property setting from list causes maximum recursion depth exceeded
18,989,362
4
2013-09-24T18:33:28Z
18,989,386
13
2013-09-24T18:35:01Z
[ "python", "recursion" ]
I have the following class: ``` class vehicle(object): def __init__(self, name): self.name = name self.kinds_list = ["tank", "car", "motorbike", "bike", "quad" ] @property def kind(self): return self.kind @kind.setter def kind(self, x): if x in self.kinds_list: ...
The reason you reached the maximum recursion depth is that inside your setter, you do `self.kind = ...`, which recursively calls the same setter. You should store the value as some private attribute, just rename `self.kind` to `self._kind`. ``` class vehicle(object): def __init__(self, name): self.name = n...
Execute Python function in Main thread from call in Dummy thread
18,989,446
6
2013-09-24T18:38:08Z
18,990,710
10
2013-09-24T19:47:57Z
[ "python", "multithreading", ".net-remoting" ]
I have a Python script that handles aynchronous callbacks from .NET Remoting. These callbacks execute in a dummy (worker) thread. From inside my callback handler, I need to call a function I've defined in my script, but I need the function to execute in the main thread. The Main thread is a remote client that sends co...
You want to use the [Queue](http://docs.python.org/2/library/queue.html) class to set up a queue that your dummy threads populate with functions and that your main thread consumes. ``` import Queue #somewhere accessible to both: callback_queue = Queue.Queue() def from_dummy_thread(func_to_call_from_main_thread): ...
how to get tuples from lists using list comprehension in python
18,990,069
5
2013-09-24T19:13:00Z
18,990,147
10
2013-09-24T19:17:09Z
[ "python", "list", "tuples", "list-comprehension" ]
I have two lists and want to merges them into one list of `tuples`. I want to do it with `list comprehension`, I can get it working using `map`. but would be nice to know how list comprehension here will work. code here ``` >>> lst = [1,2,3,4,5] >>> lst2 = [6,7,8,9,10] >>> tup = map(None,lst,lst2) # works fine >>> tu...
Think about list comprehensions as loops. How can you write 2 not nested loops? You can do this with somewhat wierd list comprehension: ``` [(x, lst2[i]) for i, x in enumerate(lst)] ``` or ``` [(lst[i], lst2[i]) for i in xrange(len(lst))] ``` But actually, it's better to use `zip`.
Python Twisted's DeferredLock
18,990,697
8
2013-09-24T19:46:53Z
18,993,262
13
2013-09-24T22:34:31Z
[ "python", "twisted" ]
Can someone provide an example and explain when and how to use Twisted's [DeferredLock](http://twistedmatrix.com/documents/current/api/twisted.internet.defer.DeferredLock.html). I have a DeferredQueue and I think I have a race condition I want to prevent, but I'm unsure how to combine the two.
Use a `DeferredLock` when you have a critical section that is asynchronous and needs to be protected from overlapping (one might say "concurrent") execution. Here is an example of such an asynchronous critical section: ``` class NetworkCounter(object): def __init__(self): self._count = 0 def next(sel...
Python finite difference functions?
18,991,408
18
2013-09-24T20:27:55Z
18,993,405
34
2013-09-24T22:49:16Z
[ "python", "numpy", "scipy" ]
I've been looking around in Numpy/Scipy for modules containing finite difference functions. However, the closest thing I've found is `numpy.gradient()`, which is good for 1st-order finite differences of 2nd order accuracy, but not so much if you're wanting higher-order derivatives or more accurate methods. I haven't ev...
One way to do this quickly is by convolution with the derivative of a gaussian kernel. The simple case is a convolution of your array with `[-1, 1]` which gives exactly the simple finite difference formula. Beyond that, `(f*g)'= f'*g = f*g'` where the `*` is convolution, so you end up with your derivative convolved wit...
save a pandas.Series histogram plot to file
18,992,086
18
2013-09-24T21:08:19Z
18,992,172
43
2013-09-24T21:14:24Z
[ "python", "pandas", "histogram" ]
In ipython Notebook, first create a pandas Series object, then by calling the instance method .hist(), the browser displays the figure. I am wondering how to save this figure to a file (I mean not by right click and save as, but the commands needed in the script).
Use the `Figure.savefig()` method, like so: ``` ax = s.hist() # s is an instance of Series fig = ax.get_figure() fig.savefig('/path/to/figure.pdf') ``` It doesn't have to end in `pdf`, there are many options. Check out [the documentation](http://matplotlib.org/api/figure_api.html?highlight=savefig#matplotlib.figure....
Best way to reference the User model in Django >= 1.5
18,992,847
10
2013-09-24T22:01:42Z
21,617,856
7
2014-02-07T01:53:53Z
[ "python", "django", "django-models" ]
What is the best way to reference User model in Django >= 1.5? After reading [Referencing the User model](https://docs.djangoproject.com/en/dev/topics/auth/customizing/#referencing-the-user-model), I've started using (1) for a while: (1) ``` from django.conf import settings from django.db import models class Articl...
You might [experience circular reference](http://www.caktusgroup.com/blog/2013/08/07/migrating-custom-user-model-django/) issues if you use `get_user_model` at module level. Another option for importing the auth user model is: ``` from django.conf import settings AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL',...
shebang env preferred python version
18,993,438
8
2013-09-24T22:52:07Z
26,056,481
16
2014-09-26T09:38:16Z
[ "python", "linux", "scripting", "shebang" ]
I have some python-2.x scripts which I copy between different systems, Debian and Arch linux. Debian install python as '/usr/bin/python' while Arch installs it as '/usr/bin/python2'. A problem is that on Arch linux '/usr/bin/python' also exists which refers to python-3.x. So every time I copy a file I have to correct t...
``` #!/bin/sh ''''which python2 >/dev/null 2>&1 && exec python2 "$0" "$@" # ''' ''''which python >/dev/null 2>&1 && exec python "$0" "$@" # ''' ''''exec echo "Error: I can't find python anywhere" # ''' import sys print sys.argv ``` This is first run as a shell script. You can put almost any shell code in be...
Make python code continue after exception
18,994,334
4
2013-09-25T00:34:29Z
18,994,347
14
2013-09-25T00:35:52Z
[ "python" ]
I'm trying to read all files from a folder that matches a certain criteria. My program crashes once I have an exception raised. I am trying to continue even if there's an exception but it still stops executing. This is what I get after a couple of seconds. ``` error <type 'exceptions.IOError'> ``` Here's my code ``...
Put your `try/except` structure more in-wards. Otherwise when you get an error, it will break all the loops. Perhaps after the first for-loop, add the `try/except`. Then if an error is raised, it will continue with the next file. ``` for infile in listing: try: if infile.startswith("ABC"): fo ...
Ending an infinite while loop
18,994,912
6
2013-09-25T01:51:20Z
18,994,932
21
2013-09-25T01:54:16Z
[ "python", "while-loop", "infinite-loop" ]
I currently have code that basically runs an infinite while loop to collect data from users. Constantly updating dictionaries/lists based on the contents of a text file. For reference: ``` while (True): IDs2=UpdatePoints(value,IDs2) time.sleep(10) ``` Basically, my problem is that I do not know when I want th...
You can try wrapping that code in a try/except block, because keyboard interrupts are just exceptions: ``` try: while True: IDs2=UpdatePoints(value,IDs2) time.sleep(10) except KeyboardInterrupt: print 'interrupted!' ``` Then you can exit the loop with CTRL-C.
Django Celery Task Logging
18,995,020
6
2013-09-25T02:03:10Z
19,018,398
10
2013-09-26T02:34:52Z
[ "python", "django", "logging", "celery", "django-celery" ]
I have setup Celery in a Django project on which I am working. I would like to separate the logging for celery tasks vs the remainder of celery logs (celerycam, celerybeat, etc). Based on the Celery documentation (<http://docs.celeryproject.org/en/latest/userguide/tasks.html#logging>) it seems like I should just be ab...
i'm guessing in your tasks your doing this ``` from celery.utils.log import get_task_logger logger = get_task_logger(__name__) ``` if your doing that then your logger name will be the module name, so if your task is in a tasks.py file in an app called MyApp your logger will be named 'MyApp.tasks' and you'd have to cr...
Floating Point Arithmetic error
18,995,148
6
2013-09-25T02:20:18Z
18,995,731
7
2013-09-25T03:31:23Z
[ "python", "floating-point", "double", "precision", "ieee-754" ]
I'm using the following function to approximate the derivative of a function at a point: ``` def prime_x(f, x, h): if not f(x+h) == f(x) and not h == 0.0: return (f(x+h) - f(x)) / h else: raise PrecisionError ``` As a test I'm passing `f` as `fx` and `x` as 3.0. Where `fx` is: ``` def fx(x)...
Floating-point arithmetic (and integer arithmetic and fixed-point arithmetic) has a certain granularity: Values can only change by a certain step size. For IEEE-754 64-bit binary format, that step size is about 2–52 times the value (about 2.22•10–16). That is very small for physical measurements. However, when y...
django-rest-framework: __init__() takes exactly 1 argument (2 given)
18,995,516
5
2013-09-25T03:05:17Z
18,996,820
23
2013-09-25T05:21:39Z
[ "python", "django", "django-rest-framework" ]
my error is similar to [django error: \_\_init\_\_() takes exactly 1 argument (2 given)](http://stackoverflow.com/questions/11281279/django-error-init-takes-exactly-1-argument-2-given), but as there is no correct answer and I can not find way to solve it now. So, I ask again. In views.py I write: ``` class JSONRespon...
Did you forget to use as\_view() ? ``` url(r'^snippets/$', snippets.views.SnippetListView.as_view()), ```
How to turn pandas dataframe row into ordereddict fast
18,996,714
8
2013-09-25T05:12:22Z
18,996,948
15
2013-09-25T05:31:28Z
[ "python", "pandas", "dataframe", "ordereddictionary" ]
Looking for a fast way to get a row in a pandas dataframe into a ordered dict with out using list. List are fine but with large data sets will take to long. I am using fiona GIS reader and the rows are ordereddicts with the schema giving the data type. I use pandas to join data. I many cases the rows will have differen...
Unfortunately you can't just do an apply (since it fits it back to a DataFrame): ``` In [1]: df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b']) In [2]: df Out[2]: a b 0 1 2 1 3 4 In [3]: from collections import OrderedDict In [4]: df.apply(OrderedDict) Out[4]: a b 0 1 2 1 3 4 ``` But you can...
Use Latent Semantic Analysis with sklearn
18,997,905
3
2013-09-25T06:38:50Z
18,999,170
7
2013-09-25T07:49:39Z
[ "python", "scikit-learn" ]
I am trying to write a script where I will calculate the similarity of few documents. I want to do it by using LSA. I have found the following code and change it a bit. I has as an input 3 documents and then as output a 3x3 matrix with the similarity between them. I want to do the same similarity calculation but only w...
You can use the [TruncatedSVD](http://scikit-learn.org/stable/modules/decomposition.html#truncated-singular-value-decomposition-and-latent-semantic-analysis) transformer from sklearn 0.14+: you call it with `fit_transform` on your database of documents and then call the `transform` method (from the same `TruncatedSVD` ...
flake8 complains on boolean comparison "==" in filter clause
18,998,010
19
2013-09-25T06:44:56Z
18,998,106
30
2013-09-25T06:50:28Z
[ "python", "mysql", "sqlalchemy", "flake8" ]
I have a boolean field in the mysql db table. ``` # table model class TestCase(Base): __tablename__ = 'test_cases' ... obsoleted = Column('obsoleted', Boolean) ``` To get the count of all the non-obsoleted test cases, that can be done simply like this: ``` caseNum = session.query(TestCase).filter(TestCa...
That's because SQLAlchemy filters are one of the few places where `== False` actually makes sense. **Everywhere else** you should *not* use it. Add a `# noqa` comment to the line and be done with it. Or you can use [`sqlalchemy.sql.expression.false`](http://docs.sqlalchemy.org/en/rel_1_0/core/sqlelement.html#sqlalche...
Selenium - Unresponsive Script Error (Firefox)
18,998,721
4
2013-09-25T07:25:56Z
19,151,816
7
2013-10-03T05:57:40Z
[ "javascript", "python", "firefox", "selenium" ]
This question has been asked before, but the answer given does not seem to work for me. The problem is, when opening a page using Selenium, I get numerous "Unresponsive Script" pop ups, referencing varying scripts. When I open the page using Firefox without Selenium, I get no errors. Also, oddly, when I open the page ...
After trying many settings, I think I have found one that works, and, alas, it was mentioned here, I just didn't really understand how to use it (b/c I had never dealt with firefox profile setting in selenium): [Selenium & Firefox: How can i turn off "Unresponsive script" warnings?](http://stackoverflow.com/questions/7...
how to count the total number of lines in a text file using python
19,001,402
11
2013-09-25T09:42:00Z
19,001,475
24
2013-09-25T09:45:52Z
[ "python", "file", "file-io", "sum" ]
For example if my text file is: ``` blue green yellow black ``` Here there are four lines and now I want to get the result as four. How can I do that?
You can use [`sum()`](http://docs.python.org/2/library/functions.html#sum) with a generator expression: ``` with open('data.txt') as f: print sum(1 for _ in f) ``` Note that you cannot use `len(f)`, since `f` is an [iterator](http://docs.python.org/2/library/stdtypes.html#iterator-types). `_` is a special variabl...
how to count the total number of lines in a text file using python
19,001,402
11
2013-09-25T09:42:00Z
19,001,477
8
2013-09-25T09:45:58Z
[ "python", "file", "file-io", "sum" ]
For example if my text file is: ``` blue green yellow black ``` Here there are four lines and now I want to get the result as four. How can I do that?
You can use `sum()` with a generator expression here. The generator expression will be `[1, 1, ...]` up to the length of the file. Then we call `sum()` to add them all together, to get the total count. ``` with open('text.txt') as myfile: count = sum(1 for line in myfile) ``` It seems by what you have tried that ...
how to count the total number of lines in a text file using python
19,001,402
11
2013-09-25T09:42:00Z
27,517,681
15
2014-12-17T03:05:34Z
[ "python", "file", "file-io", "sum" ]
For example if my text file is: ``` blue green yellow black ``` Here there are four lines and now I want to get the result as four. How can I do that?
This link ([How to get line count cheaply in Python?](http://stackoverflow.com/questions/845058/how-to-get-line-count-cheaply-in-python)) has lots of potential solutions, but they all ignore one way to make this run considerably faster, namely by using the unbuffered (raw) interface, using bytearrays, and doing your ow...
Check if any alert exists using selenium with python
19,003,003
21
2013-09-25T10:56:09Z
19,019,311
32
2013-09-26T04:19:41Z
[ "python", "testing", "selenium", "alertdialog", "window-handles" ]
I'm trying to write a test with selenium in python language for a web page that manages users. In this page someone can add role for users and if a role exists while adding it, an alert raises. I don't know if the alert is a javascript alert or an element of the web page. I want to automatically check the existence of ...
What I do is to set a conditional delay with WebDriverWait just before the point I expect to see the alert, then switch to it, like this: ``` from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exce...
finding non-unique elements in list not working
19,006,095
3
2013-09-25T13:19:22Z
19,006,206
10
2013-09-25T13:25:03Z
[ "python", "python-2.7" ]
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', ...
Removing elements of a list while iterating over it is never a good idea. The appropriate way to do this would be to use a [`collections.Counter`](http://docs.python.org/2/library/collections.html#collections.Counter) with a [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions)...
Running Flask locally. I want to display images based on names generated in JavaScript
19,006,741
3
2013-09-25T13:47:46Z
19,008,255
10
2013-09-25T14:52:22Z
[ "javascript", "python", "python-2.7", "flask" ]
I am using d3 and Flask to display tree diagrams in my browser. The whole thing is stored and operated locally. I want to display a relevant image when the user hovers over each node in the tree diagram. For the JSON data that the tree diagram is based on, I am using url\_for and my static folder, like this: ``` d3....
I assume you are running a Flask application locally (in your browser, you are typing something like `localhost:8000`). First, you need to understand what `url_for` does. It helps you generate the URL that the static file (in your case, an image or a javascript source file) that the HTML needs to load. So, when you ha...
Compare two different files line by line in python
19,007,383
7
2013-09-25T14:13:56Z
19,007,888
26
2013-09-25T14:36:53Z
[ "python", "file" ]
I have two different files and I want to compare theirs contents line by line, and write their common contents in a different file. Note that both of them contain some blank spaces. Here is my pseudo code: ``` file1 = open('some_file_1.txt', 'r') file2 = open('some_file_2.txt', 'r') FO = open('some_output_file.txt', '...
This solution reads both files in one pass, excludes blank lines, and prints common lines regardless of their position in the file: ``` with open('some_file_1.txt', 'r') as file1: with open('some_file_2.txt', 'r') as file2: same = set(file1).intersection(file2) same.discard('\n') with open('some_output_f...
Pythonic way to correctly separate Model from application using SQLAlchemy
19,008,260
9
2013-09-25T14:52:27Z
19,008,403
19
2013-09-25T14:57:47Z
[ "python", "flask", "flask-sqlalchemy" ]
I'm having a hard time to make my application run. Flask-SQLAlchemy extension creates an empty database whenever I try to separate module in packages. To better explain what I'm doing, let me show how my project is structured: ``` Project | |-- Model | |-- __init__.py | |-- User.py | |-- Server | |-- __init__.py...
Right now, you have set up your application using what is a rough equivalent to the "[Application Factory](http://flask.pocoo.org/docs/patterns/appfactories/)" pattern (so called by the Flask documentation). This is a Flask idea, not a Python one. It has some advantages, but it also means that you need to do things suc...
Import arbitrary python source file. (Python 3.3+)
19,009,932
19
2013-09-25T16:07:51Z
19,011,259
24
2013-09-25T17:17:13Z
[ "python", "python-3.x", "python-3.3" ]
How can I import an arbitrary python source file (whose filename could contain any characters, and does not always ends with `.py`) in **Python 3.3+**? I used [`imp.load_module`](http://docs.python.org/3/library/imp.html#imp.load_module) as follows: ``` >>> import imp >>> path = '/tmp/a-b.txt' >>> with open(path, 'U'...
Found a solution from [`importlib` test code](http://hg.python.org/cpython/file/436b606ecfe8/Lib/test/test_importlib/source/test_file_loader.py#l56). Using [importlib.machinery.SourceFileLoader](http://docs.python.org/3/library/importlib.html#importlib.machinery.SourceFileLoader): ``` >>> import importlib.machinery >...
How to make Ipython output a list without line breaks after elements?
19,010,036
11
2013-09-25T16:11:50Z
19,010,160
21
2013-09-25T16:17:52Z
[ "python", "list", "ipython", "ipython-notebook" ]
The IPython console prints a list of elements with line breaks so that each element is displayed in its own line. This is usually a feature, but in my case it is a bug: I need to copy and paste long lists, so I need a compact representation. How can I achieve this?
You can use `%pprint` command to turn on/off pprint feature: ``` In [1]: range(24) Out[1]: [0, 1, 2, ... 21, 22, 23] In [2]: %pprint Pretty printing has been turned OFF In [3]: range(24) Out[3]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] ``` If you want to turn off ...
Python - Find duplicates in a list of dictionaries and group them
19,011,124
6
2013-09-25T17:08:19Z
19,011,403
8
2013-09-25T17:25:44Z
[ "python", "json", "list", "dictionary" ]
i'm not a programmer and also new to python, i have a list of dicts coming from a json file: ``` # JSON file (film.json) [{"year": ["1999"], "director": ["Wachowski"], "film": ["The Matrix"], "price": ["19,00"]}, {"year": ["1994"], "director": ["Tarantino"], "film": ["Pulp Fiction"], "price": ["20,00"]}, {"year": ["20...
Because your data is not sorted, use a [`collections.defaultdict()` object](http://docs.python.org/2/library/collections.html#collections.defaultdict) to materialize a list for new keys, then key by film title: ``` from collections import defaultdict grouped = defaultdict(list) for film in f: grouped[film['film'...
Using BeautifulSoup to select div blocks within HTML
19,011,613
3
2013-09-25T17:38:08Z
19,012,021
7
2013-09-25T18:00:56Z
[ "python", "html", "python-2.7", "beautifulsoup", "urllib2" ]
I am trying to parse several div blocks using Beautiful Soup using some html from a website. However, I cannot work out which function should be used to select these div blocks. I have tried the following: ``` import urllib2 from bs4 import BeautifulSoup def getData(): html = urllib2.urlopen("http://www.racingpo...
The correct use would be: ``` soup.find_all('div', class_="crBlock ") ``` By default, beautiful soup will return the entire tag, including contents. You can then do whatever you want to it if you store it in a variable. If you are only looking for one div, you can also use `find()` instead. For instance: ``` div = s...